text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
A computer algebra system written in pure Python . To get started to with contributing
.subsfunction is quite slow. When I have a long expression
e(can contain nonlinear terms like
x**2,
y*x*z), calling
e.subs(some_dict)takes quite sometime (a sec or so). In fact subs is often slower than solving for large equations. Am I using
subscorrectly?
import sympy as sp from sympy import exp, oo sp.init_printing() x = sp.Symbol("x") a, m, h = sp.symbols("a, m, h", positive = True) A = sp.Symbol("A") f = exp(-2 * a * m * x**2 / h) int_f = sp.integrate(f, (x, 0, oo)) eq1 = 2 * (abs(A))**2 * (int_f) - 1 print(sp.solve(eq1, A))
Sum((-1)**(x+1) + (-1)**(x+2) , (x, 1, oo)).is_convergent()is not returning the expected result and raises a TypeError saying Invalid NaN comparison , is this a meaningful error or Am I missing something useful ?Maybe I could raise an issue ?
Last year expansion was causing slowdowns in the
.equals method. In sympy/sympy#19673 we had
In [10]: e1 = 100*(x**3 + 1)**99 In [11]: e2 = 300*x**2*(x**3 + 1)**99 In [12]: %time e1.equals(e2) CPU times: user 1.13 s, sys: 9.37 ms, total: 1.14 s Wall time: 1.15 s Out[12]: False
It seems like the
.equals method has gotten faster. Anyone know what's changed?
(1+x)**nas a binomial expansion , not sure I could find one . I ask this because I'm working on an issue which involves something like
(1+x)**n- x**n, now the issue works perfectly when we use numbers like
(1+x)**3 - x**3and we could solve this through
gammasimp()giving
3*x**2 + 3*x + 1but symbolically not sure how we could approach it . Maybe if we could expand the
(1+x)**nas a binomial expansion and cancel out the first term which would always be
x**nthen the maybe the issue wouldn't be that tough to solve . Currently gammasimp() isn't of much help ! and returns back the same expression !
>>> k, n = symbols('k, n', positive=True, integer=True) >>> from sympy import oo >>> limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)), n, oo) oo >>> limit((n+1)**2/((n+1)**(3) - (n)**(3)), n, oo) 1/3 >>> limit((n+1)**2/((n+1)**(3) - (n)**(3)).gammasimp(), n, oo) 1/3 >>> limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)).gammasimp(), n, oo) 0
gammasimp()there, so have to get that case correctly too ! Never thought a
gammasimp()would alter limits from
ooto
0but it does .Maybe if I find it too buggy and some more places where it the
(n+1)**k - n**kcombo goes wrong , i'll raise this !
|
https://gitter.im/sympy/sympy?at=6164a20f2197144e845d4edc
|
CC-MAIN-2022-27
|
refinedweb
| 466
| 78.14
|
Opened 8 years ago
Closed 8 years ago
#2352 closed enhancement (duplicate)
Allow Paginator to Support Non QuerySets
Description
I write quite a few Custom SQL queries. In addition, I like the built in paginator package that django provides. The problem is that paginator.py asks for a QuerySet, when all it uses a QuerySet for is to query_set.count(). Anyways, my point is... paginator.py should allow for queries returned by cursor.fetchall() (and similar). It's already so generic that this tiny patch provides this enhancement:
/django/core/paginator.py
def _get_hits(self): if self._hits is None: try: self._hits = self.query_set.count() except: self._hits = len(self.query_set) return self._hits
All I added was the try-except block to default to len(self.query_set) if .count() fails
Attachments (0)
Change History (2)
comment:1 Changed 8 years ago by SmileyChris
comment:2 Changed 8 years ago by adrian
- Resolution set to duplicate
- Status changed from new to closed
My patch in #2093 fixes this and more! :)
It is still waiting to be applied (or at least critiqued).
|
https://code.djangoproject.com/ticket/2352
|
CC-MAIN-2014-10
|
refinedweb
| 182
| 60.61
|
i'm a total beginner when it comes to using C.
I need to measure an Input as precisely as possible. Sadly C (in combination with the Wiring-Pi library) is the best choice for such an Project.
Does somebody have a simple C-Code which prints a timestamp (Microseconds) everytime the input changes from 0 to1 or vica versa.
I found some code that could help, but i'm not able to combine this into working code.
For the timestamp:
Some wiringpi code:
Code: Select all
#include <sys/time.h> struct timeval tv; gettimeofday(&tv,NULL); tv.tv_sec // seconds tv.tv_usec // microseconds
i also have some working python code, but its not precise enough:
Code: Select all
#include <wiringPi.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> int main() { if (wiringPiSetup () == -1) exit (1) ; pinMode(1, INPUT); while(1) { digitalRead(1, 0); } return 0 ; }
Thanks in advance!
Code: Select all
import wiringpi2 as wiringpi import time i=0 wiringpi.wiringPiSetupGpio() wiringpi.pinMode(18, 0) current_milli_time = lambda: int(round(time.time() * 1000)) while True: if wiringpi.digitalRead(18)==1: if i==0: i=1 start=current_milli_time() current=current_milli_time()-start print current
Hopefully someone else already did this!
|
https://lb.raspberrypi.org/forums/viewtopic.php?f=33&t=87961&p=619202
|
CC-MAIN-2019-51
|
refinedweb
| 199
| 61.53
|
I am trying to search my SQLite3 database using a pythonic variable as a search term. The term I'm searching for is a part of the contents of the cell in the database (e.g. Smith in a cell: [Harrison GB, Smith JH]) and is often in the middle of the string in a cell.
I have tried to code it as shown below:
def read_from_db():
c.execute("SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE (?)",(var1,))
data = c.fetchall()
print(data)
for row in data:
searchlist.append(row)
var1="Smith"
read_from_db()
ERROR
c.execute("SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE '%?%'",(var1,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
...authors="%?%"
Consider concatenating the
% wildcards to the binded value,
var1:
c.execute("SELECT authors, year, title, abstract" + " FROM usertable WHERE authors LIKE (?)", ('%'+var1+'%',))
The reason you need to do so is the
? placeholder substitutes a string literal in parameterized queries and for
LIKE expressions, wildcards with values together are string literals as denoted by their enclosed single quotes:
SELECT authors, year, title, abstract FROM usertable WHERE authors LIKE '%Smith%'
Your initial attempt failed because you wrap
? with single quotes and the cursor cannot bind the param to prepared statement properly and so the symbol is taken literally as question mark.
|
https://codedump.io/share/IGBlMl1ijuaB/1/search-sqlite3-database-using-a-python-variable
|
CC-MAIN-2017-26
|
refinedweb
| 226
| 66.44
|
This post is about how to create styles in Excel spreadsheets with the most excellent xlwt for Python. The documentation for xlwt (version 0.7.2) is a little sketchy on how to use formatting. So here goes…
To apply formatting to a cell you pass an instance of the
xlwt.XFStyle class as the fourth argument to the
xlwt.Worksheet.write method. The best way to create an instance is to use the
xlwt.easyxf helper, which takes a string that specifies the formatting for a cell.
The other thing about using styles is you should only make one instance of each, then pass that same style object every time you want to apply it to a cell.
An example which uses a few styles:
import xlwt styles = dict( bold = 'font: bold 1', italic = 'font: italic 1', # Wrap text in the cell wrap_bold = 'font: bold 1; align: wrap 1;', # White text on a blue background reversed = 'pattern: pattern solid, fore_color blue; font: color white;', # Light orange checkered background light_orange_bg = 'pattern: pattern fine_dots, fore_color white, back_color orange;', # Heavy borders bordered = 'border: top thick, right thick, bottom thick, left thick;', # 16 pt red text big_red = 'font: height 320, color red;', )
I have no idea what it is based on, but 20 = 1 pt. So 320 = 16 pt text.
book = xlwt.Workbook() sheet = book.add_sheet('Style demo') for idx, k in enumerate(sorted(styles)): style = xlwt.easyxf(styles[k]) sheet.write(idx, 0, k) sheet.write(idx, 1, styles[k], style) book.save('Example.xls')
It isn’t included with the current distribution on the cheese shop, but there is a useful Excel spreadsheet demonstrating cell patterns in the source repository.
You can find the complete list of possible cell formats by reading the source for
xlwt.Styles.
So would I be able to extract the XF class object from xlrd and use it to style xlwt?
|
https://buxty.com/b/2011/07/styling-your-excel-data-with-xlwt/
|
CC-MAIN-2019-22
|
refinedweb
| 315
| 71.04
|
After an item has been scraped by a spider, it is sent to the Item Pipeline which process use for item pipelines are:
Writing your own item pipeline is easy. Each item pipeline component is a single Python class that must implement the following method:
This method is called for every item pipeline component and must either return a Item (or any descendant class) object or raise a DropItem exception. Dropped items are no longer processed by further pipeline components.
Additionally, they may also implement the following methods:
This method is called when the spider is opened.
This method is called when the spider is closed.
Let’s take a look at the following hypothetic)
The following pipeline stores all scraped items (from all spiders) into a a single items.jl file, containing one item per line serialized in JSON format:
import json class JsonWriterPipeline(object): def __init__(self): self.file = open('items.jl', 'wb').
To activate an Item Pipeline component you must add its class to the ITEM_PIPELINES list, like in the following example:
ITEM_PIPELINES = [ 'myproject.pipeline.PricePipeline', 'myproject.pipeline.JsonWriterPipeline', ]
Sometimes you need to keep resources about the items processed grouped per spider, and delete those resource when a spider finishes.
An example is a filter that looks for duplicate items, and drops those items that were already processed. Let say that our items have an unique id, but our spider returns multiples items with the same id:
from scrapy.xlib.pydispatch import dispatcher from scrapy import signals from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.duplicates = {} dispatcher.connect(self.spider_opened, signals.spider_opened) dispatcher.connect(self.spider_closed, signals.spider_closed) def spider_opened(self, spider): self.duplicates[spider] = set() def spider_closed(self, spider): del self.duplicates[spider] def process_item(self, item, spider): if item['id'] in self.duplicates[spider]: raise DropItem("Duplicate item found: %s" % item) else: self.duplicates[spider].add(item['id']) return item
|
http://readthedocs.org/docs/scrapy/en/0.9/topics/item-pipeline.html
|
crawl-003
|
refinedweb
| 319
| 55.84
|
I was trying to do some midi to CV conversion using supercollider (on Bela Salt), but Im getting noticeable latency.
has anyone else noticed this?
or am i doing something fundamentally wrong?
(Im on latest update of Bela software)
here's my code:
(it works, just the latency)
s = Server.default;
s.options.numAnalogInChannels = 8; // can be 2, 4 or 8
s.options.numAnalogOutChannels = 8; // can be 2, 4 or 8
s.options.numDigitalChannels = 16;
s.options.maxLogins = 4;
s.options.pgaGainLeft = 4; // sets the gain for the left audio input to 4 dB
s.options.pgaGainRight = 5; // sets the gain for the left audio input to 5 dB
s.options.headphoneLevel = -6; // sets the headphone level to -6 dB
s.options.speakerMuted = 0; // enable the speaker amp
s.options.dacLevel = 0; // sets the gain of the dac to 0 dB
s.options.adcLevel = 0; // sets the gain of the adc to 0 dB
s.options.numMultiplexChannels = 0; // do not enable multiplexer channels
s.options.blockSize = 16;
s.options.numInputBusChannels = 2; // Use only the L/R audio channels
s.options.numOutputBusChannels = 2; // Use only the L/R audio channels
s.options.numAudioBusChannels = 1024;
s.options.memSize = 8192 * 16; // the default is 8192 which is quite little
s.waitForBoot{
"Server Booted".postln;
// input
~sw_in=16;
~t1_in=15;
~t2_in=14;
~t3_in=1;
~t4_in=3;
// output
~led1=2;
~led2=4;
~led3=8;
~led4=9;
~led_pwm=7;
~t1_out=0;
~t2_out=5;
~t3_out=12;
~t4_out=12;
Ndef(\led_pwm,{DigitalIO.ar(~led_pwm, pinMode:1, output:LFPulse.ar( freq:(44100/32), width: 0.5))});
Ndef(\midich1, { arg g=0,note;
AnalogOut.kr(0, note.linlin(0,127,0,1));
DigitalIO.kr(~t1_out,output:g, pinMode:1 );
DigitalIO.kr(~led1,output:0, pinMode:g );
});
MIDIdef.noteOn(\noteon1, {
arg vel, note;
Ndef(\midich1).set(\note,note);
Ndef(\midich1).set(\g,1);
},chan:0);
MIDIdef.noteOff(\noteoff1, {
arg vel, note;
Ndef(\midich1).set(\note,note);
Ndef(\midich1).set(\g,0);
},chan:0);
MIDIClient.init;
MIDIIn.connectAll;
s.sync;
};
as far as i can see, this approach should mean that all noteon/off are doing it updating the ugen, so seems like it should be quick. but Im pretty inexperienced at supercollider so perhaps missing something obvious.
note:
Ive got something similar (CV output of trig/pitch) running under PureData and theres no latency.
similarly the CSound midi in demo, has no latency either. (not tried with CV out yet) ,
so alsa/midi seems fine on the board.
thetechnobear I was trying to do some midi to CV conversion using supercollider (on Bela Salt), but Im getting noticeable latency.
In your code set the server latency to 0.
s.latency = 0
Otherwise your OSC messages from sclang will be sent to scynth with 0.2 (the default) latency.
s.latency = 0
hmm not sure. There has been problems with ndef before, which I thought maybe had been addressed by fixing this. However, the other difference in MIDI between SC and the rest is that it uses the ALSA Sequencer, instead of the ALSA raw interface (), so maybe the problem lies in there? Also, the MIDI I/O takes place on the language (sclang), and the audio/analog I/O takes place on the server (scsynth), so there is another source of latency there (though it should be reasonably small at non-high CPU usages).
ndef
sclang
scsynth
ok, was user error - down to not using SC for a while....
(basically its better to use a simple synthdef here, as you can keep the same synth node)
so all good
a quick question ...
Salt CV out specs say can go -5v to +5v - is this achieved with AnalogOut -1 to 1 ?
so I could use:
AnalogOut.kr(0, note.linlin(0,119,-1,1));
to get a -5v to 5v , to get a 10v / 10octave range?
also the knobs to they always add a positive offset to the output.
(so , centre = 0.5 , CCW = 0, CW =1, rather than centre = 0 , CCW = -1, CW =1)
thetechnobear Salt CV out specs say can go -5v to +5v - is this achieved with AnalogOut -1 to 1 ?
no, that's with analog out 0..1. A bit confusing perhaps, but at least it keeps it coherent: analogs are always 0..1 and audio are always -1..1, except for the audio-expander capelet, that allows you to treat the analogs like audio, so they go -1..1.
thetechnobear also the knobs to they always add a positive offset to the output.
You should consider the analog input having a 10V range (0..1 in the digital domain), where the pot acts as an offset for the CV input, thus shifting the CV input range from -10V..0V to 0V..10V
giuliomoro
yeah a bit confusing, but all makes sense...
I guess I can view this as:
input : 10v range = digital 0..1 , -5v to 5v with knob in centre position, knob is -5v to +5v ,
output: 10v range = digital 0..1, fixed at -5 to 5v.
same as you said, but means I can just think of it all as as the same bipolar voltages, but is converted to 0..1 in the digital domain.
Its not actually mattered till now, as Ive always just see it in the digital domain as 0..1, but for cv/pitch its useful, as need to get scaling right - and also different modules have different ranges on their v/oct inputs - that said, it all becomes relative quite quickly...
(and, I guess if I want to get cv out into the 0..10v range, I can use a cv offset module)
think i found a small bug
DigitalIn.kr(16);
will "crash" the server
I was mistyped , as i was after DigitalIn.kr(6) for the switch.
i guess an error in range checking somewhere.
(as DigitalIn.kr(20) also crashes rather than saying unavailable)
note I have:
s.options.numDigitalChannels = 16;
thetechnobear DigitalIn.kr(16);
Well you are trying to read past the last DigitalIn channel (the last one being 15, the first one being 0).
DigitalIn
Yeah there should probably be a range check at create time, when the pin number is a constant, or at kr if the pin is at kr. However, I think there was a conscious decision not to check the range then the pin number is at audio rate (similarly, none of these checks is performed when doing digitalRead() in C++).
digitalRead()
Maybe you want to add this to this issue or create a new one ?
giuliomoro
how accurate are the voltages from Salt?
I'm using AnalogOut.kr(0, note.linlin(0,120,0,1))
and the voltages don't seem to be accurate
I can see from
note.linlin(0,120,0,1) - that im getting 0.1, 0.2 etc for the note C, but these are not corresponding to -4, -3 etc.
this code should output the correct voltages
// MIDI to CV
MIDIClient.init;
MIDIIn.connectAll;
// input pins
~sw_in=6;
~t1_in=15;
~t2_in=14;
~t3_in=1;
~t4_in=3;
// output pins
~led_pwm=7;
~led1=2;
~led2=4;
~led3=8;
~led4=9;
~t1_out=0;
~t2_out=5;
~t3_out=12;
~t4_out=13;
// pwm for leds
Ndef(\led_pwm,{DigitalIO.ar(~led_pwm, pinMode:1, output:LFPulse.ar( freq:(44100/32), width: 0.5))});
// send pitch and gate
SynthDef(\cvout, {
arg opin, tpin, lpin, gate=0,note=0.5;
AnalogOut.kr(opin, note);
DigitalIO.kr(tpin,output:gate, pinMode:1 );
DigitalIO.kr(lpin,output:0, pinMode:gate );
}).add;
// setup for cv pitch/trig mappings
~synths = [
Synth(\cvout,[\opin, 0, \tpin, ~t1_out, \lpin, ~led1] ),
Synth(\cvout,[\opin, 1, \tpin, ~t2_out, \lpin, ~led2] ),
Synth(\cvout,[\opin, 2, \tpin, ~t3_out, \lpin, ~led3] ),
Synth(\cvout,[\opin, 3, \tpin, ~t4_out, \lpin, ~led4] )
];
// note on, send out pitch/gate (midi channel 1-4)
MIDIdef.noteOn(\noteon, {
arg vel, note, chan;
var v =note.linlin(0,120,0,1);
// [note,note.linlin(0,120,0,1), v , vel, chan, "note on"].postln;
~synths[chan].set(\note, v);
~synths[chan].set(\gate, vel>0);
},chan:[0,1,2,3]);
// note off, send out pitch/gate (midi channel 1-4)
MIDIdef.noteOff(\noteoff, {
arg vel, note, chan;
var v =note.linlin(0,120,0,1);
~synths[chan].set(\note, v);
~synths[chan].set(\gate, 0);
},chan:[0,1,2,3]);
but according to my oscilloscope , which im not sure is accurate,
i find i need to alter the scaling of offset to something more like:
v = (v * 0.9 ) + 0.105;
could you possibly run the above with a calibrated oscilloscope and see if my findings are correct?
or if its an issue with my salt?
Im guessing this is not a SC thing, rather salt?
(obviously usually this is not an issue - its really only Pitch CV that has to be accurate)
I think an offset is to be expected, but the scaling should be fairly accurate tight. It may also depend on the actual tolerance of the components on the board. I will test the one I have here.
giuliomoro I will test the one I have here.
thanks that would be awesome,
as i say, my issues is Im caught in catch-22, my scope can be calibrated but i don't have anything to calibrate it too.
I don't mind if it needs scaling/offset - as once I know the values, these likely can be hardcoded.
perhaps together we might find there the scaling is reasonably similar between boards, so will be a useful starting point for all users.
anyway, certainly the above scaling seem to improve the pitch cv, though it's still not perfect.
I think what I might need to do is perhaps ignore the voltage (as I cannot read it accurately) ,
and create a SC/PD patch that allows me to use the pots to 'tune' the output of an oscillator.
i think with twiddling the pots, it could be relatively quick to find the scale/offset. (it was doing it in code, which was a slow edit/compile/test cycle ) - then once known I can then hopefully just hardcode them.
I guess such a utility could be useful for others.... if we find 'calibration' is required for individual boards?!
btw: Im assuming there are no hardware 'trim' pots on the Salt/Salt+ for calibration? this might be worth considering for any Salt v2. (?!)
btw2: if we do find that scaling/offset is needed for cv in/out , do you think this might be possible to do low level via some kind of config? that way individual applications don't need to 'worry about it' ?!
some thoughts?
to see if you think my approach is valid.
assumptions:
- we are after V = mP+c
- finding scale (m) is more important than offset (c) , since all eurorack oscillators have tune knobs
- use digital oscillators to check tuning, they will track accurately (analog don't always)
- both analog cv in and out , on salt might not be 100% accurate
- cv in, be extremely careful of offset caused by knob position, this has to be zero'd out
the last one, means I cannot plug a cv out into cv in to read voltage, BUT interestingly once we know CV out is accurate, we can use this to see if CV in is accurate!
idea:
cv out send v/oct to a reliably digital oscillators, which I can then read with a tuner.
2 pots (per cv out) which are m and c
from there, we should then be able to 'auto calibrate' the CV in, by connecting a cv out to cv in.
another approach(*) ... is to go the opposite route...
Ive a CV sequencer, that (i think) I trust cv output from.
so I could use this to determine any scale/offset required of the input.
then once we know the input scaling... we can use this to calibrate the output by connecting cv out to cv in.
(*) interestingly, Ive realised the two approaches differ mainly by, do you trust a CV source (sequencer) or a CV sink (oscillator)
what do you think? flawed ? useful?
ok, some more 'accurate' results...
(these scales give 'acceptable' in tune results, over at least 5 octaves)
midi -> cv out -> MI : Plaits Oscillator -> tuner
output scale factor 0.911484
this scale seemed "good" for all cv outs (both salt and salt+) ,
but its noticeable each cv out has a slightly different offset, but less than a semitone when converted to a pitch.
as mentioned before offset required is unimportant , as usually the target oscillator etc, will have a offset adjustment.
all on salt
midi -> cv out (salt) -> cv in -> SinOsc ->tuner
input scale factor 1.00395
ok, theoretically , offset is useful here BUT since we have a hardwire offset with the pots in practice its again unimportant.
Squarp Pyramid CV out -> cv in -> SinOsc -> tuner
input scale factor 1.00245
(again, offset unimportant, due to hardwire pot)
Squarp Pyramid -> MI : Plaits Oscillator -> tuner
this was to give an indication of how well the Pyramid track (test 2b) and MI Plaits (test 1), to see how they might have influenced calibration.
generally they track very well together, not 100% perfect, there probably is a tiny scaling factory required.
but much smaller than the above...
unfortunately, as i don't have another accurate pitch tracking CV generator nor, oscillator, I cant really say which introduces the error, it could be one or both
but i think it's negligible.
offsets are pretty irrelevant, though they theoretically reduce your CV range.
theres a bit of scaling on input... circa 1.003
output scaling is more significantly ~0.911. (it might be a touch less, given diff of test 2a.b)
Im pretty confident of these numbers as test 2a/2b/3 show inputs as fairly accurate.
of course this is only one salt/salt+ it may be other units vary..
It would be more accurate/easier to do this test by measuring voltages, but you need a well calibrated voltmeter/oscilloscope to get decent results.
this is the code i used, which i ran interactively, altering it for bits of the tests (hence lines commented out)
MIDIClient.init;
MIDIIn.connectAll;
// input
~sw_in=6;
~t1_in=15;
~t2_in=14;
~t3_in=1;
~t4_in=3;
// output
~led_pwm=7;
~led1=2;
~led2=4;
~led3=8;
~led4=9;
~t1_out=0;
~t2_out=5;
~t3_out=12;
~t4_out=13;
Ndef(\led_pwm,{DigitalIO.ar(~led_pwm, pinMode:1, output:LFPulse.ar( freq:(44100/32), width: 0.5))});
// 0.911484 cvout
// 1.00395 cvout -> cvin
// 1.00245 pyramid ->cvin
g = Group.new;
g.freeAll;
(
SynthDef (\cvio, {
arg ipin,note=64;
// var m = 0.911484;
var mul = AnalogIn.kr(2);
var add = AnalogIn.kr(3);
// var m = 1.00395; // cvout > cvin
// var c = 0.0;
var m = (mul / 10.0) + 1.0;
var c = (add - 0.5) / 10.0;
// var vout = (note.linlin(0,120,0,1) * m ) + c;
var vin = AnalogIn.kr(ipin);
// var diff = vout - vin;
// vin.poll(0.1, label:\vin);
// diff.poll(0.1, label:\diff);
var v = ((vin * m ) + c );
var notein = v.linlin(0,1,0,120);
// var freq = notein.midicps;
var freq = (notein - 24).midicps;
var sig = SinOsc.ar(freq);
m.poll(0.1,label:\mul);
c.poll(0.1,label:\add);
v.poll(0.1,label:\volt);
Out.ar(0,sig);
}).add;
)
~synthtest.free;
~synthtest= Synth(\cvio,[\ipin, 0],g);
(
SynthDef(\cvout, {
arg opin, tpin, lpin, gate=0,note=64;
// var mul = AnalogIn.kr(0);
// var add = AnalogIn.kr(1);
// var m = (mul + 0.5 );
// var c = add;
var m = 0.911484;
var c = 0.0;
var v = (note.linlin(0,120,0,1) * m ) + c;
// m.poll(0.1,label:\mul);
// c.poll(0.1,label:\add);
// v.poll(0.1,label:\volt);
AnalogOut.kr(opin,v);
DigitalIO.kr(tpin,output:gate, pinMode:1 );
DigitalIO.kr(lpin,output:0, pinMode:gate );
}).add;
)
~synths = [
Synth(\cvout,[\opin, 7, \tpin, ~t1_out, \lpin, ~led1],g),
];
MIDIdef.noteOn(\noteon, {
arg vel, note, chan;
~synths[0].set(\note, note);
~synths[0].set(\gate, vel>0);
~synthtest.set(\note, note);
});
MIDIdef.noteOff(\noteoff, {
arg vel, note, chan;
~synths[0].set(\note, note);
~synths[0].set(\gate, 0);
});
That output scale value seems pretty bad!
I have a couple of scopes here including a fairly newly calibrated one, I will hook it up tomorrow and have a look...
AndyCap
definitely more than i expected it to be, 10% seems quite high to be down to 'component' tolerances, and you would have expected RebelTech to have tested this during development.
I'd have also hoped that if there was possibility of error there would have be some trimpots to allow the user to tune it.
(even as an amateur, i used trim pots on my bela -> axoloti interface, it was easy to do as they just fed the opamp that was doing the scaling)
I'll be interested to hear your results... perhaps different boards are better/worst!?
btw: im assuming this is a hardware 'issue', as seems unlikely to be software related , so this should be replicated in C or PD - but id like to test this assumption.
10% off seems quite a bit. That may have to do with Supercollider? How many "audioOutChannels" are you using in supercollider? If it's more than 2, then some rescaling is applied to the analog outs. However, that may not be what you are seeing there.
On my unit here, I get
when outputting 1: +4.82V
when outputting 0.5: -0.27V
when outputting 0: -5.39V
So that is about 10.21V pk-to-pk (2% error on the specs), and the mid-point seems to be in the middle. Unfortunately, the -0.3V offset does not center the range on 0.
In core/PRU.cpp there is the following:
core/PRU.cpp
if(belaHw == BelaHw_Salt) {
for(unsigned int n = 0; n < context->analogOutChannels * context->analogFrames; n++)
{
// also rescale it to avoid
// headroom problem on the analog outputs with a sagging
// 5V USB supply
const float analogOutMax = 0.93;
context->analogOut[n] = (1.f - context->analogOut[n]) * analogOutMax;
}
}
so you can in principle change analogOutMax to fix the scaling of the outputs.
analogOutMax
If you think it is useful, we can have that parameter made more accessible, in the ~/.bela/belaconfig file for instance. We could also make it so that each channel has a different calibration value, if that's important.
~/.bela/belaconfig
We avoided the trimmers because the range was designed to be slightly larger than needed, and therefore should be trimmable digitally.
giuliomoro how many "audioOutChannels" are you using in supercollider?
2
ok, so Ive did the test in C++, again using a tuner, same results
#include <Bela.h>
#include <Midi.h>
#include <stdlib.h>
#include <cmath>
Midi midi;
const char* gMidiPort0 = "hw:1,0,0";
bool setup(BelaContext *context, void *userData)
{
midi.readFrom(gMidiPort0);
midi.writeTo(gMidiPort0);
midi.enableParser(true);
return true;
}
float gVOct = 0.0;
bool gGate = false;
int gCVPin = 0;
int gGatePin = 0;
// float gVOctScale = 0.911484f;
float gVOctScale = 1.0f;
enum {kVelocity, kNoteOn, kNoteNumber};
void render(BelaContext *context, void *userData)
{
int num = 0;
while((num = midi.getParser()->numAvailableMessages()) > 0){
static MidiChannelMessage message;
message = midi.getParser()->getNextChannelMessage();
if(message.getType() == kmmNoteOn){
int note= message.getDataByte(0);
int velocity = message.getDataByte(1);
gVOct = float(note) / 120.0f ; // 10 octaves = 10v
gGate = velocity > 0;
if(gGate) {
rt_printf("note on %d, %f\n", note, gVOct);
} else {
rt_printf("note off %d, %f\n", note, gVOct);
}
} else if(message.getType() == kmmNoteOff){
int note= message.getDataByte(0);
// int velocity = message.getDataByte(1);
gVOct = float(note) / 120.0f ; // 10 octaves = 10v
gGate = false;
rt_printf("note off %d, %f\n", note, gVOct);
}
}
for(unsigned int n = 0; n < context->analogFrames; ++n) {
analogWriteOnce(context, n, gCVPin, gVOct *gVOctScale);
}
for(unsigned int n = 0; n < context->digitalFrames; ++n) {
pinModeOnce(context, n, gGatePin, OUTPUT);
digitalWriteOnce(context, n, gGatePin, gGate);
}
}
void cleanup(BelaContext *context, void *userData)
{
}
so it doesn't appear to be a Supercollider thing...
then I ran your test @giuliomoro, I ran it with 2 different calibrations for my scope, the factory , and then the one Ive measured....
and both showed very similar results
1 = ~ 4.8/4.9v
0.5 = - 0.6v
0 = -6.1v
so thats about 10.9 - 11vPP , which multiplied by my scale factor (0.911) - ends up very close to 10v
that would explain it IF you hadn't mentioned PRU.cpp
since thats also doing a scaling, ... so 0.93 x 0.911 = 0.84723
so im a bit confused how that relates.
and its true if I replace 0.93 with 0.847 in PRU.cpp , them indeed I don't need the scaling in C++/SC code.....
so perhaps this (and an offset , so we get mX+c) being configurable is the solution?!
Here is the C++ code I used:
#include <Bela.h>
bool setup(BelaContext *context, void *userData)
{
return true;
}
static float val = 0;
void render(BelaContext *context, void *userData)
{
static int count = 0;
for(unsigned int n = 0; n < context->analogFrames; ++n)
{
if(count == 512)
{
count = 0;
val = val + 0.5f;
if(val > 1)
val = 0;
}
count++;
for(unsigned int ch = 0; ch < context->analogOutChannels; ++ch)
analogWriteOnce(context, n, ch, val);
}
}
void cleanup(BelaContext *context, void *userData)
{
}
ok, so Ive worked out the issue...
here is a trace , with the multiplying factor in PRU.cpp removed
this is using giuliomoro code, but modified to shows 0.1 increments, so 10 steps.
the important point to see here is the first step is too short, compared to the other steps.
this is because its is hitting the rails (probably an opamp somewhere clipping)
ok, no problem i thought, i'll offset it, because the centre point is wrong...
but doing that, I can see its actually hitting the opamp rail at the top end, at 4.88v
(interestingly, this seems to be the same as @giuliomoro top !)
so what we are seeing is rails are at 4.88v and -6.2v ...
(its this offset which is the 'issue', RebelTech should have put a trimpot in place, to allow it to be centred in the opamps rails...)
ok, so back to the scaling factor...
well we can see above, scaling for 10v for steps in the above diagram won't work, as the 10th step is incomplete.
so what we need to do (and you can see marked on trace above) is take 9 steps,
so 9 steps = 9v , and we have 10.63v ... so 9/10.63 = 0.84666 - sound familiar ?
yes, this is very close to PRU.cpp 0.93 scaling , multiplied by my scaling factor of 0.911 (0.93x0.911 = 0.847)
plus this into PRU.cpp and this gives me 10vpp, linearly scaled properly , but with a -110mV offset.
could we remove the offset?
not without compromise, offset by +110mv you'll hit the top rail,
so the compromise would be to have a range of 0 to 0.976 ... this could be scaled/offset correctly to -5v to 4.88v, then 0.976 to 1.0 would be 4.88v.
so you loose range, but gain accuracy.
this may be actually the best solution, since many things go -5v to 5v...
seems -5.1 to 4.88v is not really much more useful than -5v to 4.88v but is accurate?
... I think this is probably what I do, in which case, as mentioned above really we'd want Mx+C in PRU.cpp
any other lessons?
well I think my scope is pretty accurate - given the proof my voltages pretty much matches what I calculated using musical tuning.
so that implies that there can be quite a bit of difference in salts, given my is showing 10.9-11vPP, vs @giuliomoro 10.2vPP ... and that means the scaling factor would need to be different.
(my rough guess is if you scale your voltages correctly, is your offset will be around the same 110mv mine is )
there is possibly one remaining question (for me) , w
hat does the code comment in PRU.cpp mean, and is it a red-herring?
''''
// headroom problem on the analog outputs with a sagging
// 5V USB supply
''''
it indeed seems to be doing the right thing, reducing the voltage to bring within the voltage range required.
(albeit, not recognising that this appears to be different per unit)
BUT.. what does this have to do with 5v usb supply?
as far as my tests showed, neither having salt connected to a computer (usb host) , or a controller (usb device) made any difference to the voltages.
thetechnobear BUT.. what does this have to do with 5v usb supply?
as far as my tests showed, neither having salt connected to a computer (usb host) , or a controller (usb device) made any difference to the voltages.
how did you test?
try to measure the supply voltage you get from different sources (computer, controller) it may well be that they both output less then 5v. usb power is notorious for output divergence (i have seen 4.7 to 5.2 v). also measure, when everything is connected that will be connected later as well (periphery that could influence the load and therefore the voltage)
the opamp rail can only go as high as the supply voltage (minus a few mv), so if you measure less then 5v on both of your power sources, that could well be the issue. i had some similar problems with an arduino and inconsistent readings from analog in, because i used different computers, or even different usb ports on the same computer.
lokki I meant no change in the cv output voltage on analog out. which I was measuring with a scope at the time.
Usb should have no effect as this is powered by the eurorack which has a very strong power supply.
thetechnobear hmm, ok. so power is not switched to usb supply when usb is plugged in? shouldn't be i guess.
what voltage does the euro rack 5v supply read with everything connected?
|
https://forum.bela.io/d/693-supercollider-midi-performance
|
CC-MAIN-2019-30
|
refinedweb
| 4,327
| 67.45
|
Directory Listing
tag 1.12.5
Check for the udev/devfs addons rather than binaries #147221..
Punt irqbalance from rc
Start volumes after we have loaded modules. Don't do this in trunk - as we're going to move more logic from /sbin/rc to init scripts
Don't stop services that are depended on by coldplugged services.
Fix start-stop-daemon using the --name option #143951 thanks to Dustin J. Mitchell
Only send a process the TERM signal once, #141832
Add bootchart suppport, #74425 and #141114. Thanks to Paul Pacheco.
Don't stop deps of inactive services
Enable RC_NEED="foo" and RC_USE="bar" in /etc/conf.d/${SERVICE} so that users can overlay service dependencies with their own. Bug #140865
Fix quoting in valid_i and give better feedback about services not starting/stopping
Allow start-stop-daemon to be used by non services
Report services scheduled to be started by another service as started OK for splash.
Remove snapshots correctly
Use dolisting instead of ls for consitency
Reference coldplugged scripts correctly
Make sure modules-update generates the devfs config files properly #136174.
Make sure modprobe.conf is generated properly when done by hand #132668 by Alexander Skwar.
fix typo in message about /etc/modprobe.conf not being needed
Force stricter mount options on /proc /sys /dev/pts /proc/bus/usb.
Fix "before net" dependencies, #135872 thanks to Oldrich Jedlicka. pppd.sh now uses passwordfd instead of very nasty regex stuff, thanks to Oldrich Jedlicka, Alin Nastac and me :), #134337
Move 'dmesg -n 1' earlier with new udev stuff that floods the console.
Store coldplug services for future use "*"
Rewrite modules-update to make it readable and usuable without old modutils.
Tweak is_older_than than so it skips checking the timestamps on directories, just the files in the directory.
Document --verbose option in rc-update #130643 by Christian Heim.
Last patch had dumb logic, this fixes
Ensure that coldplugged net services are shutdown in the correct order
Disable CTRL+C in depscan.sh while booting #126512 by Marko Djukic. Also add -h/--help and such.
style/misc touchups
start-stop-daemon only removes the daemon stopping from the daemon started list, #130166.
net services are now calculated properly in trace_dependencies. arping.sh now tests if the interface exists or not.
improve wording in clock skew message #130040 by Gordon
Allow finer grained RC_COLDPLUG control
bootmisc is no longer a critical service, fixed RC_COLDPLUG default variable
RC_COLDPLUG now controls if we add coldplugged services to the boot runlevel or not, #129331.
Allow more than 1 inactive dependant service to start us when it is started, #125819 thanks to Arnuad Fab.
Overhaul rc-update and make it more user friendly.
merge ROOT support from trunk
Add patch by Alun Jones to respect RC_QUIET_STDOUT in conf.d/rc #123606.
Don't use -options with ps so we're more portable.
use ewarn instead of echo
Update modules-update to run depmod even if /proc/modules doesnt exist and warn if the depdir doesnt exist but the user ran in verbose mode #117212 by Alex Guensche
syntax touchup
Fix grepping of --assume-kernel in modules-update as pointed out by Patrick McLean in #117212.
Changed runscript.sh to store it's services to restart like rc.
Misc quoting fixes. Fixed scheduling restart services a little.
Services that need a service which is inactive at boot are now scheduled to start when the inactive service starts, #118801.
Style fix
add fuse to NET_FS_LIST #118552
Don't ask to start non existant services, ie net.
Exit with the correct code
interactive boot cleanups
cp portability fixes
more copyright updates
More bash-3.1 fixes
update copyright years
Interfaces can be dynamically added to bridges again, #117406. Updated copyright to 2006.
start volume related stuff much earlier in the boot process
handle ${TMPFILE2}.err better #116745 by Daniele Gaffuri
Add new variable RC_DOWN_INTERFACE and documentation so that interfaces are kept up for Wake On LAN support, #113880.
Ensure that tty has keyboard and stty reports icanon before enabling interactive rc, #112161.
add support for --verbose --debug --help
Fix ordering for services having a 'before net' dependency
Dont set default RC_VOLUME_ORDER anymore in functions.sh #113700.
Fix for bug #104288.
Backport changes needed for udev/devfs addons.
Fixed stopping when no process to wired interfaces, and can work with ifplugd and netplug too.
Merge STYLE fixes from trunk into runscript.sh
merge trunk quoting fixes into 1.12 rc-daemon.sh
Fix test_service_state() so it always returns 1 when it's not in that state..
merge MAKEDEV updates from trunk to branches to address #108250 and #108249
run some features of rc-update as non-root #107775
tweak how default values are set for rc variables
dont mount $svcdir with -n since /etc/mtab is writable
Added ifplugd module, but we prefer netplug by default
Update rc-help.sh to show custom init.d opts #49663 and in general make the output a lot more useful.
Merge revisions r1445:1448 from trunk.-daemon now handles --signal correct - fixes #103182
Implemented interactive startup - fixes #5353 Thanks to Paul Pacheco for the patch
Parallel startup races should now be fixed
Fixed sed in depdir() in modules-update to work this time
Add support for --pid and --pidfile= in rc-daemon.sh
Remove tail from depdir() in /sbin/modules-update
add info for RC_BOOTLOG
Remove last remainder of previous 'fix'.
Merge from trunk (rev 1390).
Merge from trunk (rev 1384:1388).
Added # vim:ts=4 to all net-script files and re-indented /dep{cache,tree} are now chmodded 0644 so users can read them
Merge from trunk (rev 1350).
rc-daemon now works with mysql - fixes #100982, thanks to bju from the forums
Only create /dev/core if /proc/kcore exists #100978 by Timo Hirvonen.
When a service is stopped, the IN_BACKGROUND variable is cleared before any dependencies are stopped so they are not marked inactive. The IN_BACKGROUND variable is then restored so the parent script can be marked inactive.
add a --debug option to depscan.sh.
Do not run depmod in modules-update if System.map is missing, bug #59188.
Branch baselayout-1.12.
Fixed module depends in net.lo Remove the 'no net scripts in boot runlevel' restriction as we now have a hotplug policy setup instead
add davfs to the net filter list
make sure /proc/cmdline is readable in get_bootconfig()
runscript and rc-service fixes for inactive status
import Xen support
etc/{resolv,ntp,yp}.conf now link to /var/lib/net-scripts
add a generic framework for bootlogging
fixup is_net_fs to work with /proc/mounts when available
is_net_fs now works with what $1 was mounted as, not would it would be remounted as - fixes #53104
report ${myservice} instead of $0 when disallowing net scripts to work in the boot runlevel - fixes #91534
filter gfs in the net fs list #93911 by Thomas Rasch
make sure initial swapon sends errors to /dev/null #93143
Quiet down valid_i() if /softlevel do not yet exist, try #2.
added #!/bin/bash or #!/bin/sh to modules and helpers so they now get nice syntax highlighting and indent
add the -f option to the unset exit
try to minimize user interaction during boot with RC_FORCE_AUTO
style updates
rework the addon code abit to support profiling
run irqbalance once /var is rw #85304
touchup syntax error message
make sure devs dont call exit in init.d scripts #85298
simplify init.d syntax checking and allow users to run /etc/init.d/script status #85892
make sure /dev is mounted with sane settings #87745or column/color logic for when used in portage.
export the service name for scripts to access #86348
move the udev/selinux code after we mount /dev
modified to use bash_variable}...
Updated livecd-functions.sh to include better ppc64 serial console support.
Get modules-update to clean up after itself if we on a 2.6 kernel without modules.conf).
prepend rc-daemon.sh functions with rc_ to avoid name conflicts
2004 -> 2005
udev/selinux lovin
rc-daemon.sh now support stoppings with a custom signal
rc-daemon.sh now checks to see if a given pid matches the pid of a given executable before stopping
support --oknodo and --test for start-stop-daemon calls
rc-daemon.sh now provides a working wrapper for start-stop-daemon fixes bug #7198 removed ps calls from net scripts
whitespace fixes
Updated livecd-functions.sh to match what we are using on the LiveCD.
Update /sbin/modules-update to work without modprobe.old (modutils) for 2.6 kernels.
Localize the addons.
Localize the addons.
Split *_volume() stuff a bit more.
Add {start,stop}-volumess() to /sbin/functions.sh, as well as RC_VOLUME_ORDER to /etc/conf.d/rc.
Fix /sbin/functions.sh not to run stty during 'emerge depend'.
dont use the vague 'none' when mounting stuff #78684
style updates
use pure bash instead of awk ... thanks to ciaranm for holding my hand
net dependancies corrected in runscript.sh - fixes #77839
rc-update STYLE updates
BSD compat fix
RC_USE_FSTAB support
tweak start_critical_service to use service names passed to it
dont unpack an empty udev tarball
tweak get_mount_fstab to be more error resistant missing 'local x' to filter_environ() (bug #26429)
Fix get_bootparam() to check if /proc/cmdline exists
Last minute fixes
|
http://sources.gentoo.org/cgi-bin/viewvc.cgi/baselayout/tags/baselayout-1.12.5/sbin/?view=log
|
CC-MAIN-2014-23
|
refinedweb
| 1,546
| 64.41
|
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 7.4, “How to hide a class (or classes) with Scala import statements.”
Problem
You want to hide one or more Scala classes while importing other members from the same package.
Solution
To hide a class during the import process, use the renaming syntax shown in Recipe 7.3, “Renaming Members on Import”, but point the class name to the
_ wildcard character.
The following example hides the
Random class, while importing everything else from the java.util package:
import java.util.{Random => _, _}
This can be confirmed in the REPL:
scala> import java.util.{Random => _, _} import java.util.{Random=>_, _} // can't access Random scala> val r = new Random <console>:10: error: not found: type Random val r = new Random ^ // can access other members scala> new ArrayList res0: java.util.ArrayList[Nothing] = []
In that example, the following portion of the code is what “hides” the
Random class:
import java.util.{Random => _}
The second
_ character inside the curly braces is the same as stating that you want to import everything else in the package, like this:
import java.util._
Note that the
_ import wildcard must be in the last position. It yields an error if you attempt to use it in other positions:
scala> import java.util.{_, Random => _} <console>:1: error: Wildcard import must be in last position import java.util.{_, Random => _} ^
This is because you may want to hide multiple members during the import process, and to do, so you need to list them first.
To hide multiple members, list them before using the final wildcard import:
scala> import java.util.{List => _, Map => _, Set => _, _} import java.util.{List=>_, Map=>_, Set=>_, _} scala> new ArrayList res0: java.util.ArrayList[Nothing] = []
This ability to hide members on import is useful when you need many members from one package, and therefore want to use the
_ wildcard syntax, but you also want to hide one or more members during the import process, typically due to naming conflicts.
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations:
|
http://alvinalexander.com/scala/scala-imports-syntax-to-hide-classes-members-on-import/
|
CC-MAIN-2021-04
|
refinedweb
| 386
| 63.7
|
I'm currently programming a game in Java with the JMonkey engine - a 3D space combat game - and I'm quite interested in AI, so I wanted to do some kind of learning system. I had the idea of having factions maintain spatial memory of where they last saw ships - over time, they would estimate where a ship they saw a while ago might be (based on its last seen speed and direction, maximum speed...) by giving each area in space a probability and a danger rating and so on. This info could be used to plot safe paths for trading, plan patrol routes, and such. The specifics of this aren't at concern here (though if you have comments I would still like to hear them) - what I'm worried about is that my implementation might not be the best. Here is the essence of the problem:
public class SectorGraph { /* * The world graph, containing knowledge and estimations of ship locations. Because * coordinates could be positive or negative, we split this up into eight different * ArrayLists for each side of each axis' origin a point could be on. Each world node * is a cube defined by its minimum position (and a constant size, see Globals class) * Each of these spaces is split into an arraylist for each dimension, so for example * to look up WorldNode 3, -63, 109 we would do: PosNegPosNodes.get(3).get(62).get(108). */ private ArrayList<ArrayList<ArrayList<WorldNode>>> PosPosPosNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> PosPosNegNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> PosNegPosNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> PosNegNegNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> NegPosPosNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> NegPosNegNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> NegNegPosNodes; private ArrayList<ArrayList<ArrayList<WorldNode>>> NegNegNegNodes;
New ArrayLists are created and inserted on demand. This all seems a bit messy, but I can't think of a better way to do it with the possibility of positions going off infinitely in any direction. I have three values that can be changed to make it more efficient: a maximum lifetime for a WorldNode before it is cleaned up, and a time period between updates of the graph, and a size for each world node (cube side length).
However, it does seem like there's still going to be a lot of time jumping through lists and filling lists with nulls (for example if we insert a fresh node at (0, 1000, 1000) and there's nothing around it, we need to insert a lot of ArrayLists just to get there). I first thought of just having a list of nodes, but that seemed like it would get even worse with having to step through a very long list.
Any comments or suggestions regarding this? Would perhaps some kind of Map that maps a coordinate to a world node possibly be better? Any ideas would be great.
Thanks,
-Joe
|
http://www.dreamincode.net/forums/topic/40522-efficiency-problem-representing-a-matrix-of-cubes-in-3d-space/
|
CC-MAIN-2016-44
|
refinedweb
| 477
| 52.02
|
From: David Abrahams (dave_at_[hidden])
Date: 2004-02-24 20:29:16
"Peter Dimov" <pdimov_at_[hidden]> writes:
> Powell, Gary wrote:
>> For me it's a matter of future expansion, and maintenance, we have
>> boost::bind, and boost::lambda::bind, and perhaps soon
>> boost:fcpp::lambda which is the namespace which the function? If we
>> use apprev. 4 everythg, thn, we lose contx.
>
> No we do not. The abbrv anlgy is flwd. It's more like English::this
> English::kind English::of English::writing versus en::this en::alternative
> en::style.
Believe it or not the latter caused me a bigger mental hiccup.
-- Dave Abrahams Boost Consulting
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2004/02/61668.php
|
CC-MAIN-2020-50
|
refinedweb
| 128
| 62.04
|
I'm trying to ramp up the speed of a fan from 0 to 1.0 animation speed. I have a script that begins the animation playback and I thought using a Mathf.SmoothDamp would do it, but it just gives me really slow playback. Script is below - anyone have any thoughts as to another way of doing this?
(for clarity, I've omitted the code for the StopFan() function, since it doesn't affect this issue)
var fanStart : float = 0.0;
var fanEnd : float = 5.0;
var smoothTime : float = 2.0;
var velChange : float = 0.0;
private var clicked : boolean = false;
private var switchMe : GameObject;
switchMe = GameObject.Find("finalSwitch");
private var fan : GameObject;
fan = GameObject.Find("fanPivot");
private var fpsCharacter : GameObject;
fpsCharacter = GameObject.Find("Graphics");
function OnMouseUp()
{
if(clicked)
{
StopFan();
}
else if (!clicked)
{
StartFan();
}
}
function StartFan()
{
animation["switchedOn"].speed = 1.0;
animation.Play();
audio.Play();
var rampUpSpeed : float = Mathf.SmoothDamp(fanStart,fanEnd,velChange,smoothTime);
fan.animation["fanRotation"].speed = rampUpSpeed;
fan.animation.Play();
fan.audio.Play();
clicked = true;
}
Answer by aldonaletto
·
Feb 09, 2012 at 01:12 AM
You must create a routine with a loop that counts time from 0 to the desired ramp duration in seconds, and use Mathf.Lerp(fanStart, fanEnd, time/duration) to calculate the fan speed at each iteration.
To let Unity work while you're counting time, insert a simple yield in the loop, what makes the function a coroutine. Coroutines run in the background: they stop at the yield instruction and let Unity free till the next update cycle, when the coroutine execution is automatically resumed right after the yield.
function StartFan(){
animation["switchedOn"].speed = 1.0;
animation.Play();
audio.Play();
RampUpSpeed(10.0); // start the coroutine RampUpSpeed with 10 seconds ramp duration
fan.animation.Play();
fan.audio.Play();
clicked = true;
}
function RampUpSpeed(duration: float){
var t: float = 0;
while (t < duration){ // loop during "duration" seconds:
t += Time.deltaTime; // count time...
// and set speed from fanStart to fanEnd proportionally to time/duration:
fan.animation["fanRotation"].speed = Mathf.Lerp(fanStart, fanEnd, t/duration);
yield; // let Unity free till next update cycle
}
}
NOTE: If the fan sound is constant and loopable, you can even set its frequency proportional to the speed - just add the line below right before the yield instruction:
fan.audio.pitch = t/duration;
Holy cow! That did it! Thanks so much for taking the trouble. And the audio pitch change was gravy. It was a simple solution, but it just kept eluding me. Thanks again!
An additional note: since the coroutine runs automatically in the background, make sure that you only call StartFan once for each fan - if called multiple times, multiple RampUpSpeed coroutines start to run, what may produce weird results, and even slow down or crash the game.
Does the coroutine finish its run after the "yield" statement, or is there something else I should do to clear it from memory?
Also, your comment raised another question - if I wanted to turn the fan off and thus slowly come to a stop, would I do something like a RampDownSpeed function, or would that feed into the potential issue you mentioned? Thanks!
The coroutine frees the allocated memory automatically upon return (after the loop has ended, in this case) - you don't need to do anything else.
To ramp down, you must make sure the first coroutine has ended before starting your RampDownSpeed function. Coroutines are resumed each update cycle right after all Update functions were called. If you start RampDownSpeed while RampUpSpeed has not finished, the one executed last will "hide" the other (both modify the animation speed, but only the change did last will take effect)
That's what I guessed - thanks for confirming it for me. Right now, it's all working beautifully, and I sincerely appreciate your generous suggestions and feedback!
Answer by tingham
·
Feb 07, 2012 at 02:58 AM
Your fanStart value isn't being updated to the current speed value (the result of the lerp/smooth damp so your constant value for T just returns the same value during each iteration.
// C#
float currentSpeed = 0f;
float finalSpeed = 1f;
void Update () {
animation["fanRotation"].speed = currentSpeed;
}
IEnumerator RampFanSpeed () {
while (currentSpeed < finalSpeed) {
currentSpeed = Mathf.Lerp(currentSpeed, finalSpeed, 0.25f);
}
}
Yes -- need to call SmoothDamp every frame until rampUpSpeed is done, and the time parm is messed up.
Lerp requires an increasing number from 0 to 1. So, Time.deltaTime (always around 0.02) doesn't work for Lerp, but is great for SmoothDamp.
I'm having a hard time figuring out how this would work in a coroutine..
Mathf.Smoothdamp, need help troubleshooting!
0
Answers
Animation ["1"].speed = 0; Doesn't work
2
Answers
How to change animation speed in Unity 5
0
Answers
Can I make animations snap to a frame?
2
Answers
Speed button for animations?
2
Answers
|
https://answers.unity.com/questions/214632/ramping-animation-speed.html
|
CC-MAIN-2020-16
|
refinedweb
| 803
| 57.37
|
Related
How To Work with the ZeroMQ Messaging Library
Introduction
There are many ways you can choose to describe ZeroMQ; nevertheless, it remains as what it really is: a truly remarkable communication library that benefits the developers greatly with its rich and mature feature set.
In this second installment of DigitalOcean ZeroMQ articles, following our previous one on the installation of the application, we are going to dive into its usage and discover ways to actually implement this fast and powerful library. We’ll make our way through various examples divided into successive sections, beginning with simple messaging between processes (i.e. using the request/response pattern).
Note: This article constitutes our second piece on the subject. If you are interested in learning more about it (i.e. what it is and how it compares to a complete message broker), check out ZeroMQ Introduction and Installation How-to before reading this tutorial.
About
ZeroMQ
ZeroMQ is a library used to implement messaging and communication systems between applications and processes - fast and asynchronously.
If you have past experience with other application messaging solutions such as RabbitMQ, it might come a little bit challenging to understand the exact position of ZeroMQ.
When compared to some much larger projects, which offer all necessary parts of enterprise messaging, ZeroMQ remains as just a lightweight and fast tool to craft your own.
This Article
Although technically not a framework, given its functionality and the key position it has for the tasks it solves, you can consider ZeroMQ to be the backbone for implementing the actual communication layer of your application.
In this article, we aim to offer you some examples to inspire you with all the things you can do.
Note: We will be working with the Python language and its classic interpreter (Python C interpreter) in our examples. After installing the necessary language bindings, you should be able to simply translate the code and use your favorite instead without any issues. If you would like to learn about installing Python on a CentOS VPS, check out our How to set up Python 2.7 on CentOS 6.4 tutorial.
Programming with ZeroMQ
ZeroMQ as a library works through sockets by following certain network communication patterns. It is designed to work asynchronously, and that’s where the MQ suffix to its name comes - from thread queuing messages before sending them.
ZeroMQ Socket Types
ZeroMQ differs in the way its sockets work. Unlike the synchronous way the regular sockets work, ZeroMQ’s socket implementation “present an abstraction of an asynchronous message queue”.
The way these sockets work depend on the type of socket chosen. And flow of messages being sent depend.
ZeroMQ Transport Types
ZeroMQ offers four different types of transport for communication. These are:
In-Process (INPROC): Local (in-process) communication transport.
Inter-Process (IPC): Local (inter-process) communication transport.
TCP: Unicast communication transport using TCP.
PGM: Multicast communication transport using PGM.
Structuring ZeroMQ Applications
ZeroMQ works differently than typical and traditional communication set ups. It can have either side of the link (i.e. either the server or the client) bind and wait for connections. Unlike standard sockets, ZeroMQ works by the notion of knowing that a connection might occur and hence, can wait for it perfectly well.
Client - Server Structure
For structuring your client and server code, it would be for the best to decide and elect one that is more stable as the binding side and the other(s) as the connecting.
Example:
Server Application Client Application ---------------------[ < .. < .. < .. < .. ...................... Bound -> Port:8080 Connects <- Port:8080
Client - Proxy - Server Structure
To solve the problems caused by both ends of the communication being in a dynamic (hence unstable) state, ZeroMQ provides networking devices (i.e. utensils out of the box). These devices connect to two different ports and route the connections across.
- Streamer: A streamer device for pipelined parallel communications.
- Forwarder: A forwarding device for pub/sub communications.
- Queue: A forwarding device for request/reply communications.
Example:
Server App. Device | Forward Client App. ............ > .. > . ]------------------[ < .. < .. ......... Connects 2 Port Binding Connects
Programming Examples
Using our knowledge from the past section, we will now begin utilizing them to create simple applications.
Note: Below examples usually consist of applications running simultaneously. For example, for a client/server setup to work, you will need to have both the client and the server application running together. One of the ways to do this is by using the tool Linux Screen. To learn more about it, check out this DigitalOceanTutorial. To install screen on a CentOS system, remember that you can simply run:
yum install -y screen.
Simple Messaging Using Request/Reply Pattern
In terms of communicating between applications, the request/reply pattern probably forms the absolute classic and gives us a good chance to start with the fundamental basics of ZeroMQ.
Use-cases:
For simple communications between a server and client(s).
Checking information and requesting updates.
Sending checks and updates to the server.
Echo or ping/pong implementations.
Socket type(s) used:
- zmq.REP
- zmq.REQ
Server Example: server.py
Create a “server.py” using nano (
nano server.py) and paste the below self-explanatory contents.
import zmq # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.REP) sock.bind("tcp://127.0.0.1:5678") # Run a simple "Echo" server while True: message = sock.recv() sock.send("Echo: " + message) print "Echo: " + message
When you are done editing, save and e xit by pressing CTRL+X followed with Y.
Client Example: client.py
Create a “client.py” using nano (
nano client.py) and paste the below contents.
import zmq import sys # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.REQ) sock.connect("tcp://127.0.0.1:5678") # Send a "message" using the socket sock.send(" ".join(sys.argv[1:])) print sock.recv()
When you are done editing, save and exit by pressing CTRL+X followed with Y.
Note: When working with ZeroMQ library, remember that each thread used to send a message (i.e.
.send(..)) expects a
.recv(..) to follow. Failing to implement the pair will cause exceptions.
Usage
Our
server.py is set to work as an “echoing” application. Whatever we choose to send to it, it will send it back (e.g. “Echo: message”).
Run the server using your Python interpreter:
python server.py
On another window, send messages using the client application:
python client.py hello world! # Echo: hello world!
Note: To shut down the server, you can use the key combination: Ctrl+C
Working with Publish/Subscribe Pattern
In the case of publish/subscribe pattern, ZeroMQ is used to establish one or more subscribers, connecting to one or more publishers and receiving continuously what publisher sends (or seeds).
A choice to specify a prefix to accept only such messages beginning with it is available with this pattern.
Use-cases:
Publish/subscribe pattern is used for evenly distributing messages across various consumers. Automatic updates for scoreboards and news can be considered as possible areas to use this solution.
Socket type(s) used:
- zmq.PUB
- zmq.SUB
Publisher Example: pub.py
Create a “pub.py” using nano (
nano pub.py) and paste the below contents.
import zmq import time # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.PUB) sock.bind("tcp://127.0.0.1:5680") id = 0 while True: time.sleep(1) id, now = id+1, time.ctime() # Message [prefix][message] message = "1-Update! >> #{id} >> {time}".format(id=id, time=now) sock.send(message) # Message [prefix][message] message = "2-Update! >> #{id} >> {time}".format(id=id, time=now) sock.send(message) id += 1
When you are done editing, save and exit by pressing CTRL+X followed with Y.
Subscriber Example: sub.py
Create a “sub.py” using nano (
nano sub.py) and paste the below contents.
import zmq # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.SUB) # Define subscription and messages with prefix to accept. sock.setsockopt(zmq.SUBSCRIBE, "1") sock.connect("tcp://127.0.0.1:5680") while True: message= sock.recv() print message
When you are done editing, save and exit by pressing CTRL+X followed with Y.
Note: Using the
.setsockopt(..) procedure, we are subscribing to receive messages starting with string
1. To receive all, leave it not set (i.e.
"").
Usage
Our
pub.py is set to work as a publisher, sending two different messages - simultaneously - intended for different subscribers.
Run the publisher to send messages:
python pub.py
On another window, see the print outs of subscribed content (i.e.
1):
python sub.py! # 1-Update! >> 1 >> Wed Dec 25 17:23:56 2013
Note: To shut down the subscriber and the publisher applications, you can use the key combination: Ctrl+C
Pipelining the Pub./Sub. with Pipeline Pattern (Push/Pull)
Very similar in the way it looks to the Publish/Subscribe pattern, the third in line Pipeline pattern comes as a solution to a different kind of problem: distributing messages upon demand.
Use-cases:
Pipelining pattern can be used in cases where are list of queued items need to be routed (i.e. pushed in line) for the one asking for it (i.e. those who pull).
Socket type(s) used:
- zmq.PUSH
- zmq.PULL
PUSH Example: manager.py
Create a “manager.py” using nano (
nano manager.py) and paste the below contents.
import zmq import time # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.PUSH) sock.bind("tcp://127.0.0.1:5690") id = 0 while True: time.sleep(1) id, now = id+1, time.ctime() # Message [id] - [message] message = "{id} - {time}".format(id=id, time=now) sock.send(message) print "Sent: {msg}".format(msg=message)
The file
manager.py will act as a task allocator.
PULL Example: worker_1.py
Create a “worker1.py” using nano (`nano worker1.py`) and paste the below contents.
import zmq
# ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" sock = context.socket(zmq.PULL) sock.connect("tcp://127.0.0.1:5690") while True: message = sock.recv() print "Received: {msg}".format(msg=message)
The file
worker_1.py will act as a task processes (consumer/worker).
Usage
Our
manager.py is set to have a role of an allocator of tasks (i.e. a manager), PUSHing the items. Likewise,
worker_1.py set to work as a worker instance receives these items, when it’s done processing by PULLing down the list.
Run the publisher to send messages:
python manager.py
On another window, see the print outs of subscribed content (i.e.
1):
python worker_1.py! # 1-Update! >> 1 >> Wed Dec 25 17:23:56 2013
Note: To shut down the subscriber and the publisher applications, you can use the key combination: Ctrl+C
Exclusive Pair Pattern
Exclusive pair pattern implies and allows establishing one-tone sort of communication channels using the
zmq/PAIR socket type.
Bind Example: bind.py
Create a “bind.py” using nano (
nano bind.py) and paste the below contents.
import zmq # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" socket = context.socket(zmq.PAIR) socket.bind("tcp://127.0.0.1:5696")
When you are done editing, save and exit by pressing CTRL+X followed with Y.
Connect Example: connect.py
Create a “connect.py” using nano (
nano connect.py) and paste the below contents.
import zmq # ZeroMQ Context context = zmq.Context() # Define the socket using the "Context" socket = context.socket(zmq.PAIR) socket.connect("tcp://127.0.0.1:5696")
When you are done editing, save and exit by pressing CTRL+X followed with Y.
Usage
You can use the above example to create any bidirectional uni-connection communication applications.
Note: To shut down either, you can use the key combination: Ctrl+C
4 Comments
|
https://www.digitalocean.com/community/tutorials/how-to-work-with-the-zeromq-messaging-library
|
CC-MAIN-2020-05
|
refinedweb
| 1,973
| 52.56
|
Hi All,
In our SAP system, we have some enhancement implementations which are imported into our system. These implementations are in some other software provider namespace, we have the repair license and deleted some enhancement implementations. These changes/repairs are saved as Reparis and in local transport request. Can i transport this repair request(local request) into test SAP system(already these implementations exist here)?
Please let me know if it is possible to transport repair request? if so how to do that.
Thanks in advance,
Best regards,
Venkat
The problem is that the package you're saving to has no transport layer defined, and so can only be saved against a local request. One solution is to change the package so that it has the same transport layer as your regular "Z" developments. Another is to move the package.
You already have an active moderator alert for this content.
I agree with Matthew + you may also create a transport request of type "transport of copies"
May i know What is the meaning of local request, is it saved as $tmp. If yes, I hope not possible,Why don't you change the package and move it to the other server systems. Any problem.
Add comment
|
https://answers.sap.com/questions/40892/tranport-repair-request.html
|
CC-MAIN-2019-22
|
refinedweb
| 206
| 62.98
|
Created on 2018-08-10 10:07 by vtudorache, last changed 2018-10-18 02:20 by wordtech.
Run the python script below.
import tkinter
root = tkinter.Tk()
text = tkinter.Text(root)
vbar = tkinter.Scrollbar(root)
vbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
text.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)
text.config(yscrollcommand=vbar.set)
vbar.config(command=text.yview)
lines = ['This is the line number %d.\n' % i for i in range(256)]
text.insert(tkinter.END, ''.join(lines))
def click_trace(event):
text.insert('%d.%d' % (1, 0), 'Clicked at (%d,%d) on %s.\n' % (event.x, event.y, vbar.identify(event.x, event.y)))
vbar.bind('<Button-1>', click_trace)
root.mainloop()
When the slider is at the top of the scrollbar, clicking on its upper half doesn't allow dragging. The little script shows that the Scrollbar considers it as being on "through1" - in Tk the zone between the upper arrow and the "slider" - and not on "slider". Another consequence is that one can drag (up and down) the slider when clicking a little bit below the slider, on "through2" region. This issue doesn't manifest on Windows, where the scrollbar's arrows are shown.
I've seen this issue when trying to explore the reasons of another (34047, fixed) concerning the slider locked at the end of the scrollbar in IDLE.
The bug needs forwarding to the Tcl/Tk community. This is the script written in Tcl (run with tclsh8.6 script.tcl for Tcl 8.6 and tclsh8.5 script.tcl for 8.5):
package require Tk
scrollbar .vbar -width 10
text .edit
pack .vbar -side right -fill y
pack .edit -side left -fill both -expand 1
.vbar configure -command {.edit yview}
.edit configure -yscrollcommand {.vbar set}
bind .vbar {<Button-1> } {
set cx %x
set cy %y
set dz [.vbar identify $cx $cy]
puts "You clicked at ($cx,$cy) on $dz.\n"
}
for {set i 1} {$i <= 256} {incr i} {
.edit insert "$i.0" "This is the line number $i.\n"
}
I will post two videos made on my MacBook, showing an expected behavior with Tk 8.5 and the scroll problems with Tk 8.6 on macOS.
Now, the video for TK 8.5 showing expected behavior on macOS.
I just committed, which fixes the scrolling issue in Tk. Running the test scripts here indicate the behavior is now correct; clicking several pixels below the bottom part of the scroll button causes the scroll to jump, instead of smoothly scrolling. (One must click the scroll button directly for smooth scrolling, which is the expected behavior.) The fix involved removing support for a small scroll button variant, which was causing the confusion; by sticking with a single variant, the normal size scroller, the behavior is correct and consistent.
It seems that Kevin's fix solves the issues.
New changeset adf493227f1efd5d6b34f46b854142bf3b5a411c by Ned Deily in branch '3.6':
bpo-34370: Update Tk 8.6 used with macOS installers
New changeset d9cfe5ed2c2c61eeae915b76f5e10aadbbb28da6 by Ned Deily in branch '3.7':
bpo-34370: Update Tk 8.6 used with macOS installers
FYI, for the python.org binary macOS installers for the 3.7.1rc1 and 3.6.7rc1 releases, I cherry-picked a post-8.6.8 development snapshot of Tk 8.6 that should include Kevin's fix. I would appreciate any feedback one way or the other whether this version of Tk 8.6 improves things over the vanilla 8.6.8 version used for the 3.7.0 and 3.6.6 releases. Thanks!
Ned, please hold off a bit on this--another developer is doing some final fine-tuning of the scrolling code so it fully passes Tk's test suite. I'm waiting for the final commit of this code any day now.
The scroll problem (clicking on the upper half of the slider is taken as "through1") still persists for me on Mojave with 3.7.1 RC1 downloaded from python.org and including Tcl/Tk.
Thanks for testing, Vlad. And thanks for the followup, Kevin. I guess we'll wait to hear more from Kevin.
I just installed 3.7.1rc on current High Sierra and observed same as Vlad.
New changeset f55c3ae657595d12ce78aca76c9c6b998d632424 by Ned Deily in branch '3.6':
bpo-34370: Revert to using released Tk 8.6.8 with macOS installers
New changeset d8b6425e58a1fccdf8ddbbcde63066c13c1bcfaf by Ned Deily in branch '3.7':
bpo-34370: Revert to using released Tk 8.6.8 with macOS installers
Release of Tk 8.6.9 very soon; includes fixes for Mac scrolling as well as support for 10.14 macOS, with Dark Mode.
|
https://bugs.python.org/issue34370
|
CC-MAIN-2020-16
|
refinedweb
| 771
| 71
|
HI, I am following the quick tutorial ""
I tried to put my domain in here <ds:SaleDomainContext>, but there my domain is not on the list. There are only AuthticationService and UserRegistrationService. I did add those reference mentioned in the tutorial and rebuild the solution. Please advise
Hi sdnd2000,
1. please check if the namespace is defined correctly as below
xmlns:ds="clr-namespace:RIAExampleApp.Web"
2. After creating service, "Build"/"Rebuild" whole application is needed in order to access domain service on client side.
3. Right click on silverlight project (not .web project) - Properties - Silverlight - WCF Ria service link. here select the web part project.
Best Regards,
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.
Would you like to participate?
|
http://social.msdn.microsoft.com/Forums/silverlight/en-US/3bdc4a22-f6a5-41c2-9b8e-79a3abb24839/is-that-reference-issue?forum=silverlightwcf
|
CC-MAIN-2014-41
|
refinedweb
| 148
| 59.5
|
21714RE: [PrimeNumbers] Web page:
Expand Messages
- Aug 12, 2010
> Date: Wed, 11 Aug 2010 14:48:32 +0000Very funny: I've ported it "as is" in Python but it is very slow.
> Subject: [PrimeNumbers] Web page:
> Hello all:
> This is mi new web page (in spanish and english).
>
> sincerely
> Sebastián Martín Ruiz
import math
def prime3(n):
"""Prime numbers generator"""
t = 1
lim = 2 * int( n * math.log(n) ) + 1
for k in range(1, lim+1):
t += 1
f = 0
for j in range(2, k+1):
g = 0
for s in range(1,j+1):
g += (j // s) - ((j-1) // s)
f += 1 + ( -(g-2) // j )
t -= f // n
return t
I succeed in reducing one for-loop buffering common elements of sums, but it is again slower than eratosthenes sieve.
def prime2(n):
"""Prime numbers generator (better)"""
t = 1
lim = 2 * int( n * math.log(n) ) + 1
af = [0, 0]
f = 0
for j in range(2, lim+1):
g = 0
for s in range(1, j+1):
g += (j // s) - ((j-1) // s)
h = -(g-2) // j
f += 1 + h
af.append(f)
for k in range(1, lim+1):
t += 1
f = af[k]
t -= f // n
return t
In few seconds, this one proves to work for all n < 1000. Duration increases very quickly, so I tested some samples n < 20000.
It would be fine if it were possible to further reduce the two nested for-loops.
M.
[Non-text portions of this message have been removed]
- << Previous post in topic
|
https://groups.yahoo.com/neo/groups/primenumbers/conversations/messages/21714
|
CC-MAIN-2015-32
|
refinedweb
| 257
| 74.02
|
The Event Log is the place that a lot of important system components and applications send their status, warning and error messages. The problem is that most users either don’t know about it or don’t bother to look at it.
There is a utility, Control Panel/ Administrative Tools/ Event Viewer, that you can use to check that your machine is working properly but it would be better if really important messages were brought more forcibly to your attention – this is what Eventer is designed to do.
It is a service that monitors the event log and emails new events as they occur.
To create Eventer all you have to do is create a new service called Eventer following the steps given earlier.
Start a new empty project called Eventer, add a code file called Eventer and add references to:
System, System.Configuration and System.ServiceProcess.
and add to the start of the program:
using System;using System.ServiceProcess;using System.Configuration.Install;using System.ComponentModel;using System.Diagnostics;using System.Net.Mail;using System.Net;
The Eventer service starts in the usual way:
public class Eventer : ServiceBase{ public Eventer() { this.ServiceName = "Eventer"; this.CanStop = true; this.CanPauseAndContinue = false; this.AutoLog = true; }
The AutoLog property being set to true means that the service automatically writes start and stop events into the event log.
The OnStart and OnStop methods are very simple because there is an EntryWrittenEvent which can be used to activate the service without the need to use a timer. All we have to do to make the service respond to the event is to add an event handler in the OnStart method and turn the events on:
protected override void OnStart( string[] args){ this.EventLog.EntryWritten += new EntryWrittenEventHandler( MyOnEntryWritten); this.EventLog.EnableRaisingEvents = true;}
Notice that in this case we can’t use the form’s designer to connect an event to an event handler – it has to be done using code. This isn’t difficult as all you need to do is add a suitable delegate, EntryWrittenEventHandler, to the event using the += operator.
Of course we still have to write the code in the MyOnEntryWritten event handler. In the OnStop method we need to remove the event handler and this is just as easy using the -= operator on the event:
protected override void OnStop(){ this.EventLog.EnableRaisingEvents = false; this.EventLog.EntryWritten -= new EntryWrittenEventHandler( MyOnEntryWritten);}
This is all we need to get the service started and stopped and the Main method only has to create an instance of the service to complete the code:
public static void Main(){ ServiceBase.Run(new Eventer());}
The installer for the service is similar to previous installers but this time the ServiceStartMode is set to Automatic which starts the service as soon as the machine is started:
[RunInstaller(true)]public class EventerInstaller : Installer{ private ServiceProcessInstaller processInstaller; private ServiceInstaller serviceInstaller; public EventerInstaller() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Eventer"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); }}
The only method we still need to write is the event handler which is called every time a new event is written to the Application event log. When you create a service object it has an EventLog property which is connected to the local machine’s Application event log. You can create other EventLog objects connected to other event logs – Security, System and so on if you want to scan for errors in specific categories - but for the moment working with the Application log provides an easy example. However, it is worth knowing that you can’t change the EventLog property to work with any other event log, you have to create new EventLog objects.
The information about the entry that has just been written and hence caused the EntryWritten event is contained in the second parameter passed to the event handler. We could test the event type and only email information about it if it was serious enough – at least a warning or an error.Again for simplicity is it easier to initially email all events in the log including low priority information events.
Our first task is to assemble the email to be sent. Version 3 (and later) of the .NET framework makes this very easy with the introduction of a range of SMTP classes.
First we create a MailMessage:
public void MyOnEntryWritten( Object source, EntryWrittenEventArgs e){ MailMessage mail= new MailMessage("from","to");
where you replace from and to by appropriate email addresses. You can also use the many properties provided by MailMessage to set, subject, from, to, and even add attachments.
In this particular case we simply need to set the subject and build up the text to be used as the body of the email:
mail.Subject = "Event Notification";mail.Body=e.Entry.Source +Environment.NewLine+e.Entry.Message +Environment.NewLine +e.Entry.TimeGenerated. ToLongDateString() +" "+ e.Entry.TimeGenerated. ToLongTimeString() +Environment.NewLine + e.Entry.MachineName + Environment.NewLine + e.Entry.EntryType;
The instructions that create the body of the email may look complicated but they simply build up the text using properties supplied by e.Entry such as date, time, message etc. You can include or leave out other details of the event to suit your requirements.
Now that we have the email ready to send we can use the SmtpClient to create a connection to an SMTP server.
The documentation gives the impression that SmtpClient is to be used with an SMTP server provided by a local IIS virtual SMTP server but in fact it is completely general and you can send email using any mail server that you have a valid account on.
First we create an SmtpClient:
SmtpClient mailbox= new SmtpClient("smtp server");
You can replace smtp server with either the IP address or URL of the mail server you plan to use. Some mail servers require you to log on before you can use them to send an email. If this is the case you will need to set the Credentials property:
mailbox.Credentials = new NetworkCredential( "user", "password");
where you replace user and password by a valid username and password.
Finally we can send the mail message using the SMTP server:
mailbox.Send(mail);}
This completes the event handler and now all you need to do is install the service using InstallUtil.
Once the service is started it will send one email for each new event in the Application log.
Of course there are a few things that need to be done to make the service robust but this is a reasonable first attempt. In particular you need to add some code to handle SMTP errors just in case the mail server isn’t correctly configured or offline.
<ASIN:047138576X>
<ASIN:0735623740>
<ASIN:0735621632>
|
http://www.i-programmer.info/projects/38-windows/276-a-windows-service-without-a-template.html?start=3
|
CC-MAIN-2013-48
|
refinedweb
| 1,121
| 51.58
|
Drawing Functions in VB.NET
In This Chapter
- Key Classes Related to Drawing
- Drawing with the .NET Namespaces
- Drawing Basics
- Drawing Basic Shapes
- Filling Shapes
- Collections of Shapes
- Working with Images
- Transformations
- Learning by Example: A Forms-Based Drawing Application
Nothing in Windows gets to the user's screen without the aid of a drawing function. This includes images, colors, and even text. The OS must render all things visually by drawing pixels to an output device (monitor, printer, and so on). Of course, Windows does a good job of hiding drawing functions from the average developer. When did you last need to call an API function to display text to the screen or change the background color of a button? Our controls, compiler, and operating system serve to limit our need to make direct calls into the drawing library. However, there is always the case where your application requirements are beyond the scope of what can be done with controls and so on. Perhaps you must create custom pie charts for your users on-the-fly. Or maybe you need to allow your users to view a group of fonts or send output to the printer. Chances are that you will eventually need to write your own custom visual display code. This is where the .NET drawing library comes into play. It provides you with a host of classes that make adding drawing capabilities to your application easy and fun.
This chapter illustrates common programming tasks using the namespaces related to drawing in the .NET Framework Class Library. The chapter starts by illustrating the key classes used to execute drawing functions with the namespace. Then follows a detailed discussion of these key classes and related code examples. Lastly, we will create a simple drawing application that serves to demonstrate how these classes can be used in the context of a larger application and serves as an experimental ground.
After reading this chapter, you should be able to do the following:
Understand how Windows manages coordinates
Draw basic shapes including lines, curves, rectangles, and polygons
Fill shapes and lines with various colors, patterns, and gradients
Work with groups of shapes
Work with bitmaps and icons in your application
Rotate, stretch, and skew graphics
Key Classes Related to Drawing
The process of drawing with the .NET Framework Class Library involves a whole host of classes. These classes can be found inside of the System.Drawing namespace and its associated third-level namespaces. At a glance, the drawing namespace in .NET is made up of the following:
System.Drawing: Provides basic graphics functionality. This chapter focuses on this namespace.
System.Drawing.Design: Focuses on providing functionality for extending the design time environment. This namespace is beyond the scope of this book.
System.Drawing.Drawing2D: Provides two-dimensional and vector graphics classes and methods. This namespace is covered within this chapter.
System.Drawing.Imaging: Exposes advanced imaging functionality. This namespace is beyond the scope of this book.
System.Drawing.Printing: Gives you classes to manage output to a print device. Chapter 6, "Font, Text, and Printing Operations," covers this namespace.
System.Drawing.Text: Wraps fonts and type management. Chapter 6 covers this namespace.
This chapter is focused on the System.Drawing and System.Drawing.Drawing2D namespaces. These two namespaces contain classes that are fundamental to the execution of common programming tasks with .NET. The namespaces Printing and Text are covered elsewhere in the book, and Design and Imaging are simply beyond the scope of this book as they encapsulate more specialized features. There are certainly great classes within these namespaces, and we encourage you to use this chapter as a leaping-off point to your own exploring. Table 9.1 lists the key classes we will be discussing.
|
http://www.informit.com/articles/article.aspx?p=29477&seqNum=3
|
CC-MAIN-2017-30
|
refinedweb
| 625
| 57.57
|
OK, maybe they only irritate me and most people find them useful, but things keep added into Firefox increasing bloat for no apparent reason. In some cases they also increase the odds of you accidentally leaking information onto the internet
It'll almost certainly grow with time, but this snippet is a bunch of steps to disable some of those annoyances, like "Pocket", "Screenshot" and "Please, please sign into your browser" mode
# Disable screenshots # # This uploads screenshots to a web based service. No thanks browse to about:config Search for "screenshots" set extensions.screenshots.disabled to True # Disable pocket # # Pocket lets you save things in a single click at the cost of # need an account with Pocket browse to about:config Search for "pocket" Set pocket.enabled to false # Disable browser login (Sign in to Sync) # # A browser is a tool to access things, I don't want to sign into it # # Firefox 60 is needed to get rid of this in about config browse to about:config search for identity.fxaccounts set identity.fxaccounts.enabled to false # For versions prior, add this to usercontent.css # (usuallly ~/.mozilla/firefox/[profilename]/chrome/userContent.css) # You may need to create the chrome directory #
@-moz-document url("about:preferences") { #category-sync { display:none!important; } }# and in userChrome.css # # In case it changes, do a view source here - chrome://browser/content/browser.xul # to find the ID
@namespace url(""); #PanelUI-fxa-status, #appMenu-fxa-status { display: none !important }# Disable Firefox snippets on new tab page Open a new tab click cog in top-right corner Untick "Snippets" # Disable Firefox "Highlights" on new tab page Open a new tab click cog in top-right corner untick "Highlights"
|
https://snippets.bentasker.co.uk/page-1805010933-Removing-Firefox-Annoyances-Misc.html
|
CC-MAIN-2019-09
|
refinedweb
| 282
| 50.46
|
SYNOPSIS
#include <regex.h>
int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
DESCRIPTION
The
The following structure types contain at least the following members:, does not match the beginning of string.
- REG_NOTEOL
The last character of the string pointed to by string is not the end of the line. Therefore, the dollar sign ($), when taken as a special character, does not match the end of string.
If nmatch is 0 or REG_NOSUB was set in the
cflags argument to
When matching a basic or extended regular expression, any given parenthesized] delimit the last such match.
- If subexpression i is not contained within another subexpression, and it did not participate in an otherwise successful match, the byte offsets in pmatch[i] are -1. A subexpression does not participate in the match if one of the following conditions exists:
- An * or a \{ \} appears immediately after the subexpression in a basic regular expression, or *, ?, or { } appears immediately after the subexpression in an extended regular expression, and the subexpression did not match (matched 0 times).
- A | is used in an extended regular expression to select this subexpression or another, and the other subexpression matched.
If, when
If REG_NEWLINE is not set in cflags, then a newline character in pattern or string is treated as an ordinary character. If REG_NEWLINE is set, a newline is treated as an ordinary character except as follows:
- A newline character in string is not matched by a period outside a bracket expression or by any form of a nonmatching list.
- A circumflex (^) in pattern, when used to specify expression anchoring, matches the zero-length string immediately after a newline in string, regardless of the setting of REG_NOTBOL.
- A dollarsign ($) in pattern, when used to specify expression anchoring, matches the zero-length string immediately before a newline in string, regardless of the setting of REG_NOTEOL.
If the preg argument to
PARAMETERS
- preg
Points to the compiled regular expression that a previous call to
regcomp()initialized.
- string
Points to a null-terminated string.
- nmatch
Is the number of matches allowed.
- pmatch
When nmatch is non-zero, points to an array with at least nmatch elements.
- eflags
The bitwise inclusive OR of zero or more of the flags defined in the header <regex.h>.
RETURN VALUES
If successful, the:
regcomp(), regerror(), regfree()
PTC MKS Toolkit 10.3 Documentation Build 39.
|
https://www.mkssoftware.com/docs/man3/regexec.3.asp
|
CC-MAIN-2021-39
|
refinedweb
| 394
| 51.99
|
Stefano Lattarini wrote: > While I don't feel qualified to discuss the merits of the matter here, > I have a couple of nits below... Hi Stefano, Thanks for the review! > On Monday 04 October 2010, Jim Meyering wrote: ... >> Makefile.in | 6 ++++-- >> NEWS | 5 +++++ >> aclocal.m4 | 4 ++-- >> configure | 10 +++++----- >> doc/automake.texi | 7 +++++++ >> lib/am/distdir.am | 6 ++++-- >> 6 files changed, 27 insertions(+), 11 deletions(-) ... >> + | BZIP2=${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 > Typo here: should be "$${BZIP2--9}". Well caught. Fixed. I should have tested with dist-bzip2, too. > But then: why not follow consistently the example of the gzip > compression? As in: > GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz > with GZIP_ENV set to a proper default in the generated makefile, > and overridable through the command line: > $ make dist GZIP_ENV=--fast To minimize namespace impact, and to keep the change compact/local. With my proposed approach, we do not impinge on user name space at all. With the above, we'd usurp BZIP2_ENV and XZ_ENV if you want to be consistent. Also, with the _ENV variables, there would have to be added definitions. No fundamental objection, but I do prefer the smaller patch. >> diff --git a/aclocal.m4 b/aclocal.m4 >> index c43a368..4a22182 100644 >> --- a/aclocal.m4 >> +++ b/aclocal.m4 > Why have you regenerated this file with a unreleased autoconf version? I regularly test unreleased versions. Sorry to have included that. I was obviously asleep at the wheel. I'm no longer accustomed to submitting patches in projects that version-control such generated files. >> diff --git a/configure >> b/configure >> index 169d82d..2940276 100755 >> --- a/configure >> +++ b/configure > Ditto. Likewise. >> diff --git a/doc/automake.texi b/doc/automake.texi >> index 22c2f27..0652aa{XZ_OPT} environment variable > BZIP2 environment variable >> +For example, @samp{make dist-bzip2 XZ_OPT=-7}. > Ditto. Thank you. Fixed. >From ebb9b294cf878ed7083376bd15a0269a0583836c Mon Sep 17 00:00:00 2001 From: Jim Meyering <address@hidden> Date: Sat, 2 Oct 2010 22:30:02 +0200 Subject: [PATCH] dist-xz: don't hard-code -9: honor setting of XZ_OPT * lib/am/distdir.am (dist-xz): Do not hard-code xz's -9: that made it impossible to override. Instead, use its XZ_OPT envvar, defaulting to -9 if not defined. Thus no change in behavior when XZ_OPT is not set, and now, this rule honors the setting of that envvar when it is set. Suggested by Lasse Collin. * NEWS (Miscellaneous changes): Mention it. * doc/automake.texi (The Types of Distributions): Describe the newly enabled environment variables. --- NEWS | 5 +++++ doc/automake.texi | 7 +++++++ lib/am/distdir.am | 6 ++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index 121989f..c64ec14 100644 --- a/NEWS +++ b/NEWS @@ -17,6 +17,11 @@ New in 1.11a: - "make dist" can now create lzip-compressed tarballs. + - You may adjust the compression options used in dist-xz and dist-bzip2. + The default is still -9 for each, but you may specify a different + level via the XZ_OPT and BZIP2 envvars respectively. E.g., + "make dist-xz XZ_OPT=-7" or "make dist-xz BZIP2=-5" + - Messages of types warning or error from `automake' and `aclocal' are now prefixed with the respective type, and presence of -Werror is noted. diff --git a/doc/automake.texi b/doc/automake.texi index 22c2f27..f8f2d8} diff --git a/lib/am/distdir.am b/lib/am/distdir.am index a11d3a4..ad789df 100644 --- -- 1.7.3.1.45.g9855b
|
http://lists.gnu.org/archive/html/automake-patches/2010-10/msg00022.html
|
CC-MAIN-2014-10
|
refinedweb
| 567
| 70.6
|
Ok, so this might be a bit hard to explain without a ton of code to support it but I will try my best.
Essentially I am doing a query (currently on ef core 2.1) with involves a 1 to many relationships. However, the "many" collection is null when it materialized.
Here is the query in question (some code removed for brevity)
IQueryable<AccountViewModel> baseQuery = from ms in _managedSupportRepository.GetAllIncluding(m => m.Users) // here is the problem // a few lines of filters like the one below where string.IsNullOrEmpty(clientVersionFilter) || !string.IsNullOrEmpty(ms.ClientVersion) && ms.ClientVersion.Contains(clientVersionFilter, StringComparison.OrdinalIgnoreCase) join c in _contractRepository.GetAll() on ms.Id equals c.AssetId into contracts from c in contracts.DefaultIfEmpty() let isAssigned = c != null where !isAssignedFilter.valueExists || isAssignedFilter.value == isAssigned join a in _autotaskAccountRepository.GetAll() on ms.TenantId equals a.Id where string.IsNullOrEmpty(accountNameFilter) || !string.IsNullOrEmpty(a.AccountName) && a.AccountName.Contains(accountNameFilter, StringComparison.OrdinalIgnoreCase) select new AccountViewModel { AccountName = a.AccountName, ActiveUsers = ms.GetConsumed(), // here is the problem ClientVersion = ms.ClientVersion, ExternalIpAddress = ms.IpAddress, Hostname = ms.Hostname, Id = ms.Id, IsActive = ms.IsActive, IsAssigned = isAssigned, LastSeen = ms.CheckInTime, Status = ms.Status }; int count = baseQuery.Count(); baseQuery = baseQuery.Paging(sortOrder, start, length); return (baseQuery.ToList(), count);
Just for clarity, the
_managedSupportRepository.GetAllIncluding(m => m.Users) method is just a wrapper around the
.Include() method.
So the problem is in the view model for active users
ActiveUsers = ms.GetConsumed(),. The
GetConsumed() method is as follows
public long GetConsumed() { return Users.Count(u => !u.IsDeleted && u.Enabled && u.UserType == UserType.Active); }
however, this throws a null reference exception because the Users collection is null.
Now my question is, why is the Users collection null when I am explicitly asking it to be loaded?
A workaround at the moment is to alter the queries first line to be this
_managedSupportRepository.GetAllIncluding(m => m.Users).AsEnumerable() which is just ridiculous as it brings all the records back (which is several thousand) so performance is nonexistent.
The reason it needs to be an IQueryable is so the paging can be applied, thus reducing the amount of information pulled from the database.
Any help is appreciated.
There are two parts to this problem:
When you do queries on EF on the provider (server evaluation), you are not -executing- your
new expressions, so this:
ActiveUsers = ms.GetConsumed(),
Never actually executes
ms.GetConsumed(). The expression you pass in for the
new is parsed and then translated to the query (SQL in case of sql server), but
ms.GetConsumed() is not executed on the provider (on the query to the database).
So you need to include
Users on the expression. For example:
select new AccountViewModel { AccountName = a.AccountName, AllUsers = Users.ToList(), ActiveUsers = ms.GetConsumed(), // etc. }
This way EF knows it needs
Users for the query and actually includes it (you are not using
Users in your expression, so EF thinks it doesn't need it even if you
Include() it... it'll probably show a warning on the
Output window in Visual Studio), otherwise it tries to project and request only the fields it understands from the
new expression (which doesn't include
Users).
So you need to be explicit here... try:
ActiveUsers = Users.Count(u => !u.IsDeleted && u.Enabled && u.UserType == UserType.Active);
And
Users will be actually included.
In this case,
Users will be included because it's in the actual expression... BUT, EF still doesn't know how to translate
ms.GetConsumed() to the provider query, so it'll work (because
Users will be loaded), but it won't be ran on the database, it'll still be run on memory (it'll will do client side projection). Again, you should see a warning about this in the
Output window in Visual Studio if you are running it there.
EF Core allows this (EF6 didn't), but you can configure it to throw errors if this happens (queries that get evaluated in memory):
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder /* etc. */ .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)); }
You can read more about this here:
|
https://entityframeworkcore.com/knowledge-base/51518671/ef-core-include---statement-is-null-for-iqueryable
|
CC-MAIN-2022-40
|
refinedweb
| 676
| 52.36
|
Table Of Contents
In my last post Compile OpenCV from source with JAVA support I explained how to Compile OpenCV from source with JAVA support, however, the OpenCV nonfree part was not included. If you are planning to use private features from OpenCV like SIFT or SURF descriptors, you should go as follows:
[1]. Download OpenCV 3.2, unpack and create build directory
following the steps of my last post.
Help us keep writing
- “Whitelist” us in your ad blocker
- Why I removed Google Analytics
- Use our Amazon link
- Download one of our free EBooks
- Become a Patreon!
- More ways to support us
[2]. Download and unpack nonfree part
nonfree part has been separated in OpenCV3+, so you need to download it separately from github opencv repo or clone the repository. Then extract opencv_contrib and move it inside your opencv folder :
cris@cris ~ $ cp Downloads/opencv-contrib opencv-3.2.0/
[3]. generate makefiles
we move to the build folder inside opencv folder and type:
cris@cris~$ cmake -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release\\ -DCMAKE_INSTALL_PREFIX=../dist -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..
With
DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules we are specifying where to found the nonfree part.
If makefiles generation went ok, you can now build. If using openCV in JAVA, you must make sure
$JAVA_HOME variable is set to JDK’s path and visible to child processes. For that when doing:
echo $JAVA_HOME the JDK path must be displayed. If not, in terminal, set de variable value to JDK path and export it, for example:
cris@cris ~$ export JAVA_HOME=/home/jdk1.8.0_111/
Notice that when generating the makefile, the output in the Java field looks like this:
That is, there is a specified ant and JNI path, and Java wrappers is set to YES.
[4]. Build
run make to build openCV with Java and create a jar:
cris@cris ~/opencv-3.2.0/build $ make -j8
-j8 is because JDK8. You should put here your JAVA version.
Make sure the files opencv-320.jar and libopencv_java320.so (.so or .dll) are created inside /build.
cris@cris ~/opencv-3.2.0/build $ ls -R | grep opencv-320.jar opencv-320.jar opencv-320.jar.dephelper cris@cris ~/opencv-3.2.0/build $ ls -R | grep libopencv_java320.so libopencv_java320.so
[5]. Edit features2d_manual.hpp file
Ok, if building was successfull, then move to
/modules/features2d/misc/java/src/cpp:
cris@cris ~/opencv-3.2.02 $ cd modules/features2d/misc/java/src/cpp/
and edit features2d_manual.hpp with your favorite text editor, as following:
- In line 8, under
#include "features2d_converters.hpp"add
#include "opencv2/xfeatures2d.hpp"
- In line 121, in create method, inside
case SITFand
case SURFreplace :
/;
[5].Rebuild to apply changes
move to your opencv/build folder and run
make install when finished, you just need to include the .so and .jar files on your openCV project and you would be able to use SIFT and SURF decriptors in your code.
|
https://elbauldelprogramador.com/en/how-to-compile-opencv3-nonfree-part-from-source/
|
CC-MAIN-2017-34
|
refinedweb
| 484
| 66.33
|
I initially posted this in the technical support forum but I think this would be a better place for it.... Sorry for the duplicity.
I'm writing my own package hoping to release it to the public once I'm satisfied with it. Right now, I am struggling to do something ... weird. As most of us are fluent in C, I will explain this as if I was writing a C syntax highlight plugin.
I would like to be able to let's say write:
- Code: Select all
#include <stdio.h>
#include <math.h>
Now, I could write:
- Code: Select all
printf("Testing: %f\n", log10(3));
Now, I would like to have functions (printf and log10) highlighted when both includes are specified but not when their related include isn't there or commented out.
I have played quite a lot with recurrence, with rules inclusion and $self/$base but can't get the proper behavior. The problem being that once inside an included rule, matches outside this rule are forgotten.
This means that if I have a super rule which defines two sub-rules, one for stdio and the other for math, once inside the sub-rules I can't get matches from the other one. I will always end up getting either one or the other sub-rule.
Hence the title of this post: being able to add rules when a match occurs.
Thanks.
|
http://www.sublimetext.com/forum/viewtopic.php?f=6&t=16487&p=62118
|
CC-MAIN-2015-06
|
refinedweb
| 236
| 71.14
|
Let’s Design a Shopify Theme
Themeforest recently opened a new section where you can buy or sell themes for Shopify! Shopify is a hosted e-commerce solution that makes it easy to get started with an online business. You can have a shop up and running in minutes.
To kick-start ThemeForest's Shopify catalog, the authors of each accepted template will receive a $100 bonus - until there are ten templates in the category.
Shopify is well known for its flexibility of design. See some examples. Shopify created (and later released as open source) the Liquid Templating Engine. Liquid allows complete design freedom for designers.
In this tutorial I will show how to design a Shopify theme using Liquid. Once you have the basics, you can design a theme, and submit it to Themeforest.
Let’s Design a Shopify Theme
What is Liquid?
Liquid is the templating engine developed for and used by Shopify. It processes Liquid template files, which have the “.liquid” extension. Liquid files are simply HTML files with embedded code. Since Liquid allows full customization of your HTML, you can literally design a shop to look like anything.
Liquid was originally developed in Ruby for use with Shopify and was released as an open source project. Since then, it has been used in other Ruby on Rails projects, and has been ported to PHP and javascript.
A Quick Preview of Liquid
Let’s look at what it takes to get started with liquid.
<ul id="products"> {% for product in products %} <li> <h2>{{ product.title }}</h2> Only {{ product.price | money_with_currency }} <p>{{ product.description | prettyprint | truncate: 200 }}</p> </li> {% endfor %} </ul>
As you can see, Liquid is just HTML with some embedded code. This is why Liquid is so powerful, it gives you full power over your code and makes it easy to work with the variables you have available.
What is going on above?
In Liquid, there are two types of markup: Output and Tags. Liquid Tags are surrounded by curly brackets and percent signs; output is surrounded by two curly brackets.
In the above snippet, the first line of Liquid is:
{% for product in products %} .... {% endfor %} This is an example of a Liquid Tag. The
for Tag loops over a collection of items and allows you to work with each one. If you have ever used for loops in PHP, Ruby, javascript, or (insert any programming language here), it works the same way in Liquid.
The next line of Liquid in the above snippet is
{{ product.title }}. This is an example of a Liquid Output. This will ask for a product’s title and display the result to the screen.
The next line of Liquid introduces something new:
{{ product.price | money_with_currency }} Here we have an example of a Liquid Filter. They allow you to process a given string or variable. Filters take the value to the left of themselves and do something with it. This particular Filter is called
format_as_money; it takes a number, prepends it with a dollar sign and wraps it with the correct currency symbol.
A simple example:
<span class="money">{{ product.price | money_with_currency }}</span>
could generate the following HTML
<span class="money">$45.00 <span class="caps">USD</span></span>
The last line of Liquid above:
{{ product.description | prettyprint | truncate: 200 }} shows how you can chain filters together. Filters act on the value that is to the left of them, even if that value happens to be the result of another filter. So the snippet in question will apply the
prettyprint filter to
product.description, and then will apply the
truncate filter to the results of
prettyprint. In this way, you can chain together as many Liquid filters as you need!
What Else Does Liquid Offer?
In terms of Liquid Tags, besides the
for tag, there are several others. Th most common ones are:
Comment:
{% comment %} This text will not be rendered {% endcomment %}
If/Else:
{% if product.description == "" %} This product has no description! {% else %} This product is described! {% endif %}
Case:
{% case template %} {% when 'product' %} This is a product.liquid {% when 'cart' %} This is a cart.liquid {% endcase %}
Liquid also offers plenty of filters you can use to massage your data. Some common ones are:
Capitalize:
{{ “monday” | capitalize }} #=> Monday
Join:
{{ product.tags | join: ’, ’ }} #=> wooden, deep snow, 2009 season
Date:
Posted on {{ article.created_at | date: “%B %d, ’%y” }} #=> Posted on January 26, ’09
Anatomy of a Shopify Theme
Shopify themes all have a simple directory structure. It consists of an assets, layout, and templates folder. Let’s look at what goes where:
- assets folder: In the assets folder you store all of the files that you want to use with your theme. This includes all stylesheets, scripts, images, audio files, etc. that you will be using. In your templates you can access these files with the
asset_urlFilter.
{{ "logo.gif" | asset_url | img_tag: "Main Logo" }} #=> <img src="/files/shops/random_number/assets/logo.gif" alt="Main Logo" />
- layout folder: This folder should contain just one file called theme.liquid. The theme.liquid holds the global elements for your Shopify theme. This code will be wrapped around all of the other templates in your shop. Here is an example of a very basic theme.liquid:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xml: <head> <title>{{shop.name}}</title> {{ 'layout.css' | asset_url | stylesheet_tag }} {{ content_for_header }} </head> <body> <div id="header"> <h1 id="logo"><a href="/">{{ shop.name }}</a></h1> </div> <div id="content"> {{ content_for_layout }} </div> <div id="footer"> All prices are in {{ shop.currency }} | Powered by <a href="" title="Shopify, Hosted E-Commerce">Shopify</a> </div> </body> </html>
Required Elements
There are two VERY important elements that must be present in a theme.liquid file. The first is
{{ content_for_header }}. This variable must be placed in the head of your theme.liquid. It allows Shopify to insert any necessary code in the document head, such as a script for statistics tracking. For thsoe familiar with WordPress, this is quite similar to the wp_head() function.
The other VERY important element is
{{ content_for_layout }}. This variable must be placed in the body of your theme.liquid; it's the place where all of your other Liquid templates will be rendered.
- templates folder: This folder holds the rest of your Shopify templates. It consists of:
- index.liquid: Displayed as the main index page of your shop.
- product.liquid: Each product will use this template to display itself.
- cart.liquid: Displays the current user’s shopping cart.
- collection.liquid: Displayed for collections of products.
- page.liquid: Displayed for any static pages that the shop may have created.
- blog.liquid: Displayed for any Shopify blogs for the shop.
- article.liquid: Displayed for any blog articles and includes a form for submitting comments.
- 404.liquid: Displayed for anytime the shop returns a 404.
- search.liquid: Displayed for shop search results.
As you might have guessed, each of these templates has access to different variables. For example, product.liquid has access to a
product variable which contains the current product being displayed, blog.liquid has access to a
blog variable, and index.liquid has access to all of them. If you’re interested in which variables you can use in which template, please review the Liquid documentation.
A Basic Skeleton to Get Started
The best thing about designing for Shopify is that you get to use all of the skills that you already have: HTML, CSS, JS, etc. The only roadblock in the process is becoming familiar with which Liquid variables are available in each template.
This is where Vision comes in.
Vision – Shopify in a Box
What is Vision?
Vision is a stand-alone application that allows you to create themes for Shopify stores on your local machine without having to sign up for a shop or setup a database or all that other geeky stuff.
What do I need to run Vision?
Vision comes complete with everything needed to run straight out of the box. If you’ve got a text editor and a web browser installed, you are ready to roll.
As if that wasn’t enough, Vision comes pre-loaded with Shopify's ready-made themes. Shopify has allowed people to use these themes as building blocks, so you can start with one of these existing themes as a base and expand upon on it!
Summary
Shopify is a fast growing e-commerce platform already with thousands of sellers looking to show off their products. Using Vision, you can hit the ground running and begin developing in no time. The first ten templates posted to Themeforest's Shopify category get an extra $100. So get started!
If you need more information about designing with Shopify, they have extensive documentation on their wiki. Check out The Shopify Theme Guide, Using Liquid, and Getting Started with Vision.
The Best Shopify Templates from ThemeForest....So Far!
Drifter
"This sleek Shopify theme features clean lines and modern design accents that showcase your products. Custom jQuery lightboxes allow your products to be viewed in full detail."
Fancy Pink
"A shopify theme with modern, fancy web 2.0 design."
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
|
http://code.tutsplus.com/tutorials/lets-design-a-shopify-theme--net-3416
|
CC-MAIN-2014-41
|
refinedweb
| 1,527
| 67.45
|
GNOME Bugzilla – Bug 396774
Make GstElementDetails extensible
Last modified: 2010-09-06 11:18:59 UTC
in buzztard I use a help interface on elemnts:
Elements that implement it can tell about where user help for this element can be found. Native gst elemnts can point to their gtk-doc html page. Wrapper plugins can point to respective native files.
This is mostly useful for applications that offer the user a dynamic list of plugins to use (like jokosher, pitivi and buzztard).
please, don't create a new interface just for a readonly value :)
a virtual function to GstElement instead?
the iface is indeed a bit too much. What about adding this to GstElementDetails?
there could be GST_ELEMENT_DETAILS_WITH_APIDOCS(longname,klass,description,author,element_name)
that also sets the sets the uri to
"file://"DATADIR""G_DIR_SEPARATOR_S"gtk-doc"G_DIR_SEPARATOR_S"html"G_DIR_SEPARATOR_S""PACKAGE""G_DIR_SEPARATOR_S""PACKAGE"-%s.html", element_name
IMHO the interface for a single gobject property would be overkill too... so the addition to GstElementDetails is probably the best. Every other possibility I can think about sounds too complicated :)
But instead of hardcoding the URI to "...." I would just specify the complete URI. IMHO having this kind of automatism seems to be very error-prone and could easily lead to URIs pointing to nowhere... though this is probably just a matter of taste ;)
The UIR I suggested would be generated from defines that configure puts into config.h. Thus it would be automatically correct :)
If people use auto* and gtk-doc, yes. Well, for most cases this should work nonetheless, right :)
Only cases where this would break is when people don't use gtk-doc or only want the docs on some website, etc... and in this cases this could still be done by not using the macro... I'm fine with this
This is kind of what GstPluginDesc::origin is supposed to be. Origin is more of a base URL, however, a documentation URL makes a lot of sense in addition to the base URL.
The reason for proposing to add this to GstElementDetails are wrapper plugins. I'll make a patch as proposed in comment #2.
Better idea:
- use a GstStructure *metadata;
How:
- needs fixes in gstelement.{c,h},gstelementfactory.{c,h}
- gst_element_class_set_metadata(GstElementClass *klass, const gchar * field, ...)
-> gst_structure_set_valist(klass->metadata, ...)
& gst_element_class_set_details_simple()
- gst_element_class_set_details, gst_element_class_set_details_simple
gst_structure_set(klass->metadata, ...)
Created attachment 97416 [details] [review]
turns GstElementDetails into a GstStructure
How would it be used:
gst_element_class_set_meta_data (gstelement_class,
"longname", G_TYPE_STRING, "File Sink",
"klass", G_TYPE_STRING, "Sink/File",
"description", G_TYPE_STRING, "Write stream to a file",
"author", G_TYPE_STRING, "Thomas <thomas@apestaart.org>",
NULL);
Question 1: do we want a macro for it?
Question 2: do we want to deprecate the older functions? I made them backwards compatible. So both gst_element_class_set_details_simple and gst_element_class_set_details create the structure too.
Created attachment 97701 [details] [review]
turns GstElementDetails into a GstStructure
I now keep GstElementDetails for backwards compat in both GstElement and GstElementFactory. The new meta element is taking one from the resered_padding.
I am not so much worried that the strings in GstElementDetails cannot be keep syncronous if one does a gst_structure_set on the new meta_data item. First I pt it into private - it should not be accessed directure. Same applied to details field in the past. If one would change the string in GstElement.deatils, the same string in GstElementFactory.factory would not be automatically updated.
I am not yet sure, if I can use one and the same structure for both GstElement and GstElementFactory.
gst_element_register() does
factory->meta_data = gst_structure_copy(klass->meta_data);
as there is no gst_structure_ref() (need to experiment with parents_refcount).
We recently got Bug #491501 filed. If we want to allow that classes set their element_details in base_init and subclases overwrite those fields, the we should use the structure based approach. Atleast then we can also overwrite only some fields: Pipeline subclasses Bin, but "Klass" remains "Generic/Bin".
Another new Detail would be icon or icon-theme-name. I could try to change the patch so that it keeps the current 4 element-details as they are and uses one of the _gst_private pointers for the GstStructure that will hold the extra details. This will be more save. For 0.11 we can rethink the api here.
I like the idea in general but we probably should consider to fix bug #491501 (the details part) first and then get this here done.
Also, IMHO, we should deprecate all the old functions as you intended.
In gstelementfactory.c:283 you should also check for longname being correct, and IMHO we should add a FIXME 0.11 for the description check. Nowadays it seems to be allowed to be empty and we can't change that right now.
Then there are some changes in the registries that seem to be unrelated to this bug, would be nice to have them as an additional patch (they seem to be fine though).
Apart from that, I don't see anything wrong in the latest patch.
Ok, as bug #491501 is done now, please let us get this done too now for the next release. Stefan? :)
GstElementDetails => core
Stefan, any news on this? Bug #491501 can only be fixed in 0.11 but this one here can be fixed now already and probably should be fixed now
I'll do it.
Created attachment 167500 [details] [review]
allow arbitrary plugin metadata
This patch does not attempt to replace the exiting fields (longname, class, author, ...); If wanted I can do that and maintain a GstElementDetails structure with copies for backwards compatibility. That would allow to port elements already now. Please also give feedback on API names.
Elements would now call this after gst_element_class_set_details_simple()
gst_element_class_set_meta_data (gstelement_class,
"Test", G_TYPE_STRING, "test-content",
"Peng", G_TYPE_STRING, "dum di dum",
NULL);
@@ +1250,3 @@
+}
+
+/* FIXME-0.11: deperate and remove gst_element_class_set_details*() */
small typo, deprecate ;)
> Looks good, (...)
I might have a few more comments, please don't commit this quite yet :)
We could also use GstTaglist a-like merging. Like we copy the parent meta-data and replace some value with the new ones.
>
> @@ +1250,3 @@
> +}
> +
> +/* FIXME-0.11: deperate and remove gst_element_class_set_details*() */
>
> small typo, deprecate ;)
fixed locally.
(In reply to comment #21)
> (In reply to comment #19)
> > Review of attachment 167500 [details] [review] [details]:
> >
> >...
This could be also done like for GstTaglist. Right now I would just use it for:
<string> help-uri
I was once thinking of a processor field (CPU, GPU, DSP, ...), this way one could maybe prefer hw-accelerated elements, but thats not really good either.
Any other thoughts?
A summary of open questions:
the patch currently adds two methods:
gst_element_class_set_meta_data (klass, fieldname, ...);
const gchar * gst_element_factory_get_meta_data_detail(factory,detail)
The setter is imho fine. Only having this getter has the limitation that it only works for string details and one cannot iterate details (gst-inspect is grabbing the GstStructure directly, which is bad as it is supposed to be private).
Regarding the known keys, we could do it like gst_tag_register(). I don't think we need flags. Any opinion on a merge behaviour for base-classes? How to name the beast - gst_element_meta_data_register()? Do we actually want to allow to externaly register new ones. I could also just internally register some and have #defines in the public API (like GST_TAG_TITLE). I think that is sufficient.
Created attachment 167691 [details] [review]
allow arbitrary plugin metadata
Small update. Fixes the type and adds two meta-data key defines as proposed in last comment. There is no enforcement of the keys. People can still use arbitrary strings but are suggested to use the defined ones and file enhancement requests for new ones.
I'm a bit undecided about this. What's the intention here exactly? Just make things more extensible at the API level and more generic at the implementation level?
Do we want to allow 'unsanctioned' new fields? (This I'm not sure about - of course it doesn't *hurt*, but is it useful? Does it make good API?)
If we do not want to allow arbitrary fields, why not just add
gst_element_class_set_doc_uri (),
gst_element_class_set_icon_name(), etc. ?
If we do want to allow arbitrary fields, I think simple API like:
gst_element_class_set_string_detail (klass, "key", "value"), or
gst_element_class_set_detail_string (klass, "key", "value"), or just
gst_element_class_set_detail (klass, "key", "value");
would be both sufficient for now and much nicer (not least for bindings). I prefer the latter, fwiw :) I would avoid the word 'METADATA' then, and just go for GST_ELEMENT_DETAIL_DOC_URI or somesuch.
I would avoid vararg functions, and G_TYPE_* and all that. Surely another two or three function calls here aren't really signficant performance-wise? Avoiding this would also make it easier to use a different implementation that's more suitable/efficient for serialisation/deserialisation at a later stage (e.g. GVariant).
I'm not in favour of a registration system for fields here, that seems a bit over the top (I saw that the patch doesn't implement that, just saying).
> /*< private >*/
> GstStructure *meta_data;
I think we should hide the implementation of this field for the reasons described above. Even if we declare it private, it never really is. We can use a dummy pointer typedef here that is then typedef'ed in gst_private.h to GstStructure *. That way we can be 100% sure we can change it later.
> gst_element_factory_get_meta_data_detail (GstElementFactory * factory,
> const gchar * detail);
Similar to what I wrote above, I'd avoid the "meta_data" phrase here and just make it
gst_element_factory_get_detail (factory, detail);
(or gst_element_factory_get_detail_string (factory, detail);
or gst_element_factory_get_string_string (factory, detail); if needed).
> I prefer the latter, fwiw :)
Just to clarify: I think I generally prefer the _set_doc_uri() variant that doesn't allow arbitrary tags, but if the consensus is that arbitrary metadata is desirable, then I favour the_set_detail() variant without the 'string' bit in the name.
Okay, so what about using the GstStructure for the new fields (and in 0.11 for the existing ones too), but add _get|set functions. Thus no gst_element_factory_get_detail() or what so ever, but:
gst_element_class_set_doc_uri ()
gst_element_class_set_icon_name()
gst_element_factory_get_doc_uri ()
gst_element_factory_get_icon_name ()
In gst-inspect we add new calls, when ever there are new fields. String based getters will return NULL in case the detail does not exist. If we add e.g. int based getters we need to do as in gst_structure (out variable, plus boolean return).
> /*< private >*/
> GstStructure *meta_data;
I would tend to keep this as it is. But I can also make it a gpointer and cast in the few methods using it.
I'll make a new patch if that sounds like a good plan.
I generally like the specific getter/setter too (set_doc_uri() etc) but it might be too limited in some cases. For example if there is the need for an audio effect specific detail later, it would mean adding a new function that is audio specific to core...
So in the end I'd prefer the gst_element_class_set_detail_string() and gst_element_class_get_detail_string() variants to allow the biggest extendability (e.g. media specific details, integers, etc)
> I generally like the specific getter/setter too (set_doc_uri() etc) but it
> might be too limited in some cases.
Ok, how about this then:
Have a general key/value setter/getter, but instead of providing key #defines we just provide
#define gst_element_class_set_doc_uri(klass,uri) \
gst_element_class_set_detail_string (klass, "gst-doc-uri", (uri))
? That still results in nice-looking code, but also allows arbitrary keys, and since we don't provide API to iterate over / enumerate the details, no one needs any defines to strcmp against either for now.
(I can live with defines though if people don't like the above)
> #define gst_element_class_set_doc_uri(klass,uri) \
> gst_element_class_set_detail_string (klass, "gst-doc-uri", (uri))
Hrm, or maybe that's awkward for dynamic bindings that do stuff at runtime based on the .gir files? Can they handle such things?
The setters indeed have the disadvantage of becoming somewhat domain specific. That was solved in the GstTaglist by having more tag defines elsewhere. Although sometimes those are not so easy to discover. People probably only find then as they share the namespace. In the same way we could introduce such defines/methods in audio/video libs as well. We'd just call them gst_element_class_set_audio_xxx() (or having a define GST_ELEMENT_METADATA_AUDIO_XXX) I'd use a 'namespace' for the actual key internaly (e.g. "audio::xxx");
If that is okay, we could still use methods instead of macros (to make it easier for bindings). Still having member spread across the packages would probably still confuse bindings.
A plan B would be to only add generic metadata in core and expose the GstStructure.:
- apps could iterate it (the only way for gst-inspect to show all of them if we start to define more in e.g. gst-plugin-base and unless we register known keys).
- wrapper plugins can add own keys and just document them in the plugin
Just as an example, it has help the camera development a lot, that we can just use arbitrary strings in a taglist for r&d phase.
So, unless new arguments show up, my preference would be #defines for the key (for no only in core) and setters/getters as in #comment 28. The naming of the defines is still ugly though (GST_ELEMENT_METADATA_XXX, GST_DELEMENT_DETAIL_XXX).
I see no problem with having the defines or methods in different packages. We're already doing it now for tags and nobody complained so far :) But setter/getter macros might really be a problem for some bindings.
Instead of exposing the GstStructure directly for iterating we could have a getter, that returns a list of struct { const char *name; const GValue *value; }.
gst-inspect can use private headers from core for the iteration, and we can add API for the list/iteration later when someone actually has a good use case for it IMHO.
Created attachment 169235 [details] [review]
allow arbitrary plugin metadata
New implementation using methods instead of #defines.
> gst_structure_set (klass->meta_data, key, value, NULL);
- ^^^ that works? I think there's a G_TYPE_STRING
argument missing
- I still would prefer to avoid exposing the GstStructure
as such directly in the public header (reason: it'd be
nice to be able to switch it to a GVariant later when we
can use that)
Created attachment 169369 [details] [review]
allow arbitrary plugin metadata
Fixed and // comment and gst_element_class_add_meta_data(). Also now using a gpointer in the public headers and casting in the implementation.
> Created an attachment (id=169369) [details] [review]
> allow arbitrary plugin metadata
>
> Fixed and // comment and gst_element_class_add_meta_data(). Also now using a
> gpointer in the public headers and casting in the implementation.
Looks ok to me. Three more comments:
- maybe make gst-inspect only use the public API for now?
(since we don't support arbitrary keys, there's no need to
iterate yet, so it's safer not to do the cast to GstStructure
here, for the unlikely corner case where
gst-inspect version != libgstreamer version)
- is the deserialisation of an empty meta string correct here?
- lastly, we could put the GstStructure * into a GstElementFactoryPrivate
instead, then we keep it private but also don't need the casts
(sorry, didn't think of that before)
* moving meta_data to GstElementFactoryPrivate, break serialisation for the registry.
* the empty string serialization is okay (used already like this for plugin->cache_data)
* I'll keep the gst-inspect like it for simplicity, lets change that as soon as we add a first !string detail
commit 65356fbb7a74568cd528907c12f77eb6a42e7ad7
Author: Stefan Kost <ensonic@users.sf.net>
Date: Tue Aug 10 14:05:22 2010 +0300
element-details: allow for arbitrary element details
Add a GstStructure to GstElementClass and GstElementFactory. Add setters/getter.
Handle it in the registry code. Print items in gst-inspect.
Fixes #396774.
API: gst_element_class_set_XXX(), gst_element_factory_get_XXX()
Irks. Just after pushing, I noticed that I have not updated the API: comment in the commit :/
Comment on attachment 169369 [details] [review]
allow arbitrary plugin metadata
committed with small cleanup (win32 update and small serialisation change)
That commit broke the build (because it uses an uninitialized variable).
commit c5888dc6cf686bd150bd3b835a7abb256b371147
Author: Olivier Crête <olivier.crete@collabora.co.uk>
Date: Mon Sep 6 14:09:52 2010 +0300
registrychunks: Use the correct variable for debug message
Debug print was using a variable that was not initialized.
|
https://bugzilla.gnome.org/show_bug.cgi?id=396774
|
CC-MAIN-2021-39
|
refinedweb
| 2,670
| 55.54
|
Counting.
Here is the source code of the C program to sort integers using Counting Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
void countingsort(int arr[], int k, int n)
{
int i, j;
int B[15], C[100];
for (i = 0; i <= k; i++)
C[i] = 0;
for (j =1; j <= n; j++)
C[arr[j]] = C[arr[j]] + 1;
for (i = 1; i <= k; i++)
C[i] = C[i] + C[i-1];
for (j = n; j >= 1; j--)
{
B[C[arr[j]]] = arr[j];
C[arr[j]] = C[arr[j]] - 1;
}
printf("\nThe Sorted array is :\n");
for(i = 1; i <= n; i++)
printf(" %d", B[i]);
}
int main()
{
int n,i,k = 0, arr[15];
printf("Enter the number of elements : ");
scanf("%d", &n);
printf("\n\nEnter the elements to be sorted :\n");
for ( i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
if (arr[i] > k)
{
k = arr[i];
}
}
countingsort(arr, k, n);
return 0;
}
$ gcc countsort.c -o countsort $ ./countsort Enter the number of elements : 10 Enter the elements to be sorted : 8 11 34 2 1 5 4 9 6 47 The Sorted array is : 1 2 4 5 6 8 9 11 34 47
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.
|
http://www.sanfoundry.com/c-program-perform-sorting-using-counting-sort/
|
CC-MAIN-2017-39
|
refinedweb
| 240
| 59.06
|
Many programming languages require parentheses around the
if condition.
For example:
if (x < 50) { }
Why can't it be written like this, without the parentheses:
if x < 50 { }
Assuming that language designers are pragmatic people, why are the parentheses required?
Simple answer: operator precedence. Remember basic highschool/elementary math: What's the answer for
7 * 4 + 3? 31? or 49?
Braces allow you to impose your OWN precedence, to override what the language's natural precedence would be:
(7 * 4) + 3 -> 31 (the natural answer by BEDMAS rules) 7 * (4 + 3) -> 49
If you're talking about the
{}, then that's to allow a multi-line block for the expression.
No braces:
if (...) a = 1; // only this line is part of the "if" b = 1; // ignore the indentation - this is always executed
v.s.
if (...) { a = 1; // part of the "if" b = 1; // also part of the "if" }
In C,
if takes actually a comma-operator, instead of just an expression. One can write:
int i = 0; if (i = i + 1, i/2 > 0) { }
So you need braces (parenthesis actually) here. The same is true for
while() for example.
return operator in C however accepts just an expression, so it does not require parenthesis:
return i + 1;
though many programmers still write it like:
return (i + 1);
|
http://www.devsplanet.com/question/35273091
|
CC-MAIN-2017-04
|
refinedweb
| 217
| 60.85
|
How do I write a multi-line string literal in C?
What ways do we have to define large string literals in C? Let’s take this example:
#include <stdio.h> char* my_str = "Here is the first line.\nHere is the second line."; int main(void) { printf("%s\n", my_str); return 0; }
We could first try to split this up as:
char* my_str = "Here is the first line. Here is the second line.";
This causes a parse error, because literal newline characters are not allowed within the quote.
We can use string literal concatenation. Multiple string literals in a row are joined together:
char* my_str = "Here is the first line." "Here is the second line.";
But wait! This doesn’t include the newline character; we still have to include it:
char* my_str = "Here is the first line.\n" "Here is the second line.";
We can also use the backslash character at the end of a line:
char* my_str = "Here is the first line.\ Here is the second line.";
This also doesn’t include the newline! We have to include again:
char* my_str = "Here is the first line.\n\ Here is the second line.";
Apparently in C++11 and in GCC with extensions, we can write “raw strings” like this:
char* my_str = R"Here is the first line. Here is the second line.";
However,
clang doesn’t seem to like this.
The “concatenated string literals” approach has the added advantage of being able to indent the string in your code. I’d use.
|
https://jameshfisher.com/2016/11/30/c-multiline-literal/
|
CC-MAIN-2019-22
|
refinedweb
| 252
| 85.89
|
Security
The /tmp directory has been an unceasing source of security
problems going back decades; there are still regular
reports of vulnerabilities from insecure usage of temporary files. Part of
the problem is that /tmp (and /var/tmp) are shared
resources that can be written to by any process, which allows attackers to
use various
race conditions (typically time-of-check-to-time-of-use (TOCTTOU) races) in
insecurely written programs to elevate their privileges. It is a bit
ironic, then, that a utility specifically geared toward running a program
with a private /tmp directory (for application sandboxing) would
run afoul of a somewhat different kind of temporary file
vulnerability—one that was long-ago excised by the advent of "sticky"
directories. But that is just
what Tavis Ormandy found.
The basic problem is that insecure programs often open files in
/tmp after checking to see whether the file exists. In the window
between the time that the test is done and the time that the file is
opened, a malicious program can swap in a file of its choosing (or, more
likely, a symbolic or hard link to a file of its choosing). When that
happens, the
buggy program is operating on a file that it does not expect and that
can cause
all manner of mayhem. For normally privileged programs, that mayhem is
largely restricted, but for setuid programs, it can lead to full system
compromise.
Long ago, attackers could use the world-writable attribute of /tmp
to delete files that were created by setuid programs. The attacker could
then replace the file with a link, and when a privileged program
re-opened the file—something that is, in general, a bad practice with
temporary files—it would be opening a file of the attacker's
choice. But, the advent of
the "sticky" bit as applied to directory permissions closed that
loophole by only allowing the file owner (or root) to delete a file in a
sticky directory. Since that time, lots of code has been written with a
sticky /tmp directory in mind.
As part of its efforts to use SELinux to provide application sandboxes, Red
Hat created the seunshare utility. That utility will run a
command with alternate /tmp and home directories, along with a
given SELinux context. seunshare will "unshare" the default
mount namespace (so that the command has its own view of the filesystem
hierarchy), mount the specified
directories over top of /tmp and the home directory, and instruct
the kernel to execute the command in the (optionally) given SELinux
context. Since the temporary directory specified is under the control of
the user, it doesn't necessarily have the sticky bit set, which leads to
the vulnerability.
In Ormandy's example, he uses ksu to show how the
/etc/passwd file could be overwritten by running ksu under
seunshare. There are likely other setuid programs that make the
assumption that their temporary files are in sticky directories, and quite
possibly some where the consequences could be more severe than just
trashing the password file. So a mechanism that was meant to provide
more security actually left a hole behind. Unfortunately, this is
not an uncommon occurrence in the security
realm.
This particular case also shows the value of disclosing security
vulnerabilities. Ormandy reported the bug back in
September and, though there was a flurry of discussion about it, that
discussion died off in late November (at least in the bug report). Things
didn't pick up again until Ormandy posted
a request for an update, along with notice that he was ready to publish
an advisory, on February 18. Hearing no complaint, he did so on February 23.
After that, the discussion picked up again, with solutions being proposed,
though no
fix is yet available for Fedora or RHEL. One has to wonder how long this
potential local privilege escalation might have languished had Ormandy not
released his advisory. As a temporary mitigation, Ormandy suggests
removing the setuid bit from seunshare or restricting access to
it. The solution that Dan Walsh has proposed removes the
-t tmpdir argument to seunshare and instead mounts a
tmpfs on /tmp (with the sticky bit set). Presumably that
will be released in the near future.
There has been an attempt to harden the
behavior of sticky directories to try to avoid some of the longstanding
/tmp directory problems—though that would not have thwarted
this particular vulnerability because it relies on the directory being
sticky. There has been resistance to that effort because it is seen as
something of an ugly hack to work around badly written code, so it has not
made it into the mainline (though Ubuntu and other kernels do have that
hardening). But temporary file vulnerabilities of various sorts still rear
their head with depressing frequency. We will undoubtedly see others crop
up in the future.
Brief items
Mozilla has released Firefox 3.6.14 and
3.5.17 and Thunderbird 3.1.8, each of
which fix some security vulnerabilities, including some that are
marked "critical". Mozilla strongly recommends that all users upgrade to
the new releases. Each Firefox release fixes eight critical, one high, and
one moderate vulnerability (3.6.14,
3.5.17),
while the Thunderbird release fixes two critical, and one moderate flaw (3.1.8).
New vulnerabilities
Abcm2ps upstream has released latest v5.9.13 version,
fixing "yet more multiple unspecified vulnerabilities":
From the Red Hat advisory:
A specially-crafted PDF file could cause Adobe Reader to crash or,
potentially, execute arbitrary code as the user running Adobe Reader when
opened. (CVE-2011-0562, CVE-2011-0563, CVE-2011-0565, CVE-2011-0566,
CVE-2011-0567, CVE-2011-0585, CVE-2011-0586, CVE-2011-0589, CVE-2011-0590,
CVE-2011-0591, CVE-2011-0592, CVE-2011-0593, CVE-2011-0594, CVE-2011-0595,
CVE-2011-0596, CVE-2011-0598, CVE-2011-0599, CVE-2011-0600, CVE-2011-0602,
CVE-2011-0603, CVE-2011-0606)
Multiple security flaws were found in Adobe reader. A specially-crafted PDF
file could cause cross-site scripting (XSS) attacks against the user
running Adobe Reader when opened. (CVE-2011-0587, CVE-2011-0604)
From the Mandriva advisory:-2011-1002).
It was discovered that the Microsoft Office processing code in libclamav
improperly handled certain Visual Basic for Applications (VBA) data. This
could allow a remote attacker to craft a document that could crash clamav
or possibly execute arbitrary code.)
It was discovered that FUSE would incorrectly follow symlinks when checking
mountpoints under certain conditions. A local attacker, with access to use
FUSE, could unmount arbitrary locations, leading to a denial of service.
CVE-2010-4540 gimp LIGHTING EFFECTS > LIGHT plugin stack buffer overflow
CVE-2010-4541 gimp SPHERE DESIGNER plugin stack buffer overflow
CVE-2010-4542 gimp GFIG plugin stack buffer overflow
CVE-2010-4543 gimp heap overflow read_channel_data() in file-psp.c.
The JNLPClassLoader class in IcedTea-Web before 1.0.1, as used in OpenJDK Runtime Environment 1.6.0, allows remote attackers to gain privileges via unknown vectors related to multiple signers and the assignment of "an inappropriate security descriptor."
It was discovered that pam-pgsql, a PAM module to authenticate using
a PostgreSQL database, was vulnerable to a buffer overflow in supplied
IP-addresses..
PHP Exif extension for 64bit platforms is affected by a casting
vulnerability that occurs during the image header parsing.
A symlink race condition vulnerability was found in
FileUtils.remove_entry_secure. The vulnerability allows local users to
delete arbitrary files and directories. (CVE-2011-1004)
Exception#to_s method can be used to trick $SAFE check, which makes a
untrusted codes to modify arbitrary strings. (CVE-2011-1005).
An attacker can invite the victim to open a DCT3 capture with Wireshark,
in order to create an overflow, leading to a denial of service or to
code execution.
Page editor: Jake Edge
Kernel development
The current development kernel is 2.6.38-rc7, released on March 1. ." Full details can be found in the
long-format changelog.
Stable updates: The 2.6.37.2 stable kernel was
released on February 24. The 2.6.32.30 longterm kernel was
released on
March 2, with a note of appreciation: ."
Just to answer your last question, we do not intend to "slow it
down". Rather, we hope to speed it up considerably by adding
developers, testing and users.
Full Story (comments: 28).
Kernel development news
This article was contributed by John Stultz
But let's just say, if you were an extraordinary cat-napper, and you had
some downtime between numerous kernel compiles while doing a long
git-bisect: You could make it work, but first you would need a good alarm
clock. The same can be said of computers.
The RTC (Real Time Clock) is a fairly minor bit of hardware on your
computer. It usually keeps track of the wall-clock time while the system is
off or suspended. It also can be used to generate interrupts in a number of
different modes (periodic, one-shot alarm, etc). This is all fairly normal
functionality
for a hardware timer device. But one of the most interesting features that
most modern RTCs support is that an alarm interrupt can be generated even
when the system is suspended (or in some hardware hibernation) forcing the
machine to wake up.
On Linux the RTC is exposed to user space via the generic RTC driver
infrastructure, which creates sysfs entries and a character device which
can be used to set hardware alarms, change the interrupt mode, etc. A
few applications out there make use of this interface, such as MythTV DVRs, which can trigger alarms so
that media computers can be suspended until the start of a TV show that
needs to be recorded.
The exposed interface is very much a low-level driver interface, where the
values written by the application are sent directly to the hardware. This
is a limitation, as it makes it so only one application at a time can
program alarm events to an RTC device. For instance, with only a single
RTC device, you can't have your system wake up for a nightly backup and
also have it wake up to record your favorite show, unless you have some
sort of centralized process managing the wakeups on behalf of other
applications. Tutorials such as this
one illustrate how complex and limiting this interface can be.
One way to overcome these limitations is to allow the kernel to manage a
list of events and have it program the RTC so the alarm will trigger for
the earliest event in the list. This avoids the need for user space
applications to coordinate in order to share the hardware. To make this
sharing possible, a generic "timerqueue" abstraction has been created to
manage a simple list of timers that could then be shared with other areas
of the kernel, like the high-resolution timers subsystem, that also have to
manage timer events. This code was merged for 2.6.38.
The next step is to rework the RTC code so that, when an alarm is set via
the character device ioctl() or sysfs interface, an rtc_timer
event is created and enqueued into the per-RTC timerqueue instead of
directly programming the hardware. The kernel then sets the hardware timer
to fire for the earliest event in the queue. In effect, this mechanism
virtualizes the RTC hardware, preserving the behavior of the existing
hardware-oriented
interfaces, while allowing the kernel to multiplex other events using the
RTC.
The question now becomes, how to expose this new functionality so it can be used?
The first approach tried was exporting the new RTC functionality to user space
directly via the POSIX clocks and timers interface. With this approach,
there is a "clockid" assigned to each RTC device, so a user space application
can use the POSIX interfaces to access the RTC. In this
approach, clock_gettime() returns the current RTC time,
clock_settime()
sets the RTC time, and timer_settime() sets a POSIX timer to expire when
the RTC reaches the desired time.
This approach is the most straightforward method of exposing the RTC, but
it does have some disadvantages. Specifically, the RTC and system time may
not be the same. On many systems, the RTC is set to local time rather than
universal time. Thus, applications would need to make the extra effort to
read the
RTC and add to that value the time between now and when they want the
timer to fire. Also, the RTC, due to simple clock skew, may not increase at
the exact same rate as the system time. Additionally, since there may be
multiple RTCs on a system, a single static CLOCK_RTC clockid would not be
sufficient. Some form of dynamic clock_id registration is needed in order
to export multiple clockids for multiple RTC devices. This functionality
is desired for exposing other hardware clocks via the POSIX interface, and
it is currently a work-in-progress
by Richard Cochran.
Interestingly, the developers who have been working on Android have
extended the RTC to be more useful as well. After all, smartphones are
optimized to save power, so they try to stay in suspend as much as
possible. But smartphones still have to wake up to do things like notify
the user of calendar events or to check for email. In order to do this,
The Android team introduced a concept called Android
Alarm Timers. These timers use a hybrid approach: when when the system
is running, alarm timers trigger a high-res timer to fire when an event is
supposed to run; however, when the system goes into suspend, the alarm timers
code looks at the list of events and sets the RTC to fire an alarm when the
earliest event is to run. This avoids making applications deal with the
(possibly unsyncronized) RTC time domain and allows applications to simply
set timers and have them fire when expected, whether or not the system is
suspended.
While never submitted to the kernel mailing list for inclusion, the Android
Alarm Timers implementation would likely meet some resistance from the
kernel community. For instance, the user-space interface for applications
to use the Android Alarm Timers is via ioctl() to a new special character
device (/dev/alarm) instead of using existing system call
interfaces. Additionally, the ioctl() interface introduces new names for
existing concepts in the kernel, duplicating CLOCK_REALTIME (which provides
UTC wall time) and CLOCK_MONOTONIC (which counts from zero starting at system
boot, and is not modified by settimeofday() calls)
via the names ANDROID_ALARM_RTC and ANDROID_ALARM_SYSTEMTIME respectively.
The Android Alarm Timers interface does introduce some new useful
concepts. For instance, the CLOCK_MONOTONIC clock does not increment during
suspend. This is reasonable behavior when you want suspend to be
transparent to applications, but when the system spends the majority of its
time in suspend and you want to schedule events that wake the system up
having only CLOCK_REALTIME increment over suspend can be limiting. So
Android Alarm Timers introduces the ANDROID_ALARM_ELAPSED_REALTIME clock,
which is similar to CLOCK_MONOTONIC, but includes time spent in suspend.
But again, it is only introduced via an ioctl() to their special
character
device, and is not exposed via any other standard timekeeping interface.
All in all, the Android Alarm Timers are a very interesting use case, and
others in the community have suggested a similar hybrid approach. Inspired
by the Android Alarm Timers, I implemented a similar hybrid alarm timers
infrastructure on top of the previously-described work virtualizing the RTC
interface. However, these timers are exposed to user space via the standard
POSIX clocks and timers interface, using the new the CLOCK_REALTIME_ALARM
clockid. The new clockid behaves identically to CLOCK_REALTIME except that
timers set against the _ALARM clockid will wake the system if it is
suspended. Additionally, because it's built upon the virtualized
rtc_timers
work, this implementation doesn't prohibit applications from making use of
the existing legacy RTC interfaces. This gives us all the benefits of
Android Alarm Timers, such as not forcing applications to deal with the RTC
time domain, while making better use of existing kernel interfaces.
The code that implements the timerqueues and reworks the generic
RTC layer to allow for multiplexing of events has been included in the
2.6.38 kernel release. The POSIX alarm timers layer will likely need
additional review and discussion, in hopes of making sure the Android
developers are able to assess compatibility issues in the design. For
instance, I've proposed a new POSIX clock (CLOCK_BOOTTIME,
along with a corresponding CLOCK_BOOTTIME_ALARM id) which would provide
the incrementing-in-suspend value that the Android developers
introduced with ANDROID_ALARM_ELAPSED_REALTIME. Also, while not likely to
be included into mainline, Android's wakelocks have some interesting
semantics with regards to their alarm timer interface. These semantics are
not easily satisfied by the posix timers interface, but it is to be
determined if we can get equivalent functionality using modified semantics
and the mainline kernel's pm_wakeup
interface.
Other open questions that need to be addressed are:
I also can imagine some interesting future work combining this
functionality with the "Wake on Directed Packet" feature of some new
network cards, which wake the system up any time a packet is sent to it.
This feature could be used to
allow web servers to function normally, servicing requests and running
jobs, while suspending and saving power during longer idle periods.
While I might not be able to sleep on the job, I look forward to my desktop
system being able to snooze and save electricity while knowing that cron
jobs like nightly backups, downloading package updates or running updatedb
will still be done.
Linux capabilities are still a work in progress. They have been in the
kernel for a long time—since the 2.1 days in 1998—but
for various reasons, it has taken more than a decade for distributions to
really
start using the feature. While capabilities ostensibly provide a way to
give limited privileges to processes, rather than the all-or-none setuid
model, the feature has been beset with incompleteness, limitations,
complexity concerns,
and other problems. Now that Fedora, Openwall, and other distributions are
working on
actually using capabilities to reduce the privileges extended to
system binaries we are seeing some of those problems shake out.
A patch
that was merged for 2.6.32 is one such example. The idea behind it was
that the CAP_NET_ADMIN capability should be enough to allow
The CAP_SYS_MODULE capability allows loading modules from
anywhere, rather than restricting the module search path to
/lib/modules/.... So, by switching to use CAP_NET_ADMIN,
network utilities, like ifconfig, could be restricted to only load
system modules, rather than arbitrary code.
There is one problem with that scheme, though, as Vasiliy Kulikov pointed out, because it allows processes with
CAP_NET_ADMIN to load any module from /lib/modules, not
just those that are networking related. Or, as he puts it:
root@albatros:~# grep Cap /proc/$$/status
CapInh: 0000000000000000
CapPrm: fffffffc00001000
CapEff: fffffffc00001000
CapBnd: fffffffc00001000
root@albatros:~# lsmod | grep xfs
root@albatros:~# ifconfig xfs
xfs: error fetching interface information: Device not found
root@albatros:~# lsmod | grep xfs
xfs 767011 0
exportfs 4226 2 xfs,nfsd
That example deserves a bit of explanation. The first command
establishes that the capabilities of the shell are just
CAP_NET_ADMIN (capability number 12 of the 34 currently defined
capabilities). Kulikov then goes on to show that the xfs module is not
loaded until he loads it via ifconfig. That is clearly not
the expected behavior. In fact it is now CVE-2011-1019
(which is just reserved at the time of this writing). For those that want
to try this out at home, Kulikov gives the proper incantation in his v2 patch:
# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) --
Note that on not-quite-bleeding-edge kernels (e.g. Fedora 14's kernel), the
34 should be changed to 33 to account for the lack of a
CAP_SYSLOG, which was just recently added. Running that command
will give you a shell with just CAP_NET_ADMIN.
Kulikov's first patch proposal simply
changed the request_module() call in the core networking
dev_load() function to only load modules that start with "netdev-",
with udev expected to set up the appropriate aliases. There are three
modules that already have aliases (ip_gre.c, ipip.c, and
sit.c) in the code, so the patch changes those to prefix
"netdev-". But David Miller was not happy with changing those names, as it
will break existing code.
There was also a bit of a digression regarding attackers recompiling
modules with a "netdev-" alias, but unless that attacker can install the
code in /lib/modules, it isn't a real problem. In this case, the
threat model is a subverted binary that has CAP_NET_ADMIN, which
is not a capability that would allow it to write to
/lib/modules. But Miller's
complaint is more substantial, as anything that used to do
"ifconfig sit0", for example, will no longer work.
After some discussion of various ways to handle that problem, Arnd Bergmann
noted that the backward compatibility
problem is only for systems that are not splitting up capabilities
(i.e. they just use root or setuid with the full capability set). For
those, the CAP_SYS_MODULE capability can be required, while the
programs that only have CAP_NET_ADMIN will be new, and thus can use the
new "netdev-" names. The code
will look something like:", name);
That solution seemed to be acceptable to Miller and others, so we may well
see it in the mainline soon. One thing to note, though, is that
capabilities are part of the kernel ABI, so changes to their behavior will
be difficult to sell, in general. This change is fixing a security
problem—and is hopefully not a behavior that any user-space application
is relying on—so it is likely to find a reasonably smooth path into
the kernel. Other changes that come up as more systems start to actually
use the various capability bits may be more difficult to do, though
we have already seen some problems
with the current definitions of various capabilities.
The 2.6.38 cycle has seen 9,148 non-merge changesets from 1,136 developers
(again, as of this writing). Compared to 2.6.37 (11,446 changesets from
1,276 developers) those numbers may seem small, but they are on a par with
most other recent kernel releases:
ReleaseChangesDevs
2.6.349,4431,151
2.6.359,8011,188
2.6.369,5011,176
2.6.3711,4461,276
2.6.389,1481,136
603,000 lines of code were added in this cycle, and 312,000 were removed,
for a net growth of 291,000 lines of code. The most active contributors of
that code were:
Most active 2.6.38 developers
By changesets
Joe Perches1992.2%
Chris Wilson1822.0%
Russell King1471.6%
Mark Brown1431.6%
Tejun Heo1071.2%
Ben Skeggs1071.2%
Alex Deucher971.1%
Eric Dumazet881.0%
Felix Fietkau881.0%
Mauro Carvalho Chehab830.9%
Thomas Gleixner790.9%
Jesper Juhl750.8%
Lennert Buytenhek720.8%
Johannes Berg700.8%
Stephen Hemminger700.8%
Al Viro680.7%
Andrea Arcangeli670.7%
Clemens Ladisch660.7%
Uwe Kleine-König660.7%
Nick Piggin650.7%
By changed lines
Vladislav Zolotarov425245.8%
Nicholas Bellinger307974.2%
Larry Finger234393.2%
Hans Verkuil209782.9%
Barry Song141741.9%
Dimitris Papastamos127941.7%
Ben Skeggs116511.6%
Rafał Miłecki111491.5%
Sven Eckelmann110811.5%
Mike Frysinger106921.5%
Sonic Zhang83601.1%
Michael Chan82801.1%
Chris Wilson81641.1%
Mark Brown76901.0%
Chuck Lever74571.0%
Joe Perches71851.0%
Shawn Guo64400.9%
Paul Walmsley56710.8%
Mark Allyn54240.7%
Nick Piggin54020.7%
Joe Perches made it to the top of the "by changesets" with a long list of
patches removing excess semicolons and casts, adding "static"
keywords, and other things of that nature. Chris Wilson's changes were
entirely in the Intel graphics driver subsystem, Russell King remains
active as the lead ARM maintainer, Mark Brown does large amounts of work in
the sound driver subsystem, and Tejun Heo had patches all over the tree,
most of which are related to cleaning up workqueue usage.
Vladislav Zolotarov's path to the top of the "lines changed" column
ostensibly should not exist anymore; among his many bnx2x driver changes
was a large firmware replacement. Nicholas Bellinger is the main author of
the LIO SCSI target patches which were merged, after extensive discussion,
for 2.6.38. Larry Finger added the Realtek RTL8192CE/RTL8188SE wireless
network adapter to the staging tree, Hans Verkuil continues his work
straightening out the Video4Linux2 subsystem, and Barry Song added a number
of IIO drivers to the staging tree.
Work on 2.6.38 was supported by a minimum of 180 employers, the most active
of whom were:
Most active 2.6.38 employers
By changesets
(None)154416.9%
Red Hat114512.5%
Intel6647.3%
(Unknown)6547.1%
Novell3834.2%
IBM3343.7%
(Consultant)3153.4%
Texas Instruments2903.2%
AMD1842.0%
Broadcom1721.9%
Wolfson Micro1701.9%
Nokia1691.8%
Oracle1361.5%
Samsung1331.5%
Google1331.5%
Atheros1321.4%
Analog Devices1151.3%
Fujitsu1121.2%
Pengutronix1091.2%
Renesas Tech.1071.2%
By lines changed
(None)13390218.2%
Broadcom9731713.2%
Red Hat565617.7%
Intel446506.1%
Analog Devices410835.6%
Rising Tide Systems318694.3%
(Unknown)304624.1%
Wolfson Micro251673.4%
Texas Instruments241933.3%
IBM161242.2%
Novell139391.9%
(Consultant)137891.9%
Freescale114541.6%
Nokia105351.4%
Oracle104151.4%
ST Ericsson95211.3%
Renesas Tech.85341.2%
Samsung79881.1%
AMD79501.1%
Oki Semiconductor70871.0%
The most significant new entry is Rising Tide Systems, a storage array
company which, unsurprisingly, has an interest in the kernel's SCSI target
implementation. Otherwise, the entries at the top of the table have changed
little over the last few
years; here is a plot showing the trends since 2.6.28:
There is a certain amount of noise, but, over this entire period, non-paid
contributors are at the top of the list, followed by Red Hat and Intel, in
that order. The most significant trends, perhaps, are TI's steady increase
over time, and IBM's slow decline.
Regardless of what individual companies do, though, the real picture that
emerges from this data is that the kernel development process remains
strong and active. The rate of change remains high, and the community from
which those changes come remains large and diverse. There may come a time
when the kernel community runs out of ideas and things to do, but it does
not seem that things will slow down anytime soon.
[As always, thanks are due to Greg Kroah-Hartman for his assistance in the
creation of these numbers. The tool used to calculate these statistics is
"gitdm"; it can be had at git://git.lwn.net/gitdm.git. The associated
configuration files can be downloaded here.]
Patches and updates
Kernel trees
Architecture-specific
Core kernel code
Development tools
Device drivers
Filesystems and block I/O
Memory management
Networking
Security-related
Virtualization and containers
Miscellaneous
Page editor: Jonathan Corbet
Distributions
This article was contributed by Don Marti
Fedora engineering manager Tom "spot" Callaway, who actively maintains a
Fedora-compatible package repository for the Chromium
web browser, said Friday he has "given
up" on getting the browser — which does
work well on Fedora — into the distribution
proper. In November 2009, he explained
why Chromium is not an official Fedora package on his blog, and those
issues remain. In a talk at the Southern
California Linux Expo (SCALE) entitled, "This
is why you FAIL," Callaway, who maintains more
than 350 packages in Fedora, listed some of what he
sees as "points of FAIL," or distribution-unfriendly
software development practices, using Chromium as an
example for many of them.
"Having your software be distribution-friendly
is a key to success," he said. In the Fedora
Activity Day event earlier at SCALE,
users brought in systems in a variety of "states
of disrepair", he said, which were caused by attempting to install
third-party software. Distribution-friendliness also
reflects on other channels, he said. The same "points
of FAIL" that affect distribution maintainers are also
problems for intermediaries who are putting the software on
embedded devices or running it as a hosted service.
In the talk, which summarized his chapter, "How
to tell if a FLOSS project is doomed to FAIL"
from the book The Open Source
Way,
Callaway discussed the bundled dependency problem.
It's worth FAIL points to include a private
copy of a library on which a program depends,
and extra FAIL points for building a modified
version. A key problem, Callaway said, is that
when a distribution does a security update for a
library, it also has to do updates for any packages
that include their own copies. (Fedora has a No
Bundled Libraries policy, and Fedora package
maintainers do modify the build process for software that the distribution
packages, in order to make it build with a system copy of the library.)
"Chromium
is perhaps the worst offender I have ever seen in my
entire career," Callaway said.
Chromium developer Evan
Martin, who was not
at the event but had posted
a list of third-party code distributed with
Chromium on his
blog, replied to
that in email:
Callaway did recognize that some versions of
system libraries might not work. The build process
should make the system copy the default, though.
If the build configuration comes up with "I found this
library and I can't use it because it has rabies or
something," then it could build an alternate copy.
Martin said that the Chromium team is willing to
accept outside contributions to facilitate this:
Chromium requires a copyright assignment agreement for
code changes, which Callaway said he has not accepted.
"After review with
a lawyer, they advised me that agreeing to that
would give Google a license to use my contributions
under any copyright license terms that they'd like,
including non-free terms," he said later. "I'd be
more than willing to give them my changes under the
terms of a Free license, but Google wants to continue
to distribute a proprietary version of their browser
(Google Chrome), and I have no interest whatsoever
in helping them with that effort," he added.
Much of the advice in Callaway's talk applied not
to large-scale projects like Chromium, but to new,
lower-profile projects. He reserved some of the
FAIL warnings for projects that don't offer basic
documentation, such as how to do a build and how to
begin interacting with the source control system.
"Lots of programmers coming through school have never
seen a source control system," he said. A project
web site should include instructions for how to check
out the code and how the project wants to receive incoming
code changes. It also counts for substantial FAIL if
"all your web site has is a picture of a marijuana
leaf," as he said one small-scale open source project does.
The build and install process is another key
area. "If your code forces an install into /opt or
/usr/local you're probably running Oracle and I'm
very very sorry," he said. Running "make install"
should just work. "Make the decision that you're
going to have an installable program that works
outside the source directory."
Some software comes in a problematic archive format;
RAR archives are a problem, he said, because the
format is proprietary. A developer once asked
Callaway about making Fedora packages for his new
archiving tool, which came in an archive created
by the same tool. "He didn't see why this was a
problem and I couldn't tell him because I was crying,"
Callaway said.
A history of having been proprietary is worth
more fail the longer it was proprietary before the
initial open source release. "Red Hat has bought
some real shiny turds," he said, giving Netscape's
backyard," he said.
The good news is that many of the points of FAIL
are relatively easy to correct. Including a copy of
the software license and setting up a mailing list
are minor tasks. The bundled dependency problem,
on the other hand, has turned out to require lots of
skilled attention from both the project maintainers
and distributions, so that one is still with us.
Both library-bundlers and library-splitters have
their points. Bundling creates more long-term
issues for administrators, but library-splitting
takes up valuable development time, especially for
cross-platform projects that need to bundle the
libraries for target platforms that don't
practice library splitting. But bundled libraries are a problem for many
Linux distributions and one that we will
likely be facing for some time to come.
Full Story (comments: none)
Distribution News
Debian GNU/Linux
Red Hat Enterprise Linux
Newsletters and articles of interest
Page editor: Rebecca Sobol
Development
This article was contributed by Koen Vervloesem
Portability is a key concept in the open source ecosystem. Thanks to
this killer feature, your author has migrated his desktop operating system
during the last ten years from Mac OS X to Linux (various distributions)
and eventually to FreeBSD, but throughout that process he could keep using
most of the same applications. When you present a recent openSUSE or PC-BSD desktop system to a computer
newbie, they won't notice much difference, apart from a different desktop
theme, perhaps. The same applications (OpenOffice.org, Firefox, K3b,
Dolphin, and so on) will be available. In many circumstances, it just
doesn't matter whether your operating system is using a Linux or FreeBSD
kernel, as long as it has drivers for your hardware (and that's the catch).
This portability, however, is not always easy to achieve. Now that Linux
is the most popular free Unix-like operating system, it shouldn't be a
surprise that some projects have begun treating non-Linux operating systems as second-class citizens. This isn't out of contempt for the BSDs or OpenSolaris, it's just a matter of limited manpower: if almost all the users of the application have a Linux operating system and if all the core developers are using Linux themselves, it's difficult to keep supporting other operating systems. But sometimes the choice to leave out support for other operating systems is explicitly made, e.g. when the developers want to implement some innovative features that require functionality that is (at least for now) only available in the Linux kernel.
In January, version 4.8 of the Xfce
desktop environment was released. In the beginning of its announcement, the developers expressed their disappointment that they couldn't offer all the new features of the release on the BSDs:
This somewhat cryptic remark was followed by a summary of the new
features, but it was clear that it was aimed at the new desktop frameworks
introduced in the last few years, such as udev, ConsoleKit and PolicyKit. udev is only available on Linux, but both ConsoleKit and PolicyKit are already supported by FreeBSD, so as LWN.net commenter "JohnLenz" supposed correctly in a comment on the announcement, the problem is for a large part on the testing side: how many FreeBSD users are using these frameworks? And how many of them test these frameworks regularly and spend the time to report bugs?
The remark in the release announcement probably puzzled a lot of BSD
enthusiasts as well, because Xfce developer Jannis Pohlmann followed up a few days later with an explanation on his personal blog. There he named udev as the culprit for the non-portability of some Xfce features:
But then Pohlmann points to the broader context:
Some Linux users, who may be used to six-month release cycles, might not
see a problem here, as they now have all those new features. But the BSD operating systems generally have a much slower development life cycle and haven't caught up yet with the whole redesign of the desktop stack. The comments on Pohlmann's blog post are instructive in this regard (although somewhat degenerating into a flame war at the end). For example, one commenter points out that HAL did acquire BSD (and Solaris) support, but only years after it had been mainstream in the Linux world, and the BSD developers only contributed the necessary patches to make it work when Gnome and KDE started making HAL mandatory.
The problem seems to be that udev is not as easy to port to non-Linux systems as HAL was. FreeBSD has the devd daemon to handle volume mounting, but devd's author Warner Losh commented that udev is not well documented, which hampers efforts to port it. However, this didn't stop Alex Hornung from porting udev to DragonFly BSD, although it's not yet a full drop-in replacement. The FreeBSD developers could take a look at his work, as DragonFlyBSD is a FreeBSD derivative.
OpenBSD developer Marc Espie also points to license
issues: udev and other software close to the Linux kernel is using
GPLv2, which the BSDs don't like to use. For example, OpenBSD developers
don't add a component to the base system if it's less free than the BSD
license, and the GPL is such a license in their eyes. However, the current
problems are also clearly a consequence of different
development styles. Components like udisks are part
of the Freedesktop specifications
(which are supposed to keep X Window System desktops interoperable), but
the BSD developers didn't seem to participate in that effort. Maybe the PC-BSD developers can play a role in this, as they want to deliver a modern desktop operating system based on FreeBSD.
All in all, there are two possible solutions to a situation like the one
the Xfce 4.8 release is facing. One solution is that the Xfce developers
create an abstraction layer supported by as many operating systems as
possible. The problem is that currently there is no such abstraction layer
for detecting devices, which makes it perfectly understandable that the
Xfce developers chose udev. It is used by their major development platform,
Linux, and one can't expect them to support frameworks on operating systems they don't use. So the other solution is that some BSD developers port udev to their operating system, which is non-trivial but (as the incomplete DragonFly BSD port shows) doable, or that they propose an abstraction layer that could be supported on non-Linux platforms. As many desktop applications have already been rewritten in the last few years from using HAL to using udev, the latter won't be a popular choice and isn't likely to happen.
Another important desktop component that is becoming more and more
Linux-centric in recent years is X.Org. Recent open source video drivers
(such as the Nouveau driver) require kernel mode setting (KMS), which is a
problem for the BSDs and OpenSolaris, as these operating systems lack
kernel support for KMS and Graphics Execution Manager (GEM). So a FreeBSD
user who wants to get decent performance out of an Nvidia graphics card,
currently has to use the proprietary driver. Fortunately, the FreeBSD Foundation recognized
the gravity of this situation and announced last year that it was willing
to sponsor a developer to work on KMS and GEM support in the FreeBSD
kernel. Last month, the foundation announced
that it had awarded a grant, co-sponsored by iXsystems (the developers of PC-BSD)
to Russian developer Konstantin Belousov to implement support for GEM, KMS,
and Direct Rendering Infrastructure (DRI) for Intel hardware. Matt Olander, Chief Technology Officer at iXsystems, says in the announcement:
More specifically, Belousov will implement GEM, port KMS, and write new DRI drivers for Intel graphics cards, including the latest Sandy Bridge generation of integrated graphic units. After this work, users should be able to run the latest X.Org open source drivers for Intel on their FreeBSD desktop. While the project is limited to Intel graphics, porting other drivers like Nouveau to FreeBSD will become a lot easier once Belusov's work is completed. And when KMS support is in place, FreeBSD users could run the X Server without root privileges, run the Wayland display server, and get access to a lot of other features that are until now only available on Linux.
This case also shows that cutting edge development often happens with
Linux primarily in mind. During the last few years, X.Org's drivers were in
a constant state of flux, with new technologies like KMS, GEM,
translation-table maps (TTM), DRI, Gallium3D and so on being introduced one after another. As these are low-level technologies tightly coupled to the Linux kernel, porting them to FreeBSD is no small task, but fortunately the FreeBSD Foundation and iXsystems have seen that it is very important to follow the lead of Linux here.
An entirely different case is systemd: Lennart Poettering has no problem with the fact that systemd is tightly glued to Linux features. In a recent interview for FOSDEM, Poettering sums up the Linux-specific functionality systemd relies on: cgroups, udev, the fanotify(), timerfd() and signalfd() system calls, filesystem namespaces, capability sets, /proc/self/mountinfo, and so on. And then comes this quote, explaining why he designed systemd with Linux in mind:
Poettering took this decision because of his experience in writing some other low-level components in the desktop stack:
He even goes further with this provocative invitation to other developers to do the same:
Poettering touches some interesting points here. We have a family of
standards that are known as POSIX (Portable Operating System Interface for
uniX), defining the API of a Unix operating system. However, the POSIX
specifications are not carved in stone and there are few operating systems
that are fully compliant (Mac OS X is one of them since the Leopard
release)..
These three cases clearly show that there's a constant tension between
portability and innovation, which are two important qualities of open
source software. In a lot of domains, Linux is taking the lead with respect
to innovation, and the BSDs are forced to follow this lead if they don't
want to be left behind. While the BSDs will probably not be interested in
adopting systemd, implementing KMS is a must-have because one cannot
imagine a modern X.Org desktop any more without it. But the biggest
portability problems will be in the layers right above the kernel that
don't have suitable abstraction layers, such as the Xfce case shows. Will
FreeBSD implement udev or will the problem be solved another way? These
kinds of questions are important and choosing when to use the POSIX or the
Linux API is a delicate balancing act: choosing a Linux-centric approach
for a low-level component like systemd is understandable because of the
performance and maintenance gains, but most applications won't necessarily
benefit from that approach.
But maybe the biggest problem these cases hint at is that Linux
development is being done at such a fast pace that other operating systems
just can't keep up. Linux distributions and Linux-centric developers are used to the "release early, release often" mantra, including swapping out key components and breaking APIs each release. The BSD world doesn't work that way, and this makes working together on a modern cross-platform open source desktop increasingly difficult. The innovation of Linux inevitably comes at a price: Linux is the de facto Unix platform now, and hence more and more programs will not be portable to other operating systems.
+ log_warning("/usr appears to be on a different file system than /. "
+ "This is not supported anymore. "
+ "Some things will probably break (sometimes even silently) "
+ "in mysterious ways.");
Full Story (comments: 6)
Full Story (comments: 1)
Newsletters and articles
Announcements
Full Story (comments: 8)
Articles of interest
New Books
Calls for Presentations
Upcoming Events
If your event does not appear here, please
tell us about it.
Audio and Video programs
Linux is a registered trademark of Linus Torvalds
|
http://lwn.net/Articles/429592/bigpage
|
CC-MAIN-2013-48
|
refinedweb
| 7,335
| 51.38
|
Password Recovery
Try the following,
First: Are you sure yove forgotton it? Try just hitting return (in case there is no password), Then try all the password you would usually use
remember passwords are CaSe senSiTive so try with the caps lock on and off, or capitalise the first "Letter"
NB. All these tools, and links are to third party tools and involve directly or indirectly changing the registry. I accept no responsibility for their use.
Your passwords are held (encrypted) in your registry and in youre "restore" directory. These tools edit one or more of these locations from a boot disk
Arm yourself with a blank (clean) Floppy Disk
Ive used this one on XP and it works
Or try the following
---
----6----
Windows XP / 2000 / NT Key is a program to reset Windows XP / 2000 / NT security if Administrator password, secure boot password or key disk is lost. ($195.00)
---------
Heres some further reading
How to Log On to Windows XP If You Forget Your Password or Your Password Expires;en-us;321305
Windows XP Security - The Big Joke
FIX for above;en-us;818200
Good Luck! PL
Cheers!
Closing Questions
Best Wishes
Pete
|
https://www.experts-exchange.com/questions/20800413/Password.html
|
CC-MAIN-2018-26
|
refinedweb
| 196
| 64.44
|
New is the latest of three Arduino libraries providing “soft” serial port support. It’s the direct descendant of ladyada’s AFSoftSerial, which introduced interrupt-driven receives – a dramatic improvement over the polling required by the native SoftwareSerial.
Without interrupts, your program’s design is considerably restricted, as it must continually poll the serial port at very short, regular intervals. This makes it nearly impossible, for example, to use SoftwareSerial to receive GPS data and parse it into a usable form. Your program is too busy trying to keep up with NMEA characters as they arrive to actually spend time assembling them into something meaningful. This is where AFSoftSerial’s (and NewSoftSerial‘s) interrupt architecture is a godsend. Using interrupt-driven RX, your program fills its buffer behind the scenes while processing previously received data.
Improvements
NewSoftSerial offers a number of improvements over SoftwareSerial:
- It inherits from built-in class
- It implements circular buffering scheme to make RX processing more efficient
- It extends support to all Arduino pins 0-19 (0-21 on Arduino Mini), not just 0-13
- It supports multiple simultaneous soft serial devices.*
- It supports a much wider range of baud rates.**
- It provides a boolean overflow() method to detect buffer overflow.
- Higher baud rates have been tuned for better accuracy.
- It supports the ATMega328 and 168.
- It supports 8MHz processors.
- It uses direct port I/O for faster and more precise operation.
- (New with version 10). It supports software signal inversion.
- (New) It supports 20MHz processors.
- (New) It runs on the Teensy and Teensy++.
- (New) It supports an end() method as a complement to begin().
*But see below for an important caveat on multiple instances.
**Be circumspect about using 300 and 1200 baud though. The interrupt handler at these rate becomes so lengthy that timer tick interrupts can be starved, causing millis() to stop working during receives.
Using Multiple Instances
There has been considerable support for an library that would allow multiple soft serial devices. However, handling asynchronously received data from two, three, or four or more serial devices turns out to be an extremely difficult, if not intractable problem. Imagine four serial devices connected to an Arduino, each transmitting at 38,400 baud. As bits arrive, Arduino’s poor little processor must sample and process each of 4 incoming bits within 26 microseconds or else lose them forever. Yikes!
It occurred to me, though, that multiple instances could still be possible if the library user were willing to make a small concession. NewSoftSerial is written on the principle that you can have as many devices connected as resource constraints allow, as long as you only use one of them at a time. If you can organize your program code around this constraint, then NewSoftSerial may work for you.
What does this mean, exactly? Well, you have to use your serial devices serially, like this:
#include <NewSoftSerial.h> // Here's a GPS device connect to pins 3 and 4 NewSoftSerial gps(4,3); // A serial thermometer connected to 5 and 6 NewSoftSerial therm(6,5); // An LCD connected to 7 and 8 NewSoftSerial LCD(8,7); // serial LCD void loop() { ... // collect data from the GPS unit for a few seconds gps.listen(); read_gps_data(); // use gps as active device // collect temperature data from thermometer therm.listen(); read_thermometer_data(); // now use therm // LCD becomes the active device here LCD.listen(); LCD.print("Data gathered..."); ... }
In this example, we assume that
read_gps_data() uses the
gps object and
read_thermometer_data() uses the
therm object. Any time you call the listen() method, it becomes the “active” object, and the previously active object is deactivated and its RX buffer discarded. An important point here is that
object.available() always returns 0 unless
object is already active. This means that you can’t write code like this:
void loop() { device1.listen(); if (device1.available() > 0) { int c = device1.read(); ... } device2.listen(); if (device2.available() > 0) { int c = device2.read(); ... } }
This code will never do anything but activate one device after the other.
Signal Inversion
“Normal” TTL serial signaling defines a start bit as a transition from “high” to “low” logic. Logical 1 is “high”, 0 is “low”. But some serial devices turn this logic upside down, using what we call “inverted signaling”. As of version 10, NewSoftSerial supports these devices natively with a third parameter in the constructor.
NewSoftSerial myInvertedConn(7, 5, true); // this device uses inverted signaling NewSoftSerial myGPS(3, 2); // this one doesn't
Library Version
You can retrieve the version of the NewSoftSerial library by calling the static member
library_version().
int ver = NewSoftSerial::library_version();
Resource Consumption
Linking the NewSoftSerial library to your application adds approximately 2000 bytes to its size.
Download
The latest version of NewSoftSerial is available here: NewSoftSerial12.zip. Note: don’t download this if you have Arduino 1.0 or later. As of 1.0, NewSoftSerial is included in the Arduino core (named SoftwareSerial).
Change Log
- initial version
- ported to Arduino 0013, included example sketch in package
- several important improvements: (a) support for 300, 1200, 14400, and 28800 baud (see caveats), (b) added bool overflow() method to test whether an RX buffer overflow has occurred, and (c) tuned RX and TX for greater accuracy at high baud rates 38.4K, 57.6K, and 115.2K.
- minor bug fixes — add .o file and objdump.txt to zip file for diagnostics.
- etracer’s inline assembler fix to OSX avr-gcc 4.3.0 interrupt handler bug added.
- ladyada’s new example sketch, fix to interrupt name, support for 328p.
- etracer’s workaround is now conditionally compiled only when avr-gcc’s version is less than 4.3.2.
- 8 MHz support and flush() and enable_timer0() methods added
- digitalread/write scrapped in favor of direct port I/O. Revised routines now get perfect RX up to 57.6K on 16MHz processors and 31.25K on 8MHz processors.
- inverted TTL signalling supported. 20MHz processors supported. Teensy and Teensy++ supported. New end() method and destructor added to clean up.
- added listen() method to explicitly activate ports.
- warn users about 1.0 conflict
Acknowledgements
Many thanks to David Mellis, who wrote the original SoftwareSerial, and to the multi-talented ladyada, whose work with AFSoftSerial is seminal. Ladyada also provided the “Goodnight, moon” example sketch, fixed a problem with the interrupt naming (see v6) and tested NSS with the 328p.
Thanks also to rogermm and several other forum users who have tested NewSoftSerial and given useful feedback.
The diligent analysis of forum user etracer yielded the root cause of a tricky problem with NSS on OSX. A bug in avr-gcc 4.3.0 causes the compiler to fail to generate the proper entry and exit sequences for certain interrupt handlers. etracer identified the problem and provided an inline workaround. etracer’s fix is in NSS 5.
User jin contributed a large body of work based on NSS and identified a potential problem that could result in data loss (fixed in NSS 5). jin also made a variant of NSS that supports 4-pin serial, with the additional pins providing a very nice RTS/CTS flow control. We may see this in NSS in the near future.
Thanks to Garret Mace, who contributed the delay tables for 20MHz processors and claims that he can send and receive at 115K baud. Cool!
Thanks to Paul Stoffregen, both for his fine work with Teensy and Teensy++, and for contributing some useful suggestions that help NewSoftSerial run on them without modification.
I appreciate any and all input.
Mikal Hart
February 15th, 2009 → 10:04 pm
[...] NewSoftSerial version 5 is available. A lot of people have been using this library — thanks! — but I really need to recognize the exceptional work of two contributors. [...]
February 20th, 2009 → 1:08 pm
[...] I posted the new library. [...]
March 2nd, 2009 → 1:46 pm
[...] ในรอบนี้ผมได้ใช้ newSoftwareSerial3 จะได้ลองด้วยว่า มีปัญหาไหม
March 11th, 2009 → 4:54 pm
[...] of the first things to do is download NewSoftSerial
June 9th, 2009 → 3:21 pm
[...] to the task at hand, which happened to be adding 3 lines of code: declaration of an instance of NewSoftSerial, calling the instance constructor with a baud rate, and a single call to pass the char from the [...]
August 1st, 2009 → 3:00 pm
[...] and the XBee module has a serial interface. So how does this really solve my problem? Enter NewSoftSerial, an updated version of the Arduino software serial library, which basically lets you drive a serial [...]
October 14th, 2009 → 1:38 pm
[...] is probably the coolest gift idea I’ve seen. Mikal, you rock. And also, thank you for NewSoftSerial. [...]
November 19th, 2009 → 3:36 pm
[...] way. Let’s move onto the software. Communication with the DS1616 is established using the NewSoftSerial library. Getting data is essentially a case of lots of bit banging. The DS1616 library [...]
December 14th, 2009 → 8:08 am
[...] So we started looking for a solution to overcome this tiny inconvenience. First we looked into a software serial but this didn’t work out, it was a bit too much for the arduino’s little processor to [...]
December 29th, 2009 → 6:59 am
[...] software serial port. I briefly thought about writing one, but then I found this great libary, the New SoftSerial. It is as simple to use as the original library, but unfortunately once I connect the RF receiver, [...]
January 20th, 2010 → 1:19 am
[...] developers for the great libraries, and to Mikal Hart in particular for his work on the TinyGPS and NewSoftSerial [...]
January 23rd, 2010 → 10:27 am
[...] このソースでは、PS2ライブラリとNewSoftSerialライブラリを利用しています。 コンパイルするには、これらのライブラリを有効にしておく必要があります。 [...]
February 27th, 2010 → 10:19 am
[...] as a well. The shield can be wired to any of the pins on the Arduino. Right now we’re using NewSoftSerial on pins 4 and 5. It can be attached to the hardware RX and TX pins, but interferes with [...]
February 27th, 2010 → 12:18 pm
[...] 急遽、Arduinoでシリアル通信をふたつやる必要が発生してホテルで開発。といっても手元にハードがないので、ほとんど勘でプログラムしているようなもの。 次の日現場で試すも、予想通り動かない。そりゃそうだ。 NewSoftwareSerialなんていう便利なものがあるのを後で知った。 [...]
March 27th, 2010 → 1:39 am
[...] chose the NewSoftSerial library to give access to the VDIP1. The first attempt was to use the AFSoftLibrary and it just [...]
April 5th, 2010 → 12:55 pm
[...] software running on the Arduino ATMEGA328 chip utilizes the wonderfully robust NewSoftSerial library for communicating with the EM-406a GPS module and the very convenient TinyGPS library for [...]
April 6th, 2010 → 1:33 am
[...] is available here. I borrowed from a couple of people’s Arduino libraries to get this done, notably NewSoftSerial from Arduiniana and the GPS Parsing code from the Arduino website for parsing the NMEA strings. [...]
May 15th, 2010 → 1:46 pm
[...] I had to use this library to communicate with the xbee from the arduino: [...]
May 31st, 2010 → 12:54 pm
[...] wird über die Serielle Schnittstelle angesteuert. Die werde ich wahrscheinlich über die NewSoftSerial Library [...]
May 31st, 2010 → 1:05 pm
[...] GPS Modul wird über die Serielle Schnittstelle angesteuert. Die werde ich wahrscheinlich über die NewSoftSerial Library [...]
June 22nd, 2010 → 4:47 pm
[...] metoda de a afla codul cartelei este de a utiliza biblioteca NewSoftSerial, disponibila gratuit aici. Fisierul zip se dezarhiveaza si se copiaza in folderul libraries al distributiei [...]
July 10th, 2010 → 3:59 pm
[...] updated the NewSoftSerial library from Arduiniana (thanks Mikal !) so that it takes 2 extra [...]
July 20th, 2010 → 1:19 am
[...] [...]
July 25th, 2010 → 11:34 am
[...] the TinyGPS library from Arduiniana downloaded and installed for it to work. They suggest using NewSoftSerial, but I couldn’t get that to work, so I scrapped that portion. Here’s my [...]
August 3rd, 2010 → 8:45 pm
[...] it as a fail and moved on, however last night when I set about writing the RFID read function using NewSoftSerial on the RFID I was getting nothing reported back back on the AVR, not a thing coming back from the [...]
August 10th, 2010 → 10:25 am
[...] [...]
September 16th, 2010 → 11:37 pm
[...] devices. At this point you will need to install two libraries into the Arduino software – NewSoftSerial and TinyGPS. Extract the folders into the libraries folder within your arduino-001x [...]
September 17th, 2010 → 12:09 am
[...] this point you will need to install two libraries into the Arduino software – NewSoftSerial and TinyGPS. Extract the folders into the librariesfolder within [...]
October 6th, 2010 → 1:48 pm
[...] there is one more library – “NewSoftSerial”, which is free of these defects and, in addidion, handles inverted serial [...]
October 6th, 2010 → 2:05 pm
[...] NewSoftSerial [...]
October 12th, 2010 → 10:18 pm
[...] one on some other pins. Per the suggestion of some people on the Arduino forums, I decided to use NewSoftSerial to do the communication. Being interrupt driven, it was much more efficient than the older [...]
December 18th, 2010 → 7:36 pm
[...] the code you will need a very useful NewSoftSerial library, that, among other things, allows you to assign TX and RX on other pins then 0 and 1 and that way [...]
January 11th, 2011 → 7:09 am
[...] up would be to try and use the awesome NewSoftSerial library by Mikal Hart to communicate with the Bluetooth Bee by emulating the UART [...]
January 18th, 2011 → 5:56 pm
[...] a software perspective we will need the NewSoftSerial Arduino library, so please download and install that before moving [...]
January 28th, 2011 → 10:06 pm
[...] goes step by step how to connect Cellular shield to Arduino mega and communicate to it by using newsoftserial Arduino library. Whole process steps are monitored in terminal window, so it is easy to follow [...]
February 4th, 2011 → 3:03 pm
[...] NewSoftSerial library [...]
February 22nd, 2011 → 11:07 pm
[...] also need the NewSoftSerial library installed in your Arduino sketchbook’s library [...]
March 18th, 2011 → 5:17 am
[...] GLCD that I bought (without knowing ANYTHING about it beforehand I might add). The code uses the NewSoftSerial library which apparently does wonders, but as of yet has not been validated as the code assumes a 9V [...]
March 21st, 2011 → 9:44 am
[...] the pin 4 and 5 there aren’t problems to upload the sketch but the maximum baudrate for NewSoftSerial (the serial library) is 57600. We performed a GSM library to controll easly the module. The GSM [...]
March 23rd, 2011 → 4:40 am
[...] forget the 10k ohm pull-down resistor). You will need to install the SdFAT library, NewSoftSerial library, TinyGPS library and the SdFat library if not already [...]
May 9th, 2011 → 8:54 am
[...] of just the standard Serial interface, see the links below for that too. You’ll also need NewSoftSerial of course and the Flash library which I’ve used to decrease memory usage. Follow the [...]
May 17th, 2011 → 2:01 am
[...] a single wire, which again, keeps the number of wires from the Arduino down. I’m using the NewSoftSerial library to talk to it, which makes life [...]
May 25th, 2011 → 10:27 am
[...] you can use multiple serial “ports”, that are actually digital I/O lines, by using the NewSoftSerial library. This works exactly like the Serial library, but you can read from multiple pins, as long as you [...]
June 23rd, 2011 → 8:59 pm
[...] it’s easier to pick which Serial port to use; Serial, Serial1, etc. AND support for the NewSoftSerial library for creating software serial ports on any pin. Inside the download zip file are two versions of the [...]
July 3rd, 2011 → 11:28 am
[...] neat thing is the NewSoftSerial library for Adruino, allowing you to turn any set of pins into additional RX/TX pins with free to set baud [...]
July 13th, 2011 → 7:09 am
[...] de instalar la librería NewSoftSerial pude compilar e instalar el Arduino Firmware en mi placa. A continuación necesitaba descargarme [...]
July 17th, 2011 → 8:51 pm
[...] a bit of this code at the end of this journal entry. The “NewSoftSerial” library was extremely easy to get working (code example [...]
July 21st, 2011 → 1:18 am
[...] Modul per Software-UART? Bitte einen Link oder Hinweis wo ich nachlesen kann. danke Schaust du hier __________________ FHZ1300 | 2x JeeLink | AVR-NETIO | FS20 | 1-Wire | 2x XBEE Pro | 4x XBEE 2.5 [...]
July 31st, 2011 → 11:07 pm
[...] actually really easy, using some code called NewSoftSerial (available from this site, at the ‘Download’ subheading). This software is much like your Serial device you use on the Arduino, but it’s in software [...]
August 20th, 2011 → 7:37 pm
[...] provided by the software library “NewSoftSerial”. The library can be downloaded from::. Since the communications port is created using software any of the Arduino port pins can be used. [...]
August 28th, 2011 → 12:48 pm
[...] NewSoftSerial library from Mikal Hart: [...]
August 28th, 2011 → 7:03 pm
[...] via jumper na própria shield. Para comunicação com essa Bee, é necessário o uso da biblioteca NewSoftwareSerial, permitindo fazer que dois pinos digitais se tornem mais uma [...]
September 6th, 2011 → 4:44 pm
[...] NewSoftSerial lib was used for communicating over serial using an IO [...]
September 8th, 2011 → 4:21 am
[...] 1– télécharger la bibliothèque NewSoftSerial pour Arduino NewSoftSerial10c.zip. Des explications et exemples plus détaillés concernant cette bibliothèque sur cette page (). [...]
September 21st, 2011 → 11:47 pm
[...] そのためソフトウェアシリアルを再現させたライブラリがありますのでそれを利用します。とはいっても標準ライブラリのSoftwareSerialは利用しません。高機能で速度もでるようになったNewSoftSerialを利用します。 [...]
October 31st, 2011 → 2:10 am
[...] NewSoftSerial Library - [...]
December 25th, 2011 → 6:30 pm
[...] arduino remotely can be found here. For communication over XBee the Arduino appears to need the NewSoftSerial library. LD_AddCustomAttr("AdOpt", "1"); LD_AddCustomAttr("Origin", "other"); [...]
December 25th, 2011 → 6:36 pm
[...] for attacheinterupt() are 2 and 3. The GPS shield uses digital 2 and 3 for GPS communication using NewSoftSerial. So I tried moving the GPS to other pins, 8 and 9 worked. Now pins 2 and 3 are free for my [...]
December 25th, 2011 → 6:36 pm
[...] arduino remotely can be found here. For communication over XBee the Arduino appears to need the NewSoftSerial library. [...]
January 24th, 2012 → 1:46 am
[...] Dans ce projet vous pouvez remarquer que je suis obligé d’utiliser deux port série, un à 9600 bauds pour l’écran lcd, et un autre à 2400 bauds pour le lectuer RFID. Normalement il me faudrait une mega (qui possède 3 port série) pour faire ce projet en hardware, mais il existe aussi des librairies Serial software ! C’est pourquoi je vais utiliser la librairie NewSoftSerial disponible ici : [...]
February 4th, 2012 → 9:10 pm
[...] went through each error, and tried to resolve it myself. Some were easy. The "NewSoftSerial" libraries were incorporated into the core libraries, and they replaced the default SoftwareSerial [...]
March 8th, 2012 → 10:30 am
[...] speed if you need a second or third (or fourth) port. On the Uno, you can do similarly using the NewSoftSerial library; however, software is slower, and if your program is pushing the limits, you may find a hardware [...]
August 5th, 2012 → 6:55 pm
[...] already. I found this wall of text which I managed to digest down into this gist (and updated it thanks to these notes) which you can see running in the above [...]
August 6th, 2012 → 1:54 am
[...] そして、シリアル通信のテストに利用したArduinoのソースです。 NewSoftSerial(Arduinoライブラリ)を利用しています。 [...]
August 8th, 2012 → 6:37 pm
[...] DroneCell and the GPS simultaneously. I stumbled upon this interesting behavior in NewSoftSerial. NewSoftSerial*|*Arduiniana. I seem to at least have something to go on… Using Multiple Instances There has been [...]
August 13th, 2012 → 1:13 pm
[...] eso es lo que es capaz de hacer la librería NewSoftSerial (más documentación aquí). Usándola podremos emplear el resto de pines como puertos serial, ya [...]
August 16th, 2012 → 2:06 pm
[...] in the download is TimeGPS.pde, but it’s a touch outdated now that Mikal Hart’s NewSoftSerial library has been rolled up into the core (since 1.0) and renamed SoftwareSerial. The problem I had [...]
August 21st, 2012 → 10:42 pm
[...] GPS模块与Arduino的通讯程序 [...]
October 26th, 2012 → 1:58 pm
[...] tried using the SoftSerial (or the NewSoftSerial) library but ran into data corruptions even at the low speeds, so I decided to look for ways to get another [...]
November 6th, 2012 → 8:58 am
[...] the example code. There some issues on the Arduino library SoftwareSerial, which changed to the NewSoftSerial once in a while. Share this:TwitterFacebookLike this:LikeBe the first to like this. Categories [...]
November 29th, 2012 → 12:22 pm
[...] - Share this: This entry was posted in AT Physics Class and tagged arduino, IR, proximity [...]
March 17th, 2013 → 2:14 pm
[...] NewSoftSerial Library - Required for the example sketches. Sets up a second (third, fourth,…) serial port on the Arduino. [...]
March 17th, 2013 → 2:19 pm
[...] NewSoftSerial Library - Required for the example sketches. Sets up a second (third, fourth,…) serial port on the Arduino. [...]
March 21st, 2013 → 11:30 pm
[...] from this project (bluetooth_chat_LCD.pde attached below) – NewSoftSerial library from Mikal Hart: – Eclipse – Android Development Kit (explicitly follow all of Google’s installation [...]
June 4th, 2013 → 8:56 pm
[...] いいね:いいね 読み込み中… カテゴリー Arduino, [...]
June 4th, 2013 → 9:03 pm
[...] いいね:いいね 読み込み中… カテゴリー Arduino, [...]
August 30th, 2013 → 6:11 pm
[...] to the GPS receiver, I’d be writing to the data logger serially. I found information here about running multiple devices serially – the short answer is that you have to access the serial [...]
September 1st, 2013 → 8:29 am
[...] kB). I used this method and solved my intermitting (and making me crazy…) problems 2) Using PString library, added by NewSoftSerial and put in official version of Arduino. It is very handy: it hands you a [...]
October 7th, 2013 → 3:29 pm
[...] developers for the great libraries, and to Mikal Hart in particular for his work on the TinyGPS and NewSoftSerial [...]
October 19th, 2013 → 4:42 am
[...] , les ports 12 & 13 de l’arduino sont utilisés (liaison arduino-module via la classe newSoftSerial) et ne permettent pas l’emploi du shield Ethernet sur une platine « arduino [...]
December 3rd, 2013 → 6:35 pm
[...] I rewrote the logger to use the Arduino’s internal UART, since — lovely though NewSoftSerial may be — it causes millis() to report wildly inaccurate times at low bit rates. I recorded a [...]
April 22nd, 2014 → 1:23 am
[...] require that protocol. The version of SoftwareSerial included in 1.0 and later is based on the NewSoftSerial library by Mikal [...]
April 22nd, 2014 → 1:59 am
[...] This requires the TinyGPS and NewSoftSerial libraries from Mikal Hart: and [...]
May 25th, 2014 → 8:46 am
[...] BT1 pin settings (which are done in hardware), the receiver is totally configuration free. I used NewSoftSerial library in the code below. The main loop simply print out the incoming bit stream. You may also use [...]
June 7th, 2014 → 8:35 am
[...] newsoftserial should be downloaded from the internet and the folder inside the zip put in (path to where you [...]
July 8th, 2014 → 6:47 am
[...] szczęście jest jeszcze jedna biblioteka „NewSoftSerial”, która jest pozbawiona tych wad i na dodatek obsługuje zanegowany sygnał [...]
July 24th, 2014 → 12:34 am
[...] Download the TrueRandom, NewSoftSerial, and Twitter [...]
October 28th, 2014 → 5:03 am
[...] NewSoftSerial [...]
December 10th, 2014 → 6:36 am
[...] NewSoftwareSerial: [...]
February 13th, 2015 → 3:21 am
[...] Download the TrueRandom, NewSoftSerial, and Twitter [...]
|
http://arduiniana.org/libraries/NewSoftSerial/
|
CC-MAIN-2015-11
|
refinedweb
| 3,804
| 60.51
|
Created on 2016-04-21 08:57 by vstinner, last changed 2016-09-01 13:15 by vstinner. This issue is now closed.
Attached patch adds the following new function:
PyObject* _PyObject_CallStack(PyObject *func,
PyObject **stack,
int na, int nk);
where na is the number of positional arguments and nk is the number of (key, pair) arguments stored in the stack.
Example of C code to call a function with one positional argument:
PyObject *stack[1];
stack[0] = arg;
return _PyObject_CallStack(func, stack, 1, 0);
Simple, isn't it?
The difference with PyObject_Call() is that its API avoids the creation of a tuple and a dictionary to pass parameters to functions when possible. Currently, the temporary tuple and dict can be avoided to call Python functions (nice, isn't it?) and C function declared with METH_O (not the most common API, but many functions are declared like that).
The patch only modifies property_descr_set() to test the feature, but I'm sure that *a lot* of C code can be modified to use this new function to beneift from its optimization.
Should we make this new _PyObject_CallStack() function official: call it PyObject_CallStack() (without the understand prefix) or experiment it in CPython 3.6 and decide later to make it public? If it's made private, it will require a large replacement patch later to replace all calls to _PyObject_CallStack() with PyObject_CallStack() (strip the underscore prefix).
The next step is to add a new METH_STACK flag to pass parameters to C functions using a similar API (PyObject **stack, int na, int nk) and modify the argument clinic to use this new API.
Thanks to Larry Hasting who gave me the idea in a previous edition of Pycon US ;-)
This issue was created after the discussion on issue #26811 which is an issue in a micro-optimization in property_descr_set() to avoid the creation of a tuple: it caches a private tuple inside property_descr_set().
"Stack" in the function name looks a little confusing. I understand that this is related to the stack of bytecode interpreter, but this looks as raising pretty deep implementation detail. The way of packing positional and keyword arguments in the continuous array is not clear. Wouldn't be better to provide separate arguments for positional and keyword arguments?
What is the performance effect of using this function? For example compare the performance of namedtuple's attribute access of current code, the code with with this patch, and unoptimized code in 3.4:
./python -m timeit -r 11 -s "from collections import namedtuple as n; a = n('n', 'a b c')(1, 2, 3)" -- "a.a"
Is there any use of this function with keyword arguments?
"Python 3.6 with property_descr_get() of Python 3.4": replace the current optimization with "return PyObject_CallFunctionObjArgs(gs->prop_get, obj, NULL);".
Oh, in fact the tested code calls a property where the final function is operator.itemgetter(0). _PyObject_CallStack() creates a temporary tuple to call PyObject_Call() which calls func->ob_type->tp_call, itemgetter_call().
Problem: tp_call API uses (PyObject *args, PyObject *kwargs). It doesn't accept directly a stack (a C array of PyObject*). And it may be more difficult to modify tp_call.
In short, my patch disables the optimization on property with my current incomplete implementation.
See also issue23507. May be your function help to optimize filter(), map(), sorted()?
call_stack-2.patch: A little bit more complete patch, it adds a tp_call_stack field to PyTypeObject an use it in _PyObject_CallStack().
Updated
* call_stack-2.patch: 0.664 usec
call_stack-2.patch makes this micro-benchmark 31% faster, not bad! It also makes calls to C functions almost 2x as fast if you replace current unoptimized calls with _PyObject_CallStack()!!
IHMO we should continue to experiment, making function calls 2x faster is worth it ;-)
Serhiy: "See also issue23507. May be your function help to optimize filter(), map(), sorted()?"
IMHO the API is generic enough to be usable in a lot of cases.
Serhiy: "Is there any use of this function with keyword arguments?"
Calling functions with keywords is probably the least common case for function calls in C code. But I would like to provide a fast function to call with keywords. Maybe we need two functions just to make the API cleaner? The difference would just be that "int k" would be omitted?
I proposed an API (PyObject **stack, int na, int nk) based on the current code in Python/ceval.c. I'm not sure that it's the best API ever :-)
In fact, there is already PyObject_CallFunctionObjArgs() which can be modified to reuse internally _PyObject_CallStack(), and its API is maybe more convenient than my proposed API.
With.
Yes, I've been working on a patch to do this as well. I called the calling convention METH_RAW, to go alongside METH_ZERO METH_O etc. My calling convention was exactly the same as yours: PyObject *(PyObject *o, PyObject **stack, int na, int nk). I only had to modify two functions in ceval.c to support it: ext_do_call() and call_function().
And yes, the overarching goal was to have Argument Clinic generate custom argument parsing code for every function. Supporting the calling convention was the easy part; generating code was quite complicated. I believe I got a very simple version of it working at one point, supporting positional parameters only, with some optional arguments. Parsing arguments by hand gets very complicated indeed when you introduce keyword arguments.
I haven't touched this patch in most of a year. I hope to return to it someday. In the meantime it's fine by me if you add support for this and rewrite some functions by hand to use it.
p.s. My last name has two S's. If you continue to leave off one of them, I shall remove one from yours, Mr. TINNER.
Since early microbenchmarks are promising, I wrote a more complete implementations which tries to use the fast-path (avoid temporary tuple/dict) in all PyObject_Call*() functions.
The next step would be to add a METH_FASTCALL flag. IMHO adding such new flag requires to enhance Argument Clinic to be able to use it, at least when a function doesn't accept keyword parameters.
PyObject_CallFunction() & friends have a weird API: if call with the format string "O", the behaviour depends if the object parameter is a tuple or not. If it's a tuple, the tuple is unpacked. It's a little bit weird. I recall that it led to a bug in the implementation in generators in Python: issue #21209! Moreover, if the format string is "(...)", parenthesis are ignored. If you want to call a function with one argument which is a tuple, you have to write "((...))". It's a little bit weird, but we cannot change that without breaking the (Python) world :-)
call_stack-3.patch:
* I renamed the main function to _PyObject_FastCall()
* I added PyObject_CallNoArg(): call a function with no parameter
* I added Py_VaBuildStack() and _Py_VaBuildStack_SizeT() helpers for PyObject_Call*() functions using a format string
* I renamed the new slot to tp_fastcall
Nice change in the WITH_CLEANUP_START opcode (ceval.c):
- /* XXX Not the fastest way to call it... */
- res = PyObject_CallFunctionObjArgs(exit_func, exc, val, tb, NULL);
+ arg_stack[0] = exc;
+ arg_stack[1] = val;
+ arg_stack[2] = tb;
+ res = _PyObject_FastCall(exit_func, arg_stack, 3, 0);
I don't know if it's a common byetcode, nor if the change is really faster.
> I believe I got a very simple version of it working at one point, supporting positional parameters only, with some optional arguments.
Yeah, that would be a nice first step.
> p.s. My last name has two S's. If you continue to leave off one of them, I shall remove one from yours, Mr. TINNER.
Ooops, I'm sorry Guido Hastings :-(
PyObject_Call*() implementations with _PyObject_FastCall() look much more complex than with PyObject_Call() (even not counting additional complex functions in modsupport.c). And I'm not sure there is a benefit. May be for first stage we can do without this.
I created a repository. I will work there and make some experiment. It would help to have a better idea of the concrete performance. When I will have a better view of all requires changes to get best performances everywhere, I will start a discussion to see which parts are worth it or not. In my latest microbenchmarks, functions calls (C/Python, mixed) are between 8% and 40% faster. I'm now running the CPython benchmark suite.
Changes of my current implementation, ad4a53ed1fbf.diff.
The good thing is that all changes are internals (really?). Even if you don't modify your C extensions (nor your Python code), you should benefit of the new fast call is *a lot* of cases.
IMHO the best tricky part are changes on the PyTypeObject. Is it ok to add a new tp_fastcall slot? Should we add even more slots using the fast call convention like tp_fastnew and tp_fastinit? How should we handle the inheritance of types with that?
(*) Add 2 new public functions:
PyObject* PyObject_CallNoArg(PyObject *func);
PyObject* PyObject_CallArg1(PyObject *func, PyObject *arg);
(*) Add 1 new private function:
PyObject* _PyObject_FastCall(PyObject *func, PyObject **stack, int na, int nk);
_PyObject_FastCall() is the root of the new feature.
(*) type: add a new "tp_fastcall" field to the PyTypeObject structure.
It's unclear to me how inheritance is handled here. Maybe it's simply broken, but it's strange because it looks like it works :-) Maybe it's very rare that tp_call is overidden in a child class?
TODO: maybe reuse the "tp_call" field? (risk of major backward incompatibility...)
(*) slots: add a new "fastwrapper" field to the wrappercase structure. Add a fast wrapper to all slots (really all? i should check).
I don't think that consumers of the C API are of this change, or maybe only a few projects.
TODO: maybe remove "fastwrapper" and reuse the "wrapper" field? (low risk of backward compatibility?)
(*) Implement fast call for Python function (_PyFunction_FastCall) and C functions (PyCFunction_FastCall)
(*) Add a new METH_FASTCALL calling convention for C functions. Right now, it is used for 4 builtin functions: sorted(), getattr(), iter(), next().
Argument Clinic should be modified to emit C code using this new fast calling convention.
(*) Implement fast call in the following functions (types):
- method()
- method_descriptor()
- wrapper_descriptor()
- method_wrapper()
- operator.itemgetter => used by collections.namedtuple to get an item by its name
(*) Modify PyObject_Call*() functins to reuse internally the fast call. "tp_fastcall" is preferred over "tp_call" (FIXME: is it really useful to do that?).
The following functions are able to avoid temporary tuple/dict without having to modify the code calling them:
- PyObject_CallFunction()
- PyObject_CallMethod(), _PyObject_CallMethodId()
- PyObject_CallFunctionObjArgs(), PyObject_CallMethodObjArgs()
It's not required to modify code using these functions to use the 3 new shiny functions (PyObject_CallNoArg, PyObject_CallArg1, _PyObject_FastCall). For example, replacing PyObject_CallFunctionObjArgs(func, NULL) with PyObject_CallNoArg(func) is just a micro-optimization, the tuple is already avoided. But PyObject_CallNoArg() should use less memory of the C stack and be a "little bit" faster.
(*) Add new helpers: new Include/pystack.h file, Py_VaBuildStack(), etc.
Please ignore unrelated changes.
Related issue: issue #23507, "Tuple creation is too slow".
Some microbenchmarks: bench_fast.py.
== Python 3.6 / Python 3.6 FASTCALL ==
----------------------------------+--------------+---------------
Tests | /tmp/default | /tmp/fastcall
----------------------------------+--------------+---------------
filter | 241 us (*) | 166 us (-31%)
map | 205 us (*) | 168 us (-18%)
sorted(list, key=lambda x: x) | 242 us (*) | 162 us (-33%)
sorted(list) | 27.7 us (*) | 27.8 us
b=MyBytes(); bytes(b) | 549 ns (*) | 533 ns
namedtuple.attr | 2.03 us (*) | 1.56 us (-23%)
object.__setattr__(obj, "x", 1) | 347 ns (*) | 218 ns (-37%)
object.__getattribute__(obj, "x") | 331 ns (*) | 200 ns (-40%)
getattr(1, "real") | 267 ns (*) | 150 ns (-44%)
bounded_pymethod(1, 2) | 193 ns (*) | 190 ns
unbound_pymethod(obj, 1, 2 | 195 ns (*) | 192 ns
----------------------------------+--------------+---------------
Total | 719 us (*) | 526 us (-27%)
----------------------------------+--------------+---------------
== Compare Python 3.4 / Python 3.6 / Python 3.6 FASTCALL ==
Common platform:
Timer: time.perf_counter
Python unicode implementation: PEP 393
Timer info: namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09)
CPU model: Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz
Platform: Linux-4.4.4-301.fc23.x86_64-x86_64-with-fedora-23-Twenty_Three
SCM: hg revision=abort: repository . not found! tag=abort: repository . not found! branch=abort: repository . not found! date=abort: no repository found in '/home/haypo/prog/python' (.hg not found)!
Bits: int=32, long=64, long long=64, size_t=64, void*=64
Platform of campaign /tmp/py34:
Python version: 3.4.3 (default, Jun 29 2015, 12:16:01) [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)]: 78 ns
Date: 2016-04-22 13:37:52
Platform of campaign /tmp/default:
Timer precision: 103 ns
Date: 2016-04-22 13:38:07
Platform of campaign /tmp/fastcall:
Python version: 3.6.0a0 (default:ad4a53ed1fbf, Apr 22 2016, 12:42:15) [GCC 5.3.1 20151207 (Red Hat 5.3.1-2)]
Timer precision: 99 ns
CFLAGS: -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
Date: 2016-04-22 13:38:21
----------------------------------+-------------+----------------+---------------
Tests | /tmp/py34 | /tmp/default | /tmp/fastcall
----------------------------------+-------------+----------------+---------------
filter | 325 us (*) | 241 us (-26%) | 166 us (-49%)
map | 260 us (*) | 205 us (-21%) | 168 us (-35%)
sorted(list, key=lambda x: x) | 354 us (*) | 242 us (-32%) | 162 us (-54%)
sorted(list) | 46.9 us (*) | 27.7 us (-41%) | 27.8 us (-41%)
b=MyBytes(); bytes(b) | 839 ns (*) | 549 ns (-35%) | 533 ns (-36%)
namedtuple.attr | 4.51 us (*) | 2.03 us (-55%) | 1.56 us (-65%)
object.__setattr__(obj, "x", 1) | 447 ns (*) | 347 ns (-22%) | 218 ns (-51%)
object.__getattribute__(obj, "x") | 401 ns (*) | 331 ns (-17%) | 200 ns (-50%)
getattr(1, "real") | 236 ns (*) | 267 ns (+13%) | 150 ns (-36%)
bounded_pymethod(1, 2) | 249 ns (*) | 193 ns (-22%) | 190 ns (-24%)
unbound_pymethod(obj, 1, 2 | 251 ns (*) | 195 ns (-22%) | 192 ns (-23%)
----------------------------------+-------------+----------------+---------------
Total | 993 us (*) | 719 us (-28%) | 526 us (-47%)
----------------------------------+-------------+----------------+---------------
For more fun, comparison between Python 2.7 / 3.4 / 3.6 / 3.6 FASTCALL.
----------------------------------+-------------+----------------+----------------+---------------
Tests | py27 | py34 | py36 | fast
----------------------------------+-------------+----------------+----------------+---------------
filter | 165 us (*) | 318 us (+93%) | 237 us (+43%) | 165 us
map | 209 us (*) | 258 us (+24%) | 202 us | 171 us (-18%)
sorted(list, key=lambda x: x) | 272 us (*) | 348 us (+28%) | 237 us (-13%) | 163 us (-40%)
sorted(list) | 33.7 us (*) | 47.8 us (+42%) | 27.3 us (-19%) | 27.7 us (-18%)
b=MyBytes(); bytes(b) | 3.31 us (*) | 835 ns (-75%) | 510 ns (-85%) | 561 ns (-83%)
namedtuple.attr | 4.63 us (*) | 4.51 us | 1.98 us (-57%) | 1.57 us (-66%)
object.__setattr__(obj, "x", 1) | 463 ns (*) | 440 ns | 343 ns (-26%) | 222 ns (-52%)
object.__getattribute__(obj, "x") | 323 ns (*) | 396 ns (+23%) | 316 ns | 196 ns (-39%)
getattr(1, "real") | 218 ns (*) | 237 ns (+8%) | 264 ns (+21%) | 147 ns (-33%)
bounded_pymethod(1, 2) | 213 ns (*) | 244 ns (+14%) | 194 ns (-9%) | 188 ns (-12%)
unbound_pymethod(obj, 1, 2) | 345 ns (*) | 247 ns (-29%) | 196 ns (-43%) | 191 ns (-45%)
func() | 161 ns (*) | 211 ns (+31%) | 161 ns | 157 ns
func(1, 2, 3) | 219 ns (*) | 247 ns (+13%) | 196 ns (-10%) | 190 ns (-13%)
----------------------------------+-------------+----------------+----------------+---------------
Total | 689 us (*) | 980 us (+42%) | 707 us | 531 us (-23%)
----------------------------------+-------------+----------------+----------------+---------------
I didn't know that Python 3.4 was so much slower than Python 2.7 on function calls!?
Note: Python 2.7 and Python 3.4 are system binaries (Fedora 22), wheras Python 3.6 and Python 3.6 FASTCALL are compiled manually.
Ignore "b=MyBytes(); bytes(b)", this benchmark is written for Python 3.
--
details:
Common platform:
Bits: int=32, long=64, long long=64, size_t=64, void*=64
Platform: Linux-4.4.4-301.fc23.x86_64-x86_64-with-fedora-23-Twenty_Three
CPU model: Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz
Platform of campaign py27:
CFLAGS: -fno-strict-aliasing
Python unicode implementation: UCS-4
Timer precision: 954 ns
Python version: 2.7.10 (default, Sep 8 2015, 17:20:17) [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)]
Timer: time.time
Platform of campaign py34:
Timer info: namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09): 84 ns
Python unicode implementation: PEP 393
Python version: 3.4.3 (default, Jun 29 2015, 12:16:01) [GCC 5.1.1 20150618 (Red Hat 5.1.1-4)]
Timer: time.perf_counter
Platform of campaign py36:
Timer info: namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09)
Python unicode implementation: PEP 393
Timer: time.perf_counter
Platform of campaign fast:
Timer info: namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09)
CFLAGS: -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
Python unicode implementation: PEP 393
Python version: 3.6.0a0 (default:ad4a53ed1fbf, Apr 22 2016, 12:42:15) [GCC 5.3.1 20151207 (Red Hat 5.3.1-2)]
Could you compare filter(), map() and sorted() performance with your patch and with issue23507 patch?
Results of the CPython benchmark suite on the revision 6c376e866330 of compared to CPython 3.6 at the revision 496e094f4734.
It's surprising than call_simple is 1.08x slower in fastcall. This slowdown is not acceptable and should be fixed. It probable explains why many other benchmarks are slower.
Hopefully, some benchmarks are faster, between 1.02x and 1.09x faster.
IMHO there are still performance issues in my current implementation that can and must be fixed. At least, we have a starting point to compare performances.
$ python3 -u perf.py ../default/python ../fastcall/python -b all
(...)
Report on Linux smithers 4.4.4-301.fc23.x86_64 #1 SMP Fri Mar 4 17:42:42 UTC 2016 x86_64 x86_64
Total CPU cores: 8
[ slower ]
### 2to3 ###
6.859604 -> 6.985351: 1.02x slower
### call_method_slots ###
Min: 0.308846 -> 0.317780: 1.03x slower
Avg: 0.308902 -> 0.318667: 1.03x slower
Significant (t=-464.83)
Stddev: 0.00003 -> 0.00026: 9.8974x larger
### call_simple ###
Min: 0.232594 -> 0.251789: 1.08x slower
Avg: 0.232816 -> 0.252443: 1.08x slower
Significant (t=-911.97)
Stddev: 0.00024 -> 0.00011: 2.2373x smaller
### chaos ###
Min: 0.273084 -> 0.284790: 1.04x slower
Avg: 0.273951 -> 0.293177: 1.07x slower
Significant (t=-7.57)
Stddev: 0.00036 -> 0.01796: 49.9421x larger
### django_v3 ###
Min: 0.549604 -> 0.569982: 1.04x slower
Avg: 0.550557 -> 0.571038: 1.04x slower
Significant (t=-204.09)
Stddev: 0.00046 -> 0.00054: 1.1747x larger
### float ###
Min: 0.261939 -> 0.269224: 1.03x slower
Avg: 0.268475 -> 0.276515: 1.03x slower
Significant (t=-12.22)
Stddev: 0.00301 -> 0.00354: 1.1757x larger
### formatted_logging ###
Min: 0.325786 -> 0.334440: 1.03x slower
Avg: 0.326827 -> 0.335968: 1.03x slower
Significant (t=-34.44)
Stddev: 0.00129 -> 0.00136: 1.0503x larger
### mako_v2 ###
Min: 0.039642 -> 0.044765: 1.13x slower
Avg: 0.040251 -> 0.045562: 1.13x slower
Significant (t=-323.73)
Stddev: 0.00028 -> 0.00024: 1.1558x smaller
### meteor_contest ###
Min: 0.196589 -> 0.203667: 1.04x slower
Avg: 0.197497 -> 0.204782: 1.04x slower
Significant (t=-76.06)
Stddev: 0.00050 -> 0.00045: 1.1111x smaller
### nqueens ###
Min: 0.274664 -> 0.285866: 1.04x slower
Avg: 0.275285 -> 0.286774: 1.04x slower
Significant (t=-68.34)
Stddev: 0.00091 -> 0.00076: 1.2036x smaller
### pickle_list ###
Min: 0.262687 -> 0.269629: 1.03x slower
Avg: 0.263804 -> 0.270789: 1.03x slower
Significant (t=-50.14)
Stddev: 0.00070 -> 0.00070: 1.0004x larger
### raytrace ###
Min: 1.272960 -> 1.284516: 1.01x slower
Avg: 1.276398 -> 1.368574: 1.07x slower
Significant (t=-3.41)
Stddev: 0.00157 -> 0.19115: 122.0022x larger
### regex_compile ###
Min: 0.335753 -> 0.343820: 1.02x slower
Avg: 0.336273 -> 0.344894: 1.03x slower
Significant (t=-127.84)
Stddev: 0.00026 -> 0.00040: 1.5701x larger
### regex_effbot ###
Min: 0.048656 -> 0.050810: 1.04x slower
Avg: 0.048692 -> 0.051619: 1.06x slower
Significant (t=-69.92)
Stddev: 0.00002 -> 0.00030: 16.7793x larger
### silent_logging ###
Min: 0.069539 -> 0.071172: 1.02x slower
Avg: 0.069679 -> 0.071230: 1.02x slower
Significant (t=-124.08)
Stddev: 0.00009 -> 0.00002: 3.7073x smaller
### simple_logging ###
Min: 0.278439 -> 0.287736: 1.03x slower
Avg: 0.279504 -> 0.288811: 1.03x slower
Significant (t=-52.46)
Stddev: 0.00084 -> 0.00093: 1.1074x larger
### telco ###
Min: 0.012480 -> 0.013104: 1.05x slower
Avg: 0.012561 -> 0.013157: 1.05x slower
Significant (t=-100.42)
Stddev: 0.00004 -> 0.00002: 1.5881x smaller
### unpack_sequence ###
Min: 0.000047 -> 0.000048: 1.03x slower
Avg: 0.000047 -> 0.000048: 1.03x slower
Significant (t=-1170.16)
Stddev: 0.00000 -> 0.00000: 1.0749x larger
### unpickle_list ###
Min: 0.325310 -> 0.330080: 1.01x slower
Avg: 0.326484 -> 0.333974: 1.02x slower
Significant (t=-24.19)
Stddev: 0.00100 -> 0.00195: 1.9392x larger
[ faster ]
### chameleon_v2 ###
Min: 5.525575 -> 5.263668: 1.05x faster
Avg: 5.541444 -> 5.281893: 1.05x faster
Significant (t=85.79)
Stddev: 0.01107 -> 0.01831: 1.6539x larger
### etree_iterparse ###
Min: 0.212073 -> 0.197146: 1.08x faster
Avg: 0.215504 -> 0.200254: 1.08x faster
Significant (t=61.07)
Stddev: 0.00119 -> 0.00130: 1.0893x larger
### etree_parse ###
Min: 0.282983 -> 0.260390: 1.09x faster
Avg: 0.284333 -> 0.262758: 1.08x faster
Significant (t=77.34)
Stddev: 0.00102 -> 0.00169: 1.6628x larger
### etree_process ###
Min: 0.218953 -> 0.213683: 1.02x faster
Avg: 0.221036 -> 0.215280: 1.03x faster
Significant (t=25.98)
Stddev: 0.00114 -> 0.00108: 1.0580x smaller
### hexiom2 ###
Min: 122.001408 -> 118.967112: 1.03x faster
Avg: 122.108010 -> 119.110115: 1.03x faster
Significant (t=16.81)
Stddev: 0.15076 -> 0.20224: 1.3415x larger
### pathlib ###
Min: 0.088533 -> 0.084888: 1.04x faster
Avg: 0.088916 -> 0.085280: 1.04x faster
Significant (t=257.68)
Stddev: 0.00014 -> 0.00017: 1.1725x larger
The following not significant results are hidden, use -v to show them:
call_method, call_method_unknown, etree_generate, fannkuch, fastpickle, fastunpickle, go, json_dump_v2, json_load, nbody, normal_startup, pickle_dict, pidigits, regex_v8, richards, spectral_norm, startup_nosite, tornado_http.
I have collected statistics about using CALL_FUNCTION* opcodes in compliled code during running CPython testsuite. According to it, 99.4% emitted opcodes is the CALL_FUNCTION opcode, and 89% of emitted CALL_FUNCTION opcodes have only positional arguments, and 98% of them have not more than 3 arguments.
That was about calls from Python code. All convenient C API functions (like PyObject_CallFunction and PyObject_CallFunctionObjArgs) used for direct calling in C code use only positional arguments.
Thus I think we need to optimize only cases of calling with small number (0-3) of positional arguments.
> Thus I think we need to optimize only cases of calling with small number (0-3) of positional arguments.
My code is optimized to up to 10 positional arguments: with 0..10 arguments, the C stack is used to hold the array of PyObject*. For more arguments, an array is allocated in the heap memory.
+ /* 10 positional parameters or 5 (key, value) pairs for keyword parameters.
+ 40 bytes on 32-bit or 80 bytes on 64-bit. */
+# define _PyStack_SIZE 10
For keyword parameters, I don't know yet what is the best API (fatest API). Right now, I'm also using the same PyObject** array for positional and keyword arguments using "int nk", but maybe a dictionary is faster to combinary keyword arguments and to parse keyword arguments.
I think you can simplify the patch by dropping keyword arguments support from fastcall. Then you can decrease _PyStack_SIZE to 4 (larger size will serve only 1.7% of calls), and may be refactor a code since an array of 4 pointers consumes less C stack than an array of 10 pointers.
Results of the CPython benchmark suite. Reference = default branch at rev 496e094f4734, patched: fastcall fork at rev 2b4b7def2949.
I got many issues to get a reliable benchmark output:
*
*
The benchmark was run with CPU isolation. Both binaries were compiled with PGO+LTO.
Report on Linux smithers 4.4.4-301.fc23.x86_64 #1 SMP Fri Mar 4 17:42:42 UTC 2016 x86_64 x86_64
Total CPU cores: 8
### call_method_slots ###
Min: 0.289704 -> 0.269634: 1.07x faster
Avg: 0.290149 -> 0.275953: 1.05x faster
Significant (t=162.17)
Stddev: 0.00019 -> 0.00150: 8.1176x larger
### call_method_unknown ###
Min: 0.275295 -> 0.302810: 1.10x slower
Avg: 0.280201 -> 0.309166: 1.10x slower
Significant (t=-200.65)
Stddev: 0.00161 -> 0.00191: 1.1909x larger
### call_simple ###
Min: 0.202163 -> 0.207939: 1.03x slower
Avg: 0.202332 -> 0.208662: 1.03x slower
Significant (t=-636.09)
Stddev: 0.00008 -> 0.00015: 2.0130x larger
### chameleon_v2 ###
Min: 4.349474 -> 3.901936: 1.11x faster
Avg: 4.377664 -> 3.942932: 1.11x faster
Significant (t=62.39)
Stddev: 0.01403 -> 0.06826: 4.8635x larger
### django_v3 ###
Min: 0.484456 -> 0.462013: 1.05x faster
Avg: 0.489186 -> 0.465189: 1.05x faster
Significant (t=53.10)
Stddev: 0.00415 -> 0.00180: 2.3096x smaller
### etree_generate ###
Min: 0.193538 -> 0.182069: 1.06x faster
Avg: 0.196306 -> 0.184403: 1.06x faster
Significant (t=65.94)
Stddev: 0.00140 -> 0.00115: 1.2181x smaller
### etree_iterparse ###
Min: 0.189955 -> 0.177583: 1.07x faster
Avg: 0.195268 -> 0.183411: 1.06x faster
Significant (t=27.04)
Stddev: 0.00316 -> 0.00304: 1.0386x smaller
### etree_process ###
Min: 0.166556 -> 0.158617: 1.05x faster
Avg: 0.168822 -> 0.160672: 1.05x faster
Significant (t=43.33)
Stddev: 0.00125 -> 0.00140: 1.1205x larger
### fannkuch ###
Min: 0.859842 -> 0.878412: 1.02x slower
Avg: 0.865138 -> 0.889188: 1.03x slower
Significant (t=-14.97)
Stddev: 0.00718 -> 0.01436: 2.0000x larger
### float ###
Min: 0.222095 -> 0.214706: 1.03x faster
Avg: 0.226273 -> 0.218210: 1.04x faster
Significant (t=21.61)
Stddev: 0.00307 -> 0.00212: 1.4469x smaller
### hexiom2 ###
Min: 100.489630 -> 94.765364: 1.06x faster
Avg: 101.204871 -> 94.885605: 1.07x faster
Significant (t=77.45)
Stddev: 0.25310 -> 0.05016: 5.0454x smaller
### meteor_contest ###
Min: 0.181076 -> 0.176904: 1.02x faster
Avg: 0.181759 -> 0.177783: 1.02x faster
Significant (t=43.68)
Stddev: 0.00061 -> 0.00067: 1.1041x larger
### nbody ###
Min: 0.208752 -> 0.217011: 1.04x slower
Avg: 0.211552 -> 0.219621: 1.04x slower
Significant (t=-69.45)
Stddev: 0.00080 -> 0.00084: 1.0526x larger
### pathlib ###
Min: 0.077121 -> 0.070698: 1.09x faster
Avg: 0.078310 -> 0.071958: 1.09x faster
Significant (t=133.39)
Stddev: 0.00069 -> 0.00081: 1.1735x larger
### pickle_dict ###
Min: 0.530379 -> 0.514363: 1.03x faster
Avg: 0.531325 -> 0.515902: 1.03x faster
Significant (t=154.33)
Stddev: 0.00086 -> 0.00050: 1.7213x smaller
### pickle_list ###
Min: 0.253445 -> 0.263959: 1.04x slower
Avg: 0.255362 -> 0.267402: 1.05x slower
Significant (t=-95.47)
Stddev: 0.00075 -> 0.00101: 1.3447x larger
### raytrace ###
Min: 1.071042 -> 1.030849: 1.04x faster
Avg: 1.076629 -> 1.109029: 1.03x slower
Significant (t=-3.93)
Stddev: 0.00199 -> 0.08246: 41.4609x larger
### regex_compile ###
Min: 0.286053 -> 0.273454: 1.05x faster
Avg: 0.287171 -> 0.274422: 1.05x faster
Significant (t=153.16)
Stddev: 0.00067 -> 0.00050: 1.3452x smaller
### regex_effbot ###
Min: 0.044186 -> 0.048192: 1.09x slower
Avg: 0.044336 -> 0.048513: 1.09x slower
Significant (t=-172.41)
Stddev: 0.00020 -> 0.00014: 1.4671x smaller
### richards ###
Min: 0.137456 -> 0.135029: 1.02x faster
Avg: 0.138993 -> 0.136028: 1.02x faster
Significant (t=20.35)
Stddev: 0.00116 -> 0.00088: 1.3247x smaller
### silent_logging ###
Min: 0.060288 -> 0.056344: 1.07x faster
Avg: 0.060380 -> 0.056518: 1.07x faster
Significant (t=310.27)
Stddev: 0.00011 -> 0.00005: 2.1029x smaller
### telco ###
Min: 0.010735 -> 0.010441: 1.03x faster
Avg: 0.010849 -> 0.010557: 1.03x faster
Significant (t=34.04)
Stddev: 0.00007 -> 0.00005: 1.3325x smaller
### unpickle_list ###
Min: 0.290750 -> 0.297958: 1.02x slower
Avg: 0.292741 -> 0.299419: 1.02x slower
Significant (t=-41.62)
Stddev: 0.00133 -> 0.00090: 1.4852x smaller
The following not significant results are hidden, use -v to show them:
2to3, call_method, chaos, etree_parse, fastpickle, fastunpickle, formatted_logging, go, json_dump_v2, json_load, mako_v2, normal_startup, nqueens, pidigits, regex_v8, simple_logging, spectral_norm, startup_nosite, tornado_http, unpack_sequence.
> Results of the CPython benchmark suite. Reference = default branch at rev 496e094f4734, patched: fastcall fork at rev 2b4b7def2949.
Oh, I forgot to mention that I modified perf.py to run each benchmark using 10 fresh processes to test multiple random seeds for the randomized hash function, instead of testing a fixed seed (PYTHONHASHSEED=1). This change should reduce the noise in the benchmark results.
I ran the benchmark suite using --rigorous.
I will open a new issue later for my perf.py change.
Could you repeat benchmarks on different computer? Better with different CPU or compiler.
> Could you repeat benchmarks on different computer? Better with different CPU or compiler.
Sorry, I don't really have the bandwith to repeat the benchmarks. PGO+LTO compilation is slow and running the benchmark suite in rigorous mode is very slow.
What do you expect from running the benchmark on a different computer?
Results look as a noise. Some tests become slower, others become faster. If results on different machine will show the same sets of slowing down and speeding up tests, this likely is not a noise.
> Results look as a noise.
As I wrote, it's really hard to get a reliable benchmark result. I did my best.
See also discussions about the CPython benchmark suite on the speed list:
I'm not sure that you will get less noise on other computers. IMHO many benchmarks are simply "broken" (not reliable).
Hi,.
New patch: 34456cce64bb.patch
$ diffstat 34456cce64bb.patch
.hgignore | 3
Makefile.pre.in | 37
b/Doc/includes/shoddy.c | 2
b/Include/Python.h | 1
b/Include/abstract.h | 17
b/Include/descrobject.h | 14
b/Include/funcobject.h | 6
b/Include/methodobject.h | 6
b/Include/modsupport.h | 20
b/Include/object.h | 28
b/Lib/json/encoder.py | 1
b/Lib/test/test_extcall.py | 19
b/Lib/test/test_sys.py | 6
b/Modules/_collectionsmodule.c | 14
b/Modules/_csv.c | 15
b/Modules/_ctypes/_ctypes.c | 12
b/Modules/_ctypes/stgdict.c | 2
b/Modules/_datetimemodule.c | 47
b/Modules/_elementtree.c | 11
b/Modules/_functoolsmodule.c | 113 +-
b/Modules/_io/clinic/_iomodule.c.h | 8
b/Modules/_io/clinic/bufferedio.c.h | 42
b/Modules/_io/clinic/bytesio.c.h | 42
b/Modules/_io/clinic/fileio.c.h | 26
b/Modules/_io/clinic/iobase.c.h | 26
b/Modules/_io/clinic/stringio.c.h | 34
b/Modules/_io/clinic/textio.c.h | 40
b/Modules/_io/iobase.c | 4
b/Modules/_json.c | 24
b/Modules/_lsprof.c | 4
b/Modules/_operator.c | 11
b/Modules/_pickle.c | 106 -
b/Modules/_posixsubprocess.c | 15
b/Modules/_sre.c | 11
b/Modules/_ssl.c | 9
b/Modules/_testbuffer.c | 4
b/Modules/_testcapimodule.c | 4
b/Modules/_threadmodule.c | 32
b/Modules/_tkinter.c | 11
b/Modules/arraymodule.c | 29
b/Modules/cjkcodecs/clinic/multibytecodec.c.h | 50
b/Modules/clinic/_bz2module.c.h | 8
b/Modules/clinic/_codecsmodule.c.h | 318 +++--
b/Modules/clinic/_cryptmodule.c.h | 10
b/Modules/clinic/_datetimemodule.c.h | 8
b/Modules/clinic/_dbmmodule.c.h | 26
b/Modules/clinic/_elementtree.c.h | 86 -
b/Modules/clinic/_gdbmmodule.c.h | 26
b/Modules/clinic/_lzmamodule.c.h | 16
b/Modules/clinic/_opcode.c.h | 10
b/Modules/clinic/_pickle.c.h | 34
b/Modules/clinic/_sre.c.h | 124 +-
b/Modules/clinic/_ssl.c.h | 74 -
b/Modules/clinic/_tkinter.c.h | 50
b/Modules/clinic/_winapi.c.h | 124 +-
b/Modules/clinic/arraymodule.c.h | 34
b/Modules/clinic/audioop.c.h | 210 ++-
b/Modules/clinic/binascii.c.h | 36
b/Modules/clinic/cmathmodule.c.h | 24
b/Modules/clinic/fcntlmodule.c.h | 34
b/Modules/clinic/grpmodule.c.h | 14
b/Modules/clinic/md5module.c.h | 8
b/Modules/clinic/posixmodule.c.h | 642 ++++++-----
b/Modules/clinic/pyexpat.c.h | 32
b/Modules/clinic/sha1module.c.h | 8
b/Modules/clinic/sha256module.c.h | 14
b/Modules/clinic/sha512module.c.h | 14
b/Modules/clinic/signalmodule.c.h | 50
b/Modules/clinic/unicodedata.c.h | 42
b/Modules/clinic/zlibmodule.c.h | 68 -
b/Modules/itertoolsmodule.c | 20
b/Modules/main.c | 2
b/Modules/pyexpat.c | 3
b/Modules/signalmodule.c | 9
b/Modules/xxsubtype.c | 4
b/Objects/abstract.c | 403 ++++---
b/Objects/bytesobject.c | 2
b/Objects/classobject.c | 36
b/Objects/clinic/bytearrayobject.c.h | 90 -
b/Objects/clinic/bytesobject.c.h | 66 -
b/Objects/clinic/dictobject.c.h | 10
b/Objects/clinic/unicodeobject.c.h | 10
b/Objects/descrobject.c | 162 +-
b/Objects/dictobject.c | 26
b/Objects/enumobject.c | 8
b/Objects/exceptions.c | 91 +
b/Objects/fileobject.c | 29
b/Objects/floatobject.c | 25
b/Objects/funcobject.c | 77 -
b/Objects/genobject.c | 2
b/Objects/iterobject.c | 6
b/Objects/listobject.c | 20
b/Objects/longobject.c | 40
b/Objects/methodobject.c | 139 ++
b/Objects/object.c | 4
b/Objects/odictobject.c | 2
b/Objects/rangeobject.c | 12
b/Objects/tupleobject.c | 21
b/Objects/typeobject.c | 1463 +++++++++++++++++++-------
b/Objects/unicodeobject.c | 58 -
b/Objects/weakrefobject.c | 22
b/PC/clinic/msvcrtmodule.c.h | 42
b/PC/clinic/winreg.c.h | 128 +-
b/PC/clinic/winsound.c.h | 26
b/PCbuild/pythoncore.vcxproj | 4
b/Parser/tokenizer.c | 7
b/Python/ast.c | 31
b/Python/bltinmodule.c | 173 +--
b/Python/ceval.c | 591 +++++++++-
b/Python/clinic/bltinmodule.c.h | 104 +
b/Python/clinic/import.c.h | 18
b/Python/codecs.c | 17
b/Python/errors.c | 105 -
b/Python/getargs.c | 284 ++++-
b/Python/import.c | 27
b/Python/modsupport.c | 244 +++-
b/Python/pythonrun.c | 10
b/Python/sysmodule.c | 32
b/Tools/clinic/clinic.py | 115 +-
pystack.c | 288 +++++
pystack.h | 64 +
121 files changed, 5420 insertions(+), 2802 deletions(-)
Status of the my FASTCALL implementation (34456cce64bb.patch):
* Add METH_FASTCALL calling convention to C functions, similar
to METH_VARARGS|METH_KEYWORDS
* Clinic uses METH_FASTCALL when possible (it may use METH_FASTCALL
for all cases in the future)
* Add new C functions:
- _PyObject_FastCall(func, stack, nargs, kwds): root of the FASTCALL branch
- PyObject_CallNoArg(func)
- PyObject_CallArg1(func, arg)
* Add new type flags changing the calling conventions of tp_new, tp_init and
tp_call:
- Py_TPFLAGS_FASTNEW
- Py_TPFLAGS_FASTINIT
- Py_TPFLAGS_FASTCALL
* Backward incompatible change of Py_TPFLAGS_FASTNEW and Py_TPFLAGS_FASTINIT
flags: calling explicitly type->tp_new() and type->tp_init() is now a bug
and is likely to crash, since the calling convention can now be FASTCALL.
* New _PyType_CallNew() and _PyType_CallInit() functions to call tp_new and
tp_init of a type. Functions which called tp_new and tp_init directly were
patched.
* New helpers function to parse functions functions:
- PyArg_ParseStack()
- PyArg_ParseStackAndKeywords()
- PyArg_UnpackStack()
* New Py_Build functons:
- Py_BuildStack()
- Py_VaBuildStack()
* New _PyStack API to handle a stack:
- _PyStack_Alloc(), _PyStack_Free(), _PyStack_Copy()
- _PyStack_FromTuple()
- _PyStack_FromBorrowedTuple()
- _PyStack_AsTuple(), _PyStack_AsTupleSlice()
- ...
* Many changes were done in the typeobject.c file to handle FASTCALL, new
type flags, handle correctly flags when a new type is created, etc.
* ceval.c: add _PyFunction_FastCall() function (somehow, I only exposed
existing code)
A large part of the patch changes existing code to use the new calling
convention in many functions of many modules. Some changes were generated
by the Argument Clinic. IMHO the best would be to use Argument Clinic in more
places, rather than patching manually the code.
> Result of the benchmark suite:
>
> slower (3):
>
> * raytrace: 1.06x slower
> * etree_parse: 1.03x slower
> * normal_startup: 1.02x slower
Hum, I recompiled the patched Python, again with PGO+LTO, and ran the same benchmark with the same command. In short, I replayed exaclty the same scenario. And... Only raytrace remains slower, etree_parse and normal_startup moved to the "not significant" list.
The difference in the benchmark result doesn't come from the benchmark. For example, I ran gain the normal_startup benchmark 3 times: I got the same result 3 times.
### normal_startup ###
Avg: 0.295168 +/- 0.000991 -> 0.294926 +/- 0.00048: 1.00x faster
Not significant
### normal_startup ###
Avg: 0.294871 +/- 0.000606 -> 0.294883 +/- 0.00072: 1.00x slower
Not significant
### normal_startup ###
Avg: 0.295096 +/- 0.000706 -> 0.294967 +/- 0.00068: 1.00x faster
Not significant
IMHO the difference comes from the data collected by PGO.
> In short, I replayed exaclty the same scenario. And... Only raytrace remains slower, (...)
Oh, it looks like the reference binary calls the garbage collector less frequently than the patched python. In the patched Python, collections of the generation 2 are needed, whereas no collection of the generation 2 is needed on the reference binary.
> unpickle_list: 1.11x faster
This result was unfair: my fastcall branch contained the optimization of the issue #27056. I just pushed this optimization into the default branch.
I ran again the benchmark: the result is now "not significant", as expected, since the benchmark is a microbenchmark testing C functions of Modules/_pickle.c, it doesn't really rely on the performance of (C or Python) functions calls.
I fixed even more issues with my setup to run benchmark. Results should be even more reliable. Moreover, I fixed multiple reference leaks in the code which introduced performance regressions. I started to write articles to explain how to run stable benchmarks:
*
*
*
Summary of benchmarks at the revision e6f3bf996c01:
Faster (25):
- pickle_list: 1.29x faster
- etree_generate: 1.22x faster
- pickle_dict: 1.19x faster
- etree_process: 1.16x faster
- mako_v2: 1.13x faster
- telco: 1.09x faster
- raytrace: 1.08x faster
- etree_iterparse: 1.08x faster
- regex_compile: 1.07x faster
- json_dump_v2: 1.07x faster
- etree_parse: 1.06x faster
- regex_v8: 1.05x faster
- call_method_unknown: 1.05x faster
- chameleon_v2: 1.05x faster
- fastunpickle: 1.04x faster
- django_v3: 1.04x faster
- chaos: 1.04x faster
- 2to3: 1.03x faster
- pathlib: 1.03x faster
- unpickle_list: 1.03x faster
- json_load: 1.03x faster
- fannkuch: 1.03x faster
- call_method: 1.02x faster
- unpack_sequence: 1.02x faster
- call_method_slots: 1.02x faster
Slower (4):
- regex_effbot: 1.08x slower
- nbody: 1.08x slower
- spectral_norm: 1.07x slower
- nqueens: 1.06x slower
Not significat (13):
- tornado_http
- startup_nosite
- simple_logging
- silent_logging
- richards
- pidigits
- normal_startup
- meteor_contest
- go
- formatted_logging
- float
- fastpickle
- call_simple
I'm now investigating why 4 benchmarks are slower.
Note: I'm still using my patched CPython benchmark suite to get more stable benchmark. I will send patches upstream later.
I splitted the giant patch into smaller patches easier to review. The first part (_PyObject_FastCall, _PyObject_FastCallDict) is already merged. Other issues were opened to implement the full feature. I now close this issue.
|
https://bugs.python.org/issue26814
|
CC-MAIN-2017-51
|
refinedweb
| 6,403
| 63.36
|
One Software Factories. What is their role in Software Factories? How can they help you develop software? Is this just more hype or will Domain Specific Languages really change the way we build software in the not too far future? Let’s find out on the next pages.
This article will start with a brief discussion of the Microsoft Software Factories initiative together with the first wave of accompanying products. We will discuss the role that these individual products play in the Software Factories initiative and show you how they relate to each other. We will use this knowledge as a context for positioning Domain Specific Languages and the Microsoft DSL Tools. We will guide you through this new technology by using a real-life example of a Domain Specific Language that we can use to model services contracts in a service-oriented world when building distributed solutions.
Software Factories
When we have a close and objective look at the industry we are working in, we cannot but conclude that our software industry doesn’t do a very good job compared to most other industries-especially those with a long history of engineering.
Overview
The way we are building software today often leads to projects running out of budget, shipping products of poor quality and therefore leads to overall unsatisfied consumers. So, it could be argued that its time for the software industry to grow up. This is exactly where the Microsoft Software Factories initiative comes in.
The theory behind Software Factories is discussed in the book called Software Factories [1]. It describes how the software industry can change the way we are working, how to build software by assembling reusable components, how to move from craftsmanship to industrialization and therefore how to increase the capacity and performance of the software industry as a whole. All of this sounds great but what does this mean for us as architects and developers?
Let’s have a look how we can translate the theory behind Software Factories to a real life scenario. The basic idea is that the “general purpose” development environment (in the .NET world this usually is Visual Studio) will be customized by the architects and developers in a company. This environment will gradually be tuned for their specific business. The development environment (Visual Studio) provides the mechanism to facilitate the customization. The development team provides the effort that is necessary to customize it. Over time, developers will find it easier to do their development tasks because more of it becomes automated. In the end, it’s the optimized development environment that we call a Software Factory.
Normally, the Software Factory is optimized for a specific type of software. This means the development environment provides developers with components, patterns, architectural rules, and semi-finished products that they can use to compose software. All of them are valid within their own specific domain. Think of a Software Factory as a product line in a real factory that is tailored for assembling a specific type of product, like a car.
Keep in mind that the Software Factory will not deliver all pieces of the puzzle-custom code is still needed-but it is the intention that Software Factories speed up development and hopefully improves long-term quality dramatically.
Before we can optimize the environment we are working in we need to have a good understanding of the type of software we are building. That means we have to identify the so-called artifacts that our software can be composed off. Think of artifacts as individual parts in our software that can be various items in the range of configuration files, source code, and even frameworks. This list of artifacts is like a recipe for a meal and is called the Software Factory Schema. This Software Factory Schema also describes the relations between the different products in the list so we know how to use them together to actually cook the meal. The Software Factory Schema only sums up and describes the artifacts; the real implementations of the products, mentioned in the Software Factory Schema, form the Software Factory Template. Think of this as a set of patterns, frameworks, templates, guidelines, etc. In the end, it’s the Software Factory Template that we use to configure a tool like Visual Studio 2005 Team System to transform it into an optimized environment for building a specific product family.
At this moment we are just in the very early stages of Software Factories. Very slowly, some early examples ([2], [3]) become available. We have to see how they evolve and if Software Factories will meet the expectations of the future.
Accompanying Tools
Now that you know that the Visual Studio environment acts as the placeholder for all Software Factory components, let’s look at some other complementary products to complete the big picture. Remember, Visual Studio provides the customization mechanism that will be used by the tools we will discuss now.
Another totally new tool is the Guidance Automation Toolkit (GAT, [4]). You can use this toolkit create guidance packages that you can load into Visual Studio. A guidance package is an integrated set of reusable scripts, patterns, and code snippets that you can use in Visual Studio 2005. By using GAT we can automate repetitive and often boring activities. We can deliver things like wizards, artifact generation and context-aware guidance that help developers work in the Software Factory. The ultimate goal of GAT is to increase the productivity of our software development process and eliminate the rote and menial tasks as much as possible by making guidance and automation available in Visual Studio.
The last piece in the Software Factory tools puzzle is the Microsoft DSL Tools. This toolkit makes it possible to create Domain Specific Languages that we can use in our Software Factory. As you will see in the remainder of this article, Domain Specific Languages and the DSL Tools are yet another way to automate and improve the software development process for certain aspects of a system.
Software Factories Ecosystem
Before we continue with Domain Specific Languages in some more detail, let’s summarize the Software Factories ecosystem. Figure 1 displays the individual tools and concepts grouped together that we call the Software Factories ecosystem. The Software Factory Schema describes the artifacts that are relevant for a specific problem domain. These artifacts, in turn, are implemented as frameworks, source code, configuration files, and Domain Specific Languages. The frameworks, code, and configuration files are used in the Guidance Automation Toolkit to create a guidance package; the Domain Specific Languages are implemented with the DSL Tools. It’s the guidance package and the Domain Specific Language together and loaded in the Visual Studio Team System environment that form the actual Software Factory. Of course this is today’s state and the entire story about tooling may change with upcoming releases of Visual Studio.
Domain Specific Languages
Now that we have a have a high level understanding of the Microsoft Software Factories initiative and the available tools in this area, we will focus on Domain Specific Languages for the rest of this article.
Definition
A Domain Specific Language is a custom language that targets a small problem domain. It describes the problem at a higher abstraction level than general purpose languages do. It just provides another view of the same problem.
That’s it, nothing more, nothing less. Let us explain a little why we think this is a proper definition of a Domain Specific Language. First of all, a Domain Specific Language can only be used to describe a specific problem. This is a big difference compared to a general purpose language like C# where we can describe all sorts of problems. It is the limited focus of a Domain Specific Language that makes it possible to describe the problem in abstractions that make sense to the problem. Because of these abstractions, the problem is easier to understand for a larger group of people. The underlying problem, however, remains just the same.
But wait, we haven’t heard the word ‘Microsoft’ or ‘DSL Tools’ in this definition, right? That’s correct. Domain Specific Languages can live perfectly without any Microsoft tooling. In fact, Domain Specific Languages have existed for quite some time now and are valid not only in the Software Factories context. Technologies like SQL, XSD, and even Windows Forms are all simple to more complex examples of Domain Specific Languages that most of us are quite familiar with. And that said, they are far from always being a graphical thing [5].
But with the availability of the DSL Tools [6] it becomes relatively easy for a developer or architect to build a Domain Specific Language. It’s the DSL Tools that also provide a way to add a graphical representation and appropriate designer to the Domain Specific Language. All of this is great but these are not the core features of a Domain Specific Language. However, these them for our design and development?
First of all, a Domain Specific Language provides a clear view of the problem domain we are writing software or parts of software for. By using a Domain Specific Language-and especially one that comes with a graphical designer-we are forced to focus our attention on the important concepts in the domain. Only the concepts that exist within the Domain Specific Language are valid candidates for discussion during the design phase of our software. This doesn’t mean that only one Domain Specific Language is used for building a software component. It is possible to use several Domain Specific Languages that together cover the whole problem domain. Also, a Domain Specific Language helps us create valid relations between the concepts. Relations between concepts that don’t make sense are simply not allowed in the language and/or designer. Because of this limited set of concepts and possible relations we will see that we stimulate standardization in the design of our software components.
Another related advantage of a Domain Specific Language is the higher level of abstraction we are dealing with. How often do design sessions using the WSDL specification for this same discussion. In addition, it is much easier to share designs of software components you crafted in a Domain Specific Language designer between team members than sharing pictures you took of a design you created on a whiteboard.
Last but not least, when we have fully adopted the usage of the Domain Specific Languages in our development process, we will notice that we can increase our productivity considerably. Not only because of the time saved in the design phase of our software, but also because of the time we can save by generating artifacts like, for example, C# source code. A very interesting side effect of generating code is the quality boost and increase of standardization this can have on our source code. This, of course (or hopefully?), results in fewer bugs, code that is easier to maintain, and developers that no longer have to code the boring stuff but can concentrate on the much more interesting parts. Be honest-isn’t that what we want?
All that Glistens Is Not Gold
Because Domain Specific Languages related to .NET and Visual Studio are in their very early stages, the consequences and issues very carefully and make sure we fully integrate Domain Specific Languages in, we-and thus with a higher level of abstraction-we re-generate the artifacts. You could even use an automatic build procedure. All manual changes that might have been made in the artifacts simply get overridden. Although this is an effective way it is definitely not the most elegant one. One issue with this approach is that it might not work for all types of artifacts. In the case of a C# file that is generated out of the Domain Specific Language, we can use the partial class technique to separate the generated code from any custom code we want to add later during development. By doing this we can still make changes in the model and re-generate the artifacts without loosing our manual changes. It becomes a little more difficult when we are dealing with a Word document that is one of the Domain Specific Language artifacts.
Another and maybe better approach is to have round-tripping implemented for a Domain Specific Language. This assures a tight coupling between the models we create and the artifacts that are generated out of the model. With this approach we solve the issue that models and artifacts might get out of sync. Round-tripping isn’t supported out of the box in the initial release of the DSL Tools. However, you can (probably) implement it by writing custom code. For a lot of us developers, things like this might sound very tempting and they will start right-away building these kinds of features into their Domain Specific Language.
However, we think it is better not to focus too much on technical features and/or limitations of the current release of the DSL Tools. The DSL Tools will evolve over time and therefore we think it is more important to focus on understanding Domain Specific Languages and the integration of of these procedures and guidelines can, of course, be part of your overall Software Factory.
A Real Life Example
Now that you understand some Domain Specific Language concepts it’s time to get real and build a small example of a Domain Specific Language. Please note that this article doesn’t cover all the details of building a Domain Specific Language with the DSL Tools. There will be plenty of articles and books that will guide you through all the details. Our example Domain Specific Language will demonstrate the kind of problems you can model with a Domain Specific Language. Our example will demonstrate the power of Domain Specific Languages.
Services Everywhere
Most developers are familiar with Web services. We all know by now how to build a Web service within Visual Studio-basically just set the [WebMethod] attribute on a class’ methods. After that you rely on ASMX to expose the service contract to the public world. While this approach might work for some developers, our experiences in the past made very clear that this might not always be the best way. Thinking about service contracts evolved over time and resulted in another, probably better, approach for designing service contracts called contract-first. This article will not cover all the details of the contract-first approach but let’s remember for now that a special flavor of contract-first-called schema-based contract-first-uses XSD schemas and WSDL for designing service contracts. Within this approach you first model your data and messages by using a schema language (like XSD) and after that you define your service interface and service operations in WSDL. From those interoperable metadata artifacts a developer can then create platform and programming language-specific code (Figure 2).
While proved and popular and often applied in enterprise scenarios, this approach is really tedious without the right tooling [7].
This is exactly where our sample Domain Specific Language comes in. Let’s be honest-there is limited tool support for crafting WSDL and not many of us feel comfortable writing WSDL by hand. Therefore, let us introduce a Domain Specific Language for designing service contracts named “Service Description Language” because WSDL and related technologies are not the right level of abstractions to achieve the goal.
Problem Domain
Our example will create a Domain Specific Language that helps us design service contracts. The artifact that is generated by this Domain Specific Language is a service contract description that is represented as WS-I BP 1.1-compliant WSDL. By using this Domain Specific Language we will be able to create WSDL files but now on a higher abstraction level that is understandable and more natural for developers.
Guided Approach
To be successful in building your own Domain Specific Language, we think it is important to stick to some sort of an approach so you don’t get lost in all kind of technical details of the DSL Tools in the design phase of your Domain Specific Language.
Therefore we suggest the following steps:
- Describe the domain concepts;
- Describe the artifacts you are planning for the Domain Specific Language;
- Build your domain model;
- Build the designer for your Domain Specific Language;
- Build the artifact generator;
- Implement validations and constraints;
- Test and deploy the Domain Specific Language;
This article uses some of these steps to demonstrate a number of concepts of Domain Specific Languages and our Service Description Language in particular. Please note that our approach isn’t as formalized as it might look like. We recognize that building a Domain Specific Language might need a few iterations and refinements during the development process. This approach helps you achieve this understanding.
Describing Domain Concepts
The first thing you have to do when building a Domain Specific Language is make sure you understand the problem that you are trying to model exactly and thoroughly. In our example this is service contracts and its relation to WSDL. Let’s have a quick look at some concepts in the Domain Specific Language and describe them in a little more detail.
Let’s start with the ServiceInterface concept which is the high-level abstraction of the service contract. The ServiceInterface describes which operations and accompanying messages are exposed by the service. It’s the ServiceInterface that actually describes what can be done with the service.
Next we have the ServiceOperation concept, which defines an operation in the ServiceInterface. The ServiceOperation describes the message exchange patterns and the accompanying messages for the operation. In other words, it defines the input and optional output message for the operation. (The sample DSL only supports two basic message exchange patterns from WSDL: one-way and request-response.) This leaves us with the next concept, the Message. A Message is a placeholder for the data structures that are used in the ServiceOperations. In real life, Messages are often described in an XSD schema and referenced in WSDL. Since the Message holds the definition of the data structures, this is where the concept of a DataContract comes in. A DataContract represents the data structure itself-think of it as the data on the wire. Just like Messages, you often define DataContracts in an XSD schema. A Message consists of one or more DataContracts. Please note that the DataContract concept in our example Domain Specific Language doesn’t necessarily relate to the Windows Communication Foundation DataContract [8].
Another concept that is embedded in the Message is the MessageHeader. You use the MessageHeader to store out-of-band data that has to flow with the message. For example, you might have user credentials that need to travel with the message to the ServiceOperation.
How did we find the concepts in our service contract domain? We had a close look at elements that can be identified in WSDL and we made sure we understood their purpose. Remember that in our example, WSDL and service contracts are the problem domain. After we looked at the elements, we tried to describe them at a higher abstraction level that makes sense to developers and architects who design and build services.
It is exactly this step in the approach that is extremely important when starting to build your own Domain Specific Language-Don’t start modelling before you know what you are trying to solve.
Table 1 gives you an overview of the concepts that exist in our Service Description Language together with their WSDL counterparts. It’s eventually the WSDL part that gets generated out of the Domain Specific Language.
Describing Artifacts
The next step in building a Domain Specific Language is describing the artifact(s) you are planning to use in your Domain Specific Language. Of course, you also need good knowledge of the artifacts to be able to describe the domain concepts in the first step, but in this step you formalize the artifacts in more detail. For example, when you think a piece of C# code is the artifact of your Domain Specific Language, you write a first version of this C# code in this step. The reason for this is that you can use this formalized artifact to validate the domain concepts you defined in the first step. For our example we just had a close look at the WSDL specification and the WS-I BP 1.1 [9]. An example of a valid and proven WSDL was enough to act as our formalized artifact. Remember that artifacts or the number of artifacts change during the development phase of your Domain Specific Language.
Building Domain Models
Based on a clear understanding of the problem domain and the knowledge of what an initial version of our artifacts looks like, let’s really start building our Domain Specific Language. To do this we need Visual Studio 2005 Team System and the Microsoft DSL Tools installed on our machine.
Note that any code or screenshots in this article are based on the November 2005 CTP release of the DSL Tools. Although significant changes are expected in the final release of the DSL Tools, we think this will have little impact on the content of this article because we don’t provide step-by-step guidance for how to build a Domain Specific Language with the DSL Tools.
Getting Started
To get started you first have to create a new solution within Visual Studio that is based on the “Domain Specific Language” template. A wizard will guide you through this process and will ask some details like name, namespace, and file extension for your language. After you’ve completed the wizard, Visual Studio will load with a solution that you can build your Domain Specific Language in.
We will use the domain model designer within Visual Studio to graphically build the domain model for our language. Figure 4 shows the domain model of the Service Description Language. The current state of the domain model only reflects the concepts we need for describing the service contract itself. Of course, this domain model can evolve over time to cover more service-related topics.
As you will see when you try this yourself, creating a domain model is just a matter of dragging elements from the toolbox to the designer area. In this step, we’ll represent the domain concepts that we defined earlier for our Domain Specific Language as classes in the domain model. You can add custom properties to classes and make them participate in relationships. As the name probably implies, you can use a Relationship to relate domain concepts with each other.
Figure 4 shows that we created a relationship from the ServiceOperation concept to the Message concept in our Service Description Language. We also created relationships from the Message concept to the DataContract and MessageHeader concept. If you have a close look at the latter relationships in the screenshot you can see they are represented by a solid line. The relationship between the ServiceOperation and Message concepts is represented by a dotted line. The difference between both is caused by the type of relationships we used in both cases.
The dotted line represents a “reference relationship” between ServiceOperation and Message. In plain English, this relation means a ServiceOperation “knows about” or “is using” a Message. The solid line represents an “embedding relationship” between a Message and a DataContract and or MessageHeader. This means that the DataContract (or MessageHeader) is part of the Message. In other words a Message consists of a DataContract and MessageHeader. As you will see later on in this article, the difference between the two types of relationships will also show up in the designer for the DSL.
As you will notice when experimenting with the DSL Tools, the domain model is persisted as XML and is stored in a file with extension .dsld and can be found in the DomainModel project in the Visual Studio solution. This will change in the RTM release of the DSL Tools.
Without going into too much detail, you saw how to translate the identified domain concepts into a domain model within the DSL Tools. Let’s look at how to continue building our language.
Building a Designer
Now let’s build a designer for the language. As we said earlier in this article, the graphical designer does not make any language a Domain Specific Language, but since providing a graphical designer for a Domain Specific Language is part of the DSL Tools we will be more than happy to use this feature.
Just like the definition of the domain model, the designer definition is stored as an XML file with a .dsldd extension and can be found in the Designer project of the Visual Studio solution. Unfortunately it isn’t possible to graphically maintain this designer definition in the November CTP of the DSL Tools. Also there is no strict relation between the domain model definition and the designer definition. Therefore you have to make sure you keep both files in sync by hand, which can be a tedious task. All of this will change in the RTM release of the DSL Tools.
Figure 5 shows a snippet of the designer definition file where we describe the MessageShape in the language. The MessageShape is the graphical representation of the Message concept in the Service Description Language. As you can see, the MessageShape is a so-called CompartmentShape and also holds the definition for the DataContractShape and the MessageHeaderShape. (Think of the embedding relation between the Message, DataContract, and MessageHeaders concepts.) Also note that we added two extra ShapeIcon elements, named RightArrow and LeftArrow, to the definition of the MessageShape. We’ll explain a little later why we needed to do that.
Using the Domain Specific Language
Now that we have completed our domain model and designer definition we are ready to use the language for the first time. To do this we can simply choose “Start debugging (F5)” from within Visual Studio Team System. This results in a new, so-called experimental environment of Visual Studio were we can use our language. We will create a new model based on the Domain Specific Language template, in our case this is the Service Description template. We’ll add a new empty model based on this template to the Visual Studio project so we’re ready to graphically model the service contract for any service we would like.
Modelling a Service
Figure 6 shows the concepts that are available for modelling the service contract. You might notice the absence of the DataContract and MessageHeader concepts. These concepts are represented as compartment shapes “inside” the MessageShape. Therefore we cannot create them stand alone from a message and thus there is no need for these concepts to appear in the toolbox.
Figure 7 illustrates that we can simply right-click on the DataContract placeholder in the MessageShape to add a DataContract to it. The same is true for adding a MessageHeader. This is all default behavior of the DSL Tools designer that we created for our language.
After playing around a little with our Domain Specific Language we modelled the service contract for a sample “RestaurantService.” As you can see in Figure 8 the service has one ServiceInterface named RestaurantServiceInterface that exposes three ServiceOperations named GetRestaurants, AddRestaurant, and RateRestaurant. When we have a look at the GetRestaurants service operation we can see that it has an incoming message named GetRestaurants and an outgoing message named GetRestaurantResponse. At this point you can also see where we needed the two extra ShapeIcons that we described earlier. What we didn’t show then is that we added a MessageType property to our Message concept. MessageType is an enumeration with InboundMessage and OutboundMessage as possible values. Based on the value of this property on the Message level we decide which icon to show in the MessageShape. The icons are specified in the ShapeIcon elements in the designer definition mentioned earlier.
Customizations
As you can see in Figure 8, all service operations have one or more DataContracts specified. We already demonstrated that you can simply right-click a MessageShape to manually add a DataContract to the message. Adding a DataContract in this way is out-of-the-box functionality that you get when creating embedding relations between concepts. However we decided to make the DSL a little more user-friendly and therefore built some additional functionality by using a piece of custom code. The default way to set a value of a property on a domain concept in the Domain Specific Language designer is to simply type the value of the property in the Visual Studio property grid. We didn’t like that too much, especially for the SchemaLocation property on our message concept. Therefore, we created a custom UiTypeEditor coupled with the SchemaLocation property of the message shape in our language. Figure 9 demonstrates that we now have the little ellipsis button (…) that appears in the Visual Studio property grid for the SchemaLocation property.
When we click the button a file dialog box pops up (Figure 10) that enables us to navigate to the XSD file that contains the parts of our message. In our example we select the RestaurantMessages.xsd file.
With the XML schema that contains a description of our messages selected, now we must select the actual message in the XSD file. To support this we created an extra menu item that is only available when right-clicking on a MessageShape. Figure 11 shows how we use this custom “Select message from XSD” menu item on the MessageShape to select a message from the XSD.
When we select this menu item another window pops up that provides us with a nice overview of all the messages that are described in the selected XSD file. Figure 12 shows that the RestaurantMessages.xsd file we selected earlier describes four messages. We can now select a message and see the DataContracts that are referenced in that message. Please note that the DataContracts itself are not defined in the RestaurantMessages.xsd file but only referenced from another XSD file.
After selecting the rateRestaurant message in the “Select message” window the MessageShape in the model gets nicely populated with the correct name of the message, DataContracts, and all the appropriate references and type information of the message and DataContracts. All of the above functionality is added by using custom code. The DSL Tools API makes it relatively easy to add features you implemented in any .NET technology you find appropriate to extend the DSL’s feature set.
Generating Artifacts
Now that we’ve finished modelling our service contract using the modelling technique described above we can generate the artifact. In the Domain Specific Language we are describing in this article we want to generate a WS-I BP 1.1-compliant WSDL file that represents the service contract description. The out-of-the-box technique that comes with the DSL Tools for generating artifacts is T4 text templates. T4 text templates have a CodeSmith-like syntax [10] and are processed by a text transformation engine that is part of the DSL Tools. This is the same engine that is used for the Guidance Automation Toolkit. Basically it comes down to mixing boilerplate text with information that comes from models you create in the language. For our Domain Specific Language we choose not to use the T4 templates and instead generated our artifacts in plain C# code. We simply added custom code that uses the model information to communicate with our code to generate WSDL. This again demonstrates the customizations possibilities of the DSL Tools API.
Closing Thoughts
We described a sample and prototype Domain Specific Language that we created for generating service contract descriptions and how they fit into Microsoft’s vision and idea of Software Factories. The language is capable of generating WSDL based on the model we created in the language designer. At this moment the language only focuses on the WSDL part of the service contract and it heavily relies on XSD for describing the messages and data contracts. One feature that we didn’t describe in this article is the possibility to read an existing WSDL file and create a graphical representation of the service contract in the language designer.
Due to the very early beta-like state of the DSL Tools we didn’t go into too much detail about the actual building of a Domain Specific Language. We primarily wanted to demonstrate the power of Domain Specific Languages in general and provide you with an example that can you could build in the current release of the DSL Tools. In this respect it is important to note that the first release of the DSL Tools might miss a few of your requirements. Don’t let this fact discourage you from starting to build Domain Specific Languages. We demonstrated that you can address these potential missing features by writing some custom code.
We will make this Domain Specific Language for modelling service contracts available for download as soon as Microsoft releases the DSL Tools. At that point we will also provide some more technical details about the features we implemented in this language. We’ll also post more details and the download in our blogs.
Links
[1] Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools;
[2] A Software Factory Approach to HL7 Version 3 Solutions;
[3] Web Service Software Factory;
[4] Guidance Automation Toolkit;
[5] Language Workbenches: The Killer-App for Domain Specific Languages?;
[6] DSL Tools;
[7] Introducing Contract-First Web Services;
[8] Distributed .NET-Learn the ABCs of Programming Windows Communication Foundation;
[9] WS-I Basic Profile 1.1;
[10] CodeSmith;
|
http://www.codemag.com/article/0607051
|
CC-MAIN-2015-32
|
refinedweb
| 5,642
| 51.89
|
We all love simplicity, yet we also love freedom of choice. Sometimes these two parameters can be at odds with each other. For instance, if I go out for a beer I'm not too happy if there's only one beer on tap (unless it happens to be one of my absolute favorites). If they have thirty different beers I face the problem of not being able to try them all out in an evening. Do a web search for "paradox of choice" for further explanations on this conundrum.
So, how does this relate to Azure AD B2C and authentication? Well, Azure AD B2C is after all a solution designed to handle more than one option for logging in to an app. But how is an end-user supposed to make the "right" choice when presented with five different options?
I've already done a deep-ish dive into Azure AD B2C and how you go about providing different options:...
You should hopefully be able to follow along with some of the concepts presented even without being familiar in depth with custom policies, but I am assuming you either know the basics already or you are able to learn the necessary details outside of this article. Either through the aforementioned walkthrough or the official docs.
In those posts I mentioned how you could send users off to specific identity providers either by using different policies or adding the domain hint parameter to the query string. In addition, since we added the Azure AD common endpoint it was possible to have some magic behind the scenes as well taking you to the right Azure AD tenant for signin.
With this post I intend to dive further into this specific topic that we often refer to as "home realm discovery" (I'll shorten this to HRD for the rest of this post.).
Why would you care about HRD?
Let's say Contoso has a contoso.com web page. When employees sign in they're likely to use their @contoso.com email addresses, and it's easy enough adding a button for that. But how do you ensure that users don't register a local account which is tied to their contoso.com email address, but not their existing Contoso identity object? Having HRD would let you override that to make sure they use the right provider.
Or in the case of consumers - in a basic Azure AD B2C setup we could present two buttons on the signup screen - "Google account" and "Facebook account". The user makes a choice, and when they return (if their session is expired) we would ask again which of the two you want to use for signing in. You could probably use cookies to keep track of what the user did the last time, but it wouldn't carry over to a new computer/device. Since we have this information stored backend it shouldn't be necessary to ask for more than the email address to figure it out. (Let's keep the fact that you can link multiple social identities to one B2C identity out of this context.)
Which mechanisms do we have at disposal to do things differently?
Hints in B2C query strings
First a repetition of the basics. In addition to offering the ability to define a number of policies Azure AD B2C can take in two parameters in the query string that can affect our choice of identity providers. You have "login_hint" which would be for prefilling the username (this could be both an email address or just "bob"), and there's "domain_hint" which would be a tag for a specific IdP. This means that if you use "login_hint=bob@contoso.com&domain_hint=contoso" the browser would take you to that specific IdP with the email already filled in.
With this knowledge in the back of our minds let us go over a couple of options.
Pre-B2C logic with multiple policies
You're not locked to using one single policy for signins so it is easy to create several policies and for instance have a JavaScript snippet send you off to the right one. If you're working with built-in policies this is an easy to implement solution, but with custom policies it doesn't really scale as you potentially end up duplicating the common parts.
A more sensible use for this could be to provide switching logic for deciding between signup and signin. In a customer setup I did we have the user type their email address when they click login. In the background a call to the Azure AD Graph API is made to see if the email address exists - if it doesn't exist you're taken to a signup form, and correspondingly you will be sent to the signin form if you have an account. (These are implemented as separate policies.)
Pre-B2C logic with domain hints
Instead of implementing one policy pr identity provider you can use the same basic logic as above where you ask for the email address and attach a domain hint to the query string. That way you can have everyone with a "contoso.com" suffix sent to Contoso's Azure AD tenant without ever presenting a choice for the user. For "unknown" suffixes you can skip the hint and present all options.
Both of these approaches may very well be all you need to reduce the complexity of the UI. There is however a drawback with both of these options - they require you to implement things outside the B2C sphere. If you just have the one web app that's probably not a big issue. If however you have 10 apps you need to implement it 10 times, and budget for maintenance over time. Not to mention that you're taking dependencies; it could be that the client implementation prevents you from changing the B2C end of things.
Can we push it all into B2C and contain it there? Yes, I think we can.
"Step zero" HRD logic in B2C with custom policies
The first step in a user journey is usually either the choice of identity provider, or typing in your credentials at a specific provider. But provided we use the login_hint parameter and provide the email address we can have a "step zero" in B2C that processes the adress through an API call and then follow up with a branching exercise within the journey by using conditional matching. (Step zero as in "a non-visible step happening before any UI kicks in".)
There are a couple things needed for this to work.
Create an Azure Function for doing the backend logic:
run.csx
#r "Newtonsoft.Json"
using System;
using System.Net;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
public static async Task<object> Run(HttpRequestMessage request, TraceWriter log)
{
log.Info($"Webhook was triggered!");
string requestContentAsString = await request.Content.ReadAsStringAsync();
dynamic requestContentAsJObject = JsonConvert.DeserializeObject(requestContentAsString);
log.Info($"Request: {requestContentAsString}");
if (requestContentAsJObject.emailAddress == null)
{
log.Info($"Empty request");
return request.CreateResponse(HttpStatusCode.OK);
}
var email = ((string)requestContentAsJObject.emailAddress).ToLower();
log.Info($"email: {email}");
char splitter = '@';
string[] splitEmail = email.Split(splitter);
var emailSuffix = splitEmail[1];
//For the "aad" identity provider
if (email == "bar@foo.com")
{
log.Info($"Identity Provider: aad");
return request.CreateResponse<ResponseContent>(
HttpStatusCode.OK,
new ResponseContent
{
version = "1.0.0",
status = (int)HttpStatusCode.OK,
userMessage = $"Your account is a generic Azure AD account.",
idp = "aad",
},
new JsonMediaTypeFormatter(),
"application/json");
}
//For B2C local accounts
if (email == "foo@bar.com")
{
log.Info($"Identity Provider: local");
return request.CreateResponse<ResponseContent>(
HttpStatusCode.OK,
new ResponseContent
{
version = "1.0.0",
status = (int)HttpStatusCode.OK,
userMessage = $"Your account seems to be a local account.",
idp = "local",
},
new JsonMediaTypeFormatter(),
"application/json");
}
//For Contoso AAD accounts
if (emailSuffix == "contoso.com")
{
log.Info($"Identity Provider: contoso");
return request.CreateResponse<ResponseContent>(
HttpStatusCode.OK,
new ResponseContent
{
version = "1.0.0",
status = (int)HttpStatusCode.OK,
userMessage = $"Your account belongs to the Contoso Identity Provider",
idp = "contoso",
},
new JsonMediaTypeFormatter(),
"application/json");
}
else
{
log.Info($"Identity Provider: none");
return request.CreateResponse<BlankContent>(
HttpStatusCode.OK,
new BlankContent
{
status = (int)HttpStatusCode.OK,
},
new JsonMediaTypeFormatter(),
"application/json");
}
}
//Default responses where there is no match
public class BlankContent
{
public int status { get; set; }
public string signInName { get; set; }
}
//For responses where there is an IdP matching
public class ResponseContent
{
public string version { get; set; }
public int status { get; set; }
public string userMessage { get; set; }
public string idp { get; set; }
public string signInName { get; set; }
}
You take in the email, and you can split it to act on the suffix alone, or provide address specific matches. Then you return the identity provider to use back to the B2C policy.
It would of course be more likely that you implement database lookups rather than hardcoding like this, but this illustrates the main points nonetheless. Also notice that we pass back a default item with a SigninName claim if there is no hit. This is a trick used for local account hinting later on.
Create a ClaimsProvider for doing the call to the backend:
<ClaimsProvider>
<DisplayName>REST APIs - HRD</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="HRD_Function">
<DisplayName>Do an IdP lookup based on email</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl"></Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="emailAddress" DefaultValue="{OIDC:LoginHint}" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="idp" />
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Create a new user journey with the necessary branching logic (not the complete journey):
<UserJourney Id="HRD_External">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="HRD" TechnicalProfileReferenceId="HRD_Function" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="true">
<Value>idp</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsProviderSelections>
<ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
</ClaimsProviderSelections>
<ClaimsExchanges>
<ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="3" Type="ClaimsExchange" ContentDefinitionReferenceId="api.signuporsignin">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="false">
<Value>idp</Value>
<Value>aad</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="AzureADExchange" TechnicalProfileReferenceId="Common-AAD" />
</ClaimsExchanges>
</OrchestrationStep>
Basically we step into the Azure Function right away, then based on the assumption something was returned from the backend we have preconditions to drive us through the rest of the journey.
You might argue that you still need something outside B2C since it requires dynamic creation of the query string instead of a static definition. That's true, but it's still far less than having the actual processing client-side and it doesn't create a dependency the same way either.
Internal hinting in B2C with custom policies
It is nice to do the branching inside custom policies. But wouldn't it be even nicer if we were able to move the hinting inside B2C as well?
With self-asserted orchestration steps you can basically collect any info you want from the user and send it off to a backend to drive further decisions.
This means that we can ask for the email address inside the custom policy, and pass it along to the same Function as in the previous approach.
So, for instance if we type in an address that matches with being an Azure AD account we send the user to that provider directly:
Notice that we also managed to pass along the email address so no retyping of that necessary either.
If we have no match for an existing Identity Provider we can present a more default-like screen with a number of choices. For the sake of choices you can do this two ways as well.
If you don't know if they have a local account (you just tried to match up specific IdPs) you can have a signin/signup option for that:
Or if you know that there is no local account there's no need for a signin option, so you can present a signup option instead:
Choosing the email signup option we're taken to a regular sign up screen:
The user journey for this would look similar to this:
<UserJourney Id="HRD_Internal">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="pre-hrd" TechnicalProfileReferenceId="SelfAsserted-EmailCollect" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="HRD" TechnicalProfileReferenceId="HRD_Function" />
</ClaimsExchanges>
</OrchestrationStep>
The important part here is adding a step to collect the email before passing it into the Azure Function.
HRD logic in B2C hinting back to JavaScript
It might become messy if you have twenty different providers and you define XML like the above for all of them. And while it is more dynamic than multiple policies it is sort of static as well. There is however yet another option you can go for - manipulating the UI through JavaScript.
The JavaScript I refer to here is not any pre-B2C JS your web app might employ, but the JS you can inject in the customized UI you create for B2C. So, while it will obviously need to be developed and maintained outside the XML files it is not a dependency external to B2C. The logic would have B2C doing the same processing as in the previous option, but instead of directing to a specific provider it would return the idp value to JS allowing for hiding and showing providers client side.
As already mentioned we can use output claims to collect info, and we can prefill them by using input claims. By hiding the value with JavaScript we can use this as a communication channel of sorts. The user journey in B2C would expose all identity providers, but the JS would tweak which one you would be able to use.
Keep in mind that since savvy end-users might be able to manipulate the HTML take care to not expose secrets this way. One thing is creating this for preferring one provider over another, but if you want to make sure that users in Contoso are prevented from using Facebook it might not be enough to just hide that option. But of course, there's nothing preventing you from combining these techniques to have hard and soft restrictions.
Since you cannot rely on the value being unmodified coming back from the user you should not store this value backend, so make sure it's not included as a persisted claim.
As you might have figured this last technique is usable outside of home realm discovery as well as a generic method for passing info to the JS side and UI tweaking.
I will leave this as an exercise for the reader at the moment. Not because it's trivial, (it introduces new challenges), but it would be better covered as a separate post not confusing you more than we've already done here. (No promises yet on a follow-up from my side.)
When implementing Azure AD B2C a little creativity goes a long way :)
The complete code and policies can be found over at:
As per usual B2C deployments you can test things directly in the Azure Portal, but if you want to test in a basic web app there's a Docker image you can spin up:
|
https://techcommunity.microsoft.com/t5/azure-developer-community-blog/advanced-home-realm-discovery-in-azure-ad-b2c/ba-p/482788
|
CC-MAIN-2020-34
|
refinedweb
| 2,523
| 52.39
|
Herman Vicens12,540 Points
Data mismatch problems
I've been trying to fix this problem in many ways unsuccessfully. Please give me an idea how to fix it.
thanks,
namespace Treehouse.CodeChallenges { class FrogStats { public static double GetAverageTongueLength(Frog[] frogs) { int count = 0; double acum = 0.0; foreach ( int x in frogs ) { acum = acum + Convert.ToDouble(frogs[count].tongueLength); count +=1; } return acum / count; } } }
namespace Treehouse.CodeChallenges { public class Frog { public int TongueLength { get; } public Frog(int tongueLength) { TongueLength = tongueLength; } } }
2 Answers
Steven Parker177,536 Points
It looks like you have the right idea, but a few issues:
- if you iterate through frogs each item will be a Frog, not an int
- you won't need to index into frogs since you will have an individual Frog item in the loop
- you don't need to convert the lengths into doubles to add them to the accumulator
- the property name is "TongueLength" (with a capital "T")
UPDATE: This type of loop ("foreach") does not give you an index like a "for" loop would. Instead, it gives you one of the items from the collection. So instead of "
int x in frogs" you might write "
var frog in frogs". Then instead of "
frogs[x].TongueLength" you might have "
frog.TongueLength"
Herman Vicens12,540 Points
Thanks Steve. It seems that I am almost done but I ran out of ideas with getting to the TongueLength property. I am getting a CS0020 error and I tried everything that my limited C# knowledge permits. Can you be more specific with the Frog and frogs in the loop? In the for loop excersise, the frogs[x].TongueLength worked. Not working in the foreach loop and don't know why?
Thanks,
Steven Parker177,536 Points
Steven Parker177,536 Points
You could re-write the challenge using a "for" loop, but I assumed you wanted to use "foreach" instead. It's a good choice, and I added an update to my answer above.
If you're still having trouble, show the code that you have at this point and I'll take another look.
|
https://teamtreehouse.com/community/data-mismatch-problems
|
CC-MAIN-2019-51
|
refinedweb
| 347
| 72.16
|
On demand data in Python, Part 1
Python iterators and generators
Learn how to process data in Python efficiently, on demand rather than pre-emptively
Content series:
This content is part # of # in the series: On demand data in Python, Part 1
This content is part of the series:On demand data in Python, Part 1
Stay tuned for additional content in this series.
We are lucky enough to live at a time when market forces have pushed the price of memory, disk, and even CPU capacity to formerly inconceivable lows. At the same time, however, booming applications such as big data, AI, and cognitive computing are pushing our requirements for these resources upward at a dizzying rate. There is some irony that at a time when computing resources are plentiful, it's becoming even more important for developers to understand how to scale down their consumption to remain competitive.
The main reason Python has remained such a popular programming language for almost two decades is that it is so easy to learn. Within an hour, you can learn how easy lists and dictionaries are to manipulate. The bad news is that the naive approach to solving many problems with lists and dictionaries can quickly get you into trouble trying to scale your app, because without care, Python tends to be a bit more resource hungry than other programming languages.
The good news is that Python has some useful features to facilitate more efficient processing. At the foundation of many of these features is Python's iterator protocol, which is the main topic of this tutorial. The full series of four tutorials will build on this to show you how to process large data sets efficiently with Python.
You should be familiar with the basics of Python, such as conditions, loops, functions, exceptions, lists, and dictionaries. This tutorial series focuses on Python 3; to run the code, you need Python 3.5 or a more recent version.
Iterators
Most likely, your earliest exposure to Python loops was code like the following:
for ix in range(10): print(ix)
Python's
for statement operates on what are called
iterators. An iterator is an object that can be invoked over
and over to produce a series of values. If the value after the
in keyword is not already an iterator,
for tries
to convert it to an iterator. The built-in
range function is
an example of one that can be converted to an iterator. It produces a
series of numbers, and the
for loop iterates over these
items, assigning each in turn to the variable
ix.
It's time to deepen your understanding of Python by taking a closer look at iterators like range. Enter the following in a Python interpreter:
r = range(10)
You have now initialized a range iterator, but that's all. Go ahead and ask
it for its first value. You ask an iterator for a value in Python by using
the built-in
next function.
>>> r = range(10) >>> print(next(r)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'range' object is not an iterator
This exception indicates that you have to convert the object to an iterator
before you use it as an iterator. You can do this using the built in
iter function.
r = iter(range(10)) print(next(r))
This time it prints 0, as you might expect. Go ahead and enter
print(next(r)) again and it will print 1, and so on. Keep on
entering this same line. At this point, you should be grateful that on
most systems, you can just press the Up arrow on the Python interpreter to
retrieve the most recent command, then press Enter to execute it again, or
even tweak it before pressing Enter, if you like.
In this case, you'll eventually get to something like the following:
>>> print(next(r)) 9 >>> print(next(r)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
We only asked for a range of 10 integers, so we fall off the end of that
range after it has produced 9. The iterator doesn't immediately do
anything to indicate it has come to an end, but any subsequent
next() calls will raise the
StopIteration
exception. As with any exception, you can choose to write your own code to
handle it. Try the following code after the iterator
r has
been used up.
try: print(next(r)) except StopIteration as e: print("That's all folks!")
It prints the message "That's all folks!" The
for statement
uses the
StopIteration exception to determine when to exit
the loop.
Other iterables
A range is only one sort of object that can be converted to an iterator. The following interpreter session demonstrates how a variety of standard types are interpreted as iterators.
>>> it = iter([1,2,3]) >>> print(next(it)) 1 >>> it = iter((1,2,3)) >>> print(next(it)) 1 >>> it = iter({1: 'a', 2: 'b', 3: 'c'}) >>> print(next(it)) 1 >>> it = iter({'a': 1, 'b': 2, 'c': 3}) >>> print(next(it)) a >>> it = iter(set((1,2,3))) >>> print(next(it)) 1 >>> it = iter('xyz') >>> print(next(it)) x
It's quite straightforward in the case of a list or tuple. A dictionary iterates over just its keys, and of course, no order is guaranteed. Order of iteration isn't guaranteed in the case of sets either, even though in this case, the first item from the iterator happened to be the first item in the tuple that was used to construct the set. A string iterates over its characters. All such objects are called iterables.
As you can imagine, not every Python object can be converted to an iterator.
>>> it = iter(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> it = iter(None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable
The best part is, of course, that you can make your own iterator types. All you need to do is define a class with certain specially named methods. Doing so is out of the scope of this tutorial series, but that's OK because the most straightforward way to create your own custom iterator is not a special class, but a special function called a generator function. I discuss this next.
Generators
You're used to the idea of a function, which takes some arguments and
returns with a value, or with None. There can be more than one possible
exit points, return statements, or just the last indented line of the
function, which is the same thing as
return None, but each
time the function runs, only one of these exit points is selected, based
on conditions in the function.
A generator function is a special type of function that interacts in a more complex, but useful way with the code that invokes it. Here is a simple example that you can paste into your interpreter session:
def gen123(): yield 2 yield 5 yield 9
This is automatically a generator function because it contains at least one yield statement in its body. This one subtle distinction is the only thing that turns a regular function into a generator function, which is a bit tricky because there is a huge difference between regular and generator functions.
Call a generator function like any other function:
>>> it = gen123() >>> print(it) <generator object gen123 at 0x10ccccba0>
This function call returns right away, and not with a value specified in the function body. Calling a generator function always returns what is called a generator object. A generator object is an iterator that produces values from the yield statements in the generator function body. In standard terminology, a generator object yields a series of values. Let's dig into the generator object from the previous code snippet.
>>> print(next(it)) 2 >>> print(next(it)) 5 >>> print(next(it)) 9 >>> print(next(it)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
Each time you call
next() on the object, you get back the next
yield value, until there are no more, in which case you get
the
StopIterator exception. Of course, because it is an
iterator, you can use it in a
for loop. Just remember to
create a new generator object, because the first one has been
exhausted.
>>> it = gen123() >>> for ix in it: ... print(ix) ... 1 2 3 >>> for ix in gen123(): ... print(ix) ... 1 2 3
Generator function arguments
Generator functions accept arguments, and these get passed into the body of the generator. Paste in the following generator function.
def gen123plus(x): yield x + 1 yield x + 2 yield x + 3
Now try it with different arguments, for example:
>>> for ix in gen123plus(10): ... print(ix) ... 11 12 13
When you are iterating over a generator object, the state of its function is suspended and resumed as you go, which introduces a new concept with Python functions. You can now in effect run code from multiple functions in a way that overlaps. Take the following session.
>>> it1 = gen123plus(10) >>> it2 = gen123plus(20) >>> print(next(it1)) 11 >>> print(next(it2)) 21 >>> print(next(it1)) 12 >>> print(next(it1)) 13 >>> print(next(it2)) 22 >>> print(next(it1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> print(next(it2)) 23 >>> print(next(it2)) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
I create two generator objects from the one generator function. I can then
get the next item from one or other object, and notice how each is
suspended and resumed independently. They are independent in every way,
including in how they fall into
StopIteration.
Make sure that you study this session carefully until you really get what's going on. Once you get it, you will truly have a basic grasp on generators and what makes them so powerful.
Note that you can use all the usual positional and keyword argument features as well.
Local state in generator functions
You can do all the normal things with conditions, loops, and local variables in generator functions and build up to very sophisticated and specialized iterators.
Let's have a bit of fun with the next example. We're all tired of being controlled by the weather. Let's create some weather of our own. Listing 1 is a weather simulator that prints a series of sunny or rainy days, with the occasional commentary.
If you think about the weather, a sunny day is often followed by another sunny day, and a rainy day is often followed by another rainy day. You can simulate this by randomly choosing the next day's weather, but with a higher probability that the weather will stay the same. One word for weather that is very likely to change is volatile, and in this generator function has an argument, volatility, which should be between 0 and 1. The lower this argument, the more chance that the weather will stay the same from day to day. In this listing, volatility is set to 0.2, which means that on average 4 out of 5 transitions should stay the same.
The listing has the added feature that if there are more than three sunny days in a row, or more than three rainy days in a row, it posts a bit of commentary.
Listing 1. Listing 1. Weather simulator
import random def weathermaker(volatility, days): ''' Yield a series of messages giving the day's weather and occasional commentary volatility - a float between 0 and 1; the greater this number the greater the likelihood that the weather will change on each given day days --volatility,)
The
weathermaker function uses many common programming
features but also illustrates some interesting aspects of generators. The
number of items yielded is not fixed. It can be as few as the number of
days, or it could be more because of the commentary on runs of sunny or
rainy days. These are yielded in different condition branches.
Run the listing and you should see something like:
$!
Of course it's based on randomness and there is a 4 out of 5 chance each time that the weather stays the same, so you could just as easily get:
$ python weathermaker.py today it is sunny!
Take some time to play around with this yourself, first of all passing
different values in for
volatility and
days, and
then tweaking the generator function code itself. Experimentation is the
best way to be sure you really understand how the generator works.
I hope this more interesting example fuels your imagination with some of
the power of generators. You could write the previous code without
generators certainly, but not only is this approach more expressive and
usually more efficient, but you have the advantage of being able to reuse
the
weathermaker generator in other interesting ways besides
the simple loop at the bottom of the listing.
Generator expressions
A common use of generators is to iterate over one iterator and manipulate it in some way, producing a modified iterator.
Let's write a generator that takes an iterator and substitutes values found in a sequence according to a provided set of replacements.
def substituter(seq, substitutions): for item in seq: if item in substitutions: yield substitutions[item] else: yield item
In the following session, you can see an example of how to use this generator:
>>>>> subs = {'hello': 'goodbye', 'world': 'galaxy'} >>> for word in substituter(s.split(), subs): ... print(word, end=' ') ... goodbye galaxy and everyone in the galaxy
Again, take some time to play around with this yourself, trying other loop manipulations until you understand clearly how the generator works.
This sort of manipulation is so common that Python provides a handy syntax for it, called a generator expression. Here is the previous session implemented using a generator expression.
>>> words = ( subs.get(item, item) for item in s.split() ) >>> for word in words: ... print(word, end=' ') ... goodbye galaxy and everyone in the galaxy
In short, any time you have parentheses around a
for
expression, it is a generator expression. The resulting object, assigned
to
words in this case, is a generator object. Sometimes you
end up using some of the more interesting bits of Python to fit such
expressions. In this case, I take advantage of the
get method on dictionaries, which looks up a key but allows me to specify a default to be returned if the key is not found. I ask for either the substitution
value of
item, if found, otherwise just
item as
is.
List comprehensions recap
You might be familiar with list comprehensions. This is a similar syntax, but using square brackets. The result of a list comprehension is a list:
>>> mylist = [ ix for ix in range(10, 20) ] >>> print(mylist) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
A generator expression's syntax is similar, but it returns a generator object:
>>> mygen = ( ix for ix in range(10, 20) ) >>> print(mygen) <generator object <genexpr> at 0x10ccccba0> >>> print(next(mygen)) 10
The main practical difference between these last two examples is that the list created in the first sits there from the moment it is created, taking up all the memory needed to store its values. The generator expression doesn't use so much storage and is rather suspended and resumed whenever it is iterated over, as the body of a generator function would be. In effect, it allows you to get the data on demand, rather than having it all prestocked for you.
An off-the-cuff analogy is that your household might drink 200 gallons of milk each year, but you don't want to have to build a storage facility in your basement for all that milk. Instead, you go to the store to buy a gallon at a time, as you need more milk. Using a generator instead of building lists all the time is a bit like using your grocery store rather than building yourself a warehouse.
There are also dictionary expressions, but these are outside the scope of this tutorial. Note that you can easily convert a generator expression into a list, and this can sometimes be a way of consuming a generator all at once, but it can also defeat the purpose of using a generator by creating memory-hungry lists if you're not careful.
>>> mygen = ( ix for ix in range(10, 20) ) >>> print(list(mygen)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
I'll sometimes construct lists from generators in this tutorial series for quick demonstrations.
Filtering and chaining
You can use a simple condition in generator expressions to filter out items
from the input iterator. The following example produces all numbers from 1
to 20 that are neither multiples of 2 or 3. It uses the handy
math.gcd function, which returns the greatest common divisor
of two integers. If the GCD of a number and 2, for example, is 1, then
that number is not a multiple of 2.
>>> import math >>> notby2or3 = ( n for n in range(1, 20) if math.gcd(n, 2) == 1 and math.gcd(n, 3) == 1 ) >>> print(list(notby2or3)) [1, 5, 7, 11, 13, 17, 19]
You can see how the
if expression is right inline within the
generator expression. Note that you can also nest the
for
expressions in generator expressions. Then again, generator expressions
are really just compact syntax for generator functions, so if you start
needing really complex generator expressions, you might end up with more
readable code just using generator functions.
You can chain together generator objects, including generator expressions.
>>> notby2or3 = ( n for n in range(1, 20) if math.gcd(n, 2) == 1 and math.gcd(n, 3) == 1 ) >>> squarednotby2or3 = ( n*n for n in notby2or3 ) >>> print(list(squarednotby2or3)) [1, 25, 49, 121, 169, 289, 361]
Such patterns of chained generators are powerful and efficient. In the
previous example, the first line defines a generator object, but none of
its work is done. The second line defines a second generator object, which
refers to the first one, but neither of the work is done for these
objects. It's not until the full iteration is requested, in this case by
the
list constructor, that all the work is done. This idea of
doing the work of iterating over things as needed is called lazy
evaluation, and it is one of the hallmarks of well-designed code using
generators. When you use such chains of generators and generator
expressions, however, remember that something has to actually trigger the iteration. In this case, it's the
list function. It could also be a
for loop. It's an easy mistake to set up all sorts of generators and then forget to trigger the iteration, in which case you end up scratching your head as to why your code is not doing anything.
The value of laziness
In this tutorial, you've learned the basics of iterators and also the most interesting sources of iterators, generator functions, and expressions.
You could certainly write all the code in this tutorial without any generators, but learning to use generators opens up more flexible and efficient ways of thinking about operating on any concepts or data that develop in a series. To repeat my analogy from earlier, it makes more sense to get a gallon of milk from the store at a time, on demand, rather than building yourself a warehouse with a year's supply. Though developers call the equivalent approach lazy evaluation, the laziness is more about the timing of when you obtain what you need. It probably doesn't seem so lazy to make a trip to the grocery store every other day. Similarly, sometimes writing code to use generators can take a bit more work and can even be a bit mind-bending, but the benefits come with more scalable processing.
Learning iterators and generators is one important step in mastering Python, and another is learning the many amazing tools provided in the standard library to process iterators. That will be the topic of the next tutorial in this series.
|
https://www.ibm.com/developerworks/library/ba-on-demand-data-python-1/index.html
|
CC-MAIN-2019-43
|
refinedweb
| 3,375
| 58.32
|
This preview shows
page 1. Sign up
to
view the full content.
Unformatted text preview: and all costs to the end of the year, the only exception being the sunk cost , the initial expenses needed to start the project. Sunk cost is referred to year zero. PV = n s k =0 ProFt k-Cost k (1 + i ) k Three types of present value analysis considered: Yes/no a speciFed project, choosing between alternative projects, picking investment options from a list of projects. Rate of return (ROR) : The value of the time value of money at which the present value of a project equals zero. 1...
View Full Document
This note was uploaded on 05/11/2010 for the course CHE CHE 3171 taught by Professor Hjortso during the Spring '10 term at LSU.
- Spring '10
- Hjortso
Click to edit the document details
|
https://www.coursehero.com/file/5889066/Weekly-2/
|
CC-MAIN-2017-09
|
refinedweb
| 142
| 70.84
|
This.
Memory Managementconstructions. Note that I am not implying that you shouldn’t use exceptions, just saying that using them appropriately is hard.izemethod to do their cleanup; this method is rarely used because of its much-delayed execution. In addition to the destructor, those classes provide the developer some methods (such as
close) to shut them down explicitly..
The RAII Model
RAII (resource acquisition is initialization) is a programming idiom intended to make code more robust. This model is restricted to object-oriented programming languages that have a predictable object destruction flow: where the developer could deduce, if he wanted to, the exact place at which an object’s destructor is called. C++ is one such language, assuming you use no garbage collector.
The basic principle behind RAII is to wrap dynamic resources—those that are allocated at some point and deallocated some time later—inside thin classes that manage them in a transparent way. These classes have several characteristics:
Their constructor allocates the resource and attaches it to the constructed instance. If the resource cannot be allocated, the construction aborts and throws an exception. Therefore all initialized objects have a valid resource.
Their destructor deallocates the resource as soon as possible. If the resource is shared among multiple instances, the wrapper class will release it only when the last instance disappears. A typical way to achieve this behavior is by using a reference counter.
They are extremely lightweight. Generally speaking, all they contain is a reference to the dynamic object they manage and some inline methods—often in the form of overloaded operators—to access it.
Wrapping resource acquisition and release within a class is good design. The caller neither needs nor wants to deal with resource-specific details.
By using RAII-modeled classes, the developer need not care about explicitly releasing the acquired resources: they will be freed automatically when the instance that manages them goes out of scope. It is important to note that these instances are almost always local variables (they live in the stack or within another object as an attribute); placing them in the heap (thus making them dynamic) makes no sense and could defeat the whole idea behind RAII.
As an example, consider the
std::ofstream class, modeled using RAII. This class has a redundant close method, provided only for cleanliness so as to allow the developer to explicitly tell where the file ceases to be open. If this function never gets called, the file will close as soon as the class’s instance goes out of scope. For example:
int read_something(void) { int value; std::ifstream f("test.tmp"); if (!f) { // First exit point throw no_such_file_exception("The file test.tmp does not exist"); } f >> value; if (value == 0) { // Second exit point throw invalid_format_exception("The file test.tmp is corrupt"); } // Third exit point return value; }
The read_something function has at least three exit points, clearly marked in the code using comments. Now notice that there is no difference in f’s handling in them. It does not matter whether the object was initialized, or if the code exited prematurely or successfully. The code simply ignores that the object exists, which is possible because
std::ifstream’s destructor closes the file. Otherwise, the code shown could leak an open file each time it took the second exit point.
For more information on the RAII programming idiom, I suggest you read The RAII Programming Idiom by Jon Hanna; it explains what RAII is in great detail and shows examples in both C++ and VB6.
Smart Pointers
A smart pointer is an RAII-modeled class that holds and manages a dynamically allocated chunk of memory. The exact behavior of the smart pointer is defined by its implementation, not by the fact that it is a smart pointer. In other words, a smart pointer is “smarter” than a raw pointer because it does some tasks automatically on behalf of the user; the tasks it does, however, depend on its specification.
Smart pointers are also helpful to specify how a pointer behaves based solely on notation. This is very useful when defining an API, because pointers in function signatures typically lead to confusion: Is the pointer an output parameter? Who is in charge of allocating the memory? Who has to release it? Using a smart pointer automatically answers some—if not all—of these questions.
The standard C++ library has a simple smart pointer, useful in many simple situations. However, due to those limitations, third-party libraries provide a wide variety of smart pointers with different features.
Smart Pointers in the Standard C++ Library
The standard C++ library comes with a smart pointer called
auto_ptr, for “automatic pointer.” It is very simple and is the least common denominator of smart pointers. No matter what, it is useful to make code more robust in many simple situations.:
std::auto_ptr<int> ptra(new int(5)); // From now on, the code is safe. The dynamically allocated // integer will be released no matter which execution path we // follow. .
Smart Pointers in Boost
Due to the inherent limitations of the standard
auto_ptr class, several third-party C++ libraries provide enhanced smart pointers. Boost is no exception. For those who do not know it, Boost is a collection of free, portable, peer-reviewed C++ libraries. These libraries work well with the standard C++ library, following its style and design principles. Some of them may eventually become part of the C++ standard.
The Boost Smart Pointers library provides six smart pointer templates in three groups: scoped pointers, shared pointers, and intrusive pointers.
Given that the official documentation for the Boost Smart Pointers library is very informative and complete, I have focused the rest of this article on presenting each available smart pointer accompanied by some code examples. If you need to learn more about them, I encourage you to read the official information.
Scoped pointers
A scoped pointer owns a dynamically allocated object, much like the standard
auto_ptr does. The difference lies in that the scoped pointer is explicitly marked as noncopyable, ensuring that during compilation time the pointer is never copied. It can be seen as a way to give a casual reader of your code a signal that you do not intend for that specific object to leave the local scope (hence the name “scoped pointer”).
Boost provides two scoped pointers:
scoped_ptr and
scoped_array. The former is good for raw pointers, while the latter is useful for dynamic arrays (those allocated with
new[]) because they are treated in a slightly different manner. These two smart pointers are extremely lightweight: they do not occupy more space than a raw pointer, and the most common operations are as cheap as the access to a raw pointer.
Here is an example to illustrate the usage of both classes by dynamically allocating a test class and letting its instances go out of scope. The printed messages show how the code properly releases the memory before exiting:
#include <cstdlib> #include <iostream> #include <boost/scoped_array.hpp> #include <boost/scoped_ptr.hpp> static int count = 0; class printer { int m_id; public: printer(void) : m_id(count++) { } ~printer(void) { std::cout << "Printer " << m_id << " destroyed" << std::endl; } }; int main(void) { boost::scoped_ptr<printer> p1(new printer); boost::scoped_array<printer> p2(new printer[5]); std::cout << "Exiting test program" << std::endl; return EXIT_SUCCESS; }
Shared pointers
A shared pointer is something you cannot live without once you’ve learned what it is. If smart pointers are great by themselves, imagine how incredible these are! Really. Remember the essay about garbage collectors at the beginning of the article? Shared pointers are the alternative I was aiming at.
More seriously, a shared pointer owns a reference to a dynamically allocated pointer—as all other smart pointers do—but does not own the object itself. This subtle difference is very important: a shared pointer counts the number of users of the dynamic object by means of a reference counter. The dynamic object is released only when the last shared pointer referencing it disappears.
You can copy and transfer shared pointers in a trivial way, yet these operations are completely safe: they do not duplicate memory nor try to release a single chunk earlier than necessary. Even more, they are also useful to write clearer code. By using a shared pointer, you no longer need to identify who is responsible for freeing a returned object nor which rules apply to an input parameter. This certainly helps when designing a public API.
Boost provides two shared pointers:
shared_ptr and
shared_array. The former is used for raw pointers, while the latter is used for dynamic arrays (those allocated with
new[]), for the same reasons as scoped pointers.
Consider a simple example:
#include <cstdio> #include <iostream> #include <boost/shared_array.hpp> class useless_buffer { size_t m_length; boost::shared_array<char> m_buffer; public: useless_buffer(const std::string& str) : m_length(str.length() * 2), m_buffer(new char[m_length]) { std::strcpy(m_buffer.get(), str.c_str()); } boost::shared_array<char> get_buffer(void) { return m_buffer; } boost::shared_array<char> copy_buffer(void) { boost::shared_array<char> copy(new char[m_length]); std::memcpy(copy.get(), m_buffer.get(), m_length); return copy; } }; int main(void) { useless_buffer buf("Hello, world!"); std::cout << buf.get_buffer().get() << std::endl; std::cout << buf.copy_buffer().get() << std::endl; return EXIT_SUCCESS; }
It is interesting to note in this example that from the caller’s point of view, there is absolutely no visible difference between the
get_buffer and
copy_buffer methods. The former returns a new reference for a local array, which the caller must not release. The latter returns a new dynamic object, which the caller must release.
As a complement to shared pointers, Boost provides the
weak_ptr smart pointer. This one does not own an object but instead holds a “weak reference” to an existing shared pointer. The shared pointer can change at will regardless of how many weak pointers are “watching” it.
More in detail, a weak pointer is associated to a shared pointer. Whenever someone needs to access the contents of a weak pointer, the weak pointer must first be converted to a shared pointer by means of the
lock method or a special constructor. If the object managed by the shared pointer goes away, any further conversion from the weak pointer to a shared pointer will fail.
Here is a fictitious example in which the use of a weak pointer might be useful. A shared pointer is accessed by two threads.
thread1 should be able to release the object, but the object should be accessible at some point in
thread2 only if it still exists. Using the weak pointer makes this situation possible without using a complex locking protocol:
boost::shared_ptr<int> ptri(new int(5)); void thread1(void* arg) { ... ptri.reset(); ... } void thread2(void* arg) { boost::weak_ptr<int> wptr(ptri); ... if (boost::shared_ptr<int> auxptr = ptri.lock()) { // Do something with 'auxptr' because the object is still available. } ... }
Intrusive pointers
The intrusive pointer is a light version of the shared pointer. It assumes that the dynamically allocated object it has to point to implements a reference counter by itself. This maintains the counter in a single place and keeps the smart pointer to the minimum size (the size of the raw pointer).
In order to define an intrusive pointer for a given object, you must first create two functions that manage its embedded reference counter. One is
intrusive_ptr_add_ref, which simply increases the counter; the other is
intrusive_ptr_release, which decreases the counter and, if it reaches zero, releases the object.
This is much clearer with an example. You may want to assume that
some_resource is a class you have written or a class provided by someone else, perhaps even the operating system itself.
#include <cstdlib> #include <iostream> #include <boost/intrusive_ptr.hpp> class some_resource { size_t m_counter; public: some_resource(void) : m_counter(0) { std::cout << "Resource created" << std::endl; } ~some_resource(void) { std::cout << "Resource destroyed" << std::endl; } size_t refcnt(void) { return m_counter; } void ref(void) { m_counter++; } void unref(void) { m_counter--; } }; void intrusive_ptr_add_ref(some_resource* r) { r->ref(); std::cout << "Resource referenced: " << r->refcnt() << std::endl; } void intrusive_ptr_release(some_resource* r) { r->unref(); std::cout << "Resource unreferenced: " << r->refcnt() << std::endl; if (r->refcnt() == 0) delete r; } int main(void) { boost::intrusive_ptr<some_resource> r(new some_resource); boost::intrusive_ptr<some_resource> r2(r); std::cout << "Program exiting" << std::endl; return EXIT_SUCCESS; }
Conclusion
I discovered smart pointers a year ago, and since then I firmly believe that their use makes code safer, more robust, and easier to read. I can no longer conceive any C++ code that directly manages dynamically allocated objects due to all the problems that can arise.
Now that you have finished this article, I hope you feel similarly and that from now on you will use these techniques to improve your own programs.
Time to code!
|
https://jmmv.dev/2006/05/smart-pointers-in-cxx.html
|
CC-MAIN-2022-27
|
refinedweb
| 2,119
| 53.21
|
Re: Early and late binding [was Re: what does 'a=b=c=[]' do]
- From: Steven D'Aprano <steve+comp.lang.python@xxxxxxxxxxxxx>
- Date: 24 Dec 2011 08:25:05 GMT
On Fri, 23 Dec 2011 17:03:11 +0000, Neil Cerutti wrote:
The disadvantage of late binding is that since the expression is live,
it needs to be calculated each time, even if it turns out to be the
same result. But there's no guarantee that it will return the same
result each time:
That's its main *advantage*.
Ah yes, sorry, poor wording on my part. Whether calculating the default
value *once* or *each time* is an advantage or disadvantage depends on
what you're trying to do. Either way, it could be just what you want, or
an annoying source of bugs.
consider a default value like x=time.time(), which will return a
different value each time it is called; or one like x=a+b, which will
vary if either a or b are changed. Or will fail altogether if either a
or b are deleted. This will surprise some people some of the time and
lead to demands that Python "fix" the "obviously buggy" default
argument gotcha.
It's hard to see anyone being confused by the resultant exception.
That's because you're coming at it from the perspective of somebody who
knows what to expect, in the middle of a discussion about the semantics
of late binding. Now imagine you're a newbie who has never thought about
the details of when the default value is created, but has a function like
"def foo(x, y=a+b)". He calls foo(x) seven times and it works, and on the
eighth time it blows up, perhaps with a NameError. It's surprising
behaviour, and newbies aren't good at diagnosing surprising bugs.
Or worse, it doesn't blow up at all, but gives some invalid value that
causes your calculations to be completely wrong. Exceptions are not the
worst bug to have -- they are the best.
It's
much harder to figure out what's going wrong with an early-bound
mutable.
Only for those who don't understand, or aren't thinking about, Python's
object model. The behaviour of early-bound mutables is obvious and clear
once you think about it, but it does require you to think about what's
going on under the hood, so to speak.
[...]
[...][...]To fake early binding when the language provides late binding, you
still use a sentinel value, but the initialization code creating the
default value is outside the body of the function, usually in a global
variable:
I'd use a function attribute.
def func(x, y=None):
if y is None:
y = func.default_y
...
func.default_y = []
That's awkward only if you believe function attributes are awkward.
I do. All you've done is move the default from *before* the function is
defined to *after* the function is defined, instead of keeping it in the
function definition. It's still separate, and if the function is renamed
your code stops working. In other words, it violates encapsulation of the
function.
That's not to say that you shouldn't do this. It's a perfectly reasonable
technique, and I've used it myself, but it's not as elegant as the
current Python default argument behaviour.
[...]
The greater efficiency was probably what decided this question for
Python, right? Since late-binding is so easy to fake, is hardly ever
what you want, and would make all code slower, why do it?
Excellent point.
--
Steven
.
- Follow-Ups:
- References:
- what does 'a=b=c=[]' do
- From: Eric
- Re: what does 'a=b=c=[]' do
- From: alex23
- Re: what does 'a=b=c=[]' do
- From: Rolf Camps
- Re: what does 'a=b=c=[]' do
- From: alex23
- Re: what does 'a=b=c=[]' do
- From: rusi
- Re: what does 'a=b=c=[]' do
- From: Chris Angelico
- Re: what does 'a=b=c=[]' do
- From: Neil Cerutti
- Re: what does 'a=b=c=[]' do
- From: Neil Cerutti
- Early and late binding [was Re: what does 'a=b=c=[]' do]
- From: Steven D'Aprano
- Prev by Date: Re: modifying a time.struct_time
- Next by Date: Re: Early and late binding [was Re: what does 'a=b=c=[]' do]
- Previous by thread: Re: Early and late binding [was Re: what does 'a=b=c=[]' do]
- Next by thread: Re: Early and late binding [was Re: what does 'a=b=c=[]' do]
- Index(es):
|
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2011-12/msg01253.html
|
CC-MAIN-2015-14
|
refinedweb
| 755
| 66.98
|
Changes to Template Haskell Library
Throughout this document, it is assumed that the current version of GHC is 7.4.1.
A proposed change will add the following constructors to TH's Type datatype...
| PromotedListT [Type] -- for types of the form '[Int, Bool] | PromotedTupleT [Type] -- for types of the form '(Int, 'False) | PromotedConsT -- ':
... and the following constructors to TH's Kind datatype:
| ConK Name -- for kinds of the form Bool | VarK Name -- k | AppK Kind Kind -- k1 k2 | ListK -- [] | TupleK Int -- (), (,), ... | ConstraintK -- Constraint
Note that there is no ForallK constructor because the internal GHC representation for kinds with variables does not use this. Kinds are automatically generalized over an entire type expression.
TH will also need to support promoted constructors other than lists and tuples, but this is in fact already supported through the use of ConT. The namespace of defined types and of promoted types is also already kept distinct. For example, if we have the definition data Foo = Foo, the results of [t| Foo |] and [t| 'Foo |] are distinct (as in, == returns False). However, applying show to these two results produces the same string. Using the naming quote syntax, we can access promoted data constructors using the single-quote form. For example, ConT 'False denotes the promoted data constructor 'False. (Note that the parsed interpretations of the ' in these two snippets are entirely unrelated.)
Alternatives
Here are two alternatives to the above changes. They are orthogonal to each other (i.e. either can be chosen without affecting whether or not the other is chosen).
Simpler Types
Instead of the new types above, we could have the following:
| PromotedTupleT Int -- '(), '(,), ... | PromotedNilT -- '[] | PromotedConsT -- ':
Client code could create full tuples and lists using a combination of the above constructors with a liberal sprinkling of AppTs.
- Pros: Matches syntax of existing TupleT and ListT. For lists, matches forms available in surface syntax.
- Cons: Believed to be harder to use in practice. The PromotedTupleT construct here is not available in surface syntax. This also loses the ability to write succinct lists, while the original format proposed above allows for nil as a 0-element list.
It may be worth noting that '(,) Int Bool is not a synonym for '(Int,Bool). '(,) Int Bool is a parse error.
Structured Kinds
Instead of the new ListK and TupleK kinds above, we could have the following:
| ListK Kind -- [k] | TupleK [Kind] -- (k1,k2,...)
- Pros: Perhaps easier to use. Mirrors surface syntax.
- Cons: Does not match internal GHC representation, including what is printed in error messages and such. Different from the way Type works.
It may be worth noting that, in the kind language, (,) Int Bool is not a synonym for (Int,Bool). (,) Int Bool is a parse error.
|
https://ghc.haskell.org/trac/ghc/wiki/TemplateHaskell/RichKinds
|
CC-MAIN-2016-40
|
refinedweb
| 451
| 65.93
|
tag:blogger.com,1999:blog-3088757874422220662009-06-25T13:02:37.772-05:00Healthy Pets BlogHealthy pets happen when natural care is used. I'm a healthy pet nut and want to share what I learn to keep our pets happy, healthy and well.Robin Plan Wysong - Best Dog Food 2009<div align="justify">I will be posting a series for the Best Dog Food of 2009 - My pick <a href="" target="_'blank'">Wysong</a> over the next few weeks. Check back for details and helpful tips on finding the best pet food and supplements for your dog, cat, ferret or even horses.<br /><br />About Wysong - Learn about the company, background and Dr. Wysong<br /><br /.<br /><br /.<br /><br />Our best product is information, much of which is free on <a href="" target="_'blank'">this website</a>. We offer <a href="" target="_'blank'">Dr. Wysong's books, monographs, CDs, and newsletters</a> ).<br /><br />Over 300 healthy <a href="" target="_'blank'">human products</a>, <a href="" target="_'blank'">cat foods and supplements</a>, <a href="" target="_'blank'">dog foods and supplements</a>, <a href="" target="_'blank'"> ferret foods</a>, and <a href="" target="_'blank'">horse feed and supplements</a> are offered to you on our sites. What we discover of value in humans, we apply to animals, and vice versa. All creatures share the same need for natural nutrition as nature intended. All creatures can enjoy health by abiding the same natural principles.<br /><br /.<br /><br />If you are a thinking person serious about health, we are here for you.<br /><br />About Wysong FAQ<br /><br />1.Q: Where did the name "Wysong" come from?<br />A: That is the name of our founder and present director, Dr. Wysong.<br /><br />2. Q: How long have you been in business?<br />A: Since about 1979. Dr. Wysong began with clinical and surgical inventions, and branched into the various facets you see today as his research demonstrated the problems in conventional medicine and the importance of prevention.<br /><br />3. Q: What is Dr. Wysong's background?<br /.<br />Publications include technical journal articles on nutrition, health care, embryology, and surgical techniques. He has authored a monthly health newsletter since 1987. His books include <a href="" target="_'blank'">Lipid Nutrition - Understanding Fats and Oils in Health and Disease</a>, <a href="">The Synorgon Diet - Achieving Healthy Weight in a World of Excess</a>, <a href="" target="_'blank'">Rationale for Animal Nutrition</a>, <a href="" target="_'blank'">The Truth About Pet Foods</a> and numerous technical product monographs.<br />Both the company by his name, and the non-profit Wysong Institute, were founded by him and continue under his direction to this day.<br /><br />4. Q: Do you have other scientists?<br />A: There are several others with DVM, PhD or MD equivalent, as well as others with MS and BS degrees in the sciences. Although nature is the underlying principle at Wysong, leading edge science is used to discover and apply that principle.<br /><br />5. Q: Does this make you different from other companies?<br /.<br /><br />6. Q: Are you a health food company?<br />A: Since many people equate "health food," with "weird food," we don't like the association. In our food divisions, we create healthy foods backed by science, not lore. Wysong, in effect, bridges the gap between nature and science.<br /><br />7. Q: Where are you located?<br />A: Our corporate and research headquarters are located in Midland, MI. We also have manufacturing operations in Lake Mills, WI.<br /><br />8. Q: Are you approved by government regulations?<br />A: We are inspected and under the purview of the FDA, USDA, OSHA, and AAFCO.<br /><br />9. Q: Can I buy stock in your company?<br />A: No, we are not a publicly traded company.<br /><br />10. Q: Are there job opportunities with Wysong?<br />A: Yes. Please send an e-mail to <a href="mailto:wysong@wysong.net">wysong@wysong.net</a> with your cover letter and resume.<br /><br />11. Q: Do you manufacture your products or do you have others do it?<br />A: Yes, we conceive, design, and directly manufacture almost all of our products. This distinguishes us from most pet food companies.<br /><br />12. Q: How do you control the quality of your products?<br /.<br /><br />13. Q: Do you do laboratory research on animals?<br />A: No. We believe that caging animals for studies is unnecessary. When we want to gather data, we ask for help from real pets in real homes and use veterinary clinical consultants across the country. Nobody gets hurt. Please see our article on <a href="" target="_'blank'">Animal Testing and Feeding Trials</a>.<br /><br />14. Q: What do you do to be environmental?<br /.<br /><br />15. Q: Isn't it kind of weird making both human and animal products? Hope you don't mix them up.<br /.<br /><br />16. Q: How do you decide what products to make?<br />A: First off, we do not see the point of making things that are already available just to try to gain profit. We make things that, in our opinion, are not made well enough yet. We also make what we would personally prefer to use.<br /><br />17. Q: There are so many choices out there, how do I decide?<br / <a href="" target="_'blank'">How To Choose a Pet Food Company</a>.<br /><br />18. Q: Why don't I see your company advertising or in all the major stores?<br />A: Our primary focus has been and is education, research, and development. We are not a marketing firm, so what advertising you do see will be with an educational emphasis.<br /><br />19. Q: Why are some of your products quite expensive?A: Because they are expensive to produce. Quality has a price.<br /><br /.<br /><br />21. Q: Where is Wysong headed in the future?<br />A: You can count on Wysong being very creative. We will continue to lead, not follow, and bring you state-of-the-art information and products to enhance health for both humans and animals.<br /><br />Also see: <a href="" target="_'blank'">Wysong As A Holistic Company</a><br /><br />< Tips to Choose a Pet Food Company<div align="justify"><br /. Additionally, taste enhancers can make non-foods palatable and <a href="" target="_'blank'">short term feeding trial</a> results do not reveal the true health measure of a pet food’s value – long, active, vital life, free from chronic degenerative disease conditions.</div><div align="justify"><br /.</div><div align="justify"><br />So if all the commonly used criteria for judging the merit of a pet food are invalid, what is the concerned pet owner to do? As in all other important decisions in life, gathering information and applying reason is the best way to the best answer. This process is even more important in food decisions because health is at issue.</div><div align="justify"><br />Ultimately a pet food can be no better than the competency and the principles of those producing it. Everything flows from that. If the pet food producer’s main objective is profit, then health will be a secondary consideration. Evaluating manufacturers, therefore, becomes the most critical element in making pet feeding choices. The following criteria will help you in this evaluation.</div><div align="justify"><br />1. PET HEALTH PHILOSOPHY: Does the literature and pet health philosophy make sense and clearly put pet health as the number one priority, or is the primary objective marketing and sales?</div><div align="justify"><br />2. LEADER CREDENTIALS: What are the credentials, experience and accomplishments of the people in charge? Is the leader a marketing person, a board of directors concerned primarily about profits, or someone competent in health and nutrition? </div><div align="justify"><br />3. PET HEALTH INFORMATION LITERATURE: Read their literature, don’t just test feed the product or read package labels. Is their literature mere marketing claims, or do they educate and provide logical and documented scientific proof for the rationale of their product? Additionally, do they propose that the only way to pet health is through feeding their products? If so, be assured that they are lying... </div><div align="justify"><br />4. MANUFACTURING CONTROL: Find out if the pet food company marketing the product is also the owner of the company manufacturing it or in close control of formulations and manufacturing parameters. Consider that anyone off the street can go to any number of pet food manufacturers and have them make a food (such contract manufacturers have files full of ready-to-go formulas), add micro amounts of “special” ingredients, create a new label and then make unsubstantiated claims about the superiority of the “revolutionary new” product.</div><div align="justify"><br />5. THE “100% COMPLETE & BALANCED PET FOOD” MYTH: Does the company promote the claim of “100% complete and balanced?” This claim is a myth and is directly responsible for far-reaching nutritional diseases in pets. Use of the claim proves a manufacturer does not properly understand animal nutrition and pet health and is under the mistaken (but profitable, since it misleads consumers into thinking they should feed only their processed food) view that manufactured foods can be perfect. </div><div align="justify"><br />6. FADS OVER FACTS: Does the company follow fads or does it lead with solid responsible information? Fads include high fiber, low cholesterol, low fat, “natural,” no preservatives, four food groups, high protein and the like. Such singular focus on faddish pet food fallacies demonstrates either an incomplete understanding of nutrition or a motive to profit from misinformed consumers.</div><div align="justify"><br />7. INGREDIENT BOOGEYMEN: Does the company incite fear mongering about “boogeyman” ingredients? Current examples of such nutritional boogiemen include: <a href="">soy, corn, wheat</a>, fat, “by-products,” seaweed, ash, meat meal, yeast and magnesium. Popular misconceptions, dubious field reports and poorly conducted science lie at the base of such beliefs. If a pet food company uses such fallacies to promote their products, they either do not understand pet nutrition or desire to play on popular ignorance for financial gain.</div><div align="justify"><br />8. FOODS AS DRUGS: Since the body can only experience health and healing from natural foods and a natural environmental context, it is presumptuous to claim a processed, manipulated, fraction-based food can do it better. In fact, such fabricated foods may create serious side effects and are far inferior to whole natural nutrition. Pet food producers who create and promote such foods attempt to capitalize on the awe of supposed advanced manufacturing technology and medicine. The illusion is created that a processed pet food, just because it is promoted like a prescription drug, is somehow high-tech and scientific, when in fact it may be no more so than most other processed pet foods.</div><div align="justify"><br />9. COSMETICS OVER PET NUTRITION: Most pet food producers target food cosmetics rather than real nutrition. Flavors, shapes, packaging, bonuses, discounts, coupons, pricing, guarantees and the like are essentially unrelated to health and nutrition. Emphasis on such features should alert the consumer that the producer may be interested primarily in mass marketing, not serious pet health and nutrition.</div><div align="justify"><br />10. INNOVATION: Since nutritional science is a rapidly growing and expanding field of knowledge, a producer truly interested in pet health should be highly innovative. Adapting new knowledge to formulations, processing, packaging and storage should be ongoing and these innovations should be clearly communicated to consumers. Most pet food companies don’t lead, they follow. Consumers would be wise to follow leaders, now followers.<br />We invite your comparison.<br /><br /></div><center><a href="" target="_blank"><img alt="Natural Raw Healthy Pet Food Wysong" src="" border="0" /></a></center> Dried Raw Pet Food Recall - Nature's Variety<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 275px; CURSOR: hand; HEIGHT: 348px" alt="" src="" border="0" /></a><br />Freeze Dried Raw Product<br /><br />Nature's Variety News - June 12, 2009<br /><br />Nature’s Variety recently identified two lots of Freeze Dried product that didn’t meet our quality standards. These products do not represent a health hazard to your pet. We have voluntarily withdrawn distribution of these specific products:<br /><br />Freeze Dried Raw Chicken Formula (UPC # 69949 60151) with a “best if used by” date of 05/25/10<br />Freeze Dried Raw Beef Formula (UPC # 69949 60251) with a “best if used by” date of 05/25/10<br /><br />From the <a href="" target="_'blank'">Nature's Variety site:</a><br /><br />Our distributor and retailer partners have kept control of these products, and because we retrieved these products so quickly, it is very unlikely that you purchased this batch of food. If, however, you believe you may have purchased one of these products, you may contact Nature’s Variety at 1.888.519.PETS (7387) for a full refund or replacement.<br /><br />We apologize for any inconvenience this has caused you. If you have any questions or concerns, do not hesitate to contact us by clicking CONTACT US at the top of this page, or call our Customer Service Team directly at 1.888.519.PETS. We will be happy to respond to you as quickly as possible.<br /><br />Our Commitment to Quality<br />At Nature’s Variety, we’re committed to product quality. Our team is passionate about providing nutritious products, formulated with high quality meat, poultry, and fish protein. Our Quality Assurance Team takes extra care to ensure the wholesomeness of our premium foods.<br /><br />Nature’s Variety has and will continue to enforce strict quality standards as we offer our nutritious foods to your special pet. Thank you for your continued trust in Nature’s Variety. Be assured, your pet’s health and happiness is our first priority. Skin Problems Cures<span style="font-family:verdana;font-size:130%;">If your furry friend suffers from <u>Hot Spots</u>, <u>Flea Bites</u>, <u>Mosquito Bites</u>, </span><u>Spider Bites</u>, <u>Eczema</u>, <u>Skin Rashes</u>, <u>Blisters</u>, <u>Chronic Scratching</u>, <u>A Dull Coat</u>, <u>Dry, Itchy, Flaky Skin</u>, <u>Scabbing</u>, <u>Split Pads</u>, <u>Acne or Burns</u>, this is an important message for you...</span> </span><p class="TableContents" style="MARGIN-BOTTOM: 14.15pt; TEXT-ALIGN: center" align="center"><span lang="EN-US" style="color:red;"><span style="font-family:verdana;"><span style="font-size:130%;">Announcing A Revolutionary New<br /><br /><u>100% Organic</u> Dog Balm<br /><br /><u><span style="BACKGROUND: yellow">Guaranteed</span></u><span style="BACKGROUND: yellow"> </span>To Help Clear Up The<br /><br /><i><u>17 Most Common Canine Skin And Coat Problems</u><?xml:namespace prefix = o /><o:p></o:p></i></span></span></span></p><br /><p class="TableContents" style="MARGIN: 0cm 31.65pt 14.15pt 35.85pt"><i><span lang="EN-US"><span style="font-family:verdana;"><span style="font-size:130%;">For centuries, this secret "miracle" compound lay hidden in the ruins of the Mayan empire. Now, for the first time in modern history, this amazing compound is being used to stimulate healing in both humans and our furry friends.<o:p></o:p></span></span></span></i></p><br /><p class="MsoNormal"><span style="mso-tab-count: 1"><strong></strong></span><span style="font-family:verdana;"><span style="font-size:130%;"><strong><u>If you've had ever had a dog with a skin or coat problem</u></strong>, you know the frustration when the prescribed method of treatment does not work, or ends up doing more harm than healing (we all know about the dangerous side effects of drugs).<o:p></o:p><o:p></o:p></span></span></p><br /><p class="MsoNormal"><span style="mso-tab-count: 1"></span><span style="font-family:verdana;"><span style="font-size:130%;">The honest-to-goodness truth is, the most effective remedies are ones that work with your dog's natural healing processes, not against them. And when it comes to clearing up their skin and coat, <b>there's only one totally natural, 100% organic product on the market that is <u>guaranteed to help clear up the 17 most common canine skin and coat problems</u> out there...</b><br /><br /><o:p></o:p><o:p></o:p></span></span></p><br /><p class="MsoNormal" style="TEXT-ALIGN: center" align="center"><b><span style="BACKGROUND: yellow; FONT-FAMILY: Arial; mso-bidi-: yellowfont-family:verdana;font-size:130%;" ><a href="" target="_'blank'">Click Here Now To Find Out More...</a></span></b></p><span style="font-family:'Times New Roman';"><br /><p class="MsoNormal" style="TEXT-ALIGN: center" align="center"><span style="font-size:100%;"></span></p><br /></span></td></tr> Whisperer Training Not For All Dogs<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 274px; CURSOR: hand; HEIGHT: 193px" alt="" src="" border="0" /></a><br /><div><a href=""></a><br />Before you listen to the TV dog trainers and try what they teach - think again and please read this new study.<br /><br /.<br /><br /><br />Contrary to popular belief, aggressive dogs are NOT trying to assert their dominance over their canine or human “pack”, according to research published by academics at the University of Bristol’s Department of Clinical Veterinary Sciences in the Journal of Veterinary Behavior: Clinical Applications and Research.<br /><br />The researchers spent six months studying dogs freely interacting at a Dogs Trust rehoming centre, and reanalysing data from studies of feral dogs, before concluding that individual relationships between dogs are learnt through experience rather than motivated by a desire to assert “dominance”.<br /><br />The study shows that dogs are not motivated by maintaining their place in the pecking order of their pack, as many well-known dog trainers preach.<br /><br />Far from being helpful, the academics say, training approaches aimed at “dominance reduction” vary from being worthless in treatment to being actually dangerous and likely to make behaviours worse.<br /><br /.<br /><br /.<br /><br />, or watched unqualified ‘behaviourists’ recommending such techniques on TV.”<br /><br /.<br /><br />.” <a href="" target="_'blank'">Source ScienceDaily</a><br /><br /><br /><br /><p><a href="" target="_'blank'"><img src="" border="0" /></a></p>< Cat Food RecallNutro Products Announces Voluntary Recall of Limited Range of Dry Cat Food Products<br />Contact:<br />Monica Barrett<br />Nutro Products, Inc.<br />(615) 628-5387<br />monica.barrett@effem.com<br /><br />FOR IMMEDIATE.<br /><br />Two mineral premixes were affected. One premix contained excessive levels of zinc and under-supplemented potassium. The second premix under-supplemented potassium. Both zinc and potassium are essential nutrients for cats and are added as nutritional supplements to NUTRO® dry cat food.<br /><br />This issue was identified during an audit of our documentation from the supplier. An extensive review confirmed that only these two premixes were affected. This recall does not affect any NUTRO® dog food products, wet dog or cat food, or dog and cat treats.<br /><br /. These products should not be sold or distributed further.<br /><br /.<br /><br />Consumers who have purchased product affected by this voluntary recall should return it to their retailer for a full refund or exchange for another NUTRO® dry cat food product. Cat owners who have questions about the recall should call 1-800-833-5330 between the hours 8:00 AM to 4:30 PM CST, or visit.<br /><br />Recalled Pet Food<br /><br />The varieties of NUTRO® NATURAL CHOICE® COMPLETE CARE® Dry Cat Foods and NUTRO® MAX® Cat Dry Foods listed below with “Best If Used By Dates” between May 12, 2010 and August 22, 2010 are affected by this voluntary recall.<br /><br />Nutro Products Recall List – Dry Cat Foods<br /><br />U.S. Product Name<br />Bag Size<br />UPC<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Kitten Food<br />4 lbs<br />0 79105 20607 5<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Kitten Food<br />8 lbs.<br />0 79105 20608 2<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Kitten Food (Bonus Bag)<br />9.2 lbs.<br />0 79105 20695 2<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Kitten Food<br />20 lbs<br />0 79105 20609 9<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Kitten Food (Sample Bag)<br />1.5 oz<br />none<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult<br />4 lbs<br />0 79105 20610 5<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult<br />8 lbs.<br />0 79105 20611 2<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult (Bonus Bag)<br />9.2 lbs<br />0 79105 20694 5<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult<br />20 lbs<br />0 79105 20612 9<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult (Sample Bag)<br />1.5 oz<br />none<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult Oceanfish Flavor<br />4 lbs<br />0 79105 20622 8<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult Oceanfish Flavor<br />8 lbs<br />0 79105 20623 5<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult Oceanfish Flavor (Bonus Bag)<br />9.2 lbs.<br />0 79105 20698 3<br /><br />NUTRO® NATURAL CHOICE® COMPLETE CARE® Adult Oceanfish Flavor<br />20 lbs<br />0 79105 20624 2<br /><br />NUTRO® MAX® Cat Adult Roasted Chicken Flavor<br />3 lbs<br />0 79105 10228 5<br /><br />NUTRO® MAX® Cat Adult Roasted Chicken Flavor<br />6 lbs<br />0 79105 10229 2<br /><br />NUTRO® MAX® Cat Adult Roasted Chicken Flavor<br />16 lbs<br />0 79105 10230 8<br /><br />NUTRO® MAX® Cat Adult Roasted Chicken Flavor (Sample Bag)<br />1.5 oz<br />none<br /><br />NUTRO® MAX® Cat Indoor Adult Roasted Chicken Flavor<br />3 lbs<br />0 79105 10243 8<br /><br />NUTRO® MAX® Cat Indoor Adult Roasted Chicken Flavor<br />6 lbs<br />0 79105 10244 5<br /><br />NUTRO® MAX® Cat Indoor Adult Roasted Chicken Flavor<br />16 lbs<br />0 79105 10245 2<br /><br />NUTRO® MAX® Cat Indoor Adult Roasted Chicken Flavor (Sample Bag)<br />1.5 oz<br />none<br /><br />NUTRO® MAX® Cat Indoor Adult Salmon Flavor<br />3 lbs<br />0 79105 10246 9<br /><br />NUTRO® MAX® Cat Indoor Adult Salmon Flavor<br />6 lbs<br />0 79105 10247 6<br /><br />NUTRO® MAX® Cat Indoor Adult Salmon Flavor<br />16 lbs<br />0 79105 10248 3<br /><br />NUTRO® MAX® Cat Indoor Weight Control<br />3 lbs<br />0 79105 10249 0<br /><br />NUTRO® MAX® Cat Indoor Weight Control<br />6 lbs<br />0 79105 10250 6<br /><br />NUTRO® MAX® Cat Indoor Weight Control<br />16 lbs<br />0 79105 10251 3<br /><a href=""></a><br /><a href=""></a> Animals Gets Puppies From "Puppy Factory"<a href=""><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 250px; height: 187px;" src="" border="0" alt="puppy mill" /></a><br />Elite Animals of West Hollywood Meet with Animal Protection Movement Leaders at City Hall<br /><br />Companion Animal Protection Society’s Along with Animal Activists Believe that Elite Animals is Selling Pet Factory Animals and Defrauding Consumers<br /> <br />. <br /> <br /. <br /> <br /. <br /> <br /." <br /> <br /. <br /> <br /. <br /> <br />.<br /> <br / hollywoodjinky@gmail.com. For media inquires please contact Anny Deirmenjian at 781.721.4624.<br /> <br />###<br /> <br />About Companion Animal Protection Society:<br /.<br /> <br /> <br />Anny Deirmenjian<br />Account Manager<br />Image Unlimited Communications, Ltd.<br />28 Church Street, Suite 9<br />Winchester, MA 01890 <br />P. 781-721-IMAGE (4624)<br />C. 617.851.9315<br />F. 781-721-0066 Ban Greyhound Racing?Greyhounds are dogs not racing machines.<br /><br /><em>."<br /></em>Gary E. Dungan Executive Director The Humane Society of Tucson Tucson, Arizona<br /><br /><br />Sadly, greyhound racing is not a "sport" about fast dogs, but a state-sanctioned form of gambling ruled by profit. It is inherently cruel to a gentle and ancient breed of dog once favored by nobility.<br /><br />When greyhounds do not run profitably, they are of little use to the racing business. Thousands of greyhounds are killed each year in the United States alone. Despite racing industry propaganda, there are simply not enough homes for all the discarded greyhounds.<br /><br />The discards of an American business.<br /><br />Since 1990, there have been more than 51 <a href="" target="_'blank'">media-documented cases</a> of mistreatment of greyhounds, collectively involving thousands of dogs. These cases include greyhounds shot, abandoned, left starving in their crates, sold for medical experimentation, and even electrocuted.<br /><br / <a href="" target="_'blank'">raw meat</a> from diseased livestock rejected by the USDA.<br /><br />It is virtually impossible to regulate greyhound racing to ensure humane conditions for the dogs.<br /><br /.<br /><br /.<br /><a href="" target="_self"></a><br />© Copyright 1997-2002 <a href="" target="_blank'">Greyhound Protection League</a><br /><br /><a href=""><img style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 250px; CURSOR: hand; HEIGHT: 173px" alt="ban dog racing" src="" border="0" /></a><br />The ugly truth behind greyhound racing. These were dogs brought to be killed at a shelter at the end of the season because they were no longer of use for dog racing.<br /><br /><br /><br /><p></p><p></p> Seed Extract for Dog Bad BreathI have two Shelties and a cat with very bad breath. I usually take them in for teeth cleanings but I know with the economy being bad many people (like me) are looking for effective treatments at a lower cost.<br /><br />We all love our pets, but adult dogs do not have that wonderful <em>puppy breath</em>. And more importantly, the bacteria that causes bad breath and periodontal disease can actually shorten your dog's or cat's lifespan.<br /><br />I use a natural product in the pets drinking water. It's Grapefruit Seed Extract.<br />Non-toxic and safe for my pets and it really takes care of the doggy breath (and fishy cat breath). I mix 10 drops in a gallon jug of filtered water and use this for my pets drinking water. I marked the jug with Pet's Drinking Water so anyone in the family can top the pet water dish off. It has no taste when diluted like this. Never use undiluted!<br /><br />I use it as a mouth rinse myself. I dilute 4 drops in about 3 tsp of warm water, swish and swallow. I don't like the taste at all so I make sure I have it mixed well and with enough warm water. The pets don't notice any taste or smell in their water. I haven't tried this but you can mix a few drops in water and use it for a doggy mouth spray or tooth paste.<br /><br />Grapefruit seed extract combines very well with other natural remedies. It is a great team player and seems to augment the activity of other medicinal herbs. Homeopaths particularly value it because is does not interfere with the activity of homeopathic remedies.<br /><br />Regular teeth cleanings are important for you pets.. Left unchecked, resulting bacteria can enter your pet's bloodstream, causing infection or damage to vital organs such as kidneys, lungs, heart, or liver.<br /><br />You can find the Grapefruit Seed Extract from Natural Food Stores or from many online sources. I bought mine here, <a href="" target="_'blank'">iherb.com</a>. Use this code OBI850 and get $5 off your first order so you can get the GSE for less than $9.<br /><br />I have also used products from Native Remedies and they do work with a higher price tag.<br /><a href="" target="_'blank'">Get more info on Gumz-n-Teeth to prevent pet gingivitis</a>.<br /><br />There are so many uses for Grapefruit Seed Extract and I will write more but this post is about using it as part of your pets oral hygiene care. Kill Conference for Animal SheltersReflections from the <a href=""target=_'blank'>No Kill Conference </a>in Washington DC<br /><br />Why death rates in animal shelters have been cut nation-wide by 85% since the 1970's and why Minnesota shelters keep on killing<br />by Mike Fry<br /><br />Today marks the beginning of Be Kind to Animals Week and as I sit down to write this, I am both physically exhausted and incredibly inspired. I returned yesterday from Washington DC where I attended and presented at the <a href="" target="_new">No Kill Conference</a>. Coordinated by the<a href="" target="_new"> No Kill Advocacy Center</a> and hosted by the <a href="" target="_new">George Washington School of Law</a>, this event featured dynamic presentations from some of our nation's leading animal welfare advocates working in the legal and sheltering fields to end the systematic killing of animals in animal shelters.<br /><br />The event was energizing, inspiring, informative and just plain fun, with hundreds of attendees packing the presentations to standing-room-only.<br /><br />During the keynote address, Richard Avanzino, thought by many to be the founder of the national no kill movement in the United States, presented some remarkable statistics. Avanzino was the Executive Director at the San Francisco SPCA when that city virtually ended the killing of healthy dogs and cats. He is now the President of Maddie's Fund, the World's largest animal welfare foundation. Maddie's Fund focuses its resources on helping communities achieve similar, and in some cases, even better results, than were achieved in San Francisco.<br /><br />Avanzino presented statistics of shelter deaths nationally since the 1970's, when our nation's animal control and animal welfare organizations were killing, on average, about 115 dogs and cats annually for every 1,000 human residents (or about 24 million deaths). Last year, deaths at these facilities were down to about 12 per thousand humans (or about 3.6 million deaths). That is a reduction in killing of 85%.<br /><br />While that is certainly wonderful news, I could not help but reflect on the fact that, in Minnesota, things have not gone so well. In fact, in the Twin Cities, animal shelters are still killing about the same number of dogs and cats as they were in the 1970's. While shelters around the country have been implementing and embracing the various programs and services generally referred to as <a href="" target="_new">The No Kill Equation</a>, Minnesota's largest shelters have not. In fact, Minnesota's wealthiest animal shelter (annual budget in excess of $11 million) has suggested they cannot implement these programs for a variety of reasons. They have gone so far as to suggest that some are illegal, when they are not. They have said of others that they lack the resources to implement them, in spite of having millions of dollars in reserves. Other critical aspects of the No Kill Equation, they have said, are "not a priority" for them. As a result, the Animal Humane Society annually continues to unnecessarily kill between 14,000 and 16,000 dogs and cats each year. In total, shelter deaths in Twin Cities metro area shelters are about 3 times the national average, in spite of being home to one of the wealthiest animal shelters in the nation.<br /><br />It is also worth pointing out that admissions to animal shelters in the Twin Cities are actually lower than the national average, providing further evidence that the overwhelming majority of these deaths are unnecessary.<br /><br />According to Nathan Winograd, founder of the No Kill Advocacy Center and Avanzino, that reality is going to have to change.<br /><br />The American public, they say, is filled with animal-lovers who want change. And, ironically, it has been these animal welfare advocates, often working at the grass-roots level, that have brought about much of the positive change in our country. They say that many donors are actually more advanced in their thinking than some animal welfare organizations themselves.<br />They also state that because of new technologies like YouTube, Twitter and FaceBook, these grass-roots animal welfare advocates are gaining a louder voice.<br /><br />Take, for example <a href="" target="_new">a petition</a> that was recently posted online. The petition is calling for the resignation of the CEO and COO of the Animal Humane Society. The petition cites the unnecessarily high kill rate for this organization as the primary rationale for this demand. Though only recently posted, the petition has already gathered nearly 1100 signatures from Minnesota and far beyond.<br /><br />This educated and passionate public is the primary reason Windograd and Avanzino give for a wave of successes sweeping the nation. "The American public is ahead of the animal welfare movement on this issue," said Avanzino. "People have a right to demand the organizations they support live up to their mission of saving every life they can. And, animal welfare advocates are doing just that."<br /><br />These are some of the reasons Avanzino states that a no kill nation is not only inevitable, it is imminent. Data from multiple sources indicates that the USA will achieve no kill status by 2015. In examining the evidence presented at the No Kill Conference, I believe that to be true. During the next 6 years, leadership at organizations that fail to fully embrace the new paradigm of life-saving will be replaced by a new generation of leadership.<br /><br />The no kill revolution is marching Unnecessary Deaths by Animal Humane Society in Minnesota<a href=""><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 528px; CURSOR: hand; HEIGHT: 400px" alt="" src="" border="0" /></a><br /><br /><strong>14,500 Unnecessary Deaths by AHS in Minnesota </strong>- Please help these pets live - Sign a petition that gives the animals right to live back. Is that too much to ask for? The dogs and cats don't understand why they ended up at the shelter and now they don't even have a chance to find a new home, they just die!<br /><br />You do not have to live in Minnesota to help the animals - <a href="" taret="_'blank'">Go here</a>.<br /><br />Sponsored by: <a href="" target="_'blank'">Animal Advocates in MN</a><br />Over. <strong>Please sign this petition to save animals from the Animal Humane Society of Minnesota and it's current administration.</strong><br /><br />According to Janelle Dixon, CEO of AHS, the explanation of the more than 14,500 "humane deaths" by AHS included:<br />19% were owner requested<br />30% health of the animal<br />42% behavior/temperament (including animals that were just shy)<br />5% lack of space in the AHS for cats and other small animals<br />4% un-weaned babies with low survival rate.<br /><br /><strong>Some simple math paints a troubling picture.</strong>).<br /><br /><strong>All of these numbers could be dramatically lowered or eliminated.</strong>.<br /><br /><strong>The AHS of Minnesota has one of the highest kill rates of non-profit kill shelters in the US</strong>.<br /><br /><br /><strong>The AHS of Minnesota under current management is destroying far more animals than it should.</strong>.<br />To speak directly to Janelle Dixon of AHS call her at 763-522-4325.<br /><br /><br />Please help the animals. Make the greed stop at this shelter and let the pets live and find a good home! You do not have to live in Minnesota to help the animals - <a href="" taret="_'blank'">Go here< Visiting Dog ~ Cute Story<div align="center">An older, tired-looking dog wandered into my yard.<br />I could tell from his collar and well-fed belly that he had a home and was well taken care of.<br /><br />He calmly came over to me, I gave him a few pats on his head;<br />he then followed me into my house, slowly walked down the<br />hall, curled up in the corner and fell asleep.<br /><img style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 472px; CURSOR: hand; HEIGHT: 329px; TEXT-ALIGN: center" alt="" src="" border="0" /><br />An hour later, he went to the door, and I let him out.<br /><br />The next day he was back, greeted me in my yard,<br />walked inside and resumed his spot in the hall and again slept for about an hour.<br />This continued off and on for several weeks.<br /><br />Curious I pinned a note to his collar:<br />'I would like to find out who the owner of this wonderful sweet dog is<br />and ask if you are aware that almost every afternoon your dog comes to my house for a nap.'<br /><br />The next day he arrived for his nap, with a different note pinned to his collar:<br />'He lives in a home with 6 children, 2 under the age of 3 - he's trying to catch up on his sleep.<br />Can I come with him tomorrow?' </div><br /><div align="center"></div><br /><em><span style="color:#330033;">Credit for this story goes to an email I received from a dear dog lover friend. I wish I knew the original author so I could give due credit!</span></em><br /><br /><a target="_blank" href=""><img src=" Banner1.gif" alt="VetMedicines.com" Prevention SeasonIt's almost time to start the dog's on their heartworm preventive for the summer. I've grown more concerned about giving my animals drugs and exposing them to chemicals. After much research I've decided it's best to give my dogs the preventive - but on my terms not just what the vet suggests.<br /><br />The chemicals used to prevent heartworm are extremely effective and can save dogs from difficult, unpleasant and potentially dangerous treatment. However, many veterinarians recommend treatment schedules year round or for many months longer than nessary or even advised by the American Heartworm Society (AHS).<br /><br /><br />The Heartworm Season Varies By Climate<br /><br />The transmissibility season for heartworm is determined by temperature. In order for the larvae of the heartworm, carried by mosquitoes, to be transmitted to a dog, the temperature must be at least 60 degrees for a month. (I don't think we will have a month of above 60 degrees here this year!)<br /><br />When I lived in Texas, the heartworm season was quite long so I did give my dogs preventive year round.<br /><br />In Minnesota, the temperature necessary for transmission of heartworm is not usually reached at night until June or later. The beginning of the season is not likely to be earlier than June 1 in most years, and perhaps later, even though mosquitoes may be present. Temperatures begin to drop at night by September. And, the season will certainly be over the next month, although you may still see mosquitoes.<br /><br />Preventatives Kill Heartworm Larvae<br /><br />The chemicals used to control heartworm are called preventatives, but when we use them, we are actually treating larvae. Think of it this way: The chemicals kill the larvae your dog may have picked up in the period since the last dosage.<br /><br />The monthly drugs you can use include Ivermectin (Heartgard or Iverheart), Milbemycin (Interceptor) or and Selamectin (Revolution).<br /><br /><br />I keep the monthly preventive as simple as possible. I buy products that specifically prevents heartworm, rather than a silver bullet that treats everything. Some manufacturers formulate products that combine heartworm prevention with worming medication, flea, tick and mange medication, just in case your dog may encounter these parasites.<br /><br />That just-in-case scenario is not good enough to put a multitude of toxic chemicals into your dog's body. Plain Ivermectin (Heartguard) is the simplest choice, and the safest for most dogs, though certain breeds have shown some sensitivity to it. We recommend you discuss the least toxic options for your pet with your holistic veterinarian.<br /><br /><br />My dogs eat anything and are not picky about their "treats." It's still best to keep an eye on your dog for a while afterward to make sure he doesn't spit the heartworm preventive out.<br /><br />When to Start and End Medication<br /><br />To determine the best time to test for heartworm, read the guidelines posted on the <a href="" target="_'blank'">AHS Web site</a>. Each geographic area is different.<br /><br />So, you've had your dog tested this spring, and she's clear of heartworms. How do you know when to start the preventative?<br /><br />Heartworm is not transmissible from mosquitoes to dogs until the weather is quite settled and warm, and the medications work on larvae acquired after the season starts. The time to start recommended by the AHS is a month after the transmissibility season begins.<br /><br />The chemicals used for monthly prophylaxis are effective for at least six weeks.<br /><br />Only give the amount your dog needs by taking a minute to mark the due dates on your calendar to save your dogs unnecessary chemical exposure.<br /><br />Holistic veterinarians often recommend the first dose be given a month after the season begins (dealing with any larva which may have been acquired and allowing for a little overlap) and every six weeks after that, until the end of the season. The AHS recommends the last dose be given within a month after the season ends.<br /><br />How many doses will your dog need?<br />I give at most four doses to my dogs (July 1 Aug. 15, Oct. 1 and Nov. 15). If I started May 15, the last dose would be Oct. 1. Close attention to the weather, particularly night temperatures, will give you excellent information about when to start.<br /><br />Protecting The Liver<br /><br />Some dog owners prefer more holistic, natural options, like herbal or homeopathic remedies. If you want to stay away from traditional heartworm preventives, it's imperative your animals be under the care and supervision of a veterinarian with expertise in this area. Don't take chances.<br /><br />Holistic veterinarians often recommend herbal support for the liver following preventive such as a daily dose of milk thistle for the week following each treatment. Milk thistle supports the liver as it metabolizes the medication and aids in the body's detox processes.<br /><br />Having the perfect balance with the smallest amount of preventive for the shortest amount of time is key for your dog's health and well being. This balance provides the best solution to a major health threat, with the minimum amount of medication, followed by appropriate detoxification.<br /><br />Balance with natural diet, exercise and health check-ups make your dog's health and well-being better! this sweet Sheltie - Minnesota<a href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 174px; height: 250px;" src="" border="0" alt="" /></a><br /><a href=""><img style="float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;width: 60px; height: 66px;" src="" border="0" alt="sheltie" /></a><br /><br />I have a PetFinder widget on my blog and I look at the dogs up for adoption everyday. This will be in the Minnesota region. That is how I came across Santana a lovely Sheltie mix girl. See her and other dogs on <a href=""target=_'blank'>PetFinder</a>.<br /><br /><br />Santana is a 7-8 year old, 36 lb. Sheltie mix, possibly with Border Collie. Her background is a mystery since she came to the rescue group as a stray. You can tell from the pictures that her eyes are clouded over with cataracts - we were hopeful that she would be a surgical candidate to have the cataracts removed to restore some eyesight to this sweet, blind dog, but the news was not good - retinal atrophy caused the cataracts and she won't benefit from surgery. <br /><br />Most dogs with retinal degeneration can lead a normal, happy life, according to the canine opthalmologist who performed her eye exam. This is a stable condition and Dr. Olivera recommends checking for inflammation during her yearly physical exam. There currently are no signs of inflammation, but she would only require some eye drops should she have any inflammation at some point. O<br /><br />nce she is in her environment, she can map it out and she gets around amazingly well by memory and using her other senses. There are many blind dog resources available, such as and. It’s important to keep her environment consistent (don't rearrange the furniture, etc.). <br /><br />Like all dogs, Santana would just like to have a safe home where she will be loved and adored like she deserves to be! Santana is calm and good-natured. She rarely barks (a big plus!) and usually only if she’s around a dog she doesn’t know. It’s almost like she’s trying to tell them she’s not vulnerable. She’ll also bark when the activity level around her is really high, or if she gets really excited, and even then she only lets out 3 or 4 barks. <br /><br />She does well with the cat and dog in her foster home, although she does not seek interaction with them. She prefers her people! She does great with respectful children ages 6 yr and up. Because she can’t see you, it helps Santana to be able to sense your presence or hear you. She’ll be your little shadow! She’s so affectionate and just craves attention. <br /><br />She walks well on a leash and enjoys taking walks. A fenced yard is strongly recommended to ensure Santana’s safety - especially if you live on a busy street with a lot of traffic. <br /><br />We believe Santana may have had some sort of injury to her hind end, as she can’t lift up or wag her tail, but she shows that she is happy to be with you in many other ways! <br /><br />She’s not familiar with obedience commands at this point, but responds very well to a whistle. Blind dogs are trainable, just like any dog. Please visit the websites mentioned above for more information. Santana is reliably housetrained. She doesn’t signal when she needs to go out, but is kept on a consistent schedule. She is crate-trained and also does well left out with the run of the house. <br /><br />She tolerates baths and loves to be brushed. She enjoys car rides, especially because she gets to be with you! Santana is spayed, current on vaccination and heartworm negative. Her adoption fee is $50. She’s such a sweet, loving angel, and cute as a button to boot! If you would like to welcome this little darling into your heart and your home, please contact us at 651-771-5662. Puppy Mills<a href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 148px; height: 141px;" src="" border="0" alt="petland stop selling puppies"id="BLOGGER_PHOTO_ID_5332796055060011842" /></a><br />Rally This Weekend For Dog Moms - <a href=""target=_'blank'>Source HSUS</a><br />May 5, 2009<br /><br />Did you know that there are dog moms all across the country who are trapped in cages for years and years who will never know a happy Mother's Day? These moms live in <a href="" target="_blank">puppy mills</a>, mass-breeding facilities that raise dogs in shockingly poor conditions with little hope of ever becoming part of a family.<br /><br /><br />This Mother's Day weekend, we're rallying for these moms, with the goal of creating better futures for all dogs like them. We hope you'll <a href="" target="_blank">join us at a Petland near you</a>.<br /><br /><br />Rally For Moms<br />Animal protection advocates will assemble for the third time this year at Petland retail stores across the country Saturday, May 9 to call for the nation's largest chain of puppy selling pet stores to stop supporting <a href="" target="_blank">puppy mills</a>.<br /><br /><br />Join Us at a Rally<br /><a href=""target=_'blank'>Find a Petland near you»</a>Stop Selling Puppies!<br /><br /><br />Advocates will urge Petland to stop supporting the cruel puppy mill industry through the chain's puppy sales, and instead create an adoption program similar to other large pet supply retailers like PETCO and PetSmart.<br /><br /><br />In March, <a href=""target=_'blank'>demonstraters crowded the sidewalks in front of 30 different Petland stores</a> from coast to coast to tell the comapny to stop selling puppies.The InvestigationIn November, The Humane Society of the United States revealed the results of an <a href=""target=_'blank'>eight-month investigation of Petland Inc</a>. The HSUS investigation revealed that Petland is the nation's largest retail chain purchasing dogs from puppy mills.<br /><br /><br />Our March demonstrations were followed by a <a href=""target=_'blank'>nationwide class-action consumer lawsuit filed against Petland</a> and the Hunte Corporation by HSUS members and other consumers.<br /><br /><br />Can't Make It?<br />Can't make a rally this weekend? Don't live near a rally site? You can still help by encouraging your local pet store them to become puppy friendly.<br /><a href="" target="_blank" fn="puppy_friendly_stores_instructions_11-08.doc" lid="Get tips on how to help stores go puppy friendly »">How to approach your store»</a><a href="" target="_blank">Download the invitation »</a><a href="" target="_blank">Download the pledge »</a><br /><br /><br />Good News<br />In late April, life got better for dogs in Indiana when the state <br /><a href=""target=_'blank'>passed new legislation (H.E.A. 1468)</a> that provides upgraded penalties for animal abuse, and basic care standards for dogs at puppy mills.<br /><br /><br />The new legislation requires that dogs in puppy mills be let out of their cages at least once per day for exercise and increases the minimum cage size and bans painful wire cage flooring. These protections will curb some of the worst abuses at large-scale puppy mills and do not affect responsible home breeders who already raise dogs humanely. Microchips<a href=""><img id="BLOGGER_PHOTO_ID_5332792066293532706" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 200px; CURSOR: hand; HEIGHT: 150px" alt="" src="" border="0" /></a><br /><br /><h2>Microchips: Common Questions</h2>Ge.<br />The brave new world of microchipping has left pet owners with questions. In this section, the experts at <a href=""target=_'blank'>The HSUS </a>answer them.<br /><br />I have heard there are problems with microchipping pets. What are the issues surrounding microchipping?<br /><br /).<br /><br />What is the problem for animal shelters and humane societies with different types of microchips available on the market?<br /><br /.<br /><br />My animal has already been microchipped, how do I know if my local shelter will be able to read the information on it?<br /><br />The only way to know for sure if your local animal care facilities have the ability to read the microchip implanted in your pet is to call them. Visit, or check your local listings to find your local shelter.<br /><br />My animal has not yet been microchipped. If I purchase one, how do I know if my local shelter will be able to read the information on it?<br /><br />This is the responsibility of the business or group providing the microchip. Ask whether the chip being implanted in your pet is compatible with the readers in place in your community. If there is any question, call your local animal shelter to be sure.<br /><br />What do I do if my local animal care facility cannot read the chip that is implanted in my pet?<br /><br />Call the microchip manufacturer and ask that they send at least one scanner to your local facilities free of charge.<br /><br />Why isn't there a scanner that can read all the different types of microchips?<br /><br /.<br /><br />What is The HSUS doing to help?<br /><br />The HSUS has appealed to the microchip manufacturers to develop or modify existing scanners to make them capable of detecting all microchips, regardless of brand. The HSUS will continue to monitor the situation and assist in developing a long-term solution.<br /><br />Given the present issues surrounding microchipping, should I microchip my pet?<br /><br /.<br /><br />How long do microchips last? Do they ever need to be replaced?<br /><br />Microchips are designed to last the lifetime of a pet—a chip typically lasts at least 25 years. Chips do not need replacing. Once the microchip is implanted, it will remain there and active for the life of the pet.<br /><br />What else can I do to ensure that my pet will be returned should he or she become lost?<br /><br />All pets should wear identification tags at all times. Tags should include a local contact number, as well as a number for a friend or out-of-town.<br /><br />Updated Sept. 14, 2006<br /><br /><a href=""target=_'blank'>Visit HSUS </a>for more great pet help. About Puppy Mills<a href=""><img style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 510px; CURSOR: hand; HEIGHT: 90px; TEXT-ALIGN: center" alt="puppy mills" src="" border="0" /></a>Image © The Humane Society of the United States.<br /><h2>THE TRUTH ABOUT PUPPY MILLS</h2><br /><div align="justify">Every year, millions of puppies are mass-produced at puppy mills. Most of these dogs are shipped to pet stores across the country. Many more are sold directly to the public, either through the Internet or newspaper ads. Pet stores are not required to inform their customers that their new dog came from a puppy mill, and classified ads are not obligated to tell potential buyers if the puppies they’re selling were born and raised in dismal conditions.</div><div align="justify"><br />Even though most puppy mills are inspected and licensed by the U.S. Department of Agriculture, loopholes in the system allow many mills to get away with poor living conditions for their dogs. The facilities where these puppies are bred are often filthy and overcrowded. Their construction usually consists of a number of small wooden or wire crates and cages that are stacked one on top of the other or cramped side by side. Some of the larger dogs in puppy mills, like those used only for breeding, are barely able to turn around in their tiny cages. </div><div align="justify"><br />Because the dogs are often underfed and lack proper veterinary care, there are a number of medical issues commonly found in mill dogs, including epilepsy, cataracts, personality disorders, periodontal disease, and mammary tumors. Also, because the dogs receive little in the way of human companionship, their social skills are often lacking, making them problematic house pets.<br />Unfortunately, the shocking level of neglect and carelessness in puppy mills goes on mostly unhindered. The plight of mill dogs has yet to be resolved.</div><div align="justify"><br />RESOURCES ABOUT PUPPY MILLS:</div><div align="justify"><a href="" target="_blank">Last Chance for Animals</a></div><div align="justify"><a href="" target="_blank">The Human Society of the United States</a></div><div align="justify"><a href="" target="_blank">North Shore Animal League America</a> </div><div align="justify"><br />North Shore Animal League America, the world’s largest animal rescue and adoption organization, has rescued, rehabilitated and found permanent homes for many victims of these cruel puppy mills, and offers a free <a href="" target="_blank">Puppy Mill Behavior Profile and Pet Rehabilitation Guide</a>.<br /><br />Puppy mills thrive because they exist out of the public eye. Though they are legal, it's a breeding factory for puppies that has been the cause of many behavior and medical problems. Learn more about the undercover world of puppy mills.<br /><br />Puppy mills are factory-like facilities that produce large numbers of purebred puppies.<br /><br />Puppy mills use the internet and newspaper ads to sell directly to the public, as well as selling their puppies through pet stores.<br /><br />According to The Humane Society of the United States, exhaustive documentation on the problems surrounding puppy mills include the following: “overbreeding, inbreeding, minimal veterinary care, poor quality of food and shelter, lack of human socialization, overcrowded cages and the killing of unwanted animals.<br /><br />Buying a dog from a puppy mill, either directly of indirectly, may likely lead to having an animal that will need urgent veterinary care or caring for whatever genetic diseases the animal may be carrying. These symptoms may not surface for several years into the animal’s life.<br /><br />The greatest victims in the puppy mill problem are the breeding parents, because they will live their life in that cage and it generally ends fairly brutally.<br /><br />There are about one to two hundred thousand dogs in puppy mills at any given time in the United States.<br /><br />All breeds of dogs are at risk of being bred in a puppy mill; even larger ones like Saint Bernards.<br /><br />It’s common to see chronic infection in puppy mills, such as chronic eye infections, chronic ear infections that lead to blindness and deafness. Dental disease is a also huge problem.<br /><br />© The Humane Society of the United States.<br /><br />Watch videos with Cesar Millan<br /><br /><embed name="flashObj" pluginspage="" src="" width="496" height="279" type="application/x-shockwave-flash" swliveconnect="true" allowfullscreen="true" flashvars="videoRef=06652%5F00" bgcolor="#000000"></embed><br /><br /><embed name="flashObj" pluginspage="" src="" width="496" height="279" type="application/x-shockwave-flash" swliveconnect="true" allowfullscreen="true" flashvars="videoRef=0665454%5F00" bgcolor="#000000"></embed><br /><br /><br /><embed name="flashObj" pluginspage="" src="" width="496" height="279" type="application/x-shockwave-flash" swliveconnect="true" allowfullscreen="true" flashvars="videoRef=06653%5F00" bgcolor="#000000"></embed><br /><br />More info <a href=""target=_'blank'>National Geographic Channel</a><br /> Dog Training Makes Aggressive Dogs<a href=""><img id="BLOGGER_PHOTO_ID_5332070554858758082" style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 131px" alt="" src="" border="0" /></a><br /><div>Dogs Are Aggressive If They Are Trained Badly </div><div><br />ScienceDaily (May 1,.<br /><br /><br />The conclusions, however, are surprising: it is the owners who are primarily responsible for attacks due to dominance or competition of their pets.<br /><br /.<br /><br />According to Joaquín Pérez-Guisado, the main author of the study and a researcher from the UCO, some of the factors that cause aggressiveness in dogs are: <em.</em> </div><div><br />"Failure to observe all of these modifiable factors will encourage this type of aggressiveness and would conform to what we would colloquially call 'giving our dog a bad education'", Pérez-Guisado explains to SINC.<br /><br />The study, which has recently been published in the Journal of Animal and Veterinary Advances, is based on the following fact: <em>approximately 40% of dominance aggression in dogs is associated with a lack of authority on the part of the owners who have never performed basic obedience training with their pets or who have only carried out the bare minimum of training.</em> </div><div><br />Breed has less influence on aggressiveness<br /><br /.<br /><br /.<br /><br /.<br /><br />According to the researcher, "dogs that are trained properly do not normally retain aggressive dominance behaviour". Pérez-Guisado attributes this "exceptional" conduct to the existence of some medical or organic problem, "which can cause changes in the dog's behaviour". Source: <a href="" target="_'blank'">ScienceDaily</a><br /><br /><br /></div><blockquote>I've always felt certain breeds of dogs are given a bad name because of Bad People. I'm happy to see a study done and I hope pet guardians will learn how to raise a great dog! Robin, the HealthyPetNut</blockquote><div> I Didn't Have a Dog or a Cat...<div align="center"><a href=""><img id="BLOGGER_PHOTO_ID_5330877840750020290" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 172px; TEXT-ALIGN: center" alt="shelties" src="" border="0" /></a><br /><br /><center>How would my life have been without my Tara for 18 years? </center><br /><br />I can't imagine life without lots of fur friends ~ If it happened would it be like this?<br /><br />I could walk around the yard barefoot in safety.<br /><br />My house could be carpeted instead of tiled and laminated.<br /><br />All flat surfaces, clothing, furniture, and cars would be free of hair.<br /><br />When the doorbell rings, it wouldn't sound like a kennel.<br /><br />When the doorbell rings, I could get to the door without wading through fuzzy bodies who beat me there.<br /><br />I could sit on the couch and my bed the way I wanted, without taking into consideration how much space several fur bodies would need to get comfortable. </div><div align="center"><br /><center><img id="BLOGGER_PHOTO_ID_5330880019559280642" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 117px; TEXT-ALIGN: center" alt="" src="" border="0" /><a href=""></a></center><br /><br />I would have money and no guilt to go on a real vacation.<br /><br />I would not be on a first-name basis with 6 veterinarians, as I put their yet unborn grand kids through college.<br /><br />The most used words in my vocabulary would not be: out, sit, down, come, no, stay, and leave him/her/it ALONE.<br /><br />My house would not be cordoned off into zones with baby gates or barriers.<br /><br />I would not talk 'baby talk'. 'Eat your din din'. 'Yummy yummy for the tummy'..<br /><br />My house would not look like a day care center, toys everywhere.<br /><br />My pockets would not contain things like poop bags, treats and an extra leash.<br /><br />I would no longer have to spell the words<br />B-A-L-L,<br />F-R-I-S-B-E-E,<br />W-A-L-K,<br />T-R-E-A-T,<br />B-I-K-E,<br />G-O,<br />R-I-D-E<br /><br />I would not have as many leaves (or pine needles) INSIDE my house as outside.<br /><br />I would not look strangely at people who think having ONE dog/cat ties them down too much.<br /><br />I'd look forward to spring and the rainy season instead of dreading 'mud' season.<br /><br />I would not have to answer the question<br />'Why do you have so many animals?' from people who will never have the joy in their lives of knowing they are loved unconditionally by someone as close to an angel as they will ever get. How EMPTY my life would be!!!<br /><br />"Until one has loved an animal, part of their soul remains un-awakened."<br /><br /><center><a href=""><img id="BLOGGER_PHOTO_ID_5330878426332149426" style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 130px" alt="shetland sheepdog" src="" border="0" /></a></center><br /><br /><br /><center><a href="" target="_'blank'"><img src="" border="0" /></a></center>< God Letter ~ From The Dog<a href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 90px; height: 86px;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5330216487577808514" /></a><br />TO: GOD<br /> <br />FROM: THE DOG <br /><br />Dear God: <br />Is it on purpose our names are the same, only reversed? <br /><br />Dear God: <br />Why do humans smell the flowers, but seldom, if ever, smell one another? <br /><br />Dear God: <br />When we get to heaven, can we sit on your couch? <br />Or is it still the same old story? <br /><br />Dear God: <br />Why are there cars named after the jaguar, the cougar, the mustang, the colt, the stingray, and the rabbit, but not ONE named for a Dog?<br /> <br />How often do you see a cougar riding around? <br />We do love a nice ride! Would it be so hard to rename the ' Chrysler Eagle' the ' Chrysler Beagle'? <br /><br /><br />Dear God: <br />If a Dog barks his head off in the forest and no human hears him, is he still a bad Dog? <br /><br />Dear God: <br />We Dogs can understand human verbal instructions, hand signals, whistles, horns, clickers, beepers, scent ID's, electromagnetic energy fields, and Frisbee flight paths. <br />What do humans understand? <br /><br />Dear God: <br />More meatballs, less spaghetti, please. <br /><br />Dear God: <br />Are there mailmen in Heaven? <br />If there are, will I have to apologize? <br /><br />Dear God: <br />Let me give you a list of just some of the things I must remember to be a good Dog. <br /><br /><br />1. I will not eat the cats' food before they eat it or after they throw it up. <br /><br />2. I will not roll on dead seagulls, fish, crabs, etc., just because I like the way they smell. <br /><br />3. The Litter Box is not a cookie jar. <br /><br />4. The sofa is not a 'face towel'. <br /><br />5. The garbage collector is not stealing our stuff. <br /><br />6. I will not play tug-of-war with Dad's underwear when he's on the toilet. <br /><br />7. Sticking my nose into someone's crotch is an unacceptable way ofsaying 'hello'. <br /><br />8. I don't need to suddenly stand straight up when I'm under the coffee table . <br /><br />9. I must shake the rainwater out of my fur before entering the house - not after. <br /><br />10. I will not come in from outside and immediately drag my butt. <br /><br />11. I will not sit in the middle of the living room and lick my crotch. <br /><br />12. The cat is not a 'squeaky toy' so when I play with him and he makes that noise, it's usually not a good thing. <br /><br /><br />P.S. <br />Dear God: <br />When I get to Heaven <br />may I have my testicles back? <br /> Heartworm DiseaseIn 2004, more than a quarter of a million pets were affected by a disease that is completely preventable. Heartworm disease, spread by mosquitoes, is often un-noticed by the pet owner because of the lack of apparent symptoms. Untreated, this parasite can cause exercise intolerance, coughing, damage to the main blood vessels of the heart, liver failure and even death. Pet owners can prevent this potentially fatal disease by the use of economical monthly medications. The continued high incidence of this problem has experts looking at many biological factors and even at the shift of our population to different areas of the /><p><a href=""target=_'blank'><img border=0< Cancer Treatments<h2>Medicinal Mushrooms, Tumor Attackers</h2><br />I want to talk about cancer treatment for dogs. But first let's be clear on what cancer is and the causes in our dogs. Cancer is an uncontrolled growth of cells on or inside the body. According to the American Veterinary Medical Association, dogs get cancer at about the same rate as humans. This increases with age and accounts for almost half of deaths over the age of ten years. However more and more veterinarians are concerned about seeing younger animals with cancer.<br /><br /><br />Cancer is attributed by holistic veterinarians as a failure of the immune system, due to genetic weakness fostered by conventional breeding practices, poor diet, medication, toxic chemicals, vaccines, and stress. The underlying problem, in the holistic viewpoint, is a failure of the body's defenses to stop abnormal mutating cells from growing rapidly.<br /><br /><br /><div class="separator" style="CLEAR: both; TEXT-ALIGN: center"><a style="MARGIN-LEFT: 1em; MARGIN-RIGHT: 1em" href="" imageanchor="1"><img height="228" src="" width="290" border="0" yi="true" /></a></div>I lost my dear sweet Sheltie, Cher, 7 years ago to cancer. She had never been sick until the cancer in her nose reared its ugly nasty self. She crossed over to the Rainbow Bridge 3 weeks before her 13th birthday. Her cancer was too advanced and in the wrong place to try surgery or any other conventional treatments so I loved her for 5 months and made sure she knew without a doubt that she was special and a wonderful dog.<br /><br /><br />Now I know there are other options and there are natural ways of healing. It was because of Cher's cancer that I became a healthy pet nut and continue to learn all I can about holistic cures and healing for pets.<br /><br /><br />Unique and exotic eclectic mix of mushrooms, herbs and antioxidants have been utilized around the world for their immune enhancing, blood cleaning, overall health and anti-cancer properties.<br /><br />Dr. Harvey offers this <a href="">medicinal mushroom for tumors</a> and overall health healing.<br /><br />And this one for cancer tumors:<br /><a href="">New Beta Glucan Supreme</a><br /><br />(Tested at the University of Louisville)<br /><br />Helps reduce sickness and helps the elimination of tumors and cancer!<br />Just add this pleasant tasting, extremely powerful mix to your pets food twice a day.<br /><br />Dosage: up to 40lb dog 1/4-1/2 tsp, up to 100lb dog 1/2 to 1 1/2 tsp daily<br /><br />There are Beta Glucans out there but our new Beta Glucan Supreme is derived from the Reishi, Turkey Tail, Split-Gill, Agaricus Blazei and Shitake mushrooms which studies have shown are superior resources for the most powerful antioxidants available.<br /><br />The mushrooms are grown organically and are minimally processed by a naturally advanced, modern, solid fermentation technology, featuring low temperatures and a supersonic nanotechnology. This assures the maintenance and purity of the antioxidants. In addition to the Beta Glucan extract (primarily B1, 3/1, 6D), this product contains mushroom spore compliment, active selected mushroom extracts, and metabolites. It also contains ribonucleic acid along with unique trace minerals.<br /><br />Beta Glucan Supreme can help improve both the body's cellular and humoral immune components, while promoting normal cell function and metabolism. Beta Glucan is a powerful immune stimulator, activating the immune systems macrophages (those cells responsible for clearing pathogens).<br /><br />Studies have found Beta Glucans not only has a positive effect on the macrophages, but also supports B lymphocytes, activate the NK (natural killer) cells, and assist the suppressor T cells, through its powerful action as an antioxidant and free radical scavenger.<br /><br />Research results indicate that incorporating Beta Glucan Supreme into your pets daily meals will improve your pets health conditions and enhance their immune system.<br /><br /><div class="separator" style="CLEAR: both; TEXT-ALIGN: center"><a style="MARGIN-LEFT: 1em; MARGIN-RIGHT: 1em" href="" imageanchor="1"><img src="" border="0" yi="true" /></a></div><div class="separator" style="CLEAR: both; TEXT-ALIGN: center"></div><div class="separator" style="CLEAR: both; TEXT-ALIGN: center"></div><a href="" target="_'blank'">New Beta Glucan Supreme</a><br /><br /><a href="" target="_'blank'"><img src="" Daycare Business Ideas<div align="justify"><a href="" target="_'blank'"><img style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 251px; CURSOR: hand; HEIGHT: 198px" alt="pet business" src="" border="0" /></a><br />I've worked full time with animals for the last 8 years. It's the most fulfilling heart-warming work I've ever done. It doesn't feel like work because I'm playing with dogs much of the day.<br /><br />I'm spoiled working with these great dogs and cats and I'm not suitable for a "normal" job now. Lucky for me I found my calling and won't have to go back to working with "people" everyday.<br /><br />There are several ways you can start a pet care business and some could be home-based. The kennel here is home based so I step outside and I'm at work.<br /><br />I can tell you the pet sitting and doggy daycare business is a growing industry with many Americans willing to spend billions of dollars a year on their beloved dogs. I know this for a fact because overnight boarding has dropped over the past year. Money isn't an object when people are concerned about the care of their dog. We charge $24 a day for boarding, people will spend $30 a day for doggy daycare. It's a no-brainer to branch out into the doggy daycare business.<br /><br />If you are considering a pet related business, get it on the trend by taking a few simple steps. Be clear about the services you want to offer. Will you care for dogs alone or will you include small animal pet care? Cats, birds, rodents snakes, fish? If your focus is dogs will you take them on walks or on outings to local dog parks? Will you do both? Are you available to pet-sit when an owner is out of town or are you a "middle of the day" kind of worker? These are the kinds of questions to ask yourself.<br /><br />This, <a href="" target="_'blank'">My Pet Business </a>is the best resource I've found for pet business ideas and quickly learning the ropes. It's all on DVD.<br /><br />JUST SOME OF WHAT YOU'LL LEARN:<br /><br />The most important skill a doggie day care owner must learn<br />How to avoid costly mistakes<br />How to get through the zoning process<br />How to make sure your business is profitable<br /><br />You'll see incredible footage of doggie day care facilities from around the country. These professionals will tell you how they got started, exactly what it's like to be in this fun and challenging business and what you need to do to get started today!<br /><br />I've worked with dogs for over 8 years and love the work. Let me tell you the doggy day care and pet sitting is the new trend. People feel bad leaving their dogs in a kennel (even a loving one like mine) and they will spend a lot of money for the comfort of their dog. Now is the time to get the <a href="" target="_'blank'">DVD's </a>and play with dogs for a living. I will always work with dogs and now I can combine the doggy day care, grooming and pet sitting with my kennel. </div><div align="justify"><br /><br /> </div><div align="justify">I learned a lot from watching the DVD's but sometimes I'm more into reading so I got the <a href=""target=_'blank'>Ebooks</a>. I printed them off and placed them in a binder. They are great for training seasonal summer helpers. There's even one for your Doggy Bakery business. <a href=""target=_'blank'>My Pet Business Ebooks</a></div><div align="justify"> <br /><br /></div><div align="justify"> </div><div align="justify"></div><div align="justify">You can add products and services to your doggy daycare but don't go crazy until you have the clients. Yes, you will have clients if you do your homework and LOVE DOGS.... Homemade Dog Food Recipes<div><a href=""><img id="BLOGGER_PHOTO_ID_5327963965689773986" style="FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 150px" alt="" src="" border="0" /></a>Making homemade dog food is a healthy choice for your dog. But, it's not something all pet owners are ready to do and that's OK. If you are not ready to commit to homemade pet food at least buy the highest quality of food you can afford. <a href="" target="_'blank'">This pet food </a>is what I feed my dogs and cat. It's a raw food in kibble form so it doesn't need to be kept in the fridge. And, it was created and is sold by a vet.<br /><br />I rotate with a homemade dog food and the dry healthy food from <a href="" target="_'blank'">Dr. Elliot Harvey.</a><br /><br />If you are ready to feed healthy homemade dog food recipes <a href="" target="_'blank'">this is a great resource</a>. I loved all the recipes and keep the cookbook in my kitchen beside the other family cookbooks.<br /><br />Feeding a homemade dog food meal is healthy if it's not the same thing everyday. You need to add variety and made sure your dog is getting all the nutrients he needs.<br /><br />In order to get all the recipes found in this ebook " <a href="" target="_'blank'">Healthy Food for Dogs: Homemade Recipes</a>" you would probably have to do as John Miller did. Read dozens of books, meet the best dog-fanciers, talk with experts for hours. </div><div> </div><img id="BLOGGER_PHOTO_ID_5327964828927836450" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 200px; CURSOR: hand; HEIGHT: 117px; TEXT-ALIGN: center" alt="" src="" border="0" /><br /><br />And most of all, you would have had to create recipes, analyze their results and draw conclusions.<br /><br />Now, the best recipes and techniques can be found in this condensed, practical, complete and immediately doggy food recipe book.<br /><br />I also learned which of the products I already had in my kitchen and bathroom that work to:<br /><br />Make my own dog shampoo<br />Eliminate dogs bad breath<br />Make dog safe Insecticides<br />Make dog safe Fertilizers<br />Skunk Odor Remover recipe<br /><br />So here are two options for the healthiest way to feed your dog and the exact ways I feed my 2 Shelties.<br /><br /><a href="" target="_'blank'">Healthy homemade dog food recipes</a><br /><br /><a href="" target="_'blank'">Dr. Elliot Harvey's Great Life Performance Pet Products</a><br /><br />No matter what you committed to doing for feeding your dog, there are healthy options. Never buy dog food from discount stores (Dog Chow etc.). QuizHeartworm Quiz<br />Drs. Foster & Smith Educational Staff<br /><br /><br />See how much you know about heartworm and its prevention!<br /><br />(Answers are provided at the bottom of the page)<br /><br />1. Does heartworm only occur in dogs?<br /><br />2. What is the immature stage of the heartworm that is laid by the female worm and may be found in the blood of infected animals?<br /><br />3. What parasite transmits heartworm to pets?<br /><br />4. What are three easy steps you can take to protect your pets from heartworm?<br /><br />5. Why is regular heartworm testing important?<br /><br />6. How long does it take for an infected animal to test positive for the disease?<br /><br />7. How often are heartworm preventives administered?<br /><br />8. What determines what time of year to start giving heartworm preventives?<br /><br />9. What are three ways to prevent mosquitoes from biting your pet?<br /><br />10. Heartworm disease is determined by what kind of test?<br /><br /><br /><a href="" target="new"><img src="" border="0" /></a><img height="1" src="" width="1" border="0" /><br /><br />Answers:<br /><br />1. No. Heartworm can also occur in other animals such as cats and ferrets.<br /><br />2. Microfilariae.<br /><br />3. The mosquito.<br /><br />4. Regular blood testing for heartworm, preventive medications, and reducing your pet's exposure to mosquitoes.<br /><br />5. To ensure your pet is heartworm-free before starting or continuing a preventive medication, and to detect a heartworm infection before it causes serious and permanent damage.<br /><br />6. In dogs, tests are usually not positive until about 6-7 months after infection has occurred. In cats, it is usually about 7-8 months after initial infection.<br /><br />7. Some medications are given to pets monthly, while others are given daily.<br /><br />8. When mosquitoes are present in your part of the country, although the American Heartworm Society recommends giving preventives year round.<br /><br />9. Eliminate breeding sites, reduce exposure during times mosquitoes are most active (dawn and dusk), use repellents.<br /><br />10. Diagnosis of heartworm disease is determined by a blood test.<br /><br />Visit <a href="" target="new">Doctors Foster and Smith</a> for ordering heartworm preventive and learning more info.
|
http://feeds.feedburner.com/healthypetsblog
|
crawl-002
|
refinedweb
| 13,627
| 62.17
|
validation is not complete. Properties using calc() for example will be reported invalid but may well be valid. They are wellformed however and will be parsed and serialized properly.
CSSStyleSheet.cssText is a serialized byte string (not unicode string) currently. This may change in the future.
CSS2Properties not implemented completely (setting a shorthand property does not set related properties like setting margin does not set margin-left etc). Also the return values are not as defined in the specification as no normalizing is done yet. Prefer to use style['property'] over style.property.
The seq attribute of most classes does not hinder you to add invalid items. It will probably become readonly. Never write to it!
Content of ``seq`` will most likely change completely, seq is more of an internal property and should not be used in client code yet
although cssutils tries to preserve CSS hacks not all are (and some - mainly syntactically invalid ones - will probably never be). The following hacks are known to not be preserved:
*html syntactically invalid
html*#test-span (IMHO invalidated by the missing WS between html and “*”)
The main problem for cssutils users is that some stylesheets in the wild are not parsable without loosing some information, a pretty print for these sheets is simply not possible with cssutils (actually with hardly any css parser...).
Generally syntactically valid (wellformed) stylesheets should be preserved completely (otherwise it will be a bug in cssutils itself). Invalid stylesheets will probably loose some information like to above *html hack. Most of these hacks may be rewritten while still be working, e.g. * html should work same to *html. Until cssutils 0.9.5b2 the invalid IE-specific CSS hack using $propertyname was preserved but its usage was already discouraged (and if e.g. specifying color and $color these properties are not the same for cssutils (but are for IE...). These kind of invalid hacks are not kept during parsing anymore since cssutils 0.9.5b3! In almost any case it is possible to use at least syntactically valid CSS while still working around different browser implementations.
when PyXML is installed not all tests may run through (see issue #34 for details) as PyXMLs implementation of xml.dom.DOMException differs from the default (minidom and I guess others) implemtation. Nothing really to worry about...
1.0 131215 (1.0 only cause I was tired of the 0.9.x releases ;)
-
EXPERIMENTAL: Variable references may have a fallback value now (as implemented in Firefox 29). It is available as CSSVariable.fallback and example are:bottom: var(b); color: var(theme-colour-1, rgb(14,14,14)); left: var(L, 1px); z-index: var(L, 1); top: var(T, calc( 2 * 1px )); background: var(U, url(example.png)); border-color: var(C, #f).
FEATURE: Implemented API for MarginRule objects inside CSSPageRule, see. You can also use e.g. CSSPageRule['@top-left'] to retrieve the MarginRule it it is set etc. All dict like methods should be there. If a margin is set twice or more all properties are merged into a single margin rule. Double set properties are all kept though (see below).
FEATURE: parseStyle() has optional parameter validate=False now too to disable validation (default is always True).
FEATURE: CSSStyleDeclaration.setProperty has new option replace=True. if True (DEFAULT) the given property will replace a present property. If False a new property will be added always. The difference to normalize is that two or more properties with the same name may be set, useful for e.g. stuff like:
background: red; background: rgba(255, 0, 0, 0.5);
which defines the same property but only capable UAs use the last property value, older ones use the first value.
BUGFIX: Fixed resolution of encoding detection of a stylesheet which did not use @charset in certain circumstances (mainly when imported sheets use different encoding than importing one which should be quite rare actually).
(Known) named colors are parsed as ColorValue objects now. These are the 16 simple colors (black, white, etc) and transparent but not all Extended color keywords yet. Also changed ColorValue.type to Value.COLOR_VALUE. ColorValue has additional properties red, green, blue, alpha and colorType which is one of IDENT, HASH or FUNCTION for now.
Removed already DEPRECATED cssutils.parse and CSSParser.parse. Use the more specific functions/methods parseFile parseString parseUrl instead.
Removed already DEPRECATED cssutils.log.setlog and .setloglevel. Use .setLog and .setLevel instead.
Removed already DEPRECATED cssutils.ser.keepUnkownAtRules (note the typo). Use .keepUnknownAtRules instead.
mainly cursor, outline, resize, box-shadow, text-shadow
replace CSSValue with PropertyValue, Value and other classes.
replaces CSSValue and CSSValueList
replaces CSSPrimitiveValue with separate value and type info (value is typed, so e.g. string for e.g. STRING, IDENT or URI values, int or float) and is base class for more specific values like:
replaces CSSPrimitiveValue, additional attribute uri
replaces CSSPrimitiveValue, additional attribute dimension
replaces CSSPrimitiveValue, additional attribute red, green, blue and alpha
TODO: Not yet complete, only rgb, rgba, hsl, hsla and has values use this object and color and alpha information no done yet!
replaces CSSPrimitiveValue function, not complete yet
also renamed ExpressionValue to cssutils.css.MSValue with new API
PropertyValue.value returns value without any comments now, else use PropertyValue.cssText
cssutils.css.CSSStyleDeclaration object, so may be used like the following which is useful when you work with HTML style attributes:
>>> style = cssutils.parseStyle("background-image: url(1.png), url('2.png')") >>> cssutils.replaceUrls(style, lambda url: 'prefix/'+url) >>> print style.cssText background-image: url(prefix/1.png), url(prefix/2.png)
(I omitted the validation error message as more than one background-image is not yet defined in the cssutils validator but does parse through without problems)
PERFORMANCE/IMPROVEMENT: Added parameter parseComments=True to CSSParser. If parsing with parser = cssutils.CSSParser(parseComments=False).parse... comments in a given stylesheet are simple omitted from the resulting stylesheet DOM.
PERFORMANCE: Compiled productions in cssutils tokenizer are cached now (to clear it use cssutils.tokenize2._TOKENIZER_CACHE.clear()) which results in a slight performance improvement. Thanks to Amit Moscovich!')
API CHANGE (major): When setting an objects cssText (or selectorText etc) property the underlying object is replaced with a new one now. E.g. if setting cssutils.css.CSSStyleRule.selectorText the underlying cssutils.css.CSSStyleRule.selectorList object is swapped to a new SelectorList object. This should be expected but cssutils until now kept the exact same object and changed its content in-place. Please be aware! (Also the strange _absorb method of some objects is gone which was used for this.)
API CHANGE (minor): Renamed cssutils.ser.prefs.keepUnkownAtRules to cssutils.ser.prefs.keepUnknownAtRules due to misspelling, see Issue #37. A DeprecationWarning is issued on use.
API CHANGE: CSSRule.NAMESPACE_RULE actual value has been changed from 8 to 10 (according to the change in the CSSOM spec). The actual integer values SHOULD NOT be used anyway! Please do always use the ``CSSRule`` constants which are present in ALL CSSRule and subclass objects like CSSStyleRule, CSSImportRule etc.!
API CHANGE: CSSStyleSheet.setSerializer and CSSStyleSheet.setSerializerPref have been DEPRECATED. Use cssutils.setSerializer(serializer) or set pref in cssutils.ser.prefs instead.
FEATURE: Started experimental implementation of CSS Variables
experimental and incomplete
Related details:
- added cssutils.css.CSSStyleSheet.variables which is a cssutils.css.CSSVariablesDeclaration containing all available variables in this CSSStyleSheet including the ones defined in imported sheets.
- cssutils.ser.prefs.resolveVariables == False: If set to True tries to resolve all variable references and removes any CSSVariablesRules.
- cssutils.ser.prefs.normalizedVarNames==True: Defines if variable names should be serialized normalized (they are used as being normalized anyway)
DOCUMENTATION: Reordered and cleared docs up a bit
IMPROVEMENT: Massive speed improvement due to changes in internal parsing.
When tried in a real world situation (parsing the stylesheet for my own site inside a simple WSGI based CSS handler) the parser uses ~0.7-0.8s when using cssutils 0.9.6. With cssutils 0.9.7a0 it only needs ~0.21s so only about 1/3 to 1/4 the time...
FEATURE: Parameter index of CSSStyleSheet.deleteRule(index) and CSSMediaRule.deleteRule(index) may now also be a rule object to be removed from the contained cssRules list.
IMPROVEMENT: cssutils.resolveImports now keeps media information when to be resolved @import rule uses these. It wraps the imported rules in an @media rule which uses the same media information from the @media rule in the original sheet.
An xml.dom.HierarchyRequestErr may occur if an imported sheet itself contains @imports with media information or other rules which are not allowed in a @media rule like @namespace rules. In that case cssutils cannot resolve the @import rule and logs a WARNING but keeps the original @import.
new properties: font-stretch, font-size-adjust
Added CSSFontFaceRule.valid. A @font-face rule is valid if all font descriptions properties are valid and properties font-family and src are set.
FEATURE: Added cssutils.parseStyle(cssText, encoding='utf-8') convienience function which assumes that the given cssText is the content of an HTML style attribute. It returns a CSSStyleDeclaration.
FEATURE (experimental, request from issue #27): Added css.CSSStyleDeclaration.children() which is a generator yielding any known children of a declaration including all properties, comments or CSSUnknownRules.
FEATURE: CSSStyleDeclaration.insertRule also accepts a CSSRuleList now (same as CSSStyleSheet which does this for some time now).
FEATURE: Added CSSStyleDeclaration.keys() method which analoguous to standard dict returns property names which are set in the declaration.
BUGFIX: Parsing of CSSValues with unknown function names with a specific length of 4 or 7 chars were resulting in a SyntaxErr. Also parsing of comma separated list of CSS FUNCTION values works now.
FEATURE (experimental): Added support to at least parse sheets with Microsoft only property values for filter which start with progid:DXImageTransform.Microsoft.[...](. To enable these you need to set:
>>> from cssutils import settings >>> settings.set('DXImageTransform.Microsoft', True) >>> cssutils.ser.prefs.useMinified() >>>>> print cssutils.parseString(text).cssText a{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=90)} >>>
This currently is a major hack but if you like to minimize sheets in the wild which use this kind of CSS cssutils at least can parse and reserialize them. Also you cannot reset this change until you restart your program.
These custom CSS FUNCTION names are not normalized at all. Also stuff like expression(...) which was normalized until now is not anymore.
BUGFIX: Fixed issue #22 parsing or actually reserializing of values like content: "\\"
FEATURE: New preference option keepUnkownAtRules = False which defines if unknown atrules like e.g. @three-dee {...} are kept or not. Setting this pref to False in result removes unknown @rules from the serialized sheet which is the default for the minified settings.
IMPROVEMENT: Fixed issue #23. The examples/style.py example renderer was reusing Property objects for each HTML element so they effectively overwrote each other.
BUGFIX: Fixed issue #21. Definition of valid values for property background-position was wrong. Still mixed values like background-position: 0 top are invalid although most browsers accept them. But the CSS 2.1 spec defines it the above way. CSS3 backgrounds is not implemented yet in cssutils.
API CHANGE: cssutils.profiles.Profiles (introduced in 0.9.6a1) has been refactored:
- cssutils.profile (a cssutils.profiles.Profiles object) is now preset and available used for all validation
- moved variable cssutils.profiles.defaultprofile to attribute Profiles.defaultProfiles (and so also available as cssutils.profile.defaultProfiles)
- renamed Profiles.CSS_BOX_LEVEL_3 to Profiles.CSS3_BOX and Profiles.CSS_COLOR_LEVEL_3 to Profiles.CSS3_COLOR
- renamed Profiles.basicmacros to Profiles._TOKEN_MACROS and Profiles.generalmacros to Profiles._MACROS. As these two are always added to your property definitions there is no need to use these predefined macro dictionaries in your code.
- renamed Profiles.knownnames to Profiles.knownNames
- Profiles.validateWithProfile returns valid, matching, profiles now
- renamed named parameter in cssutils.css.Property.validate(profiles=None)() from profile to profiles
- cssutils.profiles.properties (and new cssutils.profiles.macros) use as keys the predefined constants in Profiles, like e.g. Profiles.CSS_LEVEL_2 now. If you want to use some of the predefind macros you may e.g. use cssutils.profiles.macros[Profiles.CSS_LEVEL_2]['family-name'] (in addition to the always available Profiles._TOKEN_MACROS and Profiles._MACROS).
CHANGE: Reporting levels of properties have changed. Please see cssutils.css.Property.validate() for details. E.g. valid properties in the current profile are only reported on DEBUG and not INFO level anymore. The log output has been changed too, context information is provided now (line, column and name of the relevant property)
API CHANGE: Known but invalid properties raise/log an ERROR instead of a WARNING now. Properties not expected in the current profile log an INFO. As the default profile is None even basic properties like color are logged now. You may want to change the default profile by setting e.g. cssutils.profiles.defaultprofile = cssutils.profiles.Profiles.CSS_LEVEL_2 (~ CSS 2.1) to prevent CSS 2.1 properties to be reported. Also other validation related output has been slightly changed.
The way to change a defaultprofile may change again.
API CHANGE: cssutils.script.csscombine has ONLY keyword parameters now. Use csscombine(path=path[,...]) for the old behaviour. New parameter url combines the sheet at URL now.
FEATURE: Added experimental profiles handling. You may add new profiles with new properties and their validation and set a defaultprofile used for validation. The current default profile is None so all predefined profiles are used. Currently 3 profiles are defined:
Properties defined by CSS2.1
CSS 3 color properties
Currently overflow related properties only
See the docs and source of the cssutils.profiles module for details.
FEATURE: cssutils.util._readUrl() allows fetchers to pre-decode CSS content and return unicode instances, with or without a specified source encoding (integrated from patch of Issue #19).
FEATURE: URL fetch method checks if cssutils is run in GoogleAppEngine (GAE) (if import google.appengine is successful) and uses the GAE fetch methods instead of urllib2 in that case. So in result cssutils should run on GAE just as elsewhere.
FEATURE: Function cssutils.resolveImports(sheet) returns a new stylesheet with all rules in given sheet but with all @import rules being pulled into the top sheet.
FEATURE: CSSCombine script and helper function resolve nested imports now.
FEATURE: Script csscombine has new option -u URL, --url=URL URL to parse (path is ignored if URL given) now
TODO: Preference setting. Profile?
FEATURE: xml.dom.DOMExceptions raised do now contain infos about the position where the exception occured. An exception might for example have been raised as:
raise xml.dom.SyntaxErr('the message', 10, 5)
(where 10 is the line and 5 the column of the offending text).
Therefor you may not simply use str(e) to get the exception message but you have to use msg, line, col = e.args[0], e.args[1], e.args[2]. Additionally exceptions raised have attributes e.line and e.col.
FEATURE: @page rule accepts named page selector now, e.g. @page intro or page main:left.
FEATURE: Script cssparse has new option -u URL which parses the given URL.
moved cssutils.css.cssproperties.cssvalues to cssutils.profiles.css2
added CSS Color Module Level 3 with properties color and opacity. Not implemented are SVG color names.
unknown properties raise a WARNING instead of INFO now
FEATURE experimental: Added class CSSColor which is used for RGB, RGBA, HSL, HSLA and HEX color values of CSSValue respective CSSPrimitiveValue.
FEATURE (strange): IE only CSS expressions should be parsed and serialized now an an Expression value. I have not tested this deeply and there may be problems but for some common cases this should work, e.g. for hacking maxwidth for IE you may define the following:
width: expression(document.body.clientWidth > 1000 ? "1000px": "100%")
Usage of CSS expressions is strongly discouraged as they do not validate AND may slow down the rendering and browser quite a lot!
Valid:
"somestring followed by escaped NL\ and continuing here."
and now results in:
"somestring followed by escaped NL and continuing here."
url()) => not allowed and must be written as url(")")
BUGFIX: Setting CSSPageRule.selectorText does actually work now.
BUGFIX: Other priority values than !important are parsed now. Nevertheless they log an ERROR or raise a SyntaxErr.
BUGFIX: Fixed Issue #14, added CSSStyleDeclaration().borderLeftWidth. But prefer to use CSSStyleDeclaration()['border-left.width']..cssText = '$' # just logs: ERROR CSSStyleRule: No start { of style declaration found: u'$' [1:2: ]
from 0.9.5rc2:>>> # parsing STILL does not raise errors >>> s = cssutils.parseString('$') # empty but CSSStyleSheet object >>> # using DOM methods **does raise now though** >>> s.cssText = '$' # raises: xml.dom.SyntaxErr: CSSStyleRule: No start { of style declaration found: u'$' [1:1: $]
To use the old but false behaviour add the following line at the start to your program:>>> cssutils.log.raiseExceptions = False # normally True
This should only be done in specific cases as normal raising of exceptions in methods or functions with the CSS DOM is the expected behaviour. This setting may also be removed in the future so use with care.
BUGFIX: Parsing of @rules like @mediaall ... does not result in @media all ... anymore (so not a CSSMediaRule) but parses as @mediaall so a CSSUnknownRule. The specification is not too clear here but it seems this is the way to go. To help finding typos like this probably is, for any found CSSUnknownRule (an unknown @rule) a WARNING is emitted now (but never an exception raised). These typos will most likely happen like e.g. @mediaall, @importurl(), @namespaceprefix"uri" or @pagename:left.
BUGFIX: Parsing of unicode escapes like \\abc followed by CR/LF this is now correctly combined as only a single whitespace character.
BUGFIX: Adding a malformed stylesheets.MediaQuery to a stylesheets.MediaList does fail now, e.g.:
>>> # invalid malformed medialist (missing comma): >>> sheet = cssutils.parseString('@media tv INVALID {a {top: 0;}}') ERROR MediaQuery: Unexpected syntax. [1:11: INVALID] ERROR MediaList: Invalid MediaQuery: tv INVALID >>> # the actual rule exists but has default empty content, this may be changed later as it can be seen as a bug itself >>> sheet.cssRules[0] cssutils.css.CSSMediaRule(mediaText=u'all') >>> sheet.cssText '' >>> #
API CHANGE/FEATURE: The cssutils.log may be partly used like a standard logging log. The following methods are available: (‘setLevel’, ‘getEffectiveLevel’, ‘addHandler’, ‘removeHandler’) as well as all “messaging” calls like ‘error’, ‘warning’ etc.
Therefor cssutils.log.setloglevel has been DEPRECATED and should be used via cssutils.log.setLevel. The old method is still available though.
cssutils.log.setlog has been renamed to cssutils.log.setLog but is still available but DEPRECATED too.
FEATURE: All three decoders in the codec now have an additional force argument. If force is false, the encoding from the input will only by used if is is detected explicitely via BOM or @charset rule.
FEATURE: cssparse script has new option -m --minify which results in the parsed CSS to be serialized minified
FEATURE: CSSCapture and csscombine are now available not only as standalone scripts but also via cssutils.script.CSSCapture and cssutils.script.csscombine repectively so you can use them programmatically now.
BUGFIX: A space after @rule keyword is added when serializing minified something like @media all{}. Until now it was @mediaall{} which is recognized by Safari only but probably is not valid at all. Other @rules behave similar now too.
BUGFIX: Properties of rules set via css.CSSStyleSheet.add or .insert were not set properly, e.g. parentStyleSheet or the stylesheet handling of new @import rules was buggy.
BUGFIX: Encountering OSError during resolving @import does not throw an error anymore but the resulting CSSImportRule.styleSheet will have a value of None. OSError will probably only happen when using parseFile.
IMPROVEMENT/BUGFIX: A style sheet with href == None (e.g. parsed with parseString() or build completely from scratch) uses os.getcwd() as its base href now to be able to resolve CSSImportRules.
IMPROVEMENT/BUGFIX: Rewrote csscombine script which should be much more stable now and handles namespaces correctly. Nested imports are still not resolved yet but this may come in the next release.
IMPROVEMENT/BUGFIX: Added catching of WindowsError to default fetcher (e.g. is a file URL references a file not present).
CHANGE/BUGFIX: Redone csscapture script. A few minor method changes (parameter ua of capture has been replaced by init parameter) and lots of internal improvement has been done.
CHANGE: CSSStyleSheet.add(rule) simply appends rules with no specific order in the sheet to the end of it. So e.g. COMMENTs, STYLE_RULEs, etc are appended while rules with a specific place are ordered-in as before (e.g. IMPORT_RULE or NAMESPACE_RULE). Until now rules of a specific type like COMMENTs were ordered together which does not really make sense. The csscombine script needs this functionality and the resulting combined sheets should be more readable and understandable now.
CHANGE: Default URL fetcher emits an ERROR instead of a warning if finding a different mine-type than text/css.
API CHANGE: parse() is DEPRECATED, use parseFile() instead. I know this should not happen in a release already in beta but better now than later and currently both ways are still possible.
FEATURE: CSSStyleDeclatation objects may be used like dictionaries now. The value during setting a property may be a single value string or a tuple of (value, priority):
>>> style = css.CSSStyleDeclaration() >>> style['color'] = 'red' >>> style.getProperties() [cssutils.css.Property(name='color', value=u'red', priority=u'')] >>> del style['color'] >>> style['unknown'] = ('value', 'important') INFO Property: No CSS2 Property: 'unknown'. >>> style.getProperties() [cssutils.css.Property(name='unknown', value=u'value', priority=u'impor tant')] >>> del style['never-set'] # does not raise KeyError but returns u'' like removeProperty() >>>
FEATURE: While reading an imported styleSheet all relevant encoding parameters (HTTP headers, BOM/@charset, etc) are used now as defined in
Additionally a given parameter encoding for parseString, parseFile and parseUrl functions/methods overrides any detected encoding of read sheet like HTTP information or @charset rules. Useful if e.g. HTTP information is not set properly. The given encoding is used for all imported sheets of the parsed one too! This is a cssutils only addition to the rules defined at.
FEATURE: A custom URL fetcher may be used during parsing via CSSParser.setFetcher(fetcher) (or as an init parameter). The so customized parser is reusable (as all parsers are). The fetcher is called when an @import rule is found and the referenced stylesheet is about to be retrieved.
The function gets a single parameter
the URL to read
and MUST return (encoding, content) where encoding normally is the HTTP charset given via a Content-Type header (which may simply omit the charset though) and content being the (byte) string content. The Mimetype of the fetched url should be text/css but this has to be checked by the fetcher itself (the default fetcher emits an ERROR (from 0.9.5 before a WARNING) if encountering a different mimetype). The content is then decoded by cssutils using all encoding related data available.
Example:def fetcher(url): return 'ascii', '/*test*/' parser = cssutils.CSSParser(fetcher=fetcher) parser.parse...
To omit parsing of imported sheets just define a fetcher like lambda url: None (A single None is sufficient but returning (None, None) is more explicit).
You might also want to define an encoding for each imported sheet with a fetcher which returns a (normally HTTP content-type header) encoding depending on each URL.
FEATURE: Added option -s --string to cssparse script which expects a CSS string to be parsed.
FEATURE/BUGFIX: Parsing of CSSStyleDeclarations is improved. Invalid /color: red;color: green is now correctly parsed as color: green now. At the same time the until now parsed but invalid $color: red (an IE hack) is not parse anymore but correctly dismissed!
Unknown rules in CSSStyleDeclaration are parsed now. So e.g @x; color: red; which is syntactically valid is kept completely.
BUGFIX: parseUrl does return None if an error occurs during reading the given URL. Until now an empty stylesheet was returned.
BUGFIX: Fixed parsing of values like background: url(x.gif)0 0; (missing space but still valid).
BUGFIX: Serializing CSSUnknownRules is slightly improved, blocks are correctly indentet now.
LICENSE: cssutils is licensed under the LGPL v3 now (before LGPL v2.1). This should not be a problem I guess but please be aware. So the former mix of LGPL 2.1 and 3 is resolved to a single LGPL 3 license for both cssutils and the included encutils.
INTERNAL: Moved tests out of cssutils main package into a tests package parallel to cssutils.
API CHANGE: cssutils.css.CSSSStyleSheet.replaceUrls(replacer) has been DEPRECATED but is available as an utility function so simply use cssutils.replaceUrls(sheet, replacer) instead. For the why see getUrls(sheet) below.
API CHANGE/FEATURE: parseString has a new parameter encoding now which is used if a str is given for cssText. Otherwise it is ignored. (patch by doerwalter)
API CHANGE/FEATURE: .parse() .parseString() and constructor of CSSStyleSheet have a new parameter title needed for the cascade (yet to be implemented ;).
Also the representation of CSSStyleSheet has been improved.
FEATURE: Defining a namespace with a prefix but an empty namespaceURI is not allowed in XML 1.0 (but in XML 1.1). It is allowed in CSS and therefor also in cssutils.
ATTENTION: CSS differs from XML 1.0 here!
FEATURE: Added property css.CSSImportRule.name and css.CSSMediaRule.name as decribed in. It is parsed, serialized and available in this new property now. Property name is a constructor parameter now too.
FEATURE: css.UnknownRule is now parsed properly and checked for INVALID tokens or if {}, [] or () are not nested or paired properly. CSSUnknownRule is removed from CSSOM but in cssutils it is and will be used for @rules of programs using extensions, e.g. PrinceXML CSS. It is not very usable yet as no actual properties except atkeyword, cssText and seq are present but at least it is syntactically checked properly and I hope serialized similar to other rules. This has been completely rewritten so may contain a few bugs so check your serialized sheets if you use non-standard @rules.
BUGFIX: Improved escaping. Fixed cases where e.g. an URI is given as url("\""). Also escapes of delimiters in STRINGs is improved. This is used by CSSImportRule or CSSNamespaceRule among others. All STRING values are serialized with "..." (double quotes) now. This should not be a problem but please note that e.g. a CSSValue may be slightly different now (but be as valid as before).
BUGFIX: Fixed serialization of namespaces in Selector objects. Actually all possible namespaced selectors should be preserved now:
- *
-
any element or if a default namespace is given any element in that namespace
- a
-
all “a” elements or if a default namespace is given “a” elements in that namespace
- |*
-
any element in the no namespace (the empty namespace)
- |a
-
“a” elements in the no namespace (the empty namespace)
- *|*
-
any element in any namespace including the no namespace
- *|a
-
“a” elements in any namespace including the no namespace
- p|*
-
any element in the namespace defined for prefix p
- p|a
-
“a” elements in the namespace defined for prefix p
BUGFIX: Default namespace is no longer used by attribute selectors.
Aim was to prevent building invalid style sheets. therefor namespaces must be checked e.g. when adding a new Selector etc. This probably is not fixed for all cases but much better now than before..)
BUGFIX: Changed serialization of combinators in Selector according to, e.g. a>b+c~d e serializes as a > b + c ~ d e now (single spaces around +, > and ~). A new serializer preference selectorCombinatorSpacer = u' ' has been added to overwrite this behaviour (which is set to u'' when using the CSS minifier settings)
BUGFIX: Some minor fixes including some reference improvements.
NEW since 0.9.5:p = Property(ur'c\olor', 'red') p.name == ur'color' p.literalname == ur'c\olor' # DEPRECATED: p.normalname == ur'color'
OLD until 0.9.5:p = Property(ur'c\olor', 'red') p.name == ur'c\olor' p.normalname == ur'color'
API CHANGE: iterating over css.CSSStyleDeclaration
ATTENTION: changing the Selector by changing its property seq does not update the specificity! Selector.seq.append has been made private therefor and writing to seq not be used at all!
FEATURE: Added css.CSSStyleDeclaration.getProperty(name, normalize=True) which returns the effective Property object for name.
FEATURE: Implemented, URI may be URL(...) or u\r\6c(...).
FEATURE: Implemented css.CSSFontFaceRule.
FEATURE: Added css.CSSStyleSheet.encoding which reflects the encoding of an explicit @charset rule. Setting the property to None removes an @charset rule if present and sets the encoding to the default value ‘utf-8’. Setting a value of utf-8 sets the encoding to the default value too but the @charset rule is explicitly added.
Effectively this removes the need to use css.CSSCharsetRule directly as using this new property is easier and simpler.
(A suggestion in the CSSOM but not yet resolved. IMHO it does make sense so it is present in cssutils. css.CSSCharsetRule remains though if you really want to use it).
BUGFIX/IMPROVEMENT: css.SelectorList and stylesheets.MediaList have (Python) list like behaviour partly but are directly not lists anymore (which did not work properly anyway...). The following list like possibilities are implemented for now:
The DOM additional methods and properties like length or item() are still present (and also will be in the future) but the standard Python idioms are probably easier to use.
stylesheets.StyleSheetList and css.CSSRuleList are the only direct lists for now. This may change in the future so it is safer to also use the above possibilities only for now.
BUGFIX: Fixed handling of “\ ” (an escaped space) in selectors and values.
BUGFIX: !important is normalized (lowercase) now
BUGFIX/FEATURE: Handling of unicode escapes should now work propertly.
The tokenizer resolves any unicodes escape sequences now so cssutils internally simple unicode strings are used.
The serializer should serialize a CSSStyleSheet properly escaped according to the relevant encoding defined in an @charset rule or defaulting to UTF-8. Characters not allowed in the current encoding are escaped the CSS way with a backslash followed by a uppercase 6 digit hex code point (always 6 digits to make it easier not to have to check if no hexdigit char is following).
This FEATURE was not present in any older version of cssutils.
BUGFIX: Names (of properties or values) which are normalized should be properly normalized now so simple escapes like c\olor but also unicode escapes like \43olor should result in the property name color now
BUGFIX: Selector did fail to parse negation :not( correctly
BUGFIX: CSSValueList treated a value like -1px as 2 entries, now they are correctly 1.
BUGFIX: Validation of values for background-position was wrong.
BUGFIX: CSSPrimitiveValue.primitiveValue was not recognized properly if e.g. a CSS_PX was given as ‘1PX’ instead of ‘1px’.
BUGFIX/CHANGE: Reporting of line numbers should have improved as \n is now used instead of os.linesep.
CHANGE: Invalid Properties like $top which some UAs like Internet Explorer still are use are preserved. This makes the containing Property and CSSStyleDeclaration invalid (but still wellformed although they technically are not) so if the serializer is set to only output valid stuff they get stripped anyway.
This may change and also simply may be put in a cssutils wide “compatibility mode” feature.
CHANGE: If a CSSValue cannot be validated (no property context is set) the message describing this is set to DEBUG level now (was INFO).
IMPROVEMENT: “setup.py” catches exception if setuptools is not installed and emits message
FEATURE: Added a new module cssutils.codec that registers a codec that can be used for encoding and decoding CSS. ()
FEATURE: Added implementation of stylesheets.MediaQuery which are part of stylesheets.MediaList. See the complete spec at for details.
Not complete yet: Properties of MediaQueries are not validated for now and maybe some details are missing
FEATURE: Implemented cssutils.DOMImplementationCSS. This way it is possible to create a new StyleSheet by calling DOMImplementationCSS.createCSSStyleSheet(title, media). For most cases it is probably easier to make a new StyleSheet by getting an instance of cssutils.css.CSSStyleSheet though.
FEATURE: cssutils is registered to xml.dom.DOMImplementation claiming to implement CSS 1.0, CSS 2.0, StyleSheets 1.0 and StyleSheets 2.0. This is probably not absolutely correct as cssutils currently is not a fully compliant implementation but I guess this is used very rarely anyway.
ATTENTION: This has been changed in 0.9.5, see details there!.
UPDATE: SameNamePropertyList removed in 0.9.4.
UPDATE: SameNamePropertyList removed in 0.9.4
see examples/serialize.py
BUGFIX(minor): Parameter name for CSSStyleDeclaration.XXX(name)` is normalized now, so color, c\olor and COLOR are all equivalent @page CSSRule including testcases. @import), else literal form in CSS sourcefile (e.g. @i\mport). Defaults to True.
setting of CSSImportRule.media removed, use methods of this object directly. Synchronized with CSSMediaRule.media
atrules have a new property atkeyword which is the keyword used in the CSS provided. Normally something like “@import” but may also be an escaped version like “@import” or a custom one used in CSSUnknownRule.
.
moved SelectorList, Selector and Property to own modules. Should not be used directly yet anyway.
Token: renamed IMPORTANT to IMPORTANT_SYM
refined EasyInstall (still some issues to be done)
NOT COMPLETE YET, E.G. BOM HANDLING
added tests for setting empty cssText for all @rules and CSSStyleRule
added new class cssutils.serialize.Preferences to control output or CSSSerializer
from cssutils import *
cssutils has a property “ser” which is used by all classes to serialize themselves it is definable with a custom instance of cssutils.Serializer by setting cssutils.setCSSSerializer(newserializer)
usage of *.getFormatted emits DeprecationWarning now and returns *.cssText
lots of bugfixes and refactoring of modules, classes
extension and refactoring of unittests
renamed module “comment” to “csscomment” and class “Comment” to “CSSComment”
configurable Serializer instead of pprint
reimplemented CSSMediaRule
cssutils.css.CSSStyleSheet defines literalCssText property if property cssText is set. This is the unparsed cssText and might be different to cssText e.g. in case of parser errors.
custom log for CSSparser should work again
cssparser.py filename.css [encoding[, “debug”]] 1. encoding of the filename.css to parse 2. if called with “debug” debugging mode is enabled and default log prints all messages
cssutils.css.CSSUnknownRule reintegrated and Tests added
implements css.CSSRule, there a new typevalue COMMENT (=-1) is added
lexer does handle strings almost right now...
bugfixes
simplified lexer, still lots of simplification todo.
added modules to validate Properties and Values thanks to Kevin D. Smith
MediaList renamed media type “speech” to “aural”
API CHANGES
implement *Rule.cssText setting (UnknownRule not complete)
lexer has no log anymore, simply “logs” everything to the resulting tokenlist
cssstylesheet simplified
bugfixes
simplified and cleaned up sources some bugfixes
test_cssrule test_csscharsetrule, test_cssfontfacerule, test_cssimportrule,
added unittest for __init__ module
.
!cssnormalizer does not work in this version - on hold for 1.0
!cssnormalizer does not work in this version - on hold for 1.0
API CHANGES StyleSheet.getRules() returns a RuleList now class Selector removed, integrated into Rules now
!cssnormalizer does not work in this version
API CHANGES: StyleDeclaration.addProperty is now DEPRECATED use StyleDeclaration.setProperty instead
severe API changes renamed some classes to (almost) DOM names, the CSS prefix of DOM names is ommited though
the according methods are renamed as well
class hierarchy is changed as well, please see the example
classes are organized in new modules
and no comment end delimiter. (before it had to be a complete css comment including delimiters)
validates given media types new method: addMediaType(media_type)
cssparser updated to new cssbuilder interface and logic started unittests (v0.0.0.1..., not included yet)
new CSSNormalizer.normalizeDeclarationOrder(stylesheet)
cssbuilder: added methods needed by CSSNormalizer
CSSParser.parse bugfix
|
http://pythonhosted.org/cssutils/CHANGELOG.html
|
CC-MAIN-2016-18
|
refinedweb
| 5,940
| 51.14
|
EMC exec champions NAS for VMware shops
An EMC exec said that VMware's VMotion and Distributed Resource Scheduler (DRS) could propel the use of network-attached storage (NAS) over the storage area network (SAN) devices common today.
In a recent blog, EMC Corp. vice president of technology alliances Chuck Hollis made a case for NAS ) rather than a SAN (storage area network) in large VMware Virtual Infrastructure 3 (VI3) environments. EMC owns VMware, but runs it as an independent company.
Today, the vast majority of VMware ESX hosts are attached to SAN storage – at least 70%, said Hollis.
Others, like Rod Lucero, CTO at the VMware reseller VMPowered in Minneapolis, Minn., put that number closer to 90%.
NAS has numerous advantages over SAN in a VMware environment, said Hollis in a follow-up interview. First and foremost, "a NAS namespace is a lot easier to manage than a SAN namespace," he said.
That's especially true in large VMware environments that make heavy use of VMware's VMotion and Distributed Resource Scheduler (DRS), and both features are available with VI3. DRS works with VMotion to automatically migrate virtual machines (VMs) between ESX hosts based on performance and availability policies.
The problem with DRS in a SAN environment is that, in order to make effective use of it, "you're going to need to open up your SAN to all your servers," Hollis said. From a best practices perspective, that can be "potentially problematic," Hollis said.
Those concerns can be mitigated by using SAN techniques such as zoning and LUN masking, but a much simpler alternative might be to simply use a NAS file system as the data store for VM images.
"I think that, in the long term, we'll find high-end NAS much more friendly for high-end VMotion / [Distributed Resource Scheduler] farms than today's SANs," Hollis blogged.
As an aside, Hollis said he has seen a dramatic increase in the size and sophistication of VMotion and DRS deployments. "At first VMotion was used mainly for server-to-server failover; that was the state of the art in 2005 and 2006 timeframe," he said. The introduction of DRS last summer as part of the VI3 release, however, laid the groundwork for "the optimization of service levels as opposed to simple hardware failures." Hollis personally knows of about two dozen EMC customers doing large-scale load-balancing with DRS.
File over block
Management isn't the only benefit of using NAS in a virtualization environment, Hollis said. "NAS has the potential to offer a few benefits that we might not find in the SAN world," Hollis wrote.
For one thing, NAS relies on ubiquitous and inexpensive TCP/IP and Ethernet cabling, not Fibre Channel. It also provides for decent security and access control via TCP/IP and NFS.
Furthermore, interacting with a file system makes it easier to do tiering -- positioning data on different classes of storage based on its performance and access characteristics. "Tiering can be done in block, but if you have a file presentation, you gain access to a wealth of [information lifecyle management] tools," he said.
VMPowered's Lucero, meanwhile, recommends NAS over SAN storage to his customers in cases where they'd like to replicate their storage. With a SAN, if you want to do replication, you have to replicate the entire LUN, Lucero said. With NAS, you can use file-based replication and only copy the changes to the individual files, i.e., virtual machines.
Lucero started using NAS to store VMs seven years ago at a previous employer "because that's what we had available." When VMware introduced ESX 1, the company discontinued support for NAS, but it supports it again as of ESX 3.
Where NAS nosedives
If NAS is so great, why doesn't everyone use it?
In a nutshell, for performance reasons, said Rob Stevenson, managing director for storage at TheInfoPro Inc., a market research firm focused on the IT operations at Fortune 1000 companies. With NAS, "the TCP/IP stack has to be accessed every time you access your data, so you don't get nearly as good performance," he said.
But according to Hollis, the NAS performance penalty may be overstated. "To be honest, we're not seeing a whole lot of high performance stuff being put on VMware," he said. Furthermore, whether a packet is traveling over Fibre Channel or Ethernet, "it still travels at the speed of light; the real issue is bandwidth – do I need more lanes on the highway?" High-end NAS platforms such as those from EMC, BlueArc Corp. and Network Appliance Inc. can be configured to transmit data over multiple gigabit Ethernet ports, matching the bandwidth of a single 4Gbps Fibre Channel pipe.
Stevenson said that in order to see if NAS is a good fit for an environment, simply add up the aggregate I/Os per second that you expect the ESX hosts to generate.
For Lucero, that usually translates into placing virtual machines running "non-transactional" applications on NAS -- for example, Web servers, DNS and DHCP, or common network services like Cisco fabric management apps.
But that will change, Lucero said. "Over time, NAS is going to become much more of a player, especially as we get to 10 Gig Ethernet."
Let us know what you think about the story; e-mail: Alex Barrett, News Director
Dig Deeper on VMware virtualization
PRO+
Content
Find more PRO+ content and other member only offers, here.
Start the conversation
|
http://searchservervirtualization.techtarget.com/news/1237617/EMC-exec-champions-NAS-for-VMware-shops
|
CC-MAIN-2017-04
|
refinedweb
| 919
| 60.35
|
An introduction to integration testing
Unit tests and widget tests are handy for testing individual classes, functions, or widgets. However, they generally don’t test how individual pieces work together as a whole or capture the performance of an application running on a real device. These tasks are performed with integration tests.
Integration tests work as a pair: first, deploy an instrumented application to a real device or emulator and then “drive” the application from a separate test suite, checking to make sure everything is correct along the way.
To create this test pair, use the flutter_driver package. It provides tools to create instrumented apps and drive those apps from a test suite.
In this recipe, learn how to test a counter app. It demonstrates how to setup integration tests, how to verify specific text is displayed by the app, how to tap specific widgets, and how to run integration tests.
This recipe uses the following steps:
- Create an app to test.
- Add the
flutter_driverdependency.
- Create the test files.
- Instrument the app.
- Write the integration tests.
- Run the integration test.
1. Create an app to test
First, create an app for testing. In this example, test the counter app produced by the
flutter create command. This app allows a user to tap on a button to increase a counter.
Furthermore, provide a
ValueKey to the
Text and
FloatingActionButton widgets. This allows identifying and interacting with these specific widgets inside the test suite.
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Counter App', home: MyHomePage(title: 'Counter App', // Provide a Key to this specific Text widget. This allows // identifing the widget from inside the test suite, // and reading the text. key: Key('counter'), style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( // Provide a Key to this button. This allows finding this // specific button inside the test suite, and tapping it. key: Key('increment'), onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
2. Add the
flutter_driver dependency
Next, use the
flutter_driver package to write integration tests. Add the
flutter_driver dependency to the
dev_dependencies section of the apps’s
pubspec.yaml file.
Also add the
test dependency in order to use actual test functions and assertions.
dev_dependencies: flutter_driver: sdk: flutter test: any
3. Create the test files
Unlike unit and widget tests, integration test suites do not run in the same process as the app being tested. Therefore, create two files that reside in the same directory. By convention, the directory is named
test_driver.
- The first file contains an “instrumented” version of the app. The instrumentation allows you to “drive” the app and record performance profiles from a test suite. This file can have any name that makes sense. For this example, create a file called
test_driver/app.dart.
- The second file contains the test suite, which drives the app and verifies it works as expected. The test suite also records performance profiles. The name of the test file must correspond to the name of the file that contains the instrumented app, with
_testadded at the end. Therefore, create a second file called
test_driver/app_test.dart.
This creates the following directory structure:
counter_app/ lib/ main.dart test_driver/ app.dart app_test.dart
4. Instrument the app
Now, instrument the app. This involves two steps:
Add this code inside the
test_driver/app.dart file.(); }
5. Write the tests
Now that you have an instrumented app, you can write tests for it. This involves four steps:
- Create
SerializableFindersto locate specific widgets
- Connect to the app before our tests run in the
setUpAll()function
- Test the important scenarios
- Disconnect from the app in the
teardownAll()function after the tests complete
//"); }); }); }
6. Run the tests
Now that you have an instrumented app and a test suite, run the tests. First, be sure to launch an Android Emulator, iOS Simulator, or connect your computer to a real iOS / Android device.
Then, run the following command from the root of the project:
flutter drive --target=test_driver/app.dart
This command:
- Builds the
--targetapp and installs it on the emulator / device.
- Launches the app.
- Runs the
app_test.darttest suite located in
test_driver/folder.
|
http://semantic-portal.net/flutter-cookbook-testing-integration-intro
|
CC-MAIN-2022-21
|
refinedweb
| 695
| 58.79
|
C Tutorial
Control statement
C Loops
C Arrays
C String
C Functions
C Structure
C Pointer
C File
C Header Files
C Preprocessors
C Misc
Structure examples program in C language
Here we will see some structure example programs using C. You are most welcome if you have completed our all the previous topics of C tutorial especially C structure. So, let’s see some program of structure example here.
We recommend you to see our following guide if you don’t have any idea about them.
Store data in a structures dynamically using C
In this program you will learn to store user input data by dynamic memory allocation. In C severally we need to store data in a structure dynamically. So, let’s have a look at the given C program.
// code here
Output of structure example program:
Calculate difference between two time periods using C structure
Here in this C program we will learn to calculate the difference between two time periods. Let’s try to write the code as bellow;
// C program to calculate difference between two time periods using C #include <stdio.h> struct time{ int sec; int mins; int hrs; }; void diff_of_time_period(struct time start, struct time stop, struct time *diff){ while (stop.sec > start.sec){ --start.mins; start.sec = start.mins + 60; } diff->sec = start.sec - stop.sec; while (stop.mins > start.mins){ --start.hrs; start.mins = start.mins + 60; } diff -> mins = start.mins - stop.mins; diff -> hrs = start.hrs - stop.hrs; } int main(){ struct time time_start, time_stop, time_diff; printf("Enter the starting time : \n"); printf("hour minute second : "); scanf("%d %d %d", &time_start.hrs, &time_start.mins, &time_start.sec); printf("Enter the stopping time : \n"); printf("hour minute second : "); scanf("%d %d %d", &time_stop.hrs, &time_stop.mins, &time_stop.sec); diff_of_time_period(time_start, time_stop, &time_diff); printf("\nDifference of time is = %d:%d:%d\n", time_diff.hrs, time_diff.mins, time_diff.sec); return 0; }
Compile and run the program to get the output like this.
C structure example to add two complex numbers
Here, we will write a C program to add two complex number. Let’s see the bellow structure example program;
// C program to add two complex number using structure #include <stdio.h> typedef struct complex_num{ float real; float imag; } comp; comp add(comp n1, comp n2) { comp temp; temp.real = n1.real + n2.real; temp.imag = n1.imag + n2.imag; return (temp); } int main() { comp first_num, second_num, sum; printf("Enter real and imaginary parts of first number : \n"); scanf("%f %f", &first_num.real, &first_num.imag); printf("Enter real and imaginary parts of second number : \n"); scanf("%f %f", &second_num.real, &second_num.imag); sum = add(first_num, second_num); printf("Sum = %.1f + %.1fi", sum.real, sum.imag); return 0; }
Output of this add two complex number program :
Enter real and imaginary parts of first number : 5.9 -3.88 Enter real and imaginary parts of second number : 2.8 3.9 Sum = 8.7 + 0.0i
|
https://worldtechjournal.com/c-tutorial/c-structure-examples/
|
CC-MAIN-2022-40
|
refinedweb
| 489
| 55.74
|
Today is my 32 days of #100Daysofcode and #python. Today also continue to learned more about database on python with the help of coursera. Prepared some table. Tried to made some database to read data from file.
Here is one code which made database for file.
In the code below code start with import sqlite3 library. We make the connection with emailbd.sqlite. If there Counts table already exist then first drop it out and recreate that table. After there is loop for find number of counts of emails. If row is not exists then we insert value in that row .If row already exists then we update value in that row.
import sqlite3 conn = sqlite3.connect('emailbd.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Counts') cur.execute('''CREATE TABLE Counts(email TEXT,count INTEGER)''') fname = input('enter file name:') if(len(fname)<1): fname = 'mbox-short.txt' fh = open(fname) for line in fh: if not line.startswith('From:'):continue pieces = line.split() email = pieces[1] cur.execute('SELECT count FROM Counts WHERE email = ?',(email,)) row = cur.fetchone() if row is None: cur.execute('''INSERT INTO Counts(email,count)VALUES(?,1)''',(email,)) else: cur.execute('''UPDATE Counts SET Count = Count + 1 WHERE email = ?''',(email,)) conn.commit() sqlstr = 'SELECT email, Count FROM Counts ORDER BY Count DESC LIMIT 10' for row in cur.execute(sqlstr): print(str((row[0]),(row[1]))) cur.close()
Day 32 of #100DayOfcode and #Python— Durga Pokharel (@mathdurga) January 25, 2021
learned More About Database And Made Few Tables.#100DaysOfCode ,#CodeNewbies ,#beginners pic.twitter.com/sfk25byLR5
Discussion (1)
You can check if the fname as in,
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/iamdurga/day-32-of-100daysofcode-learned-more-about-database-on-python-29al
|
CC-MAIN-2021-10
|
refinedweb
| 273
| 72.02
|
Spring 2003
ii
Contents1 SCOPE AND INTRODUCTION1.1 Scope of the Course . . . . . . . . . . . . . .1.2 About Errors . . . . . . . . . . . . . . . . . .1.3 Numerical Background . . . . . . . . . . . . .1.4 Basic Problems in Numerical Linear Algebra
....
113613
2 IDENTIFICATION2.1 SISO identification from the impulse response2.2 State-space realizations . . . . . . . . . . . .2.3 Balanced realizations . . . . . . . . . . . . . .2.4 Pade algorithm . . . . . . . . . . . . . . . . .2.5 Multi-input multi-output impulse response . .2.6 Input-Output Pairs . . . . . . . . . . . . . . .2.7 Recursive least squares . . . . . . . . . . . . .2.8 MIMO identification via I/O pairs . . . . . .2.9 Linear prediction . . . . . . . . . . . . . . . .
.........
23232933384447535460
......
67676972758085
.....
91. 91. 96. 102. 106. 111
5 KALMAN FILTERING5.1 Kalman filter implementations . . . . . . . .5.2 Error analysis . . . . . . . . . . . . . . . . . .5.3 Experimental evaluation of the different KFs5.4 Comparison of the different filters . . . . . . .
123123127134137
139140142143145150
iii
Chapter 1
This course looks at numerical issues of algorithms for signals, systems and control. In doing that aclear choice is made to focus on numerical linear algebra techniques for linear time-invariant, finitedimensional systems. At first hand, this may look as narrowing down the subject quite a bit, butthere are simple reasons for this.The fact that we deal only with numerical methods for linear time-invariant, finite dimensional systems is not really as restrictive as it seems. One encounters in fact very much the samenumerical problems when relaxing these constraints: problems in time varying systems are often based on the time-invariant counterpart becauseof the recursive use of time-invariant techniques or because one uses a reformulation into atime-invariant problem. There is e.g., hardly any difference between Kalman filtering for timevarying and time-invariant systems since they both lead to recursive least squares problems.Another typical example is that of periodic systems which can be rewritten as a time-invariantproblem by considering the lifted system nonlinear systems are typically approximated by a sequence of linearized models for whichstandard techniques are then applied. Also the approximation is sometimes using techniquesborrowed from linear systems theory infinite dimensional systems typically arise from partial differential equations. One thenuses discretizations such as finite elements methods to represent the underlying operatorby a (typically large and sparse) matrix. For both the approximation and the subsequenttreatment of the finite dimensional problem one then uses matrix techniques.So in other words, this course deals with signals that can be modeled by sets of differentialequationsP(
dd)y(t) = Q( )u(t),dtdt
or difference equationsP (E)y(k) = Q(E)u(k),1
where P (.) and Q(.) are polynomial matrices of appropriate dimensions and where u(.) is an mvector of controls or inputs, and y(.) is an p-vector of outputs, and both are functions of time.d, whenWhen the time variable is the continuous time t, the operator is the differential operator dtthe time variable is the discrete variable k, the operator is the advance operator E (often s and zare used instead of the above two). These models thus describe the following input-output behavior
Systemu(.) =
= y(.)x(.)
Other standard linear models use the n-vector of states x(.), leading to so-called state-spacemodels:dx(t) = Ax(t) + Bu(t)dty(t) = Cx(t) + Du(t),
(1.1)(1.2)
andxk+1 = Axk + Bukyk = Cxk + Duk ,
(1.3)(1.4)
where the constant matrices A, B, C and D are of appropriate dimensions. Of course, other modelsare also possible, such as transfer functions and generalized state-space models, but we will focuson the above two.The second restriction in the title of the course is the fact that we focus on numerical linearalgebra techniques. The reasons for this are the following: once we decide to focus on linear time-invariant, finite dimensional systems, it is clear thatwe are dealing with numerical linear algebra problems since the models consist of polynomialand constant matrices there has been a lot of interaction between signals, systems and control and numerical linearalgebra over the last 25 years and significant advances were made as a result of this due to the new developments in this interdisciplinary area, software tools like libraries (SLICOT) and interactive packages (MATLAB, Matrixx , SCILAB) have been developed that havemade these ideas ready to use.Although we do not cover here methods and problems of optimization, approximation, ordinarydifferential equations, two point boundary value problems, and so on, we feel that this is not reallya restriction. Indeed, numerical linear algebra methods are again at the heart of each of these otherareas.2
In view of all this, we believe the material in this course is a kind of greatest common denominator of what anybody interested in numerical methods for signals, systems and control, ought toknow. As the reader will see, that already covers quite a lot of material. That is also the reason whythis course avoids specialized topics as e.g., implementation aspects on specialized architectures,or software aspects. Since the course is meant to educate the reader rather than to provide himwith a basic set of routines, we have chosen to base the course as much as possible on MATLABfor illustrating the numerical issues being discussed.
1.2
About Errors
The systems, control, and estimation literature is replete with ad hoc algorithms to solve thecomputational problems which arise in the various methodologies. Many of these algorithms workquite well on some problems (e.g., small order matrices) but encounter numerical difficulties,often severe, when pushed (e.g., on larger order matrices). The reason for this is that little orno attention has been paid to how the algorithms will perform in finite arithmetic, i.e., on afinite-word-length digital computer.A simple example due to Moler and Van Loan [95] will illustrate a typical pitfall. Suppose itis desired to compute the matrix eA in single precision arithmetic on a computer which gives 6decimal places of precision in the fraction part of floating-point numbers. Consider the case49 24A =64 31and suppose the computation is attempted using the Taylor series formulaeA =
+X1 kA .k!
(1.5)
k=0
This is easily coded and it is determined that the first 60 terms in the series suffice for the computation, in the sense that terms for k > 60 are of the order of 10 7 and no longer add anythingsignificant to the sum. The resulting answer is22.2588 1.43277.61.4993 3.47428Unfortunately, the true answer is (correctly rounded)0.735759 0.5518191.47152 1.10364and one sees a rather alarming disparity. What happened here was that the intermediate termsin the series got very large before the factorial began to dominate. In fact, the 17th and 18thterms, for example, are of the order of 107 but of opposite signs so that the less significant partsof these numberswhile significant for the final answerare lost because of the finiteness of thearithmetic.Now for this particular example various fixes and remedies are available. But in more realisticexamples one seldom has the luxury of having the true answer available so that it is not always3
easy simply to inspect or test an answer such as the one obtained above and determine it to be inerror. Mathematical analysis (truncation of the series, in the example above) alone is simply notsufficient when a problem is analyzed or solved in finite arithmetic (truncation of the arithmetic).Clearly, a great deal of care must be taken.When one thinks of the fact that the response of the system (1.3) is:Z teA(ts) Bu(s)dsx(t) = eAt x(0) +0
then it is clear that even more problems must be expected when approximating the exponentialwith truncated Taylor expansions in this expression.The finiteness inherent in representing real or complex numbers as floating-point numbers ona digital computer manifests itself in two important ways: floating-point numbers have only finiteprecision and finite range. In fact, it is the degree of attention paid to these two considerationsthat distinguishes many reliable algorithms from more unreliable counterparts. Wilkinson [147]still provides the definitive introduction to the vagaries of floating-point computation while [90]and the references therein may be consulted to bring the interested reader up to date on roundoffanalysis.The development in systems, control, and estimation theory, of stable, efficient, and reliablealgorithms which respect the constraints of finite arithmetic began in the 1970s and is ongoing.Much of the research in numerical analysis has been directly applicable, but there are many computational issues (e.g., the presence of hard or structural zeros) where numerical analysis does notprovide a ready answer or guide. A symbiotic relationship has developed, particularly betweennumerical linear algebra and linear system and control theory, which is sure to provide a continuingsource of challenging research areas.The abundance of numerically fragile algorithms is partly explained by the following observationwhich will be emphasized by calling it a folk theorem:If an algorithm is amenable to easy hand calculation, it is probably a poor method if implemented inthe finite floating-point arithmetic of a digital computer.
For example, when confronted with finding the eigenvalues of a 2 2 matrix most peoplewould find the characteristic polynomial and solve the resulting quadratic equation. But whenextrapolated as a general method for computing eigenvalues and implemented on a digital computer,this turns out to be a very poor procedure indeed for a variety of reasons (such as roundoff andoverflow/underflow). Of course the preferred method now would generally be the double FrancisQR algorithm (see [35, 36], [120], and [148] for the messy details) but few would attempt that byhandeven for very small order problems.In fact, it turns out that many algorithms which are now considered fairly reliable in thecontext of finite arithmetic are not amenable to hand calculations (e.g., various classes of orthogonalsimilarities). This is sort of a converse to the folk theorem. Particularly in linear system andcontrol theory, we have been too easily seduced by the ready availability of closed-form solutionsand numerically naive methods to implement those solutions. For example, in solving the initialvalue problemx(t)
= Ax(t);x(0) = x0(1.6)it is not at all clear that one should explicitly want to compute the intermediate quantity e tA .Rather, it is the vector etA x0 that is desired, a quantity that may be computed more reasonably4
by treating (1.6) as a system of (possibly stiff) differential equations and using, say, an implicitmethod for numerical integration of the differential equation. But such techniques are definitelynot attractive for hand computation.Awareness of such numerical issues in the mathematics and engineering community has increasedsignificantly in the last fifteen years or so. In fact, some of the background material that is wellknown to numerical analysts, has already filtered down to undergraduate and graduate curriculain these disciplines. A number of introductory textbooks currently available (e.g., [63, 21, 33, 62,111, 112]) also reflect a strong software component. The effect of this awareness and education hasbeen particularly noticeable in the area of system and control theory, especially in linear systemtheory. A number of numerical analysts were attracted by the wealth of interesting numericallinear algebra problems in linear system theory. At the same time, several researchers in the areaof linear system theory turned their attention to various methods and concepts from numerical linearalgebra and attempted to modify and use them in developing reliable algorithms and software forspecific problems in linear system theory. This cross-fertilization has been greatly enhanced by thewidespread use of software packages and by recent developments in numerical linear algebra. Thisprocess has already begun to have a significant impact on the future directions and developmentof system and control theory, and applications, as is evident from the growth of computer-aidedcontrol system design as an intrinsic tool. Algorithms implemented as mathematical software area critical inner component of such a system.Before proceeding further we shall list here some notation to be used in the sequel:
IFnmATAHA+diag (a1 , , an )(A)i (A)(A)i (A)
a10
..the diagonal matrix
thethethethe
0anset of eigenvalues 1 , , n (not necessarily distinct) of A IFnnith eigenvalue of Aset of singular values 1 , , m (not necessarily distinct) of A IFnmith singular value of A.
Finally, let us define a particular number to which we shall make frequent reference in the sequel.The machine epsilon or relative machine precision can be defined, roughly speaking, as the smallestpositive number which, when added to 1 on our computing machine, gives a number greater than 1.In other words, any machine representable number less than gets rounded off when (floatingpoint) added to 1 to give exactly 1 again as the rounded sum. The number , of course, variesdepending on the kind of computer being used and the precision with which the computations arebeing done (single precision, double precision, etc.). But the fact that there exists such a positivenumber is entirely a consequence of finite word length.5
1.3
Numerical Background
In this section we give a very brief discussion of two concepts of fundamental importance in numerical analysis: numerical stability and conditioning. While this material is standard in textbookssuch as [46, 54, 122, 128] it is presented here both for completeness and because the two conceptsare frequently confused in the systems, control, and estimation literature.Suppose we have some mathematically defined problem represented by f which acts on datax belonging to some set of data D, to produce a solution y = f (x) in a solution set S. Thesenotions are kept deliberately vague for expository purposes. Given x D we desire to computef (x). Suppose x is some approximation to x. If f (x ) is near f (x) the problem is said to bewell-conditioned. If f (x ) may potentially differ greatly from f (x) even when x is near x, theproblem is said to be ill-conditioned. The concept of near can be made precise by introducingnorms in the appropriate spaces.A norm (usually denoted by k.k) is a real scalar function defined on a vector space V, with thefollowing properties kxk > 0, x V kxk = 0 x = 0 kxk = ||kxk, x V, C kx + yk 6 kxk + kyk, x, y VFor vectors in Cn one typically uses the 2-norm:vu nX. u|xi |2kxk2 = ti=1
and for matrices in Cmn one typically uses the induced 2-norm:kAxk2.kAk2 = sup= sup kAxk2kxk6=0 kxk2kxk2 =1or the Frobenius norm:vuXm Xn. u|aij |2kAkF = ti=1 j=1
which are used a lot in the sequel. We can then define the condition of the problem f with respectto these norms asd1 (f (x), f (x ))(f, x) = limsup
0 d2 (x,x )=where di (.,.) are distance functions in the appropriate spaces. This can be visualized by thefollowing picture
'$r
&%
map f (.)
f (x)
k
Data
Result
We see that an ball around x here is mapped by the function f (.) to a region around f (x) ofsmallest radius k. For infinitesimally small , the ratio k of both radii tends to the conditionnumber (f, x). When f (.) has an expansion around x one can writef (x + x) = f (x) + x f.x + O(kxk2 )where x f is the Frechet derivative of f at x. The condition number (f, x) is then also the normkx f k of the Frechet derivative. When (f, x) is infinite, the problem of determining f(x) fromx is ill-posed as opposed to well-posed and the Frechet derivative is thus not bounded. When(f, x) is finite and relatively large (or relatively small), the problem is said to be ill-conditioned(or well-conditioned). Further details can be found in [110].We now give two simple examples to illustrate these concepts.Example 1.1.Consider the n n matrix
A=
0 1 0 0
10 0
Now consider the perturbed matrix A with a small perturbation of the data (the n2 elements ofA) consisting of adding to the first element in the last (nth) row of A. This perturbed matrixthen has the following characteristic polynomial:. () = det.(I A ) = n which has n distinct roots 1 , , n with k = 1/n exp(2kj/n). Denoting the vector of eigenvalues by we have thuskA A k2 = , k k2 =
1/nn .
Related examples can be found in [148], where it is also shown that this is the worst possibleperturbations that can be imposed on A. For this case we thus have: (A) = lim
kA A k= lim 1/n = k k 0 n
Example 1.2.Take now a symmetric diagonal matrix A=diag (1 , , n ). For such matrices it is known that theworst place to put a perturbation in order to move an eigenvalue as much as possible is actuallyon the diagonal. Without loss of generality, let us perturb the first diagonal entry by , then clearlyit is only 1 that is perturbed to 1 + and hencekA A k2 = , k k2 = .Therefore we have (A) = lim
kA A k= lim = 1k k 0
If we want to characterize the amount of errors incurred by this erroneous function, we needto relate it to f (x). A standard way to do that in numerical linear algebra is to write f (x) as theeffect of f (.) on perturbed data x = x + x, i.e.,f (x) = f (x) = f (x + x).
(1.7a)
Notice that rigorously speaking, such a rewrite may not always be possible, especially when thedata space D has smaller dimension than the solution space S, but we will not dwell here on theseaspects. An algorithm is now said to be (backward) stable when for all data points x one canguarantee that x in the above rewrite, will be of the order of the machine accuracy . In picturesthis means the following :
x
Here the computed f (x) also corresponds to the mapping f (x) = f (x + x) of some nearby pointx + x. In words this means that what we computed is actually the exact result of slightly perturbeddata. In practice this is about as much as one could hope, since we can also assume that the collecteddata are usually not of full accuracy anyway. Roughly speaking, one has then the following property:kf (x) f (x)k = kf (x) f (x)k kx xk(f, x).
(1.7b)
The first equality comes from the rewrite of f (x) as f (x), the second approximation comes fromthe Taylor expansion of f (x) = f (x + x), provided it exists of course. So, the algorithm f is saidto be numerically (backward) stable if, for all x D, there exists x D near x such that f (x)equals f (x) (= the exact solution of a nearby problem). Near in this context should be interpretedas kx xk 6 kxk, i.e., of the order of the machine precision times the norm of the data point x.If the problem is (backward) stable, we thus havekf (x) f (x)k = kf (x) f (x)k kxk(f, x).
(1.7c)
This implies that a backward stable algorithm does not introduce any more errors in the result thanwhat is expected from the sensitivity of the problem. If moreover the problem is well-conditioned,this implies that then f (x) will be near f (x).Of course, one cannot expect a stable algorithm to solve an ill-conditioned problem any moreaccurately than the data warrant but an unstable algorithm can produce poor solutions even towell-conditioned problems. Example 1.3, below, will illustrate this phenomenon.Roundoff errors can cause unstable algorithms to give disastrous results. However, it would bevirtually impossible to account for every roundoff error made at every arithmetic operation in a9
complex series of calculations such as those involved in most linear algebra calculations. This wouldconstitute a forward error analysis. The concept of backward error analysis based on the definitionof numerical stability given above provides a more practical alternative. To illustrate this, let usconsider the singular value decomposition of a n n matrix A with coefficients in IR or C [46]A = U V H .
(1.8)
Here U and V are n n unitary matrices, respectively, and is an n n matrix of the form = diag{1 , , n }
(1.9)
with the singular value i being positive and satisfying 1 > 2 > n > 0. The computation ofthis decomposition is, of course, subject to rounding errors. Denoting computed quantities by anoverbar, we generally have for some error matrix EA :A = A + EA = U V
(1.10)
The computed decomposition thus corresponds exactly to a perturbed matrix A. When using theSVD algorithm available in the literature[46], this perturbation can be bounded by:k EA k6 k A k,
(1.11a)
where is the machine precision and some quantity depending on the dimensions m and n, butreasonably close to 1 (see also [71]). Thus, the backward error EA induced by this algorithm, hasroughly the same norm as the input error Ei that results, for example, when reading the data Ainto the computer. Then, according to the definition of numerical stability given above, when abound such as that in (1.11a) exists for the error induced by a numerical algorithm, the algorithmis said to be backward stable [148], [23]. Notice that backward stability does not guarantee anybounds on the errors in the result U , , and V . In fact this depends on how perturbations in thedata (namely EA = A A) affect the resulting decomposition (namely EU = U U, E = ,and EV = V V ). As pointed out earlier, this is commonly measured by the condition (f, A)[110]. For the singular values of a matrix A one shows [46] that(, A) = 1
(1.11b)
independently of the matrix A ! Together with (1.11a) and (1.7b,1.7c) we then obtain a forwarderror bound on the computed singular values:k k2 6 kA Ak2 = kEA k2 6 kAk2 .
(1.11c)
In a sense this can be considered as an indirect forward error analysis by merely bounding theconditioning and the backward error analysis independently and using (1.7b,1.7c).It is important to note that backward stability is a property of an algorithm while conditioningis associated with a problem and the specific data for that problem. The errors in the result dependon both the stability of the algorithm used and the conditioning of the problem solved. A goodalgorithm should therefore be backward stable since the size of the errors in the result is thenmainly due to the condition of the problem, not to the algorithm. An unstable algorithm, on theother hand, may yield a large error even when the problem is well-conditioned.Bounds of the type (1.11a) are obtained by an error analysis of the algorithm used; see, e.g.,[148], [149]. The condition of the problem is obtained by a sensitivity analysis; see, e.g., [148], [142],[122], [127] for some examples. Two simple examples will illustrate further some of the conceptsintroduced above.10
Example 1.3.Let x and y be two floating-point computer numbers and let f l(xy) denote the result of multiplyingthem in floating-point computer arithmetic. In general, the product xy will require more precisionto be represented exactly than was used to represent x or y. But what can be shown for mostcomputers is thatf l(x y) = x y(1 + )(1.12)where || < (= relative machine precision). In other words, f l(x y) is x y correct to within aunit in the last place. Now, another way to write (1.12) is asf l(x y) = x(1 + )1/2 y(1 + )1/2
(1.13)
where || < . This can be interpreted as follows: the computed result f l(x y) is the exact productof the two slightly perturbed numbers x(1 + )1/2 and y(1 + )1/2 . Note that the slightly perturbeddata (not unique) may not even be representable floating-point numbers. The representation (1.13)is simply a way of accounting for the roundoff incurred in the algorithm by an initial (small)perturbation in the data.The above example is actually the error analysis of the basic operation of multiplying two scalarnumbers. One shows [148], [46] that present day machines satisfy the following basic error boundsfor the elementary arithmetic operations:f l(x y) = (x y)(1 + 1 )
(1.14a)
f l(x y) = (x y)(1 + 2 )
(1.14b)
f l(x/y) = (x/y)(1 + 3 )
f l( x) = ( x)(1 + 4 )
(1.14c)(1.14d)
where |i | < (= relative machine precision). The reader ought to check that this implies in factthat these elementary operations are both backward and forward stable.Example 1.4.Gaussian elimination with no pivoting for solving the linear system of equationsAx = b
(1.15)
is known to be numerically unstable. The following data will illustrate this phenomenon. Let0.00011.0001.000A=,b =.1.000 1.0000.000All computations will be carried out in four-significant-figure decimal arithmetic. The true answerx = A1 b is easily seen to be0.9999.0.999911
Using row 1 as the pivot row (i.e., subtracting 10,000 row 1 from row 2) we arrive at theequivalent triangular system 0.00011.000x11.000=.01.000 104x21.000 104Note that the coefficient multiplying x2 in the second equation should be -10,001, but becauseof roundoff, becomes -10,000. Thus, we compute x2 = 1.000 (a good approximation), but backsubstitution in the equation0.0001x1 = 1.000 f l(1.000 1.000)yields x1 = 0.000. This extremely bad approximation to x1 is the result of numerical instability.The problem itself can be shown to be quite well-conditioned.This discussion only gives some indications about stability and conditioning but does not indicate how to prove these properties, or better how to find tight bounds for them. Below, we nowgive some indications about this, without going into too much details.
Sensitivity analysisA sensitivity analysis is typically done from bounding first order perturbations. We give an examplefor the symmetric eigenvalue problem. Let A have the decomposition A = U U H where thecolumns ui of U are the eigenvectors of A and the diagonal elements i of the diagonal matrix are the eigenvalues of A. Now perturb A by A and consider the perturbed equationA + A = (U + U )( + )(U H + U H ).Equating the first order terms on both sides of this equation yieldsA = U U H + U U H + U U Hor alsoU H AU = + U H U + +U H U.One then shows [148] that the two last terms in this equation are zero on the diagonal and hencethat the perturbation of the diagonals of are just the diagonal elements of U H AU , i.e.,i = uHi AuiFrom this identity one now easily derives the sensitivity of the symmetric eigenvalue problem(see [148] for more details). All this of course implied that the above first order perturbationdecomposition exists. It is well known [148] that for the case of multiple eigenvalues with Jordanblocks such a first order expansion does not exist. The analysis can thus in general be much moreinvolved than this simple general principle described above.Another way to proceed experimentally is to run a stable algorithm on the given problem. Errors onthe result will then essentially be due to the sensitivity of the problem, which can then be measuredby artificially perturbing the data and comparing differences in the result.12
Stability analysisOne uses bounds of the type (1.14a, 1.14b, 1.14c, 1.14d) for the elementary operations to start with.As shown above these bounds are good. Then one checks the propagation and accumulation of thesebounds during the evolution of the algorithm. In a sense this is comparable to the stability analysisof a dynamical system. When is the propagation of certain quantities stable ? One easily checksthat error propagation is a nonlinear phenomenon, but luckily one is only interested in bounds forthe errors, which makes the analysis more tractable. It is difficult to give a general methodologyfor performing an error analysis: therefore it is often referred to as an art in which J. H. Wilkinsoncertainly excelled [148]. Let us just mention the importance of unitary matrices in the stabilityproof of algorithms using them. Elementary orthogonal transformations such as Givens rotationsand Householder transformations have been shown to be backward stable (see [148] and also nextsection). Since these transformations (as well as their inverse) have 2-norm equal to 1, one typicallymanages to prove stability of algorithms that only use orthogonal transformations. This relies onthe fact that errors performed in previous steps of such algorithms propagate in a bounded fashionand can then be mapped back to the original data without increase in norm. How this is preciselydone differs of course for each algorithm.Also for stability analysis there is an experimental way of checking it. When running an algorithmon a well conditioned problem, it should give errors on the result which are proportional to thebackward error of the algorithm. This does not guarantee stability of the algorithm in general,since then this ought to hold for all data, but usually it is a pretty good test.
1.4
In this section we give a brief overview of some of the fundamental problems in numerical linearalgebra which serve as building blocks or tools for the solution of problems in systems, control,and estimation. For an elementary but very pleasant introduction to this material we refer to [122].For a more elaborate discussion on this material we refer to [46]. The latter is also an invaluablesource of further references to the rather extended literature in this field.
E=
0 0.... ....0... . . . . . . ..... .... .... 00 0 11
13
Applying such a matrix transformation E to an m n matrix A e.g., adds row 1 times to thelast row. If is chosen equal to an,1 /a1,1 then this eliminates the corresponding (n, 1) elementin the product EA. The complexity of this operation measured in flops (1 flop = 1 addition + 1multiplication) is n. The elimination procedure is backward stable provided || 6 1, or equivalently,if |an,1 | 6 |a1,1 |, i.e., if the eliminated element is smaller than the element used to annihilate it (alsocalled the pivot). When this is not satisfied, one typically interchanges the two concerned rowsfirst, an operation which is called pivoting. See [148], [122] for more details.Givens rotations are matrices that differ from the identity only in four elements at positions (i, i),(i, j), (j, i) and (j, j):
1 ..0..0.. 0 ::::
0 . . cos . . sin . . 0
::: G=. : 0 . . sin . . cos . . 0
:::: 0 ..0..0.. 1
The most commonly used algorithm for solving (1.15) with general A and small n (say n 6200) is Gaussian elimination with some sort of pivoting strategy, usually partial pivoting. Thisessentially amounts to factoring some permutation P of the rows of A into the product of a unitlower triangular matrix L and an upper triangular matrix U :P A = LU.
(1.17)
The algorithm uses a sequence of elementary transformations to achieve this and it is effectivelystable, i.e., it can be proved that the computed solution is near the exact solution of the system(A + E)x = b
(1.18)
with kEk 6 (n) kAk where (n) is a modest function of n depending on details of the arithmeticused, is a growth factor (which is a function of the pivoting strategy and is usuallybut notalwayssmall), and is the machine precision. In other words, except for moderately pathologicalsituations, E is smallon the order of kAk. The total complexity of the decomposition (1.14a)is 2/3n3 and the backsubstitutions for finding x have a lower order complexity than that of thedecomposition. See [122], [46] for further details.The following question now arises. If, because of roundoff errors, we are effectively solving(1.16) rather than (1.15), what is the relationship between (A + E) 1 b and A1 b? A conditionnumber for the problem (1.15) is given by(A) : = kAk kA1 k.
(1.19a)
Simple perturbation results can be used to show that perturbation in A and/or b can be magnifiedby as much as (A) in the computed solution. Estimation of (A) (since, of course, A 1 is unknown)is thus a crucial aspect of assessing solutions of (1.15) and the particular estimation procedure usedis usually the principal difference between competing linear equation software packages. One ofthe more sophisticated and reliable condition estimators presently available is based on [20] and isimplemented in LINPACK [28] and its successor LAPACK [2].A special case of the above decomposition is the Cholesky decomposition for symmetric definitematrices A.A = LLT(1.19b)Because of properties of positive definite matrices, one shows that this decomposition can be computed in a backward stable manner without pivoting. Because of symmetry the complexity of thisdecomposition is now 1/3n3 . The sensitivity of the solution is still the same as that for the generalcase. In the case of the positive definite matrices, one is also interested in the sensitivity of the decomposition itself, i.e., in (L, A). The sensitivity of this factorization has been studied by Stewartin [125] and boils down essentially to that of a Sylvester like equation (we refer to [125] for moredetails).Another important class of linear algebra problems and one for which codes are available inLINPACK and LAPACK is the linear least squares problemmin kAx bk2
(1.20)
A = QR
(1.21)
where A IRmn and has rank k, with (in the simplest case) k = n 6 m. The solution of (1.18) canbe written formally as x = A+ b. Here, standard references include [28], [78], [46], and [122]. Themethod of choice is generally based upon the QR factorization of A (for simplicity, let rank(A) = n)
15
where R IRnn is upper triangular and Q IRmn has orthonormal columns, i.e., QT Q = I.With special care and analysis the case k < n can also be handled similarly. The factorization iseffected through a sequence of Householder transformations Hi applied to A. Each Hi is symmetricand orthogonal and of the form I 2uuT /uT u where u IRm is specially chosen so that zeros areintroduced at appropriate places in A when it is premultiplied by Hi . After n such transformationswe haveRHn Hn1 H1 A =0from which the factorization (1.19a,1.19b) follows. Defining c and d by
cd
= Hn Hn1 H1 b
where c IRn , it is easily shown that the least squares solution x of (1.18) is given by the solutionof the linear system of equationsRx = c .(1.22)The above algorithm can be shown to be numerically stable and has complexity 2n 2 (m n/3) whenusing Householder transformations and 4n2 (m n/3) when using Givens transformations. Again,a well-developed perturbation theory exists from which condition numbers for the solution can beobtained, this time in terms of(A) : = kAk kA+ k.We refer to [130] [47] for more details. Least squares perturbation theory is fairly straightforwardwhen rank(A) = n, but is considerably more complicated when A is rank-deficient. The reason forthis is that while the inverse is a continuous function of the data (i.e., the inverse is a continuousfunction in a neighborhood of a nonsingular matrix), the pseudoinverse is discontinuous. Forexample, consider1 0A== A+0 0and perturbationsE1 =
0 0 0
E2 =
0 00
and
(A + E1 ) =
11+ 2
1+ 2
16
1 00 1
which gets arbitrarily far from A+ as is decreased towards 0. For a complete survey of perturbationtheory for the least squares problem and related questions, see [125], [127].Instead of Householder transformations, Givens transformations (elementary rotations or reflections) may also be used to solve the linear least squares problem. Details can be found in[28, 78, 107, 124], and [147]. Recently, Givens transformations have received considerable attentionfor the solution of both linear least squares problems as well as systems of linear equations in aparallel computing environment. The capability of introducing zero elements selectively and theneed for only local interprocessor communication make the technique ideal for parallelization.Indeed, there have been literally dozens of parallel Givens algorithms proposed and we include[41, 53, 79, 117, 81], and [94] as representative references.
(1.24)
compactly represents the entire algorithm. It is known that the algorithm for this decomposition isbackward stable and has a complexity of kn3 , where k accounts for the iteration in the algorithm17
and may vary between 10and25. For the sensitivity of eigenvalues, eigenvectors and eigenspaces werefer to [148, 123] and [46]. For the computation of the Jordan normal form there are no resultsof guaranteed backward stability around and the complexity of the decomposition is much higherthan that of the Schur decomposition. For this reason, we strongly recommend not to use thisdecomposition whenever one can use instead the more reliable Schur form.An analogous process can be applied in the case of symmetric A and considerable simplificationsand specializations result. Moreover, [107, 148, 46], and [127] may be consulted regarding animmense literature concerning stability of the QR and related algorithms, and conditioning ofeigenvalues and eigenvectors. Both subjects are vastly more complex for the eigenvalue/eigenvectorproblem than for the linear equation problem.Quality mathematical software for eigenvalues and eigenvectors is available; the EISPACK [39],[120] collection of subroutines represents a pivotal point in the history of mathematical software.This collection is primarily based on the algorithms collected in [149]. The successor to EISPACK(and LINPACK) is the recently released LAPACK [2] in which the algorithms and software havebeen restructured to provide high efficiency on vector processors, high performance workstations,and shared memory multiprocessors.Closely related to the QR algorithm is the QZ algorithm [96] for the generalized eigenvalueproblemAx = M x(1.25)where A, M IRnn . Again, a Hessenberg-like reduction, followed by an iterative process areimplemented with orthogonal transformations to reduce (1.25) to the formQAZy = QM Zy
(1.26)
where QAZ is quasi-upper-triangular and QM Z is upper triangular. For a review and referencesto results on stability, conditioning, and software related to (1.25) and the QZ algorithm see [46].The generalized eigenvalue problem is both theoretically and numerically more difficult to handlethan the ordinary eigenvalue problem, but it finds numerous applications in control and systemtheory [131, 132], [141]. The algorithm is again backward stable and its complexity is kn 3 where kvaries between 30 and 70.
r 00 018
is real and r = diag {1 , , r } with 1 > > r > 0. If A is real instead of complex, U andV will be real orthogonal.The proof of Theorem 1.1 is straightforward and can be found in, for example, [43, 46], and [122].Geometrically, the theorem says that bases can be found (separately) in the domain and codomainspaces of a linear map with respect to which the matrix representation of the linear map is diagonal.The numbers 1 , , r together with r+1 = 0, , n = 0 are called the singular values of A andthey are the positive square roots of the eigenvalues of AH A. The columns {uk , k = 1, . . . , m} of Uare called the left singular vectors of A (the orthonormal eigenvectors of AA H ), while the columns{vk , k = 1, , n} of V are called the right singular vectors of A (the orthonormal eigenvectors ofAH A). The matrix A can then also be written (as a dyadic expansion) in terms of the singularvectors as follows:A=
rX
k uk vkH .
k=1
The matrix AH has m singular values, the positive square roots of the eigenvalues of AAH . Ther [= rank (A)] nonzero singular values of A and AH are, of course, the same. The choice ofAH A rather than AAH in the definition of singular values is arbitrary. Only the nonzero singularvalues are usually of any real interest and their number, given the SVD, is the rank of the matrix.Naturally, the question of how to distinguish nonzero from zero singular values in the presenceof rounding error is a nontrivial task. The standard algorithm for computing the SVD is basedon a preliminary bidiagonalization obtained by Householder transformations followed by a furtheriteration to diagonalize the matrix. The overall process requires kn 3 operations where k lies between4 and 26. Another algorithm due to Kogbetliantz [72] uses only Givens transformations and isusually slower but is better suited for matrices with small off-diagonal elements to start with. Bothalgorithms are backward stable.It is not generally advisable to compute the singular values of A by first finding the eigenvaluesof AH A (remember the folk theorem!), tempting as that is. Consider the following real example
with a real number with || < (so that f l(1 + 2 ) = 1 where f l() denotes floating-pointcomputation). Let
1 1A = 0 .0 Then
f l(A A) =
1 11 1
pitfall in attempting to form and solve the normal equations in a linear least squares problem, andis at the heart of what makes square root filtering so attractive numerically. Very simplisticallyspeaking, square root filtering involves working directly on an A-matrix, for example updatingit, as opposed to working on (updating, say) an AT A-matrix. See [10] for further details andreferences.Square root filtering is usually implemented using the QR factorization (or some closely relatedalgorithm) as described previously rather than SVD. The key thing to remember is that in mostcurrent computing environments, the condition of the least-squares problem is squared unnecessarilyin solving the normal equations. Moreover, critical information may be lost irrecoverable by simplyforming AT A.Returning now to the SVD there are two features of this matrix factorization that make itso attractive in finite arithmetic: First, it can be computed in a numerically stable way, andsecond, singular values are well-conditioned. Specifically, there is an efficient and numericallystable algorithm due to Golub and Reinsch [45] (based on [43]) which works directly on A to givethe SVD. This algorithm has two phases: In the first phase, it computes unitary matrices U 1 andV1 such that B = U1 H AV1 is in bidiagonal form, i.e., only the elements on its diagonal and firstsuper-diagonal are non-zero. In the second phase, the algorithm uses an iterative procedure tocompute unitary matrices U2 and V2 such that U2 H BV2 is diagonal and non-negative. The SVDdefined in (1.27) is then given by = U H BV , where U = U1 U2 and V = V1 V2 . The computed Uand V are unitary to approximately the working precision, and the computed singular values can beshown to be the exact i s for A + E where kEk/kAk is a modest multiple of . Fairly sophisticatedimplementations of this algorithm can be found in [28] and [39]. The well-conditioned nature ofthe singular values follows from the fact that if A is perturbed to A + E, then it can be proved that|i (A + E) i (A)| 6 kEk.Thus, the singular values are computed with small absolute error although the relative error ofsufficiently small singular values is not guaranteed to be small. A new algorithm for computing thesingular values of a bidiagonal matrix [26] overcomes this deficiency to the extent that it computesthe singular values of a bidiagonal matrix to the same relative precision as that of the individualmatrix entries. In other words, the algorithm will obtain accurate singular values from accuratebidiagonal matrices. However, one cannot in general guarantee high accuracy in the reduction tobidiagonal form.It is now acknowledged that the singular value decomposition is the most generally reliablemethod of determining rank numerically (see [48] for a more elaborate discussion). However, itis considerably more expensive to compute than, for example, the QR factorization which, withcolumn pivoting [28], can usually give equivalent information with less computation. Thus, whilethe SVD is a useful theoretical tool, its use for actual computations should be weighed carefullyagainst other approaches.Only rather recently has the problem of numerical determination of rank become well-understood.A recent treatment of the subject can be found in the paper by Chan [18]; see also [126]. The essential idea is to try to determine a gap between zero and the smallest nonzero singular valueof a matrix A. Since the computed values are exact for a matrix near A, it makes sense to considerthe rank of all matrices in some -ball (with respect to the spectral norm k k, say) around A. Thechoice of may also be based on measurement errors incurred in estimating the coefficients of A,or the coefficients may be uncertain because of roundoff errors incurred in a previous computation20
to get them. We refer to [126] for further details. We must emphasize, however, that even withSVD, numerical determination of rank in finite arithmetic is a highly nontrivial problem.That other methods of rank determination are potentially unreliable is demonstrated by thefollowing example which is a special case of a general class of matrices studied by Ostrowski [101].Consider the matrix A IRnn whose diagonal elements are all 1, whose upper triangle elementsare all +1, and whose lower triangle elements are all 0. This matrix is clearly of rank n, i.e., isinvertible. It has a good solid upper triangular shape. All of its eigenvalues (= 1) are well awayfrom zero. Its determinant is (1)n definitely not close to zero. But this matrix is, in fact, verynearly singular and gets more nearly so as n increases. Note, for example, that
1 +1 +1
.. ....
0... 1
1 ...... ..
2 ....
. . . . .. .
n+1 2 .... .. .. +1 .0
01
2n+12n+1...2n+1
00...0
(n +).
Moreover, adding 2n+1 to every element in the first column of A gives an exactly singular matrix.Arriving at such a matrix by, say Gaussian elimination, would give no hint as to the near-singularity.However, it is easy to check that n (A) behaves as 2n+1 . A corollary for control theory: eigenvaluesdo not necessarily give a reliable measure of stability margin. As an aside it is useful to note herethat in this example of an invertible matrix, the crucial quantity, n (A), which measures nearnessto singularity, is simply 1/kA1 k, and the result is familiar from standard operator theory. There isnothing intrinsic about singular values in this example and, in fact, kA1 k might be more cheaplycomputed or estimated in other matrix norms. This is precisely what is done in estimating thecondition of linear systems in LINPACK where k k1 is used [20].Since rank determination, in the presence of roundoff error, is a nontrivial problem, all the samedifficulties will naturally arise in any problem equivalent to or involving rank determination, suchas determining the independence of vectors, finding the dimensions of certain subspaces, etc. Suchproblems arise as basic calculations throughout systems, control, and estimation theory. Selectedapplications are discussed in more detail in [71].Finally, let us close this section with a brief example illustrating a totally inappropriate use ofSVD. The rank conditionrank [B, AB, , An1 B] = n(1.28)for the controllability of (1.1) is too well-known. Suppose1 1A=,B =0 1
21
with || <
. Thenf l[B, AB] =
1 1
and now even applying SVD, the erroneous conclusion of uncontrollability is reached. Again theproblem is in just forming AB; not even SVD can come to the rescue after that numerical faux pas.
22
Chapter 2
IDENTIFICATIONIn this chapter we present a number of identification techniques for linear time invariant systems.Such techniques exist for both continuous-time and discrete-time systems, but since we start frominput/output signals, it is much more convenient to treat the discrete-time case. In practice thecontinuous-time case if often solved via the (discrete) sampled versions of the signals anyway. Sohere we treat the discrete-time case only and we will make a few remarks about the continuous-timecase when appropriate. We will consider the cases when the data collected from the system are the impulse response of the system an input output pair of the system covariance data from the system excited by white noise.In each of these cases we will consider both the single-input single-output (SISO) case and themulti-input multi-output (MIMO) case. We do not stress the theory of the identification problembut rather the various aspects of the underlying matrix problems, such as numerical accuracy,sensitivity and complexity of the algorithms.
2.1
n(z),d(z)
(2.1)
where n(z) and d(z) are scalar polynomials satisfying the condition..n = deg.d(z) > deg.n(z) = m.This amounts to say that the system is assumed to be causal. Moreover we assume the impulseresponse of the system is given, i.e., the response of(dn z n + . . . + d1 z + d0 ) yi = (nm z m + . . . + n1 z + n0 ) ui ,23
(2.2)
where {ui } = {1, 0, 0, 0, . . .}. If we denote by 1 the z-transform of this input sequence, the theoutput sequence {yi } has a z-transform equal toy(z) =
n(z) 1.d(z)
(2.3)
This is nothing but the transfer function (2.1) and thus the outputs yi are the coefficients hi of theexpansion of (2.1) in z 1 :h0 + h1 z 1 + h2 z 2 + h3 z 3 + . . . = h(z) =
n(z).d(z)
(2.4)
Rewriting this ash(z).d(z) = n(z),
(2.5)
0......0h0h1h2...
... ... 0h0... . . . h0 h1........ .. ...h0 h1 . . hn1.h1 . .hn.h2 . .hn+1............... ...
d0d1...dn1dn
nn
nn1 . .. n1 = n0
.. .
...
(2.6)
If we normalize n(z)/d(z) such that dn = 1, then the bottom part of the above system can berewritten as:
.h.n+1h1h2.hn
.. hn+2 .. h2..hn+1
...d.
..0.....
....
d1
hn hn+1 . .h2n1 . + h=0(2.7)
2n
.. h
......hh2n12n n+1 h2n+1
.dn1
.....
....h2n h2n+1 .
..................This system is solvable if the left matrix has full column rank n. Once the coefficients of d(z) areknown it is clear that those of n(z can be found from the top n + 1 equations of (2.6). Also if someof the leading parameters h0 , h1 , . . . are zero (i.e., if there is a delay in the response) then clearlythe degree m of n(z) will be lower than the degree n of d(z). One proves the following result:24
.h1h2..
.. h2....
.... .....
. hi hi+1 . .
h i+1 . . . . . . h2i1 . .......h2i .
............
(2.8)
Proof. This property follows from the Hankel structure of that matrix. Since there is an n-thorder system describing the input output behavior, (2.7) holds and the rank of the matrix (2.8)can then be at most n since each column i > n of (2.8) is also a subcolumn of the right hand sideof (2.7), and equation (2.7) says that it is a linear combination of the n previous columns in thematrix (2.8). For i = n the rank must be equal to n otherwise we would find a model of order lowerthan n using (2.7).We will also prove later on that if n is the correct order of the system, it actually follows thatthe leading n n matrix in (2.7) (above the horizontal line) is in fact invertible. This thus suggeststhe following identification algorithm.Algorithm 2.1.Construct
h1
h2...
hn
h2hn+1.............hn hn+1 . . h2n1
., B = .
h0
using
d=
d0d1...dn1
d=A
hn+1. . . 0 h0
hn+2.. . h0 h1 , b = .... ... .. .. ..h1 . . hnh2n
nn ..
n= . n1 n0
b, n = B
d1
One checks that the following MATLAB commands actually implement this, where the columnvector h is assumed to contain the impulse response {h1 , i = 0, 1, 2, . . .} of the system.25
A=hankel(h(2:n+1),h(n+1,2*n)); b=-h(n+2:2*n+1);B=hankel([zeros(1,n),h(1)],h(1:n+1)); d=A\b; d=[d;1]; n=B*d;This algorithm only uses the first 2n + 1 samples of the impulse response todetermine the 2n + 1 unknown parameters of d(z) and n(z). But what should we do if we have toour disposal the impulse response {h0 , h1 , . . . , hN } up to sample N where N 2n + 1 ? It makessense to try to use as much information as possible for determining the polynomials d(z) and n(z).Since the system (2.7) is compatible, we can as well defineA=hankel(h(2:n+1),h(n+1,N-1)); b=-h(n+2:N);and compute thenB=hankel([zeros(1,n),h(1)],h(1:n+1)); d=A\b; d=[d;1]; n=B*d;This now solves Ad = b in least squares sense. Can we say anything about the numerical reliabilityof one approach versus the other ? The sensitivity bounds we find e.g., in [46] say the following.The sensitivity of the square systemAn,n d = bnhas sensitivitykd dk 6 (An,n )kdk
kAn,n k kbn k+kAn,n kkbn k
where all norms are 2-norms. For the least squares problemAN,n d = bNthe comparable formula iskd dk 6 (AN,n )kdk
kAN,n k kbN k+kAN,n kkbN k
krkc1 + c2 (AN,n )kbk
where c1 and c2 are scalars close to 1 and r is the residual vector of the least squares system.Although it appears from this that the least squares problem may have a condition number whichis essentially the square of the linear system, it happens here that krk = 0 and then both formulaslook essentially the same. In practice, it just happens that the linear system is often much moresensitive than the least squares problem. The reason for this is twofold. First, since A n,n is asubmatrix of AN,n its singular values can only be smaller ([46]) and hence typically its conditionnumber is larger. Secondly, if the data in the interval 0 6 i 6 2n happen to be much smallerthan in the complete interval, the relative errors on these samples are typically larger as well. Anexample of this poorer behaviour of the linear system is given below, where indeed it appears thatthe least squares problem behaves much better.26
-2
-4
-6
-8
-100
100
200
300
400
500
600
700
n20 0 0d0 0 0 0 d1 = n1 n010 0 1
and we find n(z) = 1. The transfer function h(z) = n(z)/d(z) is thus a double delay h(z) = 1/z 2as expected.27
-5
x 10
3221
10
-1-1
-2-3
-4-3-5-40
-60
R0
U0
0I
V H.
This trick already reduces the amount of work to 2n2 (N n/3) + 10n3 = 2n2 N + 9 13 n3 , which isa lot of saving when N n (these operation counts are with the construction of Q included). Incombination with this the QR decomposition has the possibility to estimate the rank of the matrix28
via several techniques [18], without actually computing the singular values. This shows that whene.g., N = 1000 samples of the impulse response are given then the order of the system should ratherbe checked on a tall thin matrix rather than on a square one. If e.g., the suspected order is, say8, then the rank property of Theorem 2.1 could as well be checked on a 999 10 matrix as on a500 500 one. The complexity of the first approach is roughly 10.(500) 3 whereas for the second itis roughly 2(10)2 (990) + 9 31 (10)3 . In this particular case the latter is about 6,000 times faster !We terminate this section with a statistical interpretation of the problem or order determinationusing singular values. When equating the inputs and outputs of a system as(dn z n + . . . + d1 z + d0 ) yi = (nm z m + . . . + n1 z + n0 ) uione normally has no exact match (either due to noise on the date, or just due to rounding errorsin these equations). Let us now rewrite this as(dn z n + . . . + d1 z + d0 ) yi = (nm z m + . . . + n1 z + n0 ) ui + ei
(2.9)
where ei is some kind of noise process. The bottom part of equation (2.6) which was used todetermine d(z) now becomes
h1h2 . . hn+1en+1
.. .. h
.....d02
en+2
. d1 .
. .hn+1 . ...= .
.. hn+1
. . h2n+1 .. ..
..
. n......
........eNhN n....hN
Now this equation says that there is a linear combination of the columns of the Hankel matrixHN n,n+1 on the left that is nearly zero, or just noise ei . What the singular value decomposition.does is give the smallest possible perturbation e = [en+1 , . . . , eN ]T which can be obtained with avector d = [d0 , . . . , dn ]T normalized to have unit length. In terms of the singular value decomposition of the matrix HN n,n+1 , the vector d is then in fact the last right singular vector vn+1 ofthe Hankel matrix, and the vector e then equals n+1 un+1 , the last left singular vector scaled bythe smallest singular value. In other words, the smallest singular value is the norm (or variance)you need to allow in (2.9) to make the equation hold, with a polynomial d(z) normalized to havea coefficient vector d of unit norm. When normalizing the polynomial with dn = 1 as suggestedearlier, this has to be scaled with the factor dn /kdk.
2.2
State-space realizations
Single input single output systems can also be represented by state-space realizationsxk+1 = A.xk + b.uk
(2.10)
yk = c.xk + d.uk ,
(2.11)
where A is n n, b and c are n-vectors and d is a scalar. In z-transforms language, this becomes:(zI A)xk = b.uk
yk = c.xk + d.uk .29
When eliminating the variable xk from this, we find the transfer function h(z) of the system ash(z) = c(zI A)1 b + d.For the pair of polynomials d(z) and n(z) with transfer function and with impulse response as givenin (2.4), we actually can derive immediately a state-space realization as follows:
010 ...0h1 .
h ...... .. .
2 .... .
....,b=A=, c = 1 0 . . . . . . 0 , d = h0 . (2.12)
... .. .
.. 0
. ... ... 01
hnd0 d1 . . . . . . dn1
A proof of this is found by equating the two expressions for the transfer function [65], but asimple intuitive way of checking this is to compute the impulse response of the above state spacemodel, say for the first n samples. With zero initial state x0 = 0 and input ui = 1, 0, 0, . . . it isTobvious that x1 = A.x0 + b.u0 = b = h1 h2 . . . hnand y0 = d.u0 = h0 . For the subsequentTsteps 1 < k 6 n one easily checks that xk = A.xk1 = hk . . . hn . . . . Since the outputyk for 0 < k is just the first entry of xk one indeed checks that the outputs are matched for thefirst n samples. A more rigorous proof is given later on.Notice that if a realization {A, b, c, d} of a transfer function is given, then for any invertible. = b, c, d}tranformation T the quadruple {A,{T 1 AT, T 1 b, cT, d} also realizes the same transferfunction. One easily checks that indeed their transfer functions are identical: 1b + d = cT (zI T 1 AT )1 T 1 b + d = c(zI A)1 b + d.c(zI A)
(2.13)
Another way to check the relation between the system {A, b, c, d} and the transfer functionh(z) is by expanding the expression c(zI A)1 b + d in powers of z 1 as in (2.4) for the transferfunction. Using the Neumann expansion of (zI A)1 :(zI A)1 = z 1 (I z 1 A)1 = z 1 I + z 2 A + z 3 A2 + z 4 A3 + . . .we easily findh(z) = d + cbz 1 + cAbz 2 + cA2 bz 3 + cA3 bz 4 + . . .= h0 + h1 z 1 + h2 z 2 + h3 z 3 + h4 z 4 + . . .So we have the identities:h0 = d; hi = cAi1 b, i > 1.These can now be arranged
h1 h1 h2 h2
. h2 h3H= h3 . . .
h2 h3 . . .c.
h3 . . . . . cA ..2
..2 b A3 b . . .... . . = cA bAbA
.. cA3 .. ..
......30
(2.14)
(2.15)
Notice that this again says that the infinite Hankel matrix can indeed be factorized into a productof two rank n matrices, where n is the dimension of the smallest possible realization {A, b, c, d}.The left and right matrices in this product are also known as the observability matrix and thecontrollability matrices of the system {A, b, c, d} and we will denote them by O and C, respectively.It is well known from the control literature that if a system {A, b, c, d} is minimal (i.e., its transferfunction can not be represented by a smaller dimensional system), then O and C have full rank n[65]. Moreover, the finite dimensional matrices On and Cn :
. . cA (2.16)On = , Cn = b Ab . . . An1 b..
.cAn1
have rank n as well. Notice that this implies that the leading n n hankel matrix in (2.17). = b, c, d}is invertible, as mentioned earlier after Theorem 2.1. Also notice that any system { A,{T 1 AT, T 1 b, cT, d} has also the same impulse responsehi = cAi1 b = (cT )(T 1 AT )i1 (T 1 b) = cAi1b.The matrices O and C, on the other hand, are transformed as
cc
. cA cA .
(2.17)
C = OT T 1 CH=OBoth the expressions on the right hand side are rank factorizations of the hankel matrix H, andthe above discussion also indicates that to each factorization into some observability matrix O andcontrollability matrix C there actually corresponds a particular realization {A, b, c, d}. We nowmake this explicit in the following theorem.Theorem 2.2. Let C = OCH=O C, O and C have full rank n, then these matrixbe rank factorizations of H, i.e., the matrices O,factorization are related by = OT, C = T 1 CO and O have a left inverse and that the matricesProof. From the rank condition it follows that OC and C have a right inverse. Denoting generalized inverses with a .+ , we have: = C C+O+ O31
Algorithm 2.2Construct a rank factorization Oi Cj of the i j hankel matrix Hi,j , where both i and j are assumedlarger than n. Then
c cA
Hi,j = Oi Cj = . b Ab . . . Aj1 b..
.i1cAThen define the submatrices
. O =
ccA...cAi2
, O+ =
cAcA2...cAi1
. . C = b Ab . . . Aj2 b , C+ = Ab A2 b . . . Aj1 b ,
Since i, j > n these matrices all have full rank n and we can find A from either of the followingequations:O A = O+ , AC = C+Both these systems are compatible and hence solvable, yielding++A = OO+ = C + C .
The vectors b and c are just found as the first column and row of the matrices C, respectively O.Exercise 2.1.Prove that the realization obtained underization
10 ...0
.... 0.. ...
.... ..
...0H=
0... 01
ln+1,1 . . . . . . ln+1,n
h1h2...
h2.....
hn hn+1
32
hn+1 . . .
hn+1...
..... . h2n1
h2n
...
... ...
Hint: using the construction of Algorithm 2.2, you need only to prove that the vector [l n+1,1 . . . . . . ln+1,n ]is in fact the vector [d0 . . . . . . dn1 ].We know of several factorizations in linear algebra and the one of the above exercise is in factnot a recommended one. It essentially amounts to block LU without pivoting and requires theleading principal n n minor Hn,n of H to be easy to invert (i.e., a good condition number). Noticethat we know this matrix has to be invertible from the discussion before Theorem 2.2, but this maystill be delicate from a numerical point of view. Other factorizations that can be considered areLU with pivoting, QR factorizations and the Singular Value Decomposition.Exercise 2.2.Prove that if we choose a QR factorization of the matrix H into a form
q1,1......qn,1
q1,n......qn,n
H=
qn+1,1 . . . . . . qn+1,n
............ ...
0. . . 0 rn,n rn,n+1
where the leading nn matrix in R is upper triangular and invertible, then the realization {A, b, c, d}will have A in upper Hessenberg form and b will have only the first element non-zero (this is calleda controller-Hessenberg form).
2.3
Balanced realizations
We now show that using the SVD actually leads to realizations with very particular properties forthe quadruple {A, b, c, d}. The particular factorization we consider is described by the followingalgorithm (see [152] for a preliminary version of this).
Algorithm 2.3Decompose the n1 n2 matrix Hn1 ,n2 of rank n into the SVD:
Hn1 ,n2
u1,1......un,1un+1,1...un1 ,1
u1,n....... . . . . . un,n. . . . . . un+1,n.... . . . . . un1 ,n
10...0
0..
... 0... . . .... .... 0. . . 0 n
33
v1,1......
. . . . . . vn,1......
. . . vn2 ,1......
u1,1 . . . . . . u1,n
..
... On1 ,n = un,1 . . . . . . un,n
un+1,1 . . . . . . un+1,n
..un1 ,1
Cn2 ,n
. =
12
0...
..... ...... ....
un1 ,n
..... .... ....
1 . = Un ,n n21
12n
v1,1 . . . . . . vn,1 vn+1,1 . . . vn2 ,1 ...... .. ....
...........0 .1v1,n . . . . . . vn,n vn+1,n . . . vn2 ,nn20...
. 12 H = n Vn2 ,n
Now derive the system {A, b, c, d} from this factorization using the standard approach of Algorithm2.2.The following MATLAB code actually implements this method:function[a,b,c,d]=balss(h,n,n1,n2)%% function[a,b,c,d]=balss(h,n,n1,n2)%% this realizes a quadruple {a,b,c,d} of order n for the siso system% defined by the impulse response h{0}, h{1}, ...h{N} contained% in the column vector h=[h{0}, ..., h{N}] where N>n1+n2-1% The method makes a n1 x n2 Hankel matrix from h{1}% to h{n1+n2-1} and then gets the SVD from that. We assume% n1 geq n2 and n leq n1,n2.H=hankel(h(2:n1+1),h(n1+1:n1+n2));[q,r]=qr(H);[u,s,v]=svd(r);sq=sqrt(s(1:n,1:n));c=q(1,:)*u(:,1:n)*sq;b=sq*v(1,1:n);d=h(1);h1=q(1:n1-1,:)*u(:,1:n)*sq;h2=q(2:n1,:)*u(:,1:n)*sq;a=h1\h2;Notice that we have assumed here that n < n1 , n2 and the the order n is correct. In normalcircumstances the order has to be determined and the SVD is one of the more reliable ways todetermine this. Such things depend though on a user specified threshold of what ought to beconsidered as noise when deciding about the order of the system.The realizations obtained by the above scheme are called balanced realizations. We now derivesome properties of these realizations.Diagonal Gramians. First of all it is easy to see thatOnH1 ,n On1 ,n = n = Cn2 ,n CnH2 ,n34
(2.18)
This follows automatically from the expressions for these matrices and the fact thatUnH1 ,n Un1 ,n = In = VnH2 ,n Vn2 ,n .Moreover from the relation with the observability and controllability matrices we also have thatOnH1 ,n On1 ,n =
Cn2 ,n CnH2 ,n =
nX1 1i=0
nX2 1
H.Ai cH c Ai = Go (0, n1 1),
A i b bH A i
i=0
.= Gc (0, n2 1),
(2.19)
(2.20)
where Go (0, n1 1) and Gc (0, n2 1) are the observability and controllability Gramians over thefinite intervals (0, n1 1) and (0, n2 1), respectively. So, balanced realizations are realizations forwhich the (finite horizon) Gramians are equal and diagonal. Such realizations are well known forthe case of infinite horizon Gramians, in which case some additional properties are obtained. TheGramians Go and Gc are then also the solutions to the following Lyapunov equations:AH Go A + cH c = Go , AGc AH + b bH = GcSign symmetry. From these relations one proves [108] that the matrices of the quadruple {A, b, c, d}actually have some nice symmetry properties. Arranging the quadruple into the matrixA b.E=c dwe have that this matrix is symmetric up to some sign changes, i.e., there exist a diagonal matrixS of 1 such thatES = SE HSuch property is not met when considering the finite horizon Gramians instead, but the followingexercise indicates that we should not be very far from it.Exercise 2.3.Prove that the finite horizon Gramians are the solution to the following equations:AH Go (0, n1 1)A + cH c An1 H cH cAn1 = Go (0, n1 1)AGc (0, n2 1)AH + b bH An2 b bH An2 H = Gc (0, n2 1)Clearly if A is stable and n1 and n2 are sufficiently large the finite horizon Gramians will beclose to the infinite horizon ones, and the same sign symmetry ought to be observed. In practice,this occurs if one uses a Hankel matrix Hn1 ,n2 of which the elements have started to die out, i.e.,which is a reasonable approximation of the infinite horizon Hankel matrix.35
0.50.40.30.20.10-0.1-0.2-0.30
.E=
A bc d
0.77870.6258 0.0148 0.02070.01570.15530.62580.7569 0.0206 0.02730.02190.4308
0.02070.0273 0.9682 0.1834 0.0740 0.2420
0.01570.0219 0.06950.07400.9871 0.2081 0.15530.43080.26070.2420 0.20810.1304
which clearly has sign symmetry. When executing in MATLAB the commands=diag([-1 1 1 -1 1 1]); norm(s*e-e*s)/norm(e)one gets the response 1.7212e 14 which shows how close we are to a sign symmetric matrix,although we have hardly waited for the response to die out (we used only 100 samples of theimpulse response).Computation of poles and zeros. One possible preliminary step in many eigenvalues solversfor an arbitrary matrix M is to perform first a diagonal scaling to insure that rows and columnshave equal norm. This avoids a possible imbalance in the elements of the matrix M and improvesthe accuracy of the computed eigenvalues. For the above matrix A this step is superfluous sincesign symmetry implies that row i and column i have equal norms already. So the computation ofthe poles of the transfer function i.e., the zeros of d(z) from the eigenvalues of A ought to havesmall sensitivity. The zeros of the transfer function i.e., the zeros of the n(z) are in fact the.eigenvalues of Az = A bd1 c which for the above model is again sign symmetric. So the balancedrealization has the nice property that the computation of poles and zeros of the transfer function36
0.96370.1127 0.1127 0.6663
Az = 0.3253 0.8819 0.30890.82680.26350.7094
0.3253 0.30890.26350.8819 0.82680.7094
0.72280.48440.3465
0.48440.2657 0.4602 0.34650.46020.6550
and the poles and zeros are: 0.1940 0.9708i, 0.7679 0.6249i, 0.9900 and 1.7323, 1.0015 0.3022i, 0.1123 1.0242i, which all turn out to have reasonably low sensitivity.Low sensitivity to noise propagation. The paper that actually introduced balanced realizations [99]did so for minimizing the sensitivity of the models to various types of noise propagation. Withoutgoing into details, we give an indication here of this property. Let us write again the evolution ofthe state space equation as A bxk+1xk=.ykukc dthen errors in the inputs, state and output propagate in the same manner: A bxkxk+1=.ukykc d-9
420-2-4-6-8-100
2.4
Pade algorithm
If we do not know from beforehand what the order of the system will be one can take the viewpointto try to identify a family of realizations of growing orders 1, 2, 3, . . .. This would amount tofinding the following polynomials from the following Hankel matrices:
n(1) (z)n0=d(1) (z)z + d0
h3,h4
n(2) (z)n1 z + n 0= 2d(2) (z)z + d1 z + d0
h1 h2 h3h4 h2 h3 h4 , h5 h3 h4 h5h6
n(3) (z)n2 z 2 + n 1 z + n 0= 3d(3) (z)z + d2 z 2 + d1 z + d0
h1 h2h2 h3
, h2
and so on, where degree.n(i) (z) < degree.d(i) (z) because we do not use the parameter h0 in thisprocess. Notice that there are as many parameters on each side of the above arrows, namely 2in (z)at stage i of the above process. So we can match the functions d (i)(z) to the given parameters(i)h1 , . . . , h2i in each stage . In fact, given the original transfer function (without h0 again):n(z)= h1 z 1 + h2 z 2 + h3 z 3 + . . .d(z)n
(2.21)
(z)
the above rational functions d (i)(z) match the Taylor series (2.23) in z 1 in its first 2i terms. It will(i)be shown below that in fact what is now known as the Pade algorithm solves for all of these partialrealizations from degree 1 to n in only O(n2 ) operations !
Some history.This problem is actually known as the Pade approximation problem [15]. The relations of thisproblem to that of Hankel matrices was already observed in the late 1800s by people like H. Hankel(1862), G. F. Frobenius (1886) and T. J. Stieltjes (1894) (see [14] for more history on this). In thesystem theory literature the relation of partial realizations to Hankel matrices were rediscovered and extended to the multi-input multi-output case by Ho-Kalman [56], Youla-Tissi [151] andSilverman[118]. The O(n2 ) algorithms for these partial realizations were rediscovered by Masseyand Berlekamp [85] in the context of convolutional codes, and later on by Rissanen [113] in thecontext of identification. Several years later, de Jong [24] showed that these algorithms all sufferfrom numerical instability.Example 2.3.Consider the Taylor seriesh(z) = 1z 1 + 2z 2 + 3z 3 + 3z 4 + 1z 5 4z 6 8z 7 + . . .38
n(1) (z)1=d(1) (z)z2
3,3
n(2) (z)z1= 2d(2) (z)z 3z + 3
1 2 33 2 3 3 , 1 3 3 14
n(3) (z)z2= 3d(3) (z)z 2z 2 + z + 1
1 22 3
, 2
Exercise 2.4.Check with MATLAB that the above i-th order partial realizations fit the Taylor series in the first2i coefficients. Also check the poles and zeros of the partial realizations. Repeat the same for theseriesh(z) = 1/2z 1 + 1/2z 2 + 3/8z 3 + 3/16z 4 + 1/32z 5 1/16z 6 1/16z 7 + . . .obtained from replacing z by 2z. Results ought to be related to the previous ones. Use theidentification algorithm 2.1 with the minimum amount of data for finding the partial realizations.We now derive a simplified version of the Pade algorithm to show how the Hankel structure ofthe underlying matrices leads to an O(n2 ) algorithm. We first need the following theorem aboutthe existence of LU decompositions.Theorem 2.3. A n n invertible matrix M has a LU decomposition (without pivoting onrows or columns)M =LUiff all its leading principal minors are invertible.Proof. The only if part is simple. Since the LU decomposition exists, L and U must be invertible,otherwise M would be singular. But then the leading principal submatrices L(1 : i, 1 : i) andU (1 : i, 1 : i) of L and U are also invertible, and sinceM (1 : i, 1 : i) = L(1 : i, 1 : i)U (1 : i, 1 : i)the result follows.For the if part we construct L and U as follows. Since M (1 : i, 1 : i) is non-singular for i =1, . . . , n 1, we can solve for a vector x(i+1) in
M (1 : i, 1 : i)x(i+1)
x1,i+1
.= M (1 : i, i + 1), or also M (1 : i, 1 : i + 1) = 0. xi,i+1 1
39
(2.22)
1 x1,1 . . . x1,n 0 1 ... x2,n
M ... . ...... ..0
... .. .=. . .. .... . ...
0.. .
Since the two matrices on the left are invertible, so is the lower triangular matrix on the right.From the above equation we clearly see that we have in fact constructed the factors L (on theright) and U as the inverse of the matrix with the xi,j elements.Corollary 2.1. A n n matrix M has a LU decomposition (without pivoting on rows orcolumns)M =LUiff its leading principal minors of order 1 to n 1 are invertible. In this decomposition one cannormalize either L or U to have 1s on the diagonal. Moreover, if M is symmetric, L and U areequal up to a diagonal scaling S:M = M T = LSLT .In this latter case one can always normalize L to be unit upper triangular.Proof. We refer to [46] for this extension of the above theorem.Using these results we have the following theorem.Theorem 2.4. Let the Hankel matrix Hn+1,n+1 have non-singular leading principal minors oforder 1 to n, then:Hn+1,n+1 = LSLTwith L chosen to be unit lower triangular. Defining the unit lower triangular matrix X T = L1 ,we also have:X T Hn+1,n+1 X = S
(2.23)
and column i + 1 of X contains then the coefficients of the polynomials d(i) (z) of the partialrealizations of the corresponding impulse response.Proof. Using a similar argument as in (2.24) we find that column i + 1 of X has its i + 1 leadingcoefficients satisfying:
.H(1 : i, 1 : i + 1) (2.24) = 0. xi,i+1 1
This is precisely the equation for the denominator d(i) (z) of the partial realization built on thei i + 1 Hankel matrix H(1 : i, 1 : i + 1) (see Algorithm 2.1).40
Example 2.4.One easily
1 2
33
12331
2 1331 1
3 3 131 413 5 2 11 4 84
1 2 3 3
1 3 5
= LT SL
1 2 1
LT
1 1 2 3 31 231
135131 ==
1 21 211
=X
So far we showed that the LSLT decomposition of H, or rather the inverse X of LT , gives allthe partial realizations but such a decomposition typically requires O(n3 ) flops. We now derive afast algorithm that only requires O(n2 ) flops and is in fact a rewrite of the Pade algorithm. Theoriginal Pade algorithm involves polynomials but we prefer to use the decomposition (2.25) instead.Suppose we have this factorization up to step i, i.e.,X(1 : i, 1 : i)H(1 : i, 1 : i)X(1 : i, 1 : i)T = S(1 : i, 1 : i)then we have to find the next column of X in O(i) flops in order to wind up with an total of O(n 2 )flops after n steps ! So the next columns must be very simple to compute indeed. Let us try forcolumn I = 1 of X the shifted version of column i, i.e., the polynomial d(i) (z) is approximated bythe shifted polynomial zd(i1) (z). In other words:
X(1 : i, 1 : i) : i + 1, 1 : i + 1) = X(1
0x1,i...xi1,i1
s1,1
0 . : i + 1, 1 : i + 1)H(1 : i + 1, 1 : i + 1)X(1x(1 : i + 1, 1 : i + 1) = ..
00
0s2,2...
..... 0
0ai
si,ibi
: 0
ai
bi
ci
or a matrix that is almost diagonal, except for the elements ai and bi . In order to prove this we : i + 1, 1 : i + 1) and H(1 : i, 1 : i)X(1 : i, 1 : i).look at the last columns of H(1 : i + 1, 1 : i + 1)X(1 : i + 1, 1 : i + 1) and X(1 : i, 1 : i) are shifted with respectBecause of the last columns of X(1to each other and since the Hankel matrix has shifted rows as well, it follows that only the last41
T (1 : i + 1, 1 : i + 1) on the3 elements of that column are nonzero. Multiplying this now with Xleft hand side does not change the zero pattern of that column, which proves a i and bi are theonly nonzero off-diagonal elements. In fact one checks that ai = si,i . So starting from the righthand side of this result, one needs only two additional elementary eliminations to reduce this to adiagonal matrix:
s1,1 0 . . . 0 01 0 ... 0 01 0 ... 0 0: . . .
.... . .. : . .. .. 0 s2,2 . . ... . 0 0 1 0 10
... .... . .. .. ..
. .. .... 0 . ... 0 ai ... 0 i .
0 ... 0 1 0 0. . . 0 si,i bi 0 . . . 0 1 i 0 .. 0 i i 10.. 0 ai bi ci0 ... ... 0 1
0 . . .
00 si,i. . . 0 si+1,i+1
0......
where i = ai /si1,i1 and i = bi /si,i . From this it finally follows that the last column of the
i : i + 1, i 1 : i + 1) i .X(11
11 2 213 3 13
partial decomposition
2 31 231
3 3 1 3 = 13 111
11 2331 230 2 2 3
131133
3 3
13 31 41 303 3 13 1 4 8142
11
1 1 1 14
l1,10 ...0uu...uu1,11,21,n1,n+1.
... l2,1 l2,2 . .
.... 0 u2,2
0 .......... .
.... ln,1. . . . . . ln,n 0. . . 0 un,n un,n+1ln+1,1 . . . . . . ln+1,nand the corresponding realization {A, b, c, d} is such that
h0 x1 0 . . . 0
.... .. y1 z 1 x 2d c
= 0 y 2 z2 . . . 0b A
.. . . . . . . .... xn0 . . . 0 y n zn
is tridiagonal.
43
Proof. The result is trivial for d = h0 as well as for b and c, since these are the first column ofU and first row of L, respectively (i.e., x1 = l1,1 and z1 = u1,1 ). For the matrix A, it follows fromAlgorithm 2.2 that A satisfies bothL(1 : n, 1 : n)1 L(2 : n + 1, 1 : n) = A = U (1 : n, 2 : n + 1)U (1 : n, 1 : n)1 .From the left equality it follows that A must be lower Hessenberg and from the right equality itfollows that A must be upper Hessenberg. Together this shows that A must be tridiagonal.Corollary 2.2. If in the above LU factorization L is chosen to have 1s on diagonal then allxi = 1; if U is chosen to have 1s on diagonal then all yi = 1.This corollary shows that there are only 2n + 1 parameters in {A, b, c, d}, just as in a polynomial pair n(z)/d(z). In fact one shows that once e.g., xi = 1, the other parameters zi and yi areclosely related to the recurrence parameters i and i for the polynomials d(i) (z) of (27). The dualresult holds of course when normalizing yi = 1.Comparison of SISO identification methods via the impulse response. In the previous 4 sectionswe saw several techniques for identifying a SISO system from its impulse response (also called theMarkov parameters of the system) {hi , i = 0, 1, 2, . . .}. Ordered by increasing complexity theyare:1. the LU decomposition via the Pade algorithm. This requires only 2n2 flops but is an unstablealgorithm. Stabilized algorithms with a similar complexity are being proposed these days.2. the P LU decomposition with pivoting P . A numerically stable and a reasonable complexity:2/3n3 .3. the QR decomposition on a n1 n + 1 matrix. Numerically stable and a complexity of2n21 (n1 n/3). This algorithm usually has better sensitivity properties than LU and P LUbecause more data are involved in the identification.4. the SV D on a n1 n2 matrix (n1 6 n2 ). The algorithm is numerically stable and hascomplexity 2n1 n22 + 10n31 when using a preliminary QR decomposition for the SV D. Thishas the most reliable order estimation of the system and has the additional advantage to givebalanced realizations.
2.5
Here we look at how to extend the SISO algorithms to systems with several inputs and outputs,i.e., we assume a system of the form
y1 (.) y2 (.) ...yp (.)
Systemx(.)
44
u1 (.) u2 (.)... um (.)
where the input vector u(.) is thus m-dimensional and the output vector is p-dimensional. For this.system one could of course always identify the SISO systems hi,j (z) = ni,j (z)/di,j (z) correspondingto the impulse response of input uj (.) to output yi (.). The global transfer function between theinput vector u(.) and output vector y(.) would then be the transfer matrix
n1,1 (z)n1,m (z)...d1,1 (z)d1,m (z)
. ....
Hm,p (z) = (2.25)..
np,1 (z)np,m (z)dp,1 (z) . . . dp,m (z)But this approach has a major disadvantage. If the multivariable system has a transfer functionHp,m (z) of degree n, then it is very likely that each scalar transfer function hi,j (z) has degree n aswell. This is e.g., the case when all the dynamics of the system are present in each input/outputpair. As a consequence of this, all polynomials di,j (z), if normalized to be monic, ought to be equal.But under rounding errors or any other noise source, we can hardly expect this to happen. Theidentified transfer function Hp,m (z) would then have a resulting degree that is likely to be mnp,i.e., mp times too large. Of course part of this would be detected by model reduction techniquesapplied to this composite model, but this would be an unnecessary detour.Since the correct approach is to identify directly the multivariable system H(z), we first haveto define what is meant by the impulse response of such a system. Denote the ith unit vector by e iand consider the response of the input sequence u(j) (.) = {ej , 0, 0, 0, . . .}, i.e., all components ofu(j) (.) are zero except the j-th one which is an impulse. Denote the corresponding output vector(j)
(j)
(j)h1
into the matrix H1 , etc. Then we call the matrix sequence {H0 , H1 , H2 , . . .} thethe p-vectorsimpulse response of the system H(z). One checks that the (i, j) elements of this matrix sequenceis in fact the impulse response of the j-th component of the vector u(.) to the i-th component ofthe vector y(.), provided all other components of the input vector u(.) are kept zero. As a result ofthis we have again the relation that the matrices Hi are the coefficients of the Taylor expansion ofH(z) around z 1 :H(z) = H0 + H1 z 1 + H2 z 2 + H3 z 3 + . . .If one wants now to identify the system H(z) from this expansion then one can try to extendthe SISO techniques to this case. Early attempts [27] to extend the polynomial identificationtechniques lead to techniques where several nested rank checks have to be performed in order toreconstruct particular columns of polynomial matrix pairs D(z) and N (z). These methods will notbe described here because of the simple reason that their numerical reliability is very poor. Notonly is this approach unstable, but the algorithm is also very complex.A much more reliable approach is that of identifying directly a state space modelxk+1 = Axk + Buk
(2.26)
yk = Cxk + Duk ,where the constant matrices A, B, C and D are of dimensions n n, n p, m n, and m p,respectively. Using again the Neumann expansion of (zI A)1 we obtain very similar identitiesto the SISO case:H(z) = D + CBz 1 + CABz 2 + CA2 Bz 3 + CA3 Bz 4 + . . .= H0 + H1 z 1 + H2 z 2 + H3 z 3 + H4 z 4 + . . .45
H1 H1 H2 H3 . . .C H2 H2 H3 . . . . . . CA
2 . ....H = H2 H.3 . . . . . . . = CA B AB A2 B A3 B . . . . H3 . . CA3 ....
(2.27)
(2.28)
As before (see Algorithm 2.2) a rank factorization Oi Cj of a finite block Hankel matrix Hi,j , whereboth i and j are assumed large enough, will yield an observability and controllability matrix fromwhich the matrices A, B and C can be recovered. The number of blocks i and j ought to be chosensuch that in
C CA
Hi,j = Oi Cj = . B AB . . . Aj1 B..
.CAi1
both Oi and Cj have full rank n, assuming of course the underlying model is minimal. It is wellknown from state space theory that the minimum for i is the largest observability index and theminimum for j is the largest controllability index, and both of these are bounded by n [65]. Thisof course does not prevent to take larger values of i or j, since then the rank of these matrices doesnot change anymore. From this rank factorization one then defines the submatrices
CAC2
. CA . CA O = , O+ = ,....
..CAi2
CAi1
. . C = B AB . . . Aj2 B , C+ = AB A2 B . . . Aj1 B .
Since i, j are large enough, these matrices all have full rank n and we can find A from either of thefollowing equations:O A = O+ , AC = C+Both these systems are compatible and hence solvable, yielding++A = OO+ = C + C .
The matrices B and C are found again as the first block column and block row of the matrices C j ,respectively Oi .46
One checks readily that when using the singular value decomposition for this rank factorization,one obtains again Gramians Go (0, i1) and Gc (0, j1) over the finite intervals (0, i1) and (0, j1):HOi,nOi,n =
HCj,n Cj,n=
i1Xi=0
j1X
H.Ai C H C Ai = Go (0, i 1),
(2.29)
.= Gc (0, j 1),
(2.30)
Ai B B H Ai
(2.31)
So, balanced realizations in the MIMO case are realizations for which the (finite horizon) Gramiansare equal and diagonal.In the SISO case we had nice additional properties which only hold to a certain extent in theMIMO case. We still have that the infinite horizon Gramians are also the solutions to Lyapunovequations:AH Go A + C H C = Go , AGc AH + B B H = Gcbut this does not imply any sign symmetry anymore for the realization. Yet, it is still true thatthese realizations have good numerical properties in terms of eigenvalue sensitivity (for computingpoles and zeros) and in terms of round-off noise propagation (for simulation purposes). Roughlyspeaking, these realization have very similar numerical advantages in the MIMO case as what weshowed for the SISO case.The sensitivity of the balanced realization algorithm depends directly on the sensitivity of thesingular value decomposition. The matrices B and C are just submatrices of this rank factorizationand the dependency on the factorization is thus obvious. For the matrix A one essentially solvesO A = O +in each identification method, but the coordinate system used for balanced realizations typicallygives a low norm solution kAk, which then also results in a lower perturbation kAk for the samesensitivity. One notices this typically in the computation of the eigenvalues of A, which are thepoles of the system and are thus invariant for each identification. The best precision of these polesare usually obtained from the balanced realization.
2.6
Input-Output Pairs
In many circumstances we do not have access to the impulse response of a system. A typicalexamples is a system which is operational and for which it is too costly to affect the input (letalone apply an impulse as input) in order to measure the corresponding output. In some otherexamples it is physically impossible to affect the input and one can only observe (or measure)inputs and outputs.47
(2.32)
orH(z) = C(zI A)1 B + D
(2.33)
from input output measurements is certainly an important one. A first problem that immediatelyoccurs here is that some input output pairs generated by an irreducible (or minimal) system (2.32)or (2.33) of a certain order, could as well have been generated by a lower order one. The inputoutput pair then essentially behaves as that of a lower order system. So we need to assume thatthis does not happen. The standard assumption made in this context is that of persistence ofexcitation, which we define loosely as follows.Definition 2.1. An input-output pair {ui }, {yi } is said to be persistently exciting with respectto the underlying model (2.32)-(2.33) if the same pair can not be generated by a lower ordermodel.Depending on the context in which persistence of excitation is being used, different definitionsoccur, but they amount to the same idea. The dynamical interpretation of this is that when a pair{ui } {yi } is not persistently exciting, then not all the characteristic modes of the system are beingexcited or triggered. We will see below that impulse responses are always persistently exciting,which is why this concept was not introduced earlier.We start by considering the single input single output case:d(z)y(z) = n(z)u(z)
(2.34)
(2.35)
or:
where we assume the input to start at some time t = 0. We can rewrite this into a semi-infinitematrix vector equation
0 .. . ...
0 ...
y0 . . .
y1 . . .
y2 . . .
0 0 y0
... . . .. . y1 d
0.... . y2 .. 0 .
.. .. . u0 . .. .. ..
. u1 . .
dn u2 . . .
0 u0
. . u1 n0.. . u2 .
.. .
. . ....
nn
(2.36)
where we assumed deg n(z) = m 6 deg d(z) = n and hence dn 6= 0. Normalizing again to dn = 1,48
we have a system
u0 . . .
u1 . . .
u2 . . .
...|
{z
n+1
... . . . y0
... . . . y1
. . . .. ....
. ...
0 u0.. . u1.. . u2. ........
0y0y1y2...}
d0
.dn1
n0...
y0y1y2......
(2.37)
which we can solve for the other coefficients of n(z) and d(z) provided the matrix on the left handside has full column rank. We prove the following theorem in this context.Theorem 2.6. Let n be the order of the system generating the causal input output pair {u i }{yi }. If the pair is persistently exciting then
[U:,n+1 | Y:,n+1 ] =
is singular and
0...0y0y1y2...
[U:,n+1 | Y:,n ] =
|0...0y0y1y2...
...............
0 y0
.. . y1
.. . y2
. .. ...
{zn
(2.38)
(2.39)
Proof. Because of the assumption made, (2.36) holds and hence (2.38) is singular since the vector[n0 , . . . , nn , d0 , . . . , dn ]T is in its kernel. The second part is proved by contradiction. Assume49
[U:n+1 | Y:,n ] would not have full column rank. Then there exists a vector [n0 , . . . , nn , d0 , . . . , dn1 ]Tin its kernel. But the first row of this equation then reduces tou0 nn = 0.
(2.40)
Causality implies that the sequence yi is zero as long as ui is zero, so we can assume withoutloss of generality that u0 6= 0. But then (2.40) implies nn = 0. This now implies we also havea solution [n0 , . . . , nn1 , d0 , . . . , dn1 ]T for a system (2.35) of order n 1 instead of n, whichcontradicts the assumption of persistence of excitation.
Remark1. An impulse is always persistently exciting. This follows from (2.36) which becomes
0...010...
0.... ...... ..0 ...... ...
10...00...
0...0h0h1h2...
0h0....... ........ .... . . . . . hnh2 . . . hn+1...
u0...nnd0...dn
= 0
(2.41)
which is the standard equation we had in (2.6) and for which no assumption of persistence ofexcitation was needed.2. The assumption of minimality of a system is different from persistence of excitation sincethat is a property of a system, not of a signal pair. These should not be confused with each other.Exercise 2.5.Consider the pair {ui } = {1, 0, 0, 0, . . .} and {yi } = {1, 0, 1, 0, 0, . . .}, which is assumed to be asecond order signal pair. Then
001000...
010000...
100000...
00101010 10 10100000.........
1 0
1 = 0
and from this we find n(z)/d(z) = (z 2 1)/z 2 = 1 z 2 . Clearly the matrix containing the firstfive columns has full column rank.50
..... . [u1 y1 ] h2
. .. [0, 0] . . ...[u2 y2 ] . .
[0, 0] . ...[uy]2 2
H= = hn+1 . . .......
[u0 y0 ] ... hn+2 . . .
[u1 y1 ] . . ... hn+3 . . .
[u2 y2 ] . . .
hn+1.. . hn+2.. . hn+3.........
(2.42)
If the maximum rank in this matrix is 2n+1, then a 2(n+1)2(n+2) matrix ought to be sufficientto detect the order of the system. Using MIMO Hankel matrix ideas, one shows that the systemcan be identified from a minimum number of 2n + 1 rows of the above Hankel matrix. This provesagain that the minimum number of equations needed to construct n(z) and d(z) is 2n + 1:
[U2n+1,n+1
| Y2n+1,n ]
n1...nnd0...dn1
y0.........y2n
(2.43)
This always yields a solvable system, if n is the correct order of the underlying system.Exercise 2.6.Check that 2n + 1 equations are sufficient for the case of the impulse response, by using results ofearlier sections.Remarks1. The LU decomposition of (2.43) satisfies for identifying the system n(z), d(z).2. If more data are available, the larger least squares problem involving the matrix [U N,n+1 |YN,n ] ought to be preferred for reasons of lower sensitivity.3. For a more reliable order estimation one should use the singular value decomposition ratherthan the QR or LU decomposition. On the system.MN,2n+2 = [UN,n+1 | YN,n+1 ]
(2.44)
the following interpretation can be given to this decomposition. Although the order indicatesthat this system only has rank 2n + 1 and hence ought to have one singular value 2n+2 = 0,this cannot be expected in practice due to noise on the data as well as roundoff noise in51
the computations. The SVD of this matrix can now be interpreted in terms of perturbedequationsd(z)y(z) = n(z)u(z) + e(z)
(2.45)
or
[UN,n+1
Indeed, let
| YN,n+1 ]
n0...nnd0...dn
e0.........eN
MN,2n+2 = U V T
(2.46)
(2.47)
(2.48)
(2.49)
kvk=1
where u2n+2 and v2n+2 are the singular vectors corresponding to 2n+2 in this decomposition.This implies that if one chooses[n0 , . . . , nn , d0 , . . . , dn ]T
= v2n+2
(2.50)
then this is the choice of polynomials n(z) and d(z) with norm knk2 + kdk2 = 1, whichminimizes the errorkek2 =
NX
e2i
(2.51)
among all such polynomials. This can be interpreted as minimizing the variance of the residualerror (or noise process) over all possible models of a given order. The least squares solutionhas the interpretation that it orthogonalizes the error e to previous data vectors.The SVD can not be used here anymore to construct a balanced realization from I/O pairs.A construction using more involved concepts is given later.4. The equations to be solved still display some structure (block Hankel) which could be exploitedto yield a fast algorithm. Extensions of the Pade algorithm have been proposed to suchmatrices but they are very complex and unstable like the basic form of the Pade algorithm.Stabilized version have not been proposed yet.52
5. The complexities for identifying an n-th order system (i.e., the polynomials n(z) and d(z) oforder n) are thus 16/3n3 for the LU decomposition on a minimal matrix M2n+1,2n+1 8N n2 for the QR decomposition on MN,2n+1 where N 2n + 1
8N n2 + 9 31 (2n)3 on the same matrix using the economic SVD approach (first a QRdecomposition followed by an SVD on R).
2.7
When input output data {ui }, {yi } are being collected in real time, (i.e., newer data are availableat later time instants) we would like to have the best possible estimate of the system at eachtime instant. If we use least squares approximations then we want to solve for a family of QRdecompositions. If we use minimum variance approximations we what to solve for a family of SVDs.In both cases, Givens transformation play a crucial role in the updating of such decompositions.We explain first the QR updating problem. Consider the (weighted) least squares problem
AN
w0 aT0
w aT 1 1= ..
.wn aTN
(2.52)
where wi = N i and || < 1 is an exponential weighting factor (also called forgetting factor), andwhere aTi is a column vector of the matrix [UN,n+1 | YN,n+1 ].We assume we have a QR decomposition of AN :
0T
= QN . ..0T
AN = QN RN
(2.53)
where R is an upper triangular matrix, and we want to find the corresponding decomposition ofthe updated matrix
R+
AN +1 = QN +1 RN +1 = QN +1 . ..0T
(2.54)
"
ANaTN +1
53
QN1
R 0 aTN +1
(2.55)
and it follows from this that solving for the QR decomposition of AN +1 involves only the updatingdecomposition :"#R= Qup Rup .(2.56)aTN +1From (2.53)-(2.54) one derives indeed thatRup =and QN +1 is a mere block product of QN and Qup
QN +1 =
R+(2.57)0TQ11 q12., padded with identities :=Tq21q22
Q11
q12I
Tq21
q22
(2.58)
Since orthogonal transformations can be discarded in least squares problems once the matrix andthe right hand side have been updated with it we can leave details about storing Q behind here,and concentrating on updating R . Solving (2.54) can be done via a sequence of Givens relationsand this involves n Givens rotations if the vector aTN +1 has n elements in it. The order in whichthe elements are eliminated is indicated in the matrix below by the index i of each i (illustratedfor n = 5):
1 2 3 4
(2.59)
Each element i is eliminated by a Givens rotation between rows i and n + 1 of the matrix. Theflop count for these operations is4n + 4(n 1) + 4(1) = 4
nXi=1
i 2n2
When applying this to a N n matrix we have a total of 2N n2 . For the N 2n matrix consideredin the previous section this would be 2N (2n)2 = 8N n2 . The Householder method for the samematrix is 8N n2 but it constructs both Q and R. If only R is requested, the Householder methodreduces to 4N n2 , i.e., half of the work of the recursive least squares decomposition only. And therecursive approach meanwhile also constructed the QR decompositions of all intermediate sizes !
2.8
We now assume the system to be identified has m inputs and p outputs, so uk IRm and yk IRp .54
y1 (.) y2 (.) ...
u1 (.) u2 (.)...
yp (.)
um (.)
(2.60)
explaining the I/O measurements {ui } {yi } for i = 1, . . . , N , where N of course has to be largeenough to be able to reconstruct the model {Ann , Bnm , Cpn Dpm }. As before we have to assumepersistence of excitation of the I/O signals. The componentwise identification of the polynomialsnij (z)/dij (z) of the transfer function between input j and output i leads to an overestimate ofthe order when assembling these scalar systems into the p m transfer function. So identifyingscalar models nij (z)/dij (z) or {A, bj , ci , dij } has to be abandoned in favor of a direct identificationof {A, B, C, D}.We start by noting that the problem would be much simpler if the sequence of states x k wouldbe known as well. From xk+1xkA B=(2.61)CDykukwe can indeed write the concatenated matrixx2 x3 xNA Bx1 x2 xN 1=.y1 y2 yN 1C Du1 u2 uN 1
(2.62)
Under the assumption of persistence of excitation one shows that the right data matrix in (2.62)has full column rank n + m and has thus a right inverse. Equivalently, (2.62) can be solved in aleast squares sense for the evolution matrixA B.(2.63)E =C DSo the problem is solved as soon as the states xi are determined. But those depend on the choiceof coordinates chosen for the state space model. Replace indeed xi by xi = T 1 xi , then (2.62)becomes the related problems
x2 x3 xNx1 x2 xN 1A B=.(2.64)y1 y2 yN 1u1 u2 uN 1C Dor
T 1 x2 T 1 x3 xNy1y2 yN 1
T 1 ATCT
T 1 BD
55
T 1 x1 T 1 x2 T 1 xN 1u1u2
uN 1
(2.65)
= [ x 1 x2 . . . xN ]
(2.66)
(2.67)
where
A i BiCi Di
. Uk,i =
AiCCA...
Ai1 BDCD...
CAi2 B
uk+i1
D..
uk...
. . . AB B
. Yk,i =
yk...yk+i1
Now stacking several of these vectors Uk,i and Yk,i next to each other yields
ykyk+1 yk+j1.
......Yk,i,j =
...yk+i1 yk+i yk+i+j2Uk,i,j
. =
uk...uk+i1
yk+j1
. yk+i+j2
uk+1 ...uk+i56
(2.68)
(2.69)
(2.70)
(2.71)
.= [ xk xk+1 . . . xk+j1 ]
(2.72)
= Ci Xk,j + Di Uk,i,j
(2.73)
which says that the rows of Yk,i,j are linear combinations of the row of Xk,j and Uk,i,j . This thenleads to the following theorem.Theorem 2.7. LetYk,i,j(2.74)Hk,i,j =Uk,i,jbe a block Hankel matrix of input output pairs. Provided i > n, j > (m + p)i and {u i } {yi } is apersistently exciting pair, thenrank(Hk,i,j ) = rank(Uk,i,j ) + rank(Xk,j ) = mi + n
(2.75)
Proof. If i > n then Ci is full column rank n. If j > (m + p)i then Yk,i,j , Xk,j and Uk,i,j are allmatrices with more columns than rows. From (2.73)-(2.74) we find then thatrank(Hk,i,j ) 6 rank(Uk,i,j ) + rank(Xk,j )since the rows of Yk,i,j are linear combinations of those of Uk,i,j and Xk,j . If persistence of excitationis present then the rows of Uk,i,j and Xk,j are linearly independent, as well as the way they entervia the matrix Yk,i,j in (2.73) and then we haverank(Hk,i,j ) = rank(Uk,i,j ) + rank(Xk,j )which completes the proof.We now use this result to determine a basis for the rows of Xk+i,j . Consider two equations asin (2.73) shifted over i time steps. So in addition to (2.73) we haveYk+i,i,j
= Ci Xk+i,j + Di Uk+i,i,j .
(2.76)
Hencerank(Hk+i,i,j ) = rank(Uk+i,i,j ) + rank(Xk+i,j ) = mi + n.
(2.77)
.= [ xk+i xk+i+1 . . . xk+i+j1 ] ,
(2.78)
then T T TIm Xk+i,j= Im Hk,i,j Im Hk+i,i,j57
(2.79)
provided the underlying I/O pair is persistently exciting and i > n, j > (m + p)i.Proof. The notation Im M T stands for the row space of a matrix M . From (2.74)-(2.77) we findrank(Hk,i,j ) = rank(Hk+i,i,j ) = mi + n.
But theorem 2.7 applies also to the larger Hankel matrix Hk,2i,j :rank(Hk,2i,j ) = 2mi + n.And since Hk,2i,j is just a row permutation P of the rows of Hk,i,j and Hk+i,i,j :Hk,i,j,Hk,2i,j = PHk+i,i,jit follows that T Tdim(Im Hk,i,j Im Hk+i,i,j) = n.
(2.80)
dim(Im [M1 | M2 ]) = dim(Im [M1 ]) + dim(Im [M2 ]) dim(Im [M1 ] Im [M2 ]).So the dimension of the intersection (2.80) has the assumed dimension of (2.78). In order to provethe theorem, we thus only have to prove that T T TIm Xk+i,j Im Hk,i,j Im Hk+i,i,j
or in other words, that the row space of Xk+i,j lies in both row spaces of Hk,i,j and Hk+i,i,j . Now(2.76) and the fact that Ci has full column rank, indicates that T T . Im Hk,i,jIm Xk+i,jAlso from an appropriate concatenation of (2.67) we find T TIm Xk+i,j Im Hk+i,i,j
A11 A1201Hk,i,jI 0 V T(2.81)=A21 0302Hk+i,i,j0 QA33
where :
[A11 A12 ] has full column rank equal to the rank of Hk,i,j (or mi + n under the assumption ofpersistence of excitation)58
A33 has full row rank which must be smaller than mi + n if an intersection is to be detected A21 has full row rank equal to the dimension of the intersection, hence n.The order in which this decomposition is constructed is as follows. First the transformation V T isconstructed to compress the columns of Hk,i,j , yielding the trailing zero matrix 01 . Then the rowsof the trailing bottom matrix are compressed with the transformation Q, yielding 0 2 and a fullrow rank A33 . Then V T is updated to yield the full column rank matrix A21 and the trailing zeromatrix 03 . Notice that all three steps involve arank factorization which essentially can be done withQR decompositions. The center matrix in this decomposition has a form which trivially displaysthe intersection of row spaces of the top and bottom parts, namely :
T InA21 A11 = Im 0 .Im AT12 Im 000 AT330
InTTIm(Hk.i.j) Im(Hk+i.i.j) = V Im 0 ,0
i.e., the first n rows of V T are a representation of Xk+i,j . From this we can now construct{A, B, C, D} as explained in (2.62)-(2.65). An alternative and slightly more expensive methodbased on SVDs is proposed in [97] and matlab codes are appended below.function [H]=bhankel(M,Nr,Nc,nr,nc)%% The function [H]=bhankel(M,Nr,Nc,nr,nc) constructs% a block hankel matrix H from a given matrix M.% The matrix H will have Nr block rows and Nc block% columns, each block being nr x nc. The blocks are% given in M either columnwise (M has then nc columns)% or rowwise (M has then nr rows). M must contain at% least Nr+Nc-1 such blocks.%[mr,mc]=size(M);if mr*mc < (Nc+Nr-1)*nr*nc, disp(Data matrix too small); return, endH=zeros(Nr*nr,Nc*nc);if mr==nr,for i=1:Nr, H((i-1)*nr+1:i*nr,:)=M(:,(i-1)*nc+1:(i+Nc-1)*nc); endelseif mc==nc,for i=1:Nc, H(:,(i-1)*nc+1:i*nc)=M((i-1)*nr+1:(i+Nr-1)*nr,:); endelsedisp(Wrong dimensions);endend59
function [a,b,c,d]=abcdio(H,m,p,tol)%% The function [a,b,c,d]=abcdio(H,m,n,tol) determines a system% {a,b,c,d} which reproduces the io pairs u(k) y(k) corresponding% to%x(k+1) = a x(k) + b u(k)%y(k) = c x(k) + d u(k)%% from a given hankel matrix H containing the io pairs%%H(i,j)=z(i-j+1)with z(k)=[u(k) y(k)]%% The input and output dimensions are m and p respectively.% The tolerance tol is used to find an appropriate state% dimension for x(.) in order to fit the data.%[mh,nh]=size(H);mh2=mh/2;i=mh2/(m+p);if mh2 ~= i*(m+p), disp(Incorrect dimensions); return, end[u,s,v]=svd(H(1:mh2,:));pp=rank(s,tol);n=pp-m*i;if n < 1 , disp(Zero or negative state dimension); return, enduu=H(mh2-m-p+1:mh2-p,2:nh);yy=H(mh2-p+1:mh2,2:nh);H=H*v;h3=H(mh2+1:mh,pp+1:nh);[u3,s3,v3]=svd(h3);H(mh2+1:mh,:)=u3*H(mh2+1:mh,:);h2=H(mh2+m*i+1:mh,1:pp);[u2,s2,v2]=svd(h2);H(:,1:pp)=H(:,1:pp)*v2;x=v(:,1:pp)*v2(:,1:n);x=x;B=[x(:,2:nh);yy];A=[x(:,1:nh-1);uu];M=B/A;a=M(1:n,1:n);b=M(1:n,n+1:n+m);c=M(n+1:n+p,1:n);d=M(n+1:n+p,n+1:n+m);
2.9
Linear prediction
In this section we try to identify a system with transfer function H(z) from its response to an inputsignal which is a stationary white noise process:
Systemyk =
h(z)
60
= uk
znd(z)
where d(z) is a certain polynomial of degree n, then this problem turns out to have a simplerecursive solution. Write d(z)/z n asd(z)zn
1 + a1 z 1 + + an z nc
where a() is an nth order polynomial. The response to the system is thus:yk = cuk
nX
ai yki .
(2.82)
i=1
If the ai and c coefficients are fixed, then {yk } is again a stationary process. Therefore,E{yk , ykj } = rj
= rj
is only function of the distance i between the samples. Multiplying (2.82) by ykj and takingexpected values yieldsrj
ai rji ,
for 1 6 |j| 6
andr0 = c
a i ri
because we know that ur is uncorrelated with ykj for j > 0. One can put this together in thematrix equation
a1
r1r0 . . . rn1
.... a2 .. ,..(2.83) . .. .. .. rnrn1 . . . r0an61
which is a system of equations that has a lot of similarity with the Hankel equation for identifyinga system from its impulse response (see [82] for more details on this).The above matrix Tn is called a Toeplitz matrix and is known to be positive definite because itis the autocorrelation matrix of {yk }. From (2.83) one sees that the vector [1, a1 , . . . , an ]T /c is infact the first column of the inverse of Tn+1 , since
r0 . . . r n .. . .. .. ..
rn . . . r 0
1a1...an
c0...0
(2.84)
In order to solve (2.83) or (2.84) we thus need a factorization of T n+1 . Since it is positive definiteand symmetric there exist matrices L and X such thatTn+1 = LSLT
(2.85)
X T Tn+1 X = S
(2.86)
where L is unit lower triangular, X T = L1 is unit lower triangular and S is diagonal. This followsfrom Corollary 2.1 and the fact that any positive definite matrix has positive principal minors(see [46]). Notice that this implies also that the diagonal elements of Sare positive.There are two fast algorithms for computing the above decomposition. The Levinson algorithmgoes back to (1949) and computes X in 0(n2 ) operations. The Schur algorithm goes back to (18..)and computes L in 0(n2 ) operations.We derive here the simplest one of both algorithms but MATLAB codes for both are given inAppendix. Just us for the Pade algorithm, the key idea in the Levinson algorithm is recursivity.We assume that we have a solution to (2.84) for Ti+1 , i.e.,
r0 . . . r i .. . .. .. ..
ri . . . r 0
1(i)a1...(i)
ai
ci0...0
(2.87)
Because Ti is symmetric with respect to both the diagonal and the anti-diagonal (this is calledcentre symmetry) we can flip around this equation and get the identity
r0 .. .ri
(i)
a. . . ri i.
... ... .. (i) a1. . . r01
= . .
(2.88)
For the solution of the system (2.87), (2.88) incremented by 1 we just try out the shifted vectors62
r0 . . . ri+1 .... ..
...
ri+1 . . . r0
where i = ri+1
Pi
(i)j=1 aj ri+1j .
10(i)(i))a1 ai......(i))(i)a1ai01
ci i
0 0
= .. .. .
. .
i ci
ci0...
i0...
1 i=
i 1
ci+10...
00...
ci+1
(2.89)
1 ii 1
, i = i /ci
with ci+1 = ci (1 i2 /c2i ) = ci (1 2i ). Since the right hand sides are now in the form required by(2.87)-(2.88), the same must hold for the left hand side, i.e.,
(i+1)
ai+1
(i+1) ai
. (i+1) a11
10(i)(i)a1 ai......(i)(i)a1ai01
i
(2.90)
which is the requested update formula. The link with the decomposition (2.86) is that the lastcolumn of X in (2.86) satisfies an equation like (2.88) as easily follows from taking the last columnof Tn+1 X = X T S. The recurrence (2.90) thus generates the column of X. The complexity ofthe i-th step is 2i flops,i and i for (2.90). Summed over n steps this yields anPn i for computing2operation count of i=1 2i = n flops.
The coefficients i are called the reflection coefficients and have important physical meaningin seismic data analysis and in speech processing. They are bounded by 1 but can get close to 1when Tn is nearly singular. This follows from the determinant of Tn which equals the product ofthe coefficients Li .The numerical stability of the Levinson algorithm (in a weak sense) has been proved by Cybenko [22] and that of Schur algorithm by Bultheel [16]. Both results prove that the errors in thecomputed decompositions are proportional to (Tn ), i.e., can only be big when the problem isbadly conditioned. This does not mean that the algorithms are backward stable, but it does saythat the forward errors are comparable in size to what a backward algorithm would imply. Sincebad conditioning is indicated by reflection coefficients being close to 1, it is easy to detect whenthe problem is badly conditioned.Instead of deriving the Schur algorithm we just give the algorithm without proof and referto [25] for an elegant matrix proof. We first assume Tn to be scaled such that r0 = 1, which is63
obtained by dividing Tn by r0 . This scaling is easily absorbed in the diagonal matrix S. Then westart with the 2 (n + 1) array:# "(1)(1)1 r 1 rn 1 l 2 ln+1G =.=(1)(1)0 r 1 rn gn+10 g2Each step of the Schur algorithm consists of the following operations. First shift the bottom rowto the left to fill the zero element and also drop the last element of the top row:#"(1)(1) ln1l2.G :=(1)(1)(1)g2g3 gn+1Then perform a little 2 2 transformation 1/(1 1(1 21 )
G =
21 )"
(2)
1 l2 ln(2)(2)0 g2 gn
Ai z i
R0 R1
R1 . . .Tn+1 = .. . . ..Rn . . .
matrix
. . . Rn. ... .. .
... R1 R1 R0
Both the Levinson and the Schur algorithm have block versions which have complexity n 2 m3 insteadof n3 m3 for a general method for decomposing Tn+1 .64
Some RemarksThe covariance ri or Ri is usually estimated from the data sequence {yk }. This implies switchingfrom expectation to time averages, which only holds if the process is ergodic. Moreover, timeaverages are typically taken over a finite or windowed interval :XXTRi =wk yk yki,wk = 1.k
The above algorithms all extend to non definite Toeplitz matrices but breakdowns may thenoccur and the algorithms are then unstable in general. The stability for the definite case is linkedto the fact that for positive definite matrices no pivoting is required in the LU decomposition.The Levinson recurrence has also polynomial versions, which are:a(i+1) (z) = za(i1) (z) + i a(i) (z)where a(i) (z) is the reversed polynomial of a(i) (z), i.e., the polynomial obtained by flipping theorder of the coefficients. One checks that this is nothing but equation (2.90) in polynomial language.
65
66
Chapter 3
In this chapter we present a number of more reliable methods for analysis and design of a controlsystems using state space representations. A common factor is all these methods is the use oforthogonal state-space transformations rather than just invertible ones. We illustrate the use oforthogonal (or unitary state-space transformation in the complex case) via the concept of condensedforms introduced in [140].If one applies a general state space transformation T to a system
Transform toy(t) =
x(t) = T x(t)
= u(t)
with y IRm , x IRn and u IRp , then the new coordinates give the system
x(t) + Bu(t)
x(t) = A
y(t) = C x(t) + Du(t)
B, C, D} = {T 1 AT, T 1 B, CT, D}.with {A,
(3.1)
Since an invertible matrix T has essentially n2 degrees of freedom (only one inequality constraintdet. T 6= 0 is imposed) we can use these degrees of freedom to assign a number of zeros in the B, C, D}. We illustrate this for m = p = 1 and n = 5 and for a systemtransformed system {A,with unrepeated poles. The transformation T can be chosen to obtain one of the following forms:67
bjd
Ajcj
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1
(3.2)
bc Acd cc
1 0 1 0 0 0 0
0 0 1 0 0 0 ,0 0 0 1 0 0
0 0 0 0 1 0
(3.3)
bo Aod co
010000
001000
000100
000010
(3.4)
Notice that each of these forms has n2 elements assigned either to 0 or to 1. If one now usesorthogonal transforms instead, then the best one can hope for is to create n(n 1)/2 zeros sincethese are the degree of freedom in an orthogonal transformation U . The (symmetric) equationU T U = In indeed imposes n(n + 1)/2 constraints on the elements of U . The equivalent orthogonalforms to the three above ones would be:
bs Asd cs
0 0 0 0 0 0 0 0 0 0 68
(3.5)
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
(3.6)
(3.7)
Clearly each of these forms have a strong similarity to their non-orthogonal counterpart. Thecanonical forms have been used a lot in textbooks because of their simplicity and their use inseveral analysis and synthesis problems. The orthogonal forms, which we will call condensedforms, will be shown to be just as useful for analysis and synthesis problems, and moreover theyhave other major advantages from a numerical point of view.Remark. Canonical forms arise whenever one defines a transformation group, i.e., a set of transformation which is closed under inversion and multiplication. Clearly invertible transformations Tform a group, but so do the unitary transformations. One shows that in fact the condensed formsare canonical forms under the transformation group of orthogonal transforms.
3.2
Condensed Forms
The choice of unitary or orthogonal state-space transformations is governed by the following itemsi) the cost of these transformations in reasonable, namely O(n3 ) for each of them,ii) they do not affect the sensitivity of most underlying problems, because condition numbers areusually invariant under unitary transformations,iii) they go along with bounded error propagation, or can be implemented in a numerically stablemanner,iv) they put the state-space model in a condensed form which simplifies the subsequent controlproblem.In practice, n is considerably larger than m and p and most of the zeros will therefore be The four main condensed forms encountered in the literature are:obtained in A.i) the state-Hessenberg form, where A is upper Hessenberg,69
iv) the observer-Hessenberg form, where the compound matrix A is upper trapezoidal.C
hBD
Ah=
Ch
00000
0000
000
00
(3.8)
sBD
As=
Cs
000000
(3.9)
cBD
Ac
Cc
70
(3.10)
oBD
Ao=
Co
(3.11)
The complexity of constructing the forms (i), (iii) and (iv) is n2 (5/3n + m + p) for computing B, C, D} and an additional n3 for computing the transformationthe new state space system {A,U itself. The form (ii) also involvesan iterative process (the eigenvalues of A are computed) and B, C, D} and an additional 5 kn3 for computingthis requires n2 25 kn + m + p for computing {A,2U as well. Here k is the average number of iteration steps for finding each eigenvalue up to machineaccuracy, and typically lies between 1 and 2.We note here that there are many variants of the above forms. First of all, to every upperform there is a corresponding lower form, which we did not show here. Then, the Schur formshown above implies the use of complex arithmetic. Under real (orthogonal) transformations onecan not triangularize a matrix as shown under ii) if it has complex conjugate eigenvalues. Insteadone can always obtain a quasi-triangular form with 1 1 or 2 2 diagonal block correspondingto the real and complex conjugate eigenvalues, respectively. Finally forms (i), (iii) and (iv) havevariants in which some of the pivot elements, (i.e., the elements directly above and to the right ofthe triangle of zeros) are zero as well (see later).The construction of these condensed forms is now illustrated for the controller Hessenberg formand for m = 1. Essentially, we have to find here an orthogonal transform such that
xx x ... x 0 x x ... x
UHb = . ;U H AU = . . ... ..... . . .. . 0
x x ... x
x x ...x1 x x ... 0
U1H AU1 = . . .U1H b = . ;.. .. .. .. 0x x ...
U 1 such that
xx
.. .. x
In fact U1 is just a Householder transformation H1 putting b in the required form (see Chapter 1).If one now redefines the matrices b and A as b1 and A1 and the bottom two blocks of U1H AU1 asb2 and A2 , then one sees that the additional transformation1HU2 =H2H71
applied to
U2H U1H b1
x10...0
xH2H b2
x ... xH2H A2 H2
x ... ... xxx1 x2 xx ... x 0
0H HH HU2 U1 b1 = . U2 U1 A 1 U1 U2 = .
. .. b3A3
..00
and so on, until the required controller Hessenberg form is obtained. All transformations are alsoapplied to the vector c which does not play a role in the above construction.For the derivation of the general forms (i), (iii) and (iv) essentially the same ideas apply. Forthe derivation of form (ii) one uses the construction of the Schur form explained in Chapter 2. Inthe following sections, we show how these condensed forms are now exploited for the derivation ofefficient algorithms.
3.3
(3.12)
with state dimension n, input dimension m and output dimension p, is minimal if and only if it iscontrollable and observable. The most used algebraic definition for these two conditions are:C1: rank B AB An1 B = n(3.13)
O1:
rank
CCA...CAn1
= n
rank [ B A I ] = n A I= n .rankC72
(3.14)
(3.15)(3.16)
Exercise 3.1Prove that conditions C1 and C2 are equivalent (or equivalently conditions O1 and O2).
(3.17)
(3.18)
in other words, eigenvalues can all be moved by feedback or feedforward operations. This lastcondition is the relevant one for design purposes. We now indicate that each of these conditionsis rather questionable from a numerical point of view. Since observability and controllability aredual to each other we focus on controllability.Example 3.1We take the following matrix pair:
1 20 2
..A=.
.20 1920 20
b=
200......0
(3.19)
When constructing the controllability matrix of this example we have to take up to power 19 ofthe matrix A. Let us look at the singular values of the matrix in C1, using MATLAB:A = diag([1:20]) + diag(ones (1,19),-1) * 20;b = [zeros(19,1);20];C1 = ctrb(A,b);svd(C1)which yieldsans =2.6110e+282.1677e+28...4.0545e+047.8271e+012.0000e+01which indicates a singular matrix for all practical purposes. Yet test C2 gives as rank text foreigenvalue 20 (the worst one):73
svd([a-20*eye(size(a)),b])ans =3.6313e+01...5.9214e+00which is far from being singular.
This shows that test C1 is not that reliable. But test C2 also suffers from difficulties for theabove matrix A. Let us perturb A in position (1, 20) with a small value = 10 12 then it is wellknown for this matrix [147, 148, 149] that the eigenvalues 1, 2, . . . , 20 change in their first or seconddigit. As a consequence of this, test C2 will not be computed in the true eigenvalues of A butin strongly perturbed ones. This is independent of the vector b and will be incurred by stableeigenvalue algorithms as well. If we now take a b vector which is such that a particular eigenvalue,say 1, is not controllable, i.e.,hirank A I | b < 20
then rank test C2 applied to the computed eigenvalue of A will give completely erroneous results. b is uncontrollable in eigenvalue = 1, then aThe same can be said about test C3. If A,feedback f will not be able to move the eigenvalue = 1 in A + bf . Yet since the eigenvalues of A are so sensitive it is very unlikely that A and A + bf will both have a very close eigenvalue(and A)to = 1.Table 3.1: .Eigenvalues i (A)-.32985j1.06242.92191j3.137163.00339j4.804145.40114j 6.178648.43769j 7.2471311.82747j 7.4746315.10917j 6.9072118.06886j 5.6631320.49720j 3.8195022.06287j 1.38948
Eigenvalues 1 (A + bf ).99999-8.95872j3.73260-5.11682j9.54329-.75203j14.1481675.77659j 15.5843611.42828j14.2869413.30227j 12.9019718.59961j 14.3473923.94877j 11.8067728.45618j 8.4590732.68478
K(b; A i I).002.004.007.012.018.026.032.040.052.064
The following table was obtained for tests C2 and C3 using b = [0, 1, 1, . . . , 1]T and A as in (3.19).Instead of perturbing an element of A we perform a random orthogonal state-space transformation b). The resulting eigenvalues of A + bf for a random f and the conditionQ on the system(A,hinumbers of b | A i I in the computed eigenvalues i of A are given in Table 3.1. The machine
74
hi the correct values i (A), test C2 gives b | A 1 I 108When using instead of i (A),which indicates that the trouble here lies indeed in the eigenvalue sensitivity.
3.4
Staircase form
We now propose a method that avoids several of the above drawbacks and is based on an orthogonalstate-space transformation.Theorem 3.1. There always exist an orthogonal state-space transformation U such that
0..X2 A2,2
..........(3.20)[U H BkU H AU ] = ...
.... .. Xk Ak,k Ak,k+1 0
00Ak+1,k+1where Ai,i , i = 1, . . . , k, are i i matrices. xi , i = 1, . . . , k, are i i1 matrices of full row rank i (with 0 = m).As a consequencem = 0 > i > > k > 0
Pk
i=1 i .
Proof: This form is a block version of the controller Hessenberg form, stopping as soon as a zeropivot is encountered, at step k + 1 in this case. The proof is thus constructive. At each stepi = 1, . . . , k a QR factorization is performed of the current Bi matrix yielding Xi of full row rank.If a zero rank matrix Bi is encountered (at step k + 1 here) then we obtain the form (3.20). If not,then the method terminates with n = k and the bottom matrix Ak+1,k+1 is void.A MATLAB code for the above decomposition is given below. It also contains a variant inwhich the rank carrying stairs Xi are themselves in the special form
0 0
.. ... ..Xi = ...(3.21)... i
One shows that in general this also requires an input transformation V that can be chosen orthogonal as well.function [a1,b1,k,u,v] = stair(a,b,u,v)%[A1,B1,K,U,V]=STAIR(A,B,U,V) performs the staircase reduction of%the pair (A,B). It updates the state-space transformation U and%input transformation V such that the transformed pair (A1,B1) has%the typical staircase form (here with 4 "stairs") :%75
%| X : * * * * * | } K(1)%|: X * * * * | } K(2)%(B1:A1):=(U*B*V:U*A*U) = |:X * * * | } K(3)%|:X * * | } K(4)%|:Z |%%where each "stair" X has full row rank K(i) and has a triangular%form (right adjusted). Matrices U and V must be given as input%parameters and may be initialized with the identity matrix.%In case V is not given, this transformation is not performed%and the "stairs" X have just full row rank. The square matrix%Z (if present) contains the uncontrollable modes of (A,B).%size(b);n=ans(1);m=ans(2);[q,r,e]=qr(b);b1=r*e;a1=q*a*q;u=u*q;k(1)=rank(r);k1=1;k2=k(1)+1;if (k2 <= n) , b1(k2:n,1:m)=zeros(n-k2+1,m); endfor i=2:n,bh=a1(k2:n,k1:k2-1);ah=a1(k2:n,k2:n);[q,r,e]=qr(bh);q=[eye(k2-1),zeros(k2-1,n-k2+1);zeros(n-k2+1,k2-1),q];a1=q*a1*q;a1(k2:n,k1:k2-1)=r*e;u=u*q;r=rank(r,eps);if (k2+r <= n) , a1(k2+r:n,k1:k2-1)=zeros(n-k2-r+1,k2-k1); endif r == 0 , break , endk(i)=r;k1=k2;k2=k2+r;if k2 > n , break, endendkmax=prod(size(k));nmax=sum(k);if nargin == 4 ,k3=nmax;k2=k3-k(kmax)+1;k1=k2;if kmax > 1 ,for i=kmax:-1:2,k1=k1-k(i-1);if k2 > k1+1,[q,r]=qr(pert(a1(k2:k3,k1:k2-1)));q=pert(q);a1(k1:k2-1,:)=q*a1(k1:k2-1,:);a1(:,k1:k2-1)=a1(:,k1:k2-1)*q;u(:,k1:k2-1)=u(:,k1:k2-1)*q;a1(k2:k3,k1:k2-1)=pert(r);endk3=k2-1;k2=k1;endif k3 > k2, b1(k2:k3,:)=q*b1(k2:k3,:); endend[q,r]=qr(pert(b1(k2:k3,:)));q=pert(q);v=v*q;b1=b1*q;b1(k2:k3,:)=pert(r);end
76
HistoryA nonorthogonal version of this result was first obtained by Tse et al. (1978) [129]. The orthogonalversion is due to Van Dooren (1979) [131, 132] and was redrived by several authors in subsequentyears (Boley, Eldin, Eising, Konstantinov et.al., Paige, Patel, Skelton et.al., Varga), each with aparticular application in mind.The staircase form is now shown to be relevant for the determination of the controllability of apair (A, B).Theorem 3.2. The rank of the controllability submatrix.C (j) (A, B) = [B, AB, , Aj1 B]is j =
Pj
i=1 i
(3.22)
Proof. A state space transformation U applied to the system (3.12) results in a left transformationof the matrix C (j) (A, B), since(j)
CU (U H AU, U H B) = [U H B, U H AU U H B, . . . , (U H AU )j1 U H B]= U H [B, AB, . . . , Aj1 B]= U H C (j) (A, B).
(3.23)
Since an invertible transformation does not change the rank of a matrix one can as well check the(j)rank of CU (U H AU, U H B) which is of the form
CU
. . . . }1
X1,1
...... .....
X2,1... = 0 . ..
.. .. Xk,1 . . . }k0...00 ... ... 0
(3.24)
[ bk kAk ] = 0
.. .0
... .....2 . . . ... .. ...... . . 0 k... ... ...
Ak+1,k+1
C(A, b) = U CU (Ak , bk )
.= U .. . . .
0 ...0 ...
... ...... .... ..0 ... 0 0
...
... ... 0
b) In the multi-put case the form (3.24) is a block version of a QR factorization. It is importantto notice here that the rank is found form submatrices of the matrices A and B and that nopowers of A have to be computed explicitly. Also no eigenvalues of A are involved here. Sothis approach avoids the pitfalls of all three methods explained in Section 3.3.c) The controllability indices {ci , i = 1, . . . , m} defined for multi-input systems can be retrievedfrom the rank increases {j , j = 1, . . . , k} (see [131, 132, 141]) one proves that they in factform a dual partition of each other (see [65]).Example 3.2Take again the matrices (3.19) of Example 3.4. We see that this pair is already in staircase formwith 1 = 2 = . . . 20 = 1 and 20 = 20. All stairs are 20 and clearly nonsingular. So the systemis controllable.By duality all the above comments about controllability in fact also apply to that of observabilityby simply interchanging A with AT and B with C T . The staircase form for testing observabilitythough, is slightly different since again one prefers the form to be upper triangular. This is givenin the following theorem.Theorem 3.3. There always exists an orthogonal state-space transformation U such that
U H AUCU
where Ai.i i = 1, . . . , k are i i matrix Yi i = 1, . . . , k are i1 i matrices of full column i (with 0 = p).As a consequencep = 0 > 1 > > k > 0and Ak+1,k+1 is a square matrix of dimension (n k ) (n k ) with k =Proof. Dual to that of Theorem 3.1.
Distance to controllabilitySo it appears that the staircase form is a reliable direct method to test controllability of the multiinput system. But the form can still be sensitive to perturbations and may therefore fail in certainpathological cases [131, 132, 141]. The most reliable method for checking controllability is to convertthe rank test into a distance problem. Let us define Sc to be the set of uncontrollable (A, B) pairs:Sc = {(A, B) | rankC(A, B) < n} .Then the following distance function = min {k[A | B]k | (A + A, B + B) Sc }gives the distance of the pair (A, B) to the set of uncontrollable pairs. By definition this is a robustmeasure of controllability since a small perturbation in (A, B) give a small perturbation in (provethis!). This definition was introduced by Eising [29] was discerns between the real distance r andcomplex distance c by allowing only real or complex perturbations [29].Exercise 3.2Prove that both r and c are robust measures and that c 6 r .Use the staircase form to derive simple upper bounds for r and c .
To compute r and c one has to solve a minimization problem for which various algorithmsexist [12, 30]. Below we give a MATLAB code of the method of Boley which is based on eigenvaluecomputations of an embedded square system. We refer to [12] for more details on the method.function [upper2,upper1,lower0,location,radius]=dist(F,G);%% function [upper2,upper1,lower0,location,radius]=dist(F,G);% find distance from (F,G) to nearest uncontrollable pair% according to method of Boley SIMAX Oct 1990.%%form matrices used in paper.A=[F;G];[nrows,ncols]=size(A);E=eye(nrows);B=E(:,1:ncols);D=E(:,ncols+1:nrows);79
3.5
(3.25)
one can also associate certain spaces with the input to state map and with the state to outputmaps. One defines the following geometrical concepts to these respective mappings:{uk } = {xk } : controllability, reachability
u0y0. .
Uk = ... ;Yk = ... .(3.26)uk1yk1As shown earlier, recursive substitution of (3.25) yieldsx k = A k x 0 + B k UkY k = C k x 0 + D k Uk
(3.27)
A k BkCk Dk
AkCCA...
Ak1 BDCB...
AB BD
CAk1 CAk2 B
(3.28)
The following theorems now express directly the above spaces in forms of the matrices in (3.27).Theorem 3.4. The subspaces Rk (A, B) and Ok (A, C) are given byRk (A, B) = ImBk
Ok (A, C) = KerCk
(3.29)(3.30)
Clearly the states xk that can be reached from arbitrary Uk is Rk (A, B) = ImBk . For Ok (A, C)there are no inputs (i.e., Uk = 0) and hence
C CA
Yk = . x0 ..
. CAk1
Thus the set Ok (A, C) of initial states x0 that produce a zero output Yk is clearly KerCk .
(3.31)
(3.32)
xk = A k x0 ; Yk = . x0 ..
For zero output Yk we need x0 Ok (A, C) and the states xk corresponding to this are clearly givenby (3.32).
From the above theorem it follow that the spaces Rk (A, B) and Ok (A, C) are in fact constructedby the staircase algorithm applied to (A, B) and (AT , C T ), respectively. From the definition itfollows easily that the spaces Rk (A, B) and Ck (A, B) grow with k, whereas the dual spaces Ok (A, C)and Sk (A, C) decrease with k. From the staircase algorithm it also follows that these spacesconverge to a fixed set at an index k smaller or equal to n. Orthogonal bases for these spaces arein fact constructed by the staircase algorithm as well.Theorem 3.6. Let i be the rank increases of the staircase algorithm applied to the pair (A, B)and define i = 0 for i > k, the index of the last stair. ThenI jRj (A, B) = U Im(3.33)0Pjwith j =i=1 i and U the n n transformation constructed by the staircase algorithm ofTheorem 3.1.Proof. This follows from (3.23) indicating thatH
U Rj (A, B) = Im82
I j0
Since these spaces converge in less than n steps to the steady state results R(A, B) andO(A, C) we thus computed orthogonal basis for these respective spaces in 0(n 2 (5/3n + m + p)) operations at most. This follows from the fact that the staircase forms never requires more operationsthan the corresponding condensed forms.Remark.a) The concept of reachability has the same meaning for a continuous time system as that ofcontrollability. For a discrete time system, both concepts are different, though. It would bemore appropriate to always use reachability instead of controllability since usually, this iswhat one refers to.b) It follows from theorems 3.4 and 3.5 that if A is invertible, then,dimCk (A, B) = dimRk (A, B)dimSk (A, C) = dimOk (A, C).When A is not invertible, the concepts of reachability and constructability can indeed be verydifferent as shown by the following simple example.Example 3.3LetA =
1 10 0
,
1The matrix [B AB] =has image Imand this is the only vector that can be0
( + ) as is seen from 1 1
1x1 =+( ) = 0.0 0
01 10 0
B=
83
So C1 (A1 B) = C 2 . Although the dimensions of C1 (A, B) and R1 (A, B) differ, one easily checks alsothatAC1 (A, B) = R1 (A, B).The above results now lead to the construction of minimal B)
[U B | U AU ] = [B | A] =0
where the subsystem (Ar , Br ) is reachable. The number of rows/columns of Ar is k and the firstk columns of U span R(A, B). Similarly, the staircase algorithm applied to (A, C) yields a new C) of the formsystem (A,
" # A H
AU AU= 0 A0 =(3.36)CUC0 C0where the subsystem (A0 , C0 ) is observable. The number of rows/columns of Ao is k and the firstk columns of U span O(A, C).Combining intersections and completions of the above decompositions yields a coordinate system B, C) where(A,
0 A22 A23 B2 A B
= 0
0 A33 0 C D0C 2 C3 D
and where the subsystem {A22 , B2 , C2 , D} is both observable and reachable (i.e., minimal). More B, C, D} and {A22 , B2 , C2 , D} are equal. This is obtained byover the transfer functions of {A,the following construction. Start with a decomposition (3.35) displaying the reachable part of thesystem (apply the transformation also to C):
HAr BrUr AUr UrH B= 0 Ar 0 .CUrDCr Cr DThen take the subsystem (Ar , Cr ) and perform the decomposition (3.36) (apply again the transformation to B as well):
HAro BroUo A r Uo Uo B r= 0 Aro Bro C r UoD0 Cro Dthen define
.= Ur
84
UoIr
.. H.=A = U H AU ; BU B; C = CUto obtain"
A BC D
Aro Bro 0 Aro Bro .= 00 Ar0 0 Cro Cr D
zI AroBro
1 B + D = [ 0 Cro Cr ] Bro + D =0zI Aro
C(zI A)000zI Ar[ 0 Cro
(zI Aro )1Bro
Bro + D =0zI Aro 1
Cr ] 1000(zI Ar )
where A11 contains unobservable modes, A33 contains unreachable modes and the subsystem(A22 , B2 , C2 ) is both reachable and observable. Moreover the latter subsystem has the same transferfunction as the original system (A, B, C).
3.6
Poles and zeros are rather classical concepts when single input single output systems are concerned.They are then typically defined in terms of the transfer function of the system:y() = h() u().
(3.37)
(3.38)
and the poles are thus the zeros of the polynomial d(), while the zeros are the zeros of thepolynomial u(). A natural way to extend this to multi-input multi-output systems with transferfunctiony() = H()u()85
(3.39)
is to say that the poles of H() are those values of in the complex phase where (some entry of)H() becomes infinite, whereas the zeros of H() are those values of in the complex plane wherethe rank of H() drops below its normal value. It is easy to see that this reduces to the definitionfor the scalar case.But this definition fails in identifying coalescent poles and zeros and also fails in giving moredetailed information about multiplicities of poles and zeros. A precise definition is based on adecomposition that essentially reduces the matrix case to the scalar case.Theorem 3.9. (McMillan Form) Every rational transfer matrix H() has a decomposition intothe product of matrices:Hpm () = Mpp ()Dpm ()Nmm ()
(3.40)
where M () and N () are polynomial matrices with constant determinant (i.e., unimodular) and e ()
D() =
f1 ()
lr ()fr ()
0pr,mr
(3.41)
(3.42)
Notice that in this decomposition M () and N () are invertible and finite for any in thecomplex plane. So if H() has poles and zeros they must be poles and zero of the quasidiagonalmatrix D(). This thus leads to the following definitions.Definition 3.1. The zeros of H() are the zeros of the polynomials ei (), i = 1, . . . , r. Themultiplicities of each zero 0 are those of 0 in each polynomial ei ().Definition 3.2. The poles of H() are the zeros of the polynomials fi (), i = 1, . . . , r. Themultiplicities of each pole 0 are those of 0 in each polynomial fi ().This definition is very elegant and close to that of the scalar case, but unfortunately it relies onthe McMillan form which requires unstable transformations on the coefficients of rational matrices(see [136, 137]). The following theorem now reduces everything to that of computing eigenvaluesand their multiplicities. The new definition are based on minimal realizations and on correspondingeigenvalue and generalized eigenvalue problems.Theorem 3.10. Let {A, B, C, D} be a minimal realization of the transfer function H(), i.e.,H() = C(I A)1 B + D
(3.43)
where (A, B) is controllable (reachable) and (A, C) observable. Then the poles of H() are theeigenvalues of A and their mulplicities are the lengths of the corresponding Jordan chains; and thezeros of H() are the generalized eigenvalues ofI A B(3.44)S() =CD86
and their multiplicities are the lengths of the corresponding Jordan chains.Proof. See [114] and [143] for more details.
It is interesting to notice that this definition has a nice interpretation in terms of eigenfrequenciesundriven by the input and eigenfrequencies blocked at the output. The most natural way tod.describe this is in the continuous time case. So consider the system (3.43) where = dtThen the poles of the system are the frequencies of the eigensolutions undriven by u(t), butappearing in y(t). So since u(t) = 0 we havex(t)
= Ax(t);
x(0) = x0 .
y(t) = Cx0 e0 t .
0y(t)
h
x0u0
ddt I
A BCD
x(t)u(t)
x0 0 teu0
0 I A BCD
x0= 0.u0
This interpretation only agrees with the definitions given earlier when the transfer function H()is square and invertible. In that case we also have that S() is square and invertible since
I01C(I A)I
S() =
BIn A0H()
(3.45)
So rank drops in S() and H() must occur at the same points 0 , as long as they are not eigenvaluesof A (or poles of H()). In this case we have thatdet .S() 60In 0and since the coefficient of is, this is a polynomial of degree at most n. If the constant0 0matrix D is invertible, then one sees that0IIn A + BD 1 C BS()=(3.46)D1 C I0D87
and det .S() = det .D, det .(I (A BD 1 C)) which implies that the zeros of det .S() are theeigenvalues of the matrixA = A BD 1 C.
(3.47)
A better way to compute the zeros of S(), through, is to use a unitary transformation on S(),rather than the invertible transformation (3.46).One can always constructa transformationW which is orthogonal and reduces the columns ofhi
S()W =
I A BCD
W =
A xE
0D
(3.48)
is square invertible since S() is. One shows (see [141, 133]) that in factwhere D = (E A)E 1(I A)
(3.49)
A). Theseand that the eigenvalues of A are in fact the generalized eigenvalues of the pencil (Eare then found via the QZ algorithm:
e11
Q (E A)Z =
..... .......
a11
..
enn
ann
(3.50)
A) are obviously the ratios i = aii /eii . Notice that if det .S() 6 0and the solutions of det .(Ethen it can not occur that both aii and eii are simultaneously zero, so the ratio i is well defined.But i can be infinite if eii = 0, and it is known [32] that this occurs when the matrix D is singular.In such case there will be less than n finite zeros.If we want to extend the above results to arbitrary systems {A, B, C, D} then the above approachdoes not apply anymore. Yet Theorem 3.10 indicates that the generalized eigenvalues of S() arethe finite zeros of the system. The following staircase like decomposition now reduces the generalproblem to one we can solve again via QZ techniques.Theorem 3.11. Any system matrix
I A BCD88
V S()W =
X10...
Xk
I AfCf
BfDf
Y`
...0
... .
Y1
(3.51)
where the Xi are full row rank matrices, the Yi are full column rank matrices, and Df is invertible.Moreover the finite zeros of S() are those of
Sf () =
-3.933.68E22.74E1-6.47E-23.85E32.24E400-2.20
-3.15E-3-3.057.87E-2-5.20E-51.73E11.80E100-1.77E-3
03.03-5.96E-20-1.28E102.34E-300
000-2.55E-1-1.26E4- 3.56E10-1.27-8.44
000-3.35E-6-2.91-1.04E-40-1.00E-3-1.11E-4
89
4.03E-5-3.77E-3-2.81E-43.60E-7-1.05E-1-4.14E-12.22E-47.86E-51.38 E-5
0006.33E-51.27E19.00E1-2.03E-1 001.49E-3
0001.94E-44.31E15.69E10-7.17E-26.02E-3
0000000-1.00E-10
00001.56005.13E 68.281.5501.782.33002.45E 202.94E 5
, C = 0 0 0 0 0 1 0 0 0 , D = 0.
0 0 0 0 0 0 0 0 1
The computed zeros and the relative backward residuals 11 (s(i ))/1 (S(i )) wereZeros-26.39513728882773-2.957771985292096 .3352657201870191.74860641907556.09403261020202233- .009546070612163396
111
<<<<<
Notice that there are only 6 finite zeros. Also, the normal rank of the transfer function is 2 andthat of S() is 11. So, in order to check the reliability of the computed eigenvalues i we check ifthe 11-th singular value 11 (S(i ) is indeed small with respect to the 1st singular value 1 (S(i ).For each of the computed eigenvalues, this was the caseRemarks.1. Because of the use of orthogonal transformations only, we can prove that the above algorithmfor computing zeros is backward stable. Moreover, its complexity is O(n(n + m)(n + p)) flops(see [32]).2. The method can be applied to systems {A, B, C, D} where m 6= p, i.e., with different numberof inputs and outputs. In fact, when m = 0 it actually performs the staircase decomposition(3.27) and finds the eigenvalues of Ao in (3.40), i.e., the unobservable modes of the system.When p = 0 it finds the staircase decomposition (3.20) and finds the eigenvalues of Ar in(3.33), i.e., the unreachable modes of the system. Notice that in both cases the system doesnot need to be minimal.
90
Chapter 4
A typical control action used to influence the behaviour of the system, is linear state feedback.It consists of feeding back a linear function F x() of the state to the input u() :
A -vk 6u()
- B
-? - 1
x()
- C -6 y()
- D
F If we redefine the input u() as F x() + u(), then the system becomes:x() = (A + BF )x() + Bu().y()= (C + DF )x() + Du()
(4.1)
This control action is typically used to modify the dynamics of the system, and more particularly,the eigenvalues of the matrix A + BF . The problem to be solved in this context is :Given (A, B), what eigenvalues of A + BF can be obtained by an appropriate choice of F ?Moreover, what Jordan structure of the multiple eigenvalues can be obtained?First we notice that a similarity transformation T does not affect the solution of this problem..Indeed, the feedback Ft = F T applied to the transformed pair.(At , Bt ) = (T 1 AT, T 1 B)(4.2)yields the closed loop matrixAt + Bt Ft = T 1 (A + BF )T91
(4.3)
which has the same eigenvalues and Jordan structure as A + BF since there is only a similaritytransformation between both. We can therefore choose T so that the new coordinate systemsimplifies the construction of Ft (and F ) and also makes explicit its possible solution(s). Let usstart to put (A, B) in the formAr Br[At | Bt ] =(4.4)0 Ar 0where Ar contains the unreachable modes and (Ar , Br ) is reachable (T can be chosen unitary).Then one easily sees that Ft = [Fr | Fr ] can only affect the spectrum of Ar :A r + B r Fr .(4.5)[At + Bt Ft ] =0ArWhile the eigenvalues of Ar are unchanged, the corresponding eigenvectors can be modified [70]. Weshow below that by construction that the spectrum of Ar + Br Fr can always be chosen arbitrarily,but we will indicate constraints on the choice of Jordan structure. We first consider the single inputcase, where (At , bt ) is in controller canonical form:
an1 an2 a1 a0b0
0 10
.. ....
..At = (4.6) , bt = .
.......
.. 100
.det(zIn At ) = z n + an1 z n1 + + a1 z + a0 = a(z).
(4.7)
1[an1 fn1 , . . . , a0 f0 ]b0
(4.8)
.det(zIn (At + bt ft )) = z n + fn1 z n1 + + f0 = f (z).
(4.9)
The above discussion also suggests a simple method for constructing f . The method is knownas Ackermans formula and is also implemented in MATLAB in the function acker(A,b,l). Thealgorithm goes as follows. First construct the controllability matrixT1 = [b Ab An1 b]
(4.10)
a0 1
.. 10 .. 11
(A1 , b1 ) = T1 AT1 | T1 b = .... ..
... 1 an1 0
1 an1 . . . a1
T2 =
. an1 1
(4.11)
(4.12)
to
an1 . . . . . . a0 1 10
1.. .1.
.. (A2 , b2 ) = T2 A1 T2 | T2 b1 = .
......
(4.13)
Now compute f2 in this coordinate system and transform back to f = f2 T21 T11 .This is a typical example of the use of canonical forms and badly conditioned transformationsin order to construct the solution of a problem in a trivial coordinate system. It is well knownthat the transformation T1 can be very badly conditioned for random system of moderate size.Although the problem is trivial in this coordinate system, the transformation has turned a possiblyinsensitive problem into a very sensitive one. So we recommend instead to use the staircase form
. . . . . . . . . 1
.. 2 . . ..0
.... .(4.14)[At , bt ] = 0 . . . . . ...
.. . . . . . ... . .... ... 0 . . . 0 n 0A very simple method to solve the pole placement problem is to compute the eigenvectors x i ofAt + bt ft = XX 193
(4.15)
2 i . . .
........
.n i|{zn
xi = Ai xi = 0.
(4.16)
(4.17)
Since Ai is a rank n 1 matrix, this defines xi up to a scale factor, which we choose such thatkxi k = 1. This normalized vector is easily computed from the RQ decomposition of Ai :
0 0
HAi = ... . . . . . . ... QH(4.18)i = ..Ri Q i0 0 0
The first column of Qi is indeed in the null space of Ai and has norm 1. Decomposition (4.18) onlyrequires n 1 Givens rotations and 2n2 flops, so computing all eigenvectors requires 2n3 flops. Thefeedback vector f is then solved from the top row ofAt XX 1 = bt ft
(4.19)
1T).ft = 11 e1 (At XX
(4.20)
yielding
0.5013 0.6173i 0.3504 0.3844i
L = 1.1269 0.1590i . 0.0905 0.0763i 0.1749 0.0403iFirst use Ackermans formula (Control Toolbox):
F 1 = acker(A, B, L).The gap between prescribed and computed eigenvalues is:L1 = eig(A + B F 1); norm(sort(L1) sort(L),0 inf 0 )ans = 0.004594
which shows computed eigenvalues of poor quality! Then use the method computing the eigenvectormatrix X of the matrix (A + BF ) to be constructed. This is implemented in the MATLAB filerplace.m :[F 2, X] = rplace(A, B, L); F 2The ordered difference is this time:L2 = eig(A + B F 2); norm(sort(L2) sort(L),0 inf 0 )ans = 2.51021010
which shows much better results! This example is rather difficult for two reasons. The eigenvaluesof A are stiff as seen from the following ratio :abs(eig(A)); stif f = max(ans)/min(ans)stif f = 17.5797ctr = cond(ctrb(A, B)), cx = cond(X)ctr = 7.1746109cx = 1.8978106 .The controllability matrix is then poorly conditioned and Ackermans method usually fails forn > 10. The sensitivity of the eigenvalues after placement is also large:
0.0011 0.0011
0.0026
6 0.0196 sens = 1.0 10
0.0196 0.3441
0.3441
1.1930 1.1930
which explains the loss of at least 6 digits using any method as is also observed in the eigenvectormethod.The above eigenvector method uses the orthogonal decomposition (4.14) but then computes theresulting feedback using the Jordan form (4.15). This of course is from a numerical point of viewnot that appealing when the decomposition is sensitive. Moreover, it certainly fails when requiringmultiple eigenvalues since these automatically belong to a single Jordan block as pointed out byTheorem 4.1. The following modification, due to [91, 92] avoids these drawbacks.Algorithm 4.1. Put (A, b) in the form (4.14). Construct A1 as in (4.17) and then decompose A1as in (4.18). Since A bf 1 I is singular, so must be
a1 0
(A bf 1 I)Q1 = .(4.21)
..Ri 095
where a1 depends linearly on f . Choose f1 such that a1 = 0. Using the first column x1 of Q, thisis:eT1 (A 1 I)x1 eT1 bf x1 = 0or taking f = 1 x1 we have 1 = eT1 (A 1 I)x1 /eT1 b. One then shows
1 0
....H.Q1 (A bf )Q1 = . 0 3 .. . . . . . ... .... .0 0 n
QHb=
(4.22)that
(4.23)
(4.24)
with i =6 0 for i = 2, . . . , n. So the bottom (n 1) (n 1) subsystem is again in staircase formand the next eigenvalue can be assigned using the same procedure.Remarks.1. The same algorithm was essentially derived independently by several authors in differentcontexts [91, 92], [93], [73], [131, 132]. Each of these algorithms has a O(n 3 ) complexitybut stability results are not as strong as one would like except when the eigenvalues i arebounded by the norm of the original matrix A [73] [131, 132].2. The first proposed method [91, 92] does not require the explicit subtraction of i in (4.21)but finds Qi from implicit shift techniques. It also has an elegant implementation of theseideas in case of complex conjugate roots, by avoiding complex arithmetic altogether.
4.2
Multi-input feedback
Very similar ideas to the above ones apply for the multi input case. The following theorem holds.Theorem 4.2. Let (A, B) be a reachable multi input pair, then a feedback matrix F exists to.assign any desired spectrum to AF = A + BF . If all matrices are real then must be symmetric A multiple eigenvalue 0 of AF corresponds to at most 1with respect to the real axis = .Jordan blocks andrank(AF 0 I)i > n where i are the rank increases of the staircase form.96
iXj=1
j = n i
We will see that this theorem has important implications in deadbeat control. Yet in generalone does not want multiple eigenvalues since they have infinite sensitivity if associated with a sameJordan block. A method that tries to use the degrees of freedom in this spirit, is due to Kautsky,Nichols and Van Dooren [68]. In multi-input feedback we can minimize the sensitivity ( i ) ofi (AF ) versus perturbations in A, B, F . Let xi and yiT be right and left eigenvectors correspondingto the eigenvalue i then the sensitivity of i equals:(i ) =
k x i k2 k yi k2.|yiT xi |
(4.25)
Bc
Ac=
0 X 0 0 X 0 0 0 X 0 0 0 0 X0 0 0 0 00 0 0 0 00 0 0 0 0
X00
X0
BA11=,
0 A2
(4.26)
where B1 is of full row rank 1 and A2 has n 1 rows. Then for each eigenvector xi of A + BFwe have(A + BF )xi = i xiand from the bottom n 1 equations, again :.xi Si = Ker(A2 i [ 0 I ]).
(4.27)
Computing an orthogonal basis for each Si is cheap when the pair is in staircase form and is donevia an RQ decomposition as in (4.18). This requires O(mn2 ) for each Si and O(mn3 ) for all ofthem. The subsequent optimization for selecting the best xi in these spaces is of the same order ofcomplexity, and the feedback matrix F is then found in a similar manner to (4.20)F
= B + (A XX 1 ).
(4.28)
The following example illustrates the different methods in [68] with earlier optimization methods.Method1 is also implemented in MATLAB in the routine place.m of the Control Toolbox.97
Example 4.2.Distillation column (Klein and Moore 1982)n = 5,
0.1094 0.06280001.3062.132 0.98070001.595 3.149 1.547000.03552.632 4.2571.85500.0022700.1636 0.1625
m=2
Method 11.8%0.1%0.2%2.4%
Method 2/31.5%0.2%5.0%1.9%
Method KM2.5%1.2%0.3%3.0%
Method GR73%85%40%130%
(4.29)
where we require (A + BF ) = {0, 0, . . . , 0}. We have the following theorem in this context.Theorem 4.3. Let ` be the size of the largest Jordan block of A + BF , then (A + BF ) ` = 0and (A + BF )`+1 6= 0. This is also called the index of nilpotency [57] of A + BF .Proof.
J1
J` 1
A + BF = T T..
.Jk98
0 1
0 ..
Ji = ..
. 10
`i
then
J1`
(A + BF )` = T
.Jk
= T
.Jk`
1 T
1T .
u0 .. (4.30)xk = AkF x0 + [Ak1. .F B . . . AF B B] uk1
If now A`F = 0 then only the last ` inputs uki for i = 1, . . . ` affect the state the xk . All inputsprevious to that do not enter into the equation (4.30) because they are beaten to death by thetransition matrix AF raised to a power higher than `. This property is applied in observer designas will be shown later on. Theorem 4.2 now says thatrank(AF 0 I)i > n
(4.31)
for any eigenvalue 0 of AF . So if we want to have AiF = 0 at the eigenvalue 0 = 0 then clearlywe must haven
iX
= 0
(4.32)
j=1
which is only possible for i = k, the last index for which k 6= 0. This value k happens to be thelargest controllability index of the pair (A, B) (see [65]). The following example illustrates this.Example 4.3Consider the pair
0 1 0
[AkB] =0 1 10 0 299
0 01 0 0 1
which is in staircase from with indices 1 = 2, 2 = 1. A has eigenvalues {0, 1, 2} and we perscribeall i = 0. Two feedbacks performing this are:
0 10 1 00 1 ,A + BF1 = F1 =0 0 20
0 10 1 10 0 .F2 =,A + BF2 = 0 0 20
Clearly (A + BF1 ) has index of nilpotency 3 while (A + BF2 ) has index of nilpotency 2 only. Anindex of nilpotency of 1 is impossible according to (4.31). This would in fact imply (A + BF ) = 0which is easily seen to be impossible for this example.We thus have proven meanwhile the following Corollary to Theorem 4.2.Corollary 4.1. The smallest index of nilpotency ` of A + BF for a reachable (A, B) pair withstaircase sizes i , i = 1, . . . , k is k.An algorithm for constructing a feedback F that achieves this is described in [134] and is basedon a preliminary reduction to staircase form. The algorithm is analogous in spirit to that of Miminisand Paige [91, 92]. In fact, it constructs the minimum norm feedback F that achieves this deadbeatcontrol. The numerical stability (weak form) of this algorithm is also proven in [134].What can be said about the sensitivity of the deadbeat control problem? According to theresults of eigenvalue sensitivity of Jordan block it should be infinite. Indeed, example 1.3 showedthat the sensitivity of an eigenvalue 0 of a Jordan block of size ` is
(, J` ) = lim = .0` 1/`For the smallest perturbation , the multiple eigenvalue explodes in a cluster of ` eigenvalues atthe complex `-th roots 1/` of .But for the deadbeat control, the key issue is not the location of the eigenvalues, but the factthat (A + BF )` = 0. An indication that this property is not as sensitive is that the eigenvalues of(A + BF )` are the `-th powers of those of A + BF :i [(A + BF )` ] = `i [A + BF ] which thus are again of the order of . From this, one proves then thatk(A + B F )` k0
lim
= c
uk` .. . `1
xk = [AF B AF B B] .. + rk , . uk1
krk k
++-
0.25791119622289i0.25791119622289i0.41729341088988i0.41729341088988i
naf5 =3.808289238413386e-15101
Although the absolute values of the eigenvalues are of the order of 5 it is clear that kA + BF k isof the order of .A MATLAB code for the method constructing this minumum norm deadbeat control F fromthe staircase form is given below.function [f,u] = deadbeat(a1,b1,kr,u)%% DEADBEAT(A,B,K,U)% Computes the feedback matrix F and the state-space transformation% U such that A+B*(F*U) is nilpotent with minimal index size(K).%% PS : Perform previous to this one [U,V,K,AB]=stair(A0,B0,U0,V0)%k=prod(size(kr));size(b1);f=zeros(ans(2),ans(1));dim=ans(1);k1=1;for i=1:k,dimk=dim-k1+1;k2=k1+kr(i)-1;[ui,ar]=qr(a1(dim:-1:k1,dim:-1:k1));ui=ui(dimk:-1:1,dimk:-1:1);a1(:,k1:dim)=a1(:,k1:dim)*ui;ai=a1(k1:k2,k1:k2);bi=b1(k1:k2,:);g=-pinv(bi)*ai;a1(:,k1:k2)=a1(:,k1:k2)+b1*g;a1(k1:dim,:)=ui*a1(k1:dim,:);b1(k1:dim,:)=ui*b1(k1:dim,:);u(:,k1:dim)=u(:,k1:dim)*ui;f(:,k1:k2)=g;k1=k2+1;endRemarks.1. The sensitivity of the pole placement problem depends on what is called the solution of theproblem. Is it F the feedback matrix, or A + BF , the closed loop matrix, or (A + BF )the closed loop spectrum. In either of the three cases one can analyze the sensitivity of thefunction that calculates the solution by looking at the Frechet derivative. Bounds for thishave been derived in [87], [88], [74], [109].2. Since the pole placement problem is so sensitive, it makes more sense to solve a robust versionof it, which is to construct F such that the eigenvalues of A + BF lie in a prescribed set(say eigenvalues with a given decay rate). Techniques that fall in this class are H controland stability radius minimization [19], [100]. These methods typically guarantee a certainrobustness margin of the problem.
4.3
Observers
In many instances the state is not available for feedback and one has to estimate it first. This isdone via an observer, which uses the input and output of the plant to try to reconstruct its state.The observer itself is also a dynamical system. The corresponding equations are102
Plant
A
u(.)
? - 1-
x(.)
- C -6
y(.)
Observer
Ko- Bo
z(.) T x(.)
Ao
(4.33)
.One would like asymptotic convergence of z() to T x() so that x() = T 1 z() can be used asestimate of x() in some feedback design. The following theorem is due to Luenberger [80] andgives an algebraic solution to the problem.Theorem 4.4. Let T satisfy the equationT A Ao T Ko C = 0.
(4.34)
Bo = T B K o D
(4.35)
(4.36)
Then putting
we have
If (A, C) is observable an invertible T always exists for any choice of spectrum for A o and convergence is obtained when choosing Ao stable.Proof. Multiply the top equation in (4.33) with T and subtract it from the bottom equation, theneliminate y() using the middle equation to get[z() T x()] = Ao z() [T A Ko C]x() [T B Ko D Bo ]u().103
(4.37)
Now use (4.34), (4.35) to simplify this and obtain (4.36). If (A, C) is observable then one canalways choose T = I and solveAo = A K o C
(4.38)
via pole placement. Since this is the transpose of a standard feedback problem A To = AT C T KoTwe can always stabilize Ao via appropriate choice of Ko .The above proof already suggests how to solve these equations. Notice that (4.34) is a nonlinearequation in the unknowns T , Ao and Ko . Also there are less equations than unknowns so we canchoose some variables first. Two standard approaches are1. choose T = I and solve Ao = A Ko C via pole placement2. choose Ao stable and Ko arbitrary. Then solve for T from (4.34). Solvability of this equationis discussed in the next section.Once (4.34) is solved we just assign Bo as in (4.35).The observer problem depends on the exact solution of the algebraic equations (4.34)-(4.35).But since there are always residual errors (due to round off, or due to inaccuracies in the data A, B,C, D), the observer equation (4.36) will not be satisfied and z() does not converge asymptoticallyto T x().Instead, we have[z() T x()] = Ao [z() T x()] + Ex() + F u()
(4.39)
where kEk and kF k are small. This is essentially a stable difference/differential equation drivenwith a small input and its response will not go asymptotically to zero, but rather quickly convergeto a residual signal of norm comparable to the residual input Ex() + F u().In the discrete time case, one is tempted to choose Ao nilpotent, since then exact convergenceis obtained after a finite number of steps. In analogy to the results for pole placement, we have thefollowing result.Corollary 4.2. Let {Ao , Bo , Ko } be an observer of the observable system {A, B, C, D}. Thenthere exists a solution Ao with degree of nilpotency `, where ` is the largest observability index ofthe pair (A, C). No observer can reconstruct xk exactly after less time instants than `.The following example illustrates this.Example 4.5.Let the system {A, B, C, D} be given by:
01000
01110
00201
10000
0 0 00 0T = I 3 , A o = 1 0 0 , K o = 1 0 , Bo = B0 0 01 2104
Ao is nilpotent with degree of nilpotency 2, i.e. A2o = 0. We should have convergence after 2 steps,independently of the starting vector z0 . Start the observer with zero initial state z0 , and let theplant be governed by: 110
x0 = 1 ; u0 =; u1 =011Then at step k = 0 we have: 111
x2 = Ax1 + Bu1 = 4
8
2y1 = Cx1 + Du1 =3
4 z=Az+Bu+Ky=2o1o1o1
=+u(),
z()Ko C A oz()Bo + K o D(4.40)
C0+Du().y()=
z()
Apply u() = F x() + v() = F T 1 z() + v(): x()ABF T 1x()B=+v()z()Ko C Ao + (Bo + Ko D)F T 1z()Bo + K o Dx()1CDF Ty()=+Dv().z()Use now the observer identities to get an extended state transition matrix :#"ABF T 1.A =T A Ao T Ao + T BF T 1
BF T 1Ao
(4.41)
4.4
Certain matrix equations arise naturally in linear control and system theory. Among those frequently encountered in the analysis and design of continuous-time systems are the Lyapunov equationAX + XAT + Q = 0,
(4.43)
AX + XF + Q = 0.
(4.44)
(4.45)
AXF X + Q = 0.
(4.46)
It is important to notice that all these equations are linear in the elements x ij of the unknownmatrix X. So, using the vector notationvec(X) = [X(:, 1); X(:, 2); . . . ; X(:, m)]
(4.47)
for the n n matrix X we should be able to write any of the above equation in the formM vec(X) = vec(Q).
(4.48)
We show how to do this for the Sylvester equation (4.44) from which all others canNbe derived. Forthis we introduce the Kroneder product of twoY.N matrices X and Y , denoted as XIn MATLAB notation Kron (X, Y ) = XY represents the matrix[x11 Y, x12 Y, . . . ,x21 Y, x22 Y, . . . ,...xn1 Y,
x1m Y ;x2m Y ;
xn2 Y, . . . , xnm Y ].106
(4.49)
Using this notation we have an equivalent reformulation of the Sylvester equation (4.44) where weassume A and F to be n n and m m, respectively.Theorem 4.5. The Sylvester equation AX + XF + Q = 0 is equivalent to[(Im A) + (F T In )]vec(X) + vec(Q) = 0.NNThe eigenvalues of [(Im A) + (F TIn )] are the differences(i i )
(4.50)
i = 1, . . . , n; j = 1, . . . , m.
(4.51)
Proof. We only give a sketch of a proof here and refer to [46] for details. Clearly we havevec(AX) + vec(XF ) + vec(Q) = 0.Now
AA
(I A)vec(X) =
.A
X(:, 1)X(:, 2)...X(:, m)
f11 I . . . fm1 IX(:, 1)
(F T I)vec(X) = ... ..
f1m I . . . fmm IX(:, m)
AX(:, 1)AX(:, 2)...AX(:, m)
= vec(AX)
XF (:, 1)
..= = vec(XF ).
XF (:, m)
which yields the required result. For the eigenvalue identity, one proves essentially that in anappropriate coordinate system the matrix in (4.50) is upper triangular with the differences (4.51)on diagonal.It is important to notice that such a rewrite can be done for each of the equations, by justreplacing F by AT in (4.43) and by inverting AT and F in (4.45) and (4.46). We thus haveCorollary 4.3. The equations (4.43)-(4.46) are all linear equations in the elements of X andthey have a unique solution if and only if(A) (A) =
(A) (F ) =
(A) (A
(A) (F
)=
for
(4.46).
For the Lyapunov equation, when A is stable, the solutions of the above equations are also equalto the reachability and observability Grammians Gr (T ) and Go (T ), respectively, for T = + forthe system {A, B, C}:Z Z TTetA C T CetA dt(4.52)etA BB T etA dt;Go =Gr =0
Gr =
Ak BB T (AT )k ;
Go =
Xk=0
107
(AT )k C T CAk .
(4.53)
Since A is stable in these cases one clearly satisfies the conditions of Corollary 4.2 and the solutionsAGr + Gr AT + BB T = 0;T
AGr A Gr + BB = 0;
G o A + A T Go + C T C = 0T
A G 0A Go + C C = 0.
(4.54)(4.55)
Notice that for general A, one can determine the number of stable and unstable eigenvalues of A.We define first the inertia of a matrix as a triple of integers (s, m, u) indicating the numbers ofstable, marginal and unstable eigenvalues of that matrix. Notice that for continuous time systemsand discrete-time systems, this has a different meaning in terms of the eigenvalue locations.Theorem 4.6. Let (A, B) be reachable and (A, C) be observable thenIn (A) = In (Gr ) = In (Go ).Proof. See [58] or [38].
(4.56)
This shows the relevance of the Lyapunov equation in various types of stability tests. Anotherimportant application is that of balancing. Suppose we have a state space model {A, B, C} withGrammians Gr and Go , then a state space transformation {T 1 AT, T 1 B, CT } affects the Grammians as T 1 Gr T T and T T Go T , which is sometimes called a contradgradient transformation. Itis well known that such a transformation T can be chosen to make both matrices diagonal andequalT 1 Gr T T
= = T T Go T
(4.57)
which is exactly the balanced coordinate system. From (4.43) it follows thatT 1 Gr Go T
= 2
(4.58)
and hence the eigenvector matrix T that diagonalizes the product Gr Go is also the transformationthat balances the system {A, B, C}. This in fact only holds up to a diagonal scaling (scaling of theeigenvectors) and is accurate only when there are no repeated eigenvalues (in this case T is definedup to a diagonal scaling). A better way to choose T is to start from the Cholesky factorization ofGr and Go ;Go = LT2 L2
Gr = L1 LT1 ;
(4.59)
where L1 and L2 are both lower triangular. One then constructs the singular value decompositionof the upper triangular matrix LT1 LT2 :LT1 LT2
= U V T .
TT1/2 = = 1/2 U T L11 (L1 L1 )L1 U
T 1 Go T T
1T1/2 = .= 1/2 V T LT2 (L2 L2 )L2 V
108
(4.60)
An efficient algorithm to find the singular value decomposition of a product of two upper triangularmatrices is described in [52].For the Sylvester equations we have already seen an application in observer design, but thereit was possible to circumvent the equation by solving a pole placement problem instead (this is infact also a set of linear equations in an appropriate coordinate system). The following extension toreduced order observers does not allow to reduce the problem directly to a pole placement problemand here we have indeed to solve a Sylvester equation where T is nonsquare.Theorem 4.7. Letx = Ax + Bu(4.61)y = Cx + Dube a plant with unknown state. Then the reduced order observer of state dimension n mz = Ao z + Bo u + Ko y
(4.62)
(z T x) = Ao (z T x)
(4.63)
(4.64)
providedT A A o T Ko C = 0.T B Bo K o D = 0
If (A, C) is observable then (4.64) always has a solution where Ao is stable and
T C
invertible.
In order to solve the above equations one actually does not use the system of linear equationsbecause that involves m n equations in m n unknowns and would require typically O(m 3 n3 )operations. Instead one performs unitary transformations U and V on the matrices A and F :Au = U H AU ;
Fv = V H F V
(4.65)
(4.66)
resulting in
whereXuv = U H XV ;
Quv = U H QV.
(4.67)
Notice that because unitary transformations were chosen, the sensitivity of the problem has notchanged. We now choose U and V appropriately such that the equation (4.66) is easy to solve.In [7] it is recommended to take Au in upper Schur form and Fv in lower Schur form. Once this ischosen one can partition the system as follows: X11 x12X11 x12F11 0Q11 q12A11 a12++= 0.0 22x21 x22x21 x22f21 22q21 q22From this we find(22 + 22 )x22 + q22 = 0109
(4.68)
which has a solution if a22 + 22 6= 0 (notice that 22 and 22 are eigenvalues of A and F , respectively). Then we findx21 (22 I + F11 ) = q21 x22 f21
(4.69)(4.70)
which again is solvable if 22 is not an eigenvalue of F and 22 is not and eigenvalue of A. Fromhere on we can then perform the same procedure recursively until all of X is determined.The complexity of this algorithm is O(n3 ) + O(m3 ) for the Schur decomposition and then ofthe same order of magnitude for the subsequent backsubstitution step. The algorithm is shown tobe weakly stable in [44].Remarks1. In the case of real arithmetic, the Schur forms may have 2 2 diagonal blocks, in which caseone may have to solve a 2 2 subsystem in (4.68) rather than a scalar one. Also the systems(4.69) and (4.70) will be more involved but may be solved using the Korenecker productapproach. This will not increase the order of magnitude of the complexity but will increaseits coefficient.2. For the Lyapunov equation (4.69) and (4.70) are identical and the complexity is essentiallyhalved.3. In the case of a Sylvester equation it is more economical to choose the Hessenberg form forone of the two matrices (the largest one). The recurrence is then essentially the same for therest except that one has to solve Hessenberg systems at each step rather than triangular ones.This method is explained in [44].4. In the reduced observer problem one has in fact a quadratic equation in the unknown T , A oand Ko . Using the Schur form for Ao and the staircase form for (A, C) it is shown in [135]that one of these equations is linear and can always be solved in least squares sense. Oncethis solution is filled in, there is another equation that becomes linear, and this process canbe continued to solve the complete system of equations.5. Algorithms and software for the more general Sylvester equationA1 XF1T + A2 XF2T + Q = 0and it symmetric Lyapunov counterpartsAXF T + F XAT + Q = 0andAXAT + F XF T + Q = 0occur in implicit systems of difference and differential equations. Algorithms are given in [44]and [40].110
6. Since the Sylvester equation can be viewed as a linear equation one can compute its sensitivity.But this implies writing a large structured matrix M and computing the condition number ofM . Simplified bounds are obtained for various special cases in the literature. For the stableLyapunov equation see e.g. [55]. Relatively cheap black box condition estimators can beobtained using a few multiplications with the structured matrix M .
4.5
We consider the ARE as it occurs in the optimal control problem. The equation for the Kalmanfilter are dual and essentially the same techniques hold there as well. The equations considered noware thus in continuous time:P A + AT P P BR1 B T P + Q = 0
(4.71)
= AT [P P B(R + B T P B)1 B T P ]A + Q= AT [P 1 + BR1 B T ]1 A + Q.
(4.72)
We first consider the continuous time problem and leave the discrete time case for later since itmerely consists of transforming all techniques for the continuous time case to the analogous discretetime problem.The origin of the ARE for the continuous time problem is the solution of the optimal feedbacku = F x minimizing the functional (where we assume Q > 0, R > 0):Z {xT (t)Qx(t) + uT (t)Ru(t)}dtJ =0
subject to
x(t)
Theorem 4.8. If A, B is reachable then the optimal cost will be bounded. Otherwise therealways exist an initial state x0 which can make the cost unbounded if Q > 0.Proof. If A, B is reachable then there exists a feedback F0 such thatu(t) = F0 x(t); x u = (A + BF0 )xu ; xu (0) = x0and thenJ0 =
Z0
where c is bounded. The optimal solution J is thus bounded from above by ckx0 k22 and sinceR > 0, Q > 0, J is always positive. So J is clearly bounded. If (A, B) is not reachable, thereexist an initial state x0 (with a nonzero component along unreachable eigenvalue/eigenvector pairs)which will make the cost factor xT (t)Qx(t) grow unbounded if Q > 0.111
It is thus natural to assume (A, B) reachable. In a dual manner (A, C) observable is typicallyassumed for the Kalman filter in order to ensure bounded variance for the difference x(t) x(t). Inthe sequel we will typically make these assumptions. We will see that this also guarantees existenceof particular solutions of the ARE.Remark.The conditions of reachability and observability can be weakened to those of stabilizability anddetectability [150].Most of the methods that are numerically reliable and of reasonable complexity are based onthe Hamiltonian matrixA BR1 B TH =(4.73)QATwhich shows up in the state/costate equations xA BR1 B Txx==H.QAT
(4.74)
This equation is derived from variational principles and its solution with suitable boundary conditions also solves the optimal control problems (see [116] for details). The term Hamiltonian comesfrom the following property.0 Ithen JH = H T J.Lemma 4.1. Let J =I 0QATwhich is symmetric, henceProof. Premultiplying J with H we obtain JH =A BR1 B TJH = (JH)T = H T J T . Since J = J T we have the required result.The above property is often referred to as H being J symmetric or Hamiltonian.Lemma 4.2. If (, x) is an eigenvalue/vector pair of H then, (, Jx) is an eigenvalue/vectorpair of H T .Proof. Let Hx = x then apply x to JH = H T J. This yields JHx = (Jx) = H T (Jx) whichis the required result.Corollary 4.4. If is an eigenvalue of H, then so is , since H and H T have the sameeigenvalues.If follows from the assumption made earlier that H has no eigenvalues on the j axis.Lemma 4.3. If (A, B) is reachable or (A, Q) is observable then H has no eigenvalues on thej-axis.Proof. See [77].
The ARE is then derived from imposing = P x in this homogeneous differential equation.Inserting this in (4.74) yieldsIIx = Hx.(4.75)PP112
IP
x(t) = 0, x(t)
(4.76)
which is precisely the ARE (4.71). Writing this into the matrix product
.= Ht
= Ht =
AF0
BR1 B TATF
(4.77)
(4.78)
Theorem 4.8. If X is a k-dimensional invariant subspace of the n n matrix A, then for anybasis Xnk of X , there exists a k k matrix A such that
AX = X A.
(4.79)
Proof. Denote by xi the i-th column of X. Since Axi lies in the space spanned by X there exista column ai such that Axi = Xai . Putting these columns together yields what we needed.This now leads to the following basic theorem.Theorem 4.9. Let X be an invariant subspace of A and X1 be a basis for it. Then there existsa completion of X1 to an invertible matrix X = [X1 | X2 ]. For each such X we haveX 1 AX =
A11 A120 A22
(4.80)
If we choose X to be a unitary basis U1 then the completion can always be chosen unitary: U =[U1 | U2 ], U H U = I.113
CompletingProof. Let X1 be a basis for the invariant subspace then AX1 = X1 A for some A.X = [X1 | X2 ] then yields: Y1In1 0X 1 X =[X1 | X2 ] =0 I n2Y2if we partition X 1 and X conformably. Apply now X 1 , X to A to getA11 A12.1where Aij = Yi AXj .X AX =A21 A22But AX1 = X1 A implies A21 = Y2 AX1 = Y2 X1 A = 0 which yields (4.80). The rest of the theoremis trivial.
Remark1. The concept of invariant subspace is a direct extension of that of eigenvector. An eigenvectorx also spans a 1 dimensional space X . It satisfies indeedAX X
(4.81)
and there exists a scalar for each basis vector x of X such thatAx = x.
(4.82)
X1X2
H.
AFH=X1 HX1 =PPP114
One shows easily that the eigenvalues of H are symmetric with respect to the j axis andthat every decomposition of the type (4.77) corresponds to a real symmetric solution P , whileTheorem 4.5 in fact holds for general P .Finding the real symmetric solution to the ARE amounts to finding groupings of eigenvalues intwo sets that are symmetric to each other (with respect to the j axis). The solution P 0 of interestin optimal control is that which selects all the stable eigenvalues.1.5
0.5
-0.5
-1
-1.5-4
-3
h11 . . .
.... ..
..H11 H12.H
U HU = (4.83)=..0 H22
. h2n,2n
be the Schur decomposition of the Hamiltonian matrix H, where we ordered the eigenvalues h ii ofH such that h11 , . . . , hn,n are stable and the others unstable. Then partitioning U asU
U11 U12U21 U22115
(4.84)
we have that1P0 = U21 U11
Remarks1. We have assumed that H has no eigenvalues on the j-axis. One shows that they can infact only occur when the conditions of reachability and observability are violated. Under thesame conditions one shows that P0 is the only positive definite solution of the ARE.2. The QR algorithm for finding the Schur decomposition with reordered eigenvalues is backwardstable. Its complexity is O(n3 ) even with reordering (which implies updating U as well). [46][124].3. The inversion of U11 is O(n3 ) and can be done in a stable manner as well but the concatenationof both steps has not been proved to be stable, although experience shows this is a very reliablemethod.4. The sensitivity of the decomposition (4.83) is well known. It is shown in [122] that theinvariant subspace (and any orthogonal basis for it) has sensitivityU11= 1/ sep (H11 , H22 )
U21where sep (H11 , H22 ) is essentially the minimum distance between the eigenvalues of H11and H22 . In other words, when eigenvalues occur very close to the j axis, the solution tothe Riccati equation will be very sensitive.5. The inversion of U11 depends more on the controllability of the system. When the systemis poorly controllable, U11 is badly conditioned and P will have a large norm. This is to beexpected since in order to stabilize A + BF = A BR1 B T one requires a large feedbackgain. The bad conditioning of U11 will also affect the sensitivity of P .6. When all matrices are real, P is also real and it should be computed using the real Schurform which is a variant of (4.83) with possibly 2 2 diagonal blocks in H11 and H22 .We now give similar results for the discrete time Riccati equation, without giving new proofssince they are all similar. The problem is to minimize the functionalPTTJ= 0 xk Qxk + uk Ruksubject to xk+1 = Axk + Buk , x0 givenStabilizability is again needed to have a bounded solution for all x. From variational calculus [116],one obtains the equationsA BR1 B Txkxk+1=k+1QATr116
or also
I BR1 B T0AT
xr+1k+1
A 0Q I
xkk
(4.85)
(4.86)
Theorem 4.12. The matrix S in (4.86) satisfies SJS T = J and is called sympletic.
T A 0AQI BR1 B TIProof. One needs to proveJ=JT1Q I0I0ABR B T0Awhich proves the result.both sides equalTA0
0A
but
One way to see the relation of this eigenvalue problem with the original ARE (4.72) is torewrite it as a quadratic equation in P by getting rid of the inversion in (4.72). Multiply thebottom equation by [P 1 + BR1 B T ]AT on the left to obtain(P 1 + BR1 B T )AT (P Q) A = 0and after another multiplication with P and some regrouping:AT Q P (BR1 B T AT Q + A) + AT P + P BR1 B T AT P = 0117
543210-1-2-3-4-5-6
A + BR1 B T AT Q BR1 B T ATAT QAT
= 0.
(4.87)
(i I E 1 F )xi = 0
(4.90)
(i E F )xi = 0
(4.91)
is equivalent todet(i E F ) = 0;
when E is invertible. The important point here is that definition (4.91) even exists when E issingular and is well defined when det(E F ) 6= 0. When this last condition is met the pencil118
+ E 1 F X )
(4.92)and hence (4.92) implies
The matrix decomposition of Theorem 4.5 also carries over to generalized eigenvalue problems.Theorem 4.13. If X is a k-dimensional deflating subspace of the n n regular pencil E F , and F and a matrix Ynk such thatthen for any basis Xnk of X , there exist k k matrices E
EX = Y E;
F X = Y F .
(4.93)
Proof. Let Y be a basis for Y = EX + F X then the above equations just express that EX Yand F X Y. But this is precisely expressed by the matrix equations (4.93), which proves theresult.This now again leads to a block triangular decomposition.Theorem 4.14. Let X be a deflating subspace of a regular pencil E F and let X1 be a basisfor X and Y1 a basis for Y = EX + F X . Then there exist completions of X1 and Y1 to invertiblematrices X = [X1 | X2 ] and Y = [Y1 | Y2 ]. For each such matrices X and Y we haveF11 F12E11 E1211;Y FX =.(4.94)Y EX =0 E220 F22If the bases X1 and Y1 are chosen unitary then the completions can also be chosen unitary.Proof. Define Z as the inverse of Y and partition it as follows Z1In1ZY =.[Y1 | Y2 ] =In2Z2
(4.95)
What ought to be the E21 and F21 blocks in (4.94) equal thenE21 = Z2 EX1 ,
F21 = Z2 F X1 .
F21 = Z2 Y1 F = 0
Because of the similarities with the continuous time case we state the following theorem withoutproof.119
Theorem 4.15. To every solution P of the discrete time ARE there corresponds an n-X1dimensional deflating subspace of E F . To every n-dimensional deflating subspace ImX2of E F , there corresponds a solution P = X2 X11 of the discrete time ARE, provided X1 isinvertible.Proof. See [105].
Just as in the standard eigenvalue problem, one constructs deflating subspaces from the generalized Schur form of a regular pencil E F .Theorem 4.16. Let
`11 . . .
..E11 E12.H
,Q EU = =..0 E22
. e2n,2nH
Q FU
f11
f2n,2n
FF1112=,
0 F22
(4.96)
be the generalized Schur decomposition of the simpletic pencil E F , where we ordered thegeneralized eigenvalues fii /eii such that the first n ones are stable and the others unstable. Thenpartitioning U asU11 U12U=U21 U22we have that1P0 = U21 U11
Remarks1. The QZ algorithm with reordering [96] [133] is backward stable and has complexity O(n 3 ).For the inversion of U11 the same comments apply as for the ARE. The same holds also for thesensitivity issues of the discrete time ARE. For real pencils, there is again a real generalizedSchur from which solves the ARE in real arithmetic.2. Just as the inversion of A and E was avoided in the discrete-time ARE, we can avoid theinversion of R in both schemes. The generalized eigenvalue problems that occur in this contextare
I 0 0A0B0 0 I 0 Q ATT0 0 00 BR120
I 0 0 AT0 BT
A 0 B00 0 Q I0 0 R0
for the continuous-time and discrete-time case, respectively. In both cases one shows thatthese generalized eigenvalue problems can be used for the construction of the solution of theARE. The major advantage of this approach is that these eigenvalue problems are formulateddirectly in terms of the data of the problem, namely A, B, Q and R. This approach e.g.,allows to solve the problem when R is singular whereas the ARE do not exit in this case [133][31]. Similar enlarged pencils for solving spectral factorization problems are also described in[133]. The spirit of this approach is to solve problems directly in terms of its data wheneverpossible, without reducing it to a derived problem.3. The sensitivity of the algebraic Riccati equation has been studied in [13], [69], [75]. It isimportant to see that this is different from just the perturbation analysis of eigenspaces ofthe underlying Hamiltonian or symplectic pencils.4. There is a lot of structure in the eigenvalue problems that one considers to solve the Riccatiequations. New methods were developed that exploit this structure to yield faster algorithms.Remarkably, one can ensure at the same time that the backward error of these methods arestructured as well [9]. Moreover these methods have forward errors that are then compatiblewith the sensitivity analysis of the previous point.5. Several references address particular numerical issues of optimal control [119] and relatedproblems such as the singular case [86].
121
122
Chapter 5
KALMAN FILTERING5.1
Since the appearance of Kalmans 1960 paper [66], the so-called Kalman filter (KF) has been appliedsuccessfully to many practical problems, especially in aeronautical and aerospace applications. Asapplications became more numerous, some pitfalls of the KF were discovered such as the problemof divergence due to the lack of reliability of the numerical algorithm or to inaccurate modeling ofthe system under consideration [61].In this section we reconsider the numerical robustness of existing KFs and derive some resultsgiving new and/or better insights into their numerical performance. Here we investigate four basicKF implementations: the Conventional Kalman Filter (CKF), the Square Root Covariance Filter(SRCF), the Chandrasekhar Square Root Filter (CSRF) and the Square Root Information Filter(SRIF).We first introduce some notation. We consider the discrete time-varying linear system,xk+1 = Ak xk + Bk wk + Dk uk
(5.1)
(5.2)
where xk , uk and yk are, respectively, the state vector to be estimated ( R n ), the deterministicinput vector ( Rr ) and the the measurement vector ( Rp ), where wk and vk are the process noise( Rm ) and the measurement noise ( Rp ) of the system, and, finally, where Ak , Bk , Ck and Dkare known matrices of appropriate dimensions. The process noise and measurement noise sequencesare assumed zero mean and uncorrelated:E{wk } = 0 , E{vk } = 0 , E{wk vjT } = 0
(5.3)
(5.4)
measurement noise covariance matrix Rk are assumed to be positive definite, the following Choleskyfactorizations exist :1/21/21/2 1/2Qk = Qk [Qk ]T , Rk = Rk [Rk ]T(5.5)1/2
1/2
where the factors Qk and Rk may be chosen upper or lower triangular. This freedom of choiceis exploited in the development of the fast KF implementations presented later. The problem isnow to compute the minimum variance estimate of the stochastic variable x k , provided y1 up to yjhave been measured:xk|j = xk|y1 ,...,yj .(5.6)When j = k this estimate is called the filtered estimate and for j = k 1 it is referred to as theone-step predicted or, shortly, the predicted estimate. The above problem is restricted here to thesetwo types of estimates except for a few comments in the concluding remarks. Kalman filtering is arecursive method to solve this problem. This is done by computing the variances P k|k and/or Pk|k1and the estimates xk|k and/or xk|k1 from their previous values, this for k = 1, 2, .... Thereby oneassumes P0|1 (i.e. the covariance matrix of the initial state x0 ) and x0|1 (i.e. the mean of theinitial state x0 ) to be given.The Conventional Kalman Filter (CKF)The above recursive solution can be computed by the CKF equations, summarized in the following covariance form [1]:Rke = Rk + Ck Pk|k1 CkT
(5.7)
(5.8)
(5.9)
xk+1|k = Ak xk|k1 Kk [Ck xk|k1 yk ] + Dk uk
(5.10)
This set of equations has been implemented in various forms, see [1]. An efficient implementationthat exploits the symmetry of the different matrices in (7-10) requires per step 3n 3 /2 + n2 (3p +m/2) + n(3p2 /2 + m2 ) + p3 /6 flops (where 1 flop = 1 multiplication + 1 addition). By notexploiting the symmetry of the matrices in equations (7-10) one requires (n 3 /2 + n2 m/2 + np2 /2)more flops. In the error analysis, it is this costly implementation that is initially denoted as theCKF for reasons that are explained there. We also give some other variants that lead to furtherimprovements in the number of operations.The Square Root Covariance Filter (SRCF)Square root covariance filters propagate the Cholesky factors of the error covariance matrixPk|k1 :Pk|k1 = Sk .SkT(5.11)where Sk is chosen to be lower triangular. The computational method is summarized by thefollowing scheme [1]:"##"1/2e1/2RkCk S k0Rk00.U1 =,(5.12)1/2GkSk+1 00A k S k Bk Q k{z}|{z}|(prearray)(postarray)124
k|k1 yk ) + Dk ukxk+1|k = Ak xk|k1 Gk Re,k (Ck x
(5.13)
(5.14)
In10
0.LTkIn2{z}
(5.15)
where the rank of inc.Pk is n1 + n2 and is called its signature matrix. The CSRF propagatesrecursions for Lk and xk+1|k using [98]:#""#e1/2e1/2Rk1 CLk1Rk0,.U2 =(5.16)GkLkGk1 ALk1|{z}{z}|(prearray)(postarray)1/2
k|k1 yk ) + Dukxk+1|k = Axk|k1 Gk Re,k (C x
(5.17)
with L0 LT0 = P1|0 P0|1 . Here U2 is a p - unitary transformation, i.e. U2 p U2T = p withIp 0p =(5.18)0 Such transformations are easily constructed using skew Householder transformations (using anindefinite p -norm) and require as many operations as the classical Householder transformations[98]. For this implementation the operation count is (n1 + n2 )(n2 + 3np + p2 ) flops.The Square Root Information Filter (SRIF)The information filter accentuates the recursive least squares nature of filtering [10][1]. The1SRIF propagates the Cholesky factor of Pk|kusing the Cholesky factor of the inverses of theprocess- and measurement noise covariance matrices:1Pk|k= TkT .Tk
125
(5.19)
1/2 T
(5.20)
(5.21)
Q1k = [QkRk1 = [Rk
] .Qk
] .Rk
where the right factors are all chosen upper triangular. We now present the Dyer & McReynoldsformulation of the SRIF (except for the fact that the time and measurement updates are combinedhere as in [1]) which differs from the one presented by Bierman (see [10] for details). One recursionof the SRIF algorithm is given by [1]:
1/2Qk00
Tk A1Tk xk|k =U3 . Tk A1k Bkk1/21/20Rk+1 Ck+1 Rk+1 yk+1|{z}(prearray)
e1/2
Q k+1
00|
Tk+1 k+1|k+1 0rk+1{z}(postarray)
(5.22)
1 xk+1|k+1 = Tk+1k+1|k+1 + Dk uk
(5.23)
An operation count of this filter is 7n3 /6 + n2 (p + 7m/2) + n(p2 /2 + m2 ) flops. Here we did notcount the operations needed for the inversion and/or factorization of Q k , Rk and Ak (for the timeinvariant case e.g. these are computed only once) and again (as for the SRCF) only the diagonal1elements of the information matrix Pk|kare computed at each step.Variants of the above basic KF implementations have been developed which mainly exploit someparticular structure of the given problem in order to reduce the amount of computations. E.g. whenthe measurement noise covariance matrix Rk is diagonal, it is possible to perform the measurementupdate in p scalar updates. This is the so-called sequential processing technique, a feature that isexploited by the U DU T -algorithm to operate for the multivariable output case. A similar processingtechnique for the time update can be formulated when the process noise covariance matrix Q k isdiagonal, which is then exploited in the SRIF algorithm. Notice that no such technique can be usedfor the CSRF. The U DU T -algorithm also saves operations by using unit triangular factors U anda diagonal matrix D in the updating formulas for which then special versions can be obtained [10].By using modified Givens rotations [42] one could also obtain similar savings for the updating ofthe usual Cholesky factors, but these variants are not reported in the sequel.For the time-invariant case, the matrix multiplications and transformations that characterize thedescribed KF implementations can be made more efficient when the system matrices {A, B, C} arefirst transformed by unitary similarity transformations to so-called condensed form, whereby thesesystem matrices {At , Bt , Ct } contain a lot of zeros. From the point of view of reliability, these formsare particularly interesting here, because no loss of accuracy is incurred by these unitary similaritytransformation [140]. The following types of condensed forms can be used to obtain considerablesavings in computation time in the subsequent filter recursions [140]: the Schur form, where A t isin upper or lower Schur form, the observer-Hessenberg form, where the compound matrix ATt , CtT126
is upper trapezoidal and the the controller-Hessenberg form, where the compound matrix (A t , Bt )is upper trapezoidal. In [140], an application is considered were these efficient implementationsare also valid for the time varying case. Note that the use of condensed forms and sequentialprocessing could very well be combined to yield even faster implementations.The operation counts for particular mechanizations of these variants are all given in table 5.1and indicated by respectively the seq., Schur, o-Hess. and c-Hess. abreviations, whilefull refers to the implementations described in previous sections where the full implementationof the CKF exploits symmetry.filterCKF
SRCF
SRIF
CSRF
5.2
typecomplexityfull(3/2)n3 + n2 (3p + m/2) + n(3p2 /2 + m2 ) + p3 /6seq.(3/2)n3 + n2 (3p + m/2) + n(p2 + m2 )Schur(3/4)n3 + n2 (5p/2 + m/2) + n(3p2 /2 + m2 ) + p3 /6o-Hess. (3/4)n3 + n2 (7p/2 + m/2) + n(2p2 + m2 ) + p3 /6full(7/6)n3 + n2 (5p/2 + m) + n(p2 + m2 /2)seq.(7/6)n3 + n2 (5p/2 + m) + n(m2 /2)Schur(1/6)n3 + n2 (5p/2 + m) + n(2p2 )o-Hess. (1/6)n3 + n2 (3p/2 + m) + n(2p2 ) + 2p3 /3full(7/6)n3 + n2 (p + 7m/2) + n(p2 /2 + m2 )seq.(7/6)n3 + n2 (p + 7m/2) + n(p2 /2)Schur(1/6)n3 + n2 (p + 5m/2) + n(2m2 )c-Hess. (1/6)n3 + n2 (3m/2 + p) + n(m2 + p2 /2)full(n1 + n2 )(n2 + 3np + p2 )Schur(n1 + n2 )(n2 /2 + 3np + p2 )o-Hess. (n1 + n2 )(n2 /2 + 3np + p2 )Table 5.1: Operation counts for the different KFs
Error analysis
In this section we analyze the effect of rounding errors on Kalman filtering in the four differentimplementations described above. The analysis is split in three parts: (1) what bounds can beobtained for the errors performed in step k, (2) how do errors performed in step k propagatein subsequent steps and (3) how do errors performed in different steps interact and accumulate.Although this appears to be the logical order in which one should treat the problem of error buildup in KF, we first look at the second aspect, which is also the only one that has been studied in theliterature so far. Therefore, we first need the following lemma which is easily proved by inspection.Lemma 1:Let A be a square non-singular matrix with smallest singular value min and let E be a perturbationof the order of = kEk2 << min (A) with k.k2 denoting the 2-norm. Then(A + E)1 = A1 + 1 = A1 A1 EA1 + 2
(5.24)
(5.25)
where2k2 k2 6 2 /min(min ) = O( 2 )
127
(5.26)
Notice that when A and E are symmetric, these first and second order approximations (25) and(26) are also symmetric.We now thus consider the propagation of errors from step k to step k + 1 when no additionalerrors are performed during that update. We denote the quantities in computer with an upperbar,e1/2k|k1 , Gk , S k , T k , Rk , F k , K k , or Lk , depending on the algorithm.i.e. P k|k1 , xFor the CKF, let Pk|k1 and xk|k1 be the accumulated errors in step k, then:P k|k1 = Pk|k1 + Pk|k1 , xk|k1 = xk|k1 + xk|k1
(5.27)
(5.28)
(5.29)
1Ck ) = A k K k CkFk = Ak (I Pk|k1 CkT Re,k
(5.30)
whereand (assuming P k|k1 is not necessarily symmetric, which would e.g. occur when applying (9)bluntly):T
(5.32)
(5.33)(5.34)
T Re1 Cwhere Fk = (I Pk+1|k Ck+1k+1 k+1 )Ak has the same spectrum as Fk+1 in the time-invariant
(5.35)
(5.36)
128
which are decreasing in time when Fk and Fk are contractions (i.e. when k and k < 1). Thelatter is usually the case when the matrices Ak , Bk , Ck , Qk and Rk do not vary too wildly in time[1]. For the time-invariant case one can improve on this by saying that Fk and Fk tend to theconstant matrices F and F respectively, with (equal) spectral radius < 1 and one then hasfor some appropriate matrix norm [8]:||Pk+1|k || 2 .||Pk|k1 ||
(5.37)
||Pk+1|k+1 || 2 .||Pk|k ||
(5.38)
for sufficiently large k. Notice that is smaller than or , whence (37-38) are better boundsthan (35-36). Using this, it then also follows from (37-38) that all three errors P k|k1 , Kk andxk|k1 are decreasing in time when no additional errors are performed. The fact that past errorsare weighted in such a manner is the main reason why many Kalman filters do not diverge inpresence of rounding errors.The property (35-38) was already observed before [61], but for symmetric P k|k1 . However ifsymmetry is removed, divergence may occur when Ak (i.e. the original plant) is unstable. Indeed,from (31)(33) we see that when Ak is unstable the larger part of the error is skew symmetric:TPk+1|k Ak .(Pk|k1 Pk|k1).ATk
(5.39)
T).ATkPk+1|k+1 Ak .(Pk|k Pk|k
(5.40)
and the lack of symmetry diverges as k increases. This phenomenon is well known in the extensiveliterature about Kalman filtering and experimental experience has lead to a number of differentremedies to overcome it. The above first order perturbation analysis in fact explains why theywork :1. A first method to avoid divergence due to the loss of symmetry when Ak is unstable, is tosymmetrize P k|k1 or P k|k at each recursion of the CKF by averaging it with its transpose.This makes the errors on P symmetric and hence the largest terms in (31)(33) disappear!2. A second method to make the errors on P symmetric, simply computes only the upper (orlower) triangular part of these matrices, such as indicated by the implementation in table 5.1.3. A third technique to avoid the loss of symmetry is the so-called (Josephs) stabilized KF [11].In this implementation, the set of equations for updating P are rearranged as follows:Pk+1|k = Fk Pk|k1 FkT + Kk Rk KkT + Bk Qk BkT
(5.41)
A similar first order perturbation study as for the CKF above, learns that no symmetrizationis required in order to avoid divergence since here the error propagation model becomes :Pk+1|k = Fk Pk|k1 FkT + O( 2 )
(5.42)
(5.43)
is clearly symmetric by construction. According to (31) this now ensures the convergence to zeroof Pk|k1 and hence of Sk , Kk and xk|k1 if k is sufficiently bounded in the time-varying case.For the SRIF we start with errors Tk and xk|k and use the identity1Pk|k= TkT .Tk + TkT .Tk + TkT .Tk
(5.44)
(5.45)
to relate this problem to the CKF as well. Here one apparently does not compute x k+1|k+1 from xk|kand therefore one would expect no propagation of errors between them. Yet, such a propagationis present via the relation (45) with the errors on k+1|k+1 and k|k , which do propagate fromone step to another. This in fact is reflected in the recurrence (34) derived earlier. Since the SRIFupdate is inherently equivalent to an update of Pk|k and xk|k as in the CKF, the equations (33)(36)still hold where now the symmetry of Pk|k is ensured because of (44). From this it follows thatPk|k and xk|k , and therefore also Tk and k|k , converge to zero as k increases, provided k issufficiently bounded in the time-varying case.e1/2Finally, for the CSRF we start with errors Lk1 , Gk1 , Rk1 and xk|k1 . Because of theseerrors, (16) is perturbed exactly as follows:"
Rk1 + Rk1Gk1 + Gk1
C(Lk1 + Lk1 )A(Lk1 + Lk1 )
.U 2 =
Rk + RkGk + Gk
0Lk + Lk
(5.46)
where U 2 is also p -unitary. When = kC.Lk1 k << kRk1 k (which is satisfied when k issufficiently large), Lemma A.3 yields after some manipulations:"
e1/2Rk1
Gk1
CLk1ALk1
.U2 =
e1/2RkGke1/2
0Lk
+ O(.)
Rk
Gk = Gk1 .[Rk.Rk1 ]T + A.Lk1 .[Rke1/2 e1/2 T= Gk1 .[Rk.Rk1 ] + O(.)
(5.47)
.C.Lk1 ., respectively.
(5.48)
(5.49)e1/2
Here again thus the errors Rk1 and Gk1 are multiplied by the matrix [Rk.Rk1 ]T at eachstep. When is the identity matrix (i.e. when inc.Pk is non-negative) this is a contraction sinceeRke = Rk1+ C.Lk1 .LTk1 .C T . From this, we then derive similar formulas for the propagation ofe1/2
Kk and xk+1|k . Using Lemma 1 for the perturbation of the inverse in Kk = Gk .Rke1/2
Kk = Gk .Rk Gk .Rk.Rk .Rk+ O( 2 )e1/2 e1/2e1/2+ O( 2 ) Kk .Rk .Rk= Gk .Rk130
, we find:(5.50)
Using (49)(50) and the fact that for large k, Kk = Kk1 + O(), we then obtain1/2
e1/2e .R1 ]Gk1 .Rk1 .[Rk1e,ke1/2 e1/2e .R1 ]Kk1 .Rk1 .Rk1 .[Rk1e,k
(5.51)
(5.52)
(5.53)
Theorem 5.1.Denoting the norms of the absolute errors due to round-off during the construction of P k+1|k , Kk ,1xk+1|k , Sk , Tk , Pk+1|k+1and xk|k by p , k , x , s , t , pinv and x , respectively, we obtainthe following upper bounds (where all norms are 2-norms):1. CKFp 6 1 .12 /p2 .kPk+1|k kk 6 2 .12 /p2 .kKk kx 6 3 .(kFk k.kxk|k1 k + kKk k.kyk k + kDk k.kuk k)+k .(kCk k.kxk|k1 k + kyk k)2. SRCFs 6 4 .(1 + 1 /p ).kSk+1 k/cos1p 6 5 .(1 + 1 /p ).kPk+1|k k/cos1k 6 6 /p .(1 /p .kSk+1 k + 1 .kGk k + kSk+1 k/cos1 )x 6 7 .(kFk k.kxk|k1 k + kKk k.kyk k + kDk k.kuk k)+k .(kCk k.kxk|k1 k + kyk k)3. CSRFk 6 8 .(U2 )/p .(1 /p .kLk k + 1 .kGk k + kLk k/cos2 )x 6 9 .(kFk k.kxk|k1 k + kKk k.kyk k + kDk.kuk k)+k .(kCk.kxk|k1 k + kyk k)
131
4. SRIFt6pinv 6p6x6
where i and i are the i-th singular value of Re,k and Qe,k+1 respectively, i are constants closeto the machine precision and cosi are defined as followscos1 = kSk+1 k/k [Gk |Sk+1 ] k
The above theorem is now used together with the analysis of the propagation of errors throughthe recursion of the KF to yield bounds on the total error of the different filters at a given step k,which we denote by the prefix tot instead of .For this we first turn to the (symmetrized) CKF. For the total error tot Pk+1|k we then haveaccording to (29)(31)(33)(35) and Theorem 5.1 (for any consistent norm [123]):ktot Pk+1|k k 6 k2 .ktot Pk|k1 k + p
(5.54)
(5.55)
ktot xk+1|k k 6 k .{ktot xk|k1 k + c2 .ktot Pk|k1 k} + x
(5.56)
Here the upperbar on the s indicate that these are not the exact bounds of Theorem 5.1 (whichare derived under the assumption that the computations up to step k are exact), but analogousbounds derived for the perturbed results stored in computer at step k. Under the assumption thatat step k the accumulated errors are still of the order of the local errors performed in one step (i.e.those estimated in Theorem 5.1), one easily finds that the - and -quantities are O( 2 )-close toeach other. It is thus reasonable to assume that they are equal to each other. Denoting by tot .the norm of the corresponding matrix tot . , then finally yields:
tot Pk+1|ktot Pk|k1k 0 0p tot Kk 6 k . c1 0 0 . tot Kk1 + k (5.57)tot xk+1|ktot xk|k1c2 0 1x
where the inequality is meant elementwise. From this one then easily sees that the total errorswill remain of the order of the local errors as long as the norms k do not remain too large for along period of time. This is also confirmed by the experimental results of the next section. For atime-invariant system, k can be replaced by k if the norm is chosen appropriately as discussedin (37) , which then becomes eventually smaller than 1. Comparable results can also be statedabout the k if the time variations in the model are sufficiently smooth.Using the above inequality recursively from 0 to one finally obtains
tot P1/(1 2 )00p tot K 6 . k c1 /(1 2 )10(5.58)2tot x
if < 1, where is the largest of the k s. When k tends to a fixed value it is easily shownthat can be replaced by in (58), since the contributing terms to the summation are thosewith growing index k. For a time-invariant system, finally, this can then be replaced by as wasremarked earlier, and the condition = < 1 is then always satisfied.For the SRCF, one uses the relation to the CKF (as far as the propagation of errors from onestep to another is concerned) to derive (58) in an analogous fashion, but now with p , k and xappropriately adapted for the SRCF as in Theorem 5.1. For the SRIF one also obtains analogouslythe top and bottom inequalities of (57) for p and x adapted for the SRIF as in Theorem 5.1and where now is the largest of the k s. Upon convergence, the same remarks hold as above forreplacing by and . Finally for the CSRF, we can only derive from (52)(53) a recursion ofthe type: tot Kktot Kk1k 0k6.(5.59)+tot xk+1|ktot xk|k1c2 kx133
5.3
We show a series of experiments reflecting the results of our error analysis. For these examplesthe upper bounds for numerical round-off developed in the previous section are reasonably closeto the true error build up. The simulations are performed for a realistic flight-path reconstructionproblem, described in [145]. This analysis indicated the key relevant parameters (R ke ), the spectralnorm k and spectral radius k = (Fk ), which in turn can be affected by (A). For details on theexperiments, we refer to [145]. Because of the inclusion of the CSRF, only the time-invariant caseis considered here. The SRCF and the SRIF algorithms are closely related from numerical point ofview. They are therefore first compared to the CKF and secondly to the CSRF.Comparing the SRCF/SRIF with the CKFTwo test were performed to analyze the effect of (Rke ) and (Fk ), which turn out to be veryclose to (R) and (A).Test 1 - Fig.5.1a: ((A) = 1.0 and (R) = 102 )Since symmetry of the error state covariance matrix P is not preserved by the CKF, the round-offerror propagation model for the local error Pk|k1 says that divergence will occur if the originalsystem is unstable. This experiment confirms this also when (A) = 1.0, as is the case for theconsidered flight-path reconstruction problem [145]. Furthermore, it is observed from Fig.5.1athat the error on P with the CKF is almost completely determined by the loss of symmetryT||P k|k1 P k|k1 || = sym Pk|k1 . Different methods have been proposed to solve this problem.One particular method consists in forcing a symmetric error by averaging the off-diagonal elementsof P after each recursion. The behavior of tot Pk|k1 for this implementation, denoted by CKF(S)in Fig.5.1a, indicates that this implementation becomes again competitive, even when the originalsystem is unstable. On the other hand, the behavior of tot Pk|k1 for Josephs stabilized CKF,denoted by (J)CKF in Fig.5.1a, confirms that the round-off errors do not diverge even when thesymmetry of P is not retained. We also observe from Fig.5.1a that the round-off error on P withthese modified CKF remains 10 times higher than the SRCF/SRIF combination.Test 2 - Fig.5.1b: ((A) = 0.9 and (R) = 102 )If we make the original system stable, the CKF is numerically stable. Moreover, the accuracy withwhich the Kalman gain is computed is of the same order as that of the SRCF. This is in contrastwith a general opinion that SRFs improve the calculations of the Kalman gain or filtered estimates.We can state that they dont make accuracy poorer. From Fig.5.1b it is observed that only theerror covariance matrix P is computed more accurately, which confirms the upperbounds for theround-off errors obtained earlier.134
A comparison of the (a) and (b) bounds indicates that when the accuracy of the Kalman gainis considered no preference should exist for the SRFs to the CKF when Ak is stable and timeinvariant. However, the experimental results demonstrate that for the latter conditions the loss ofaccuracy with the CKF(S) is still higher than the SRFs. Here we only want to draw the attentionto the clear difference to be expected (and also reflected by the experiments) between the accuracyof Pk|k1 and Kk in the CKF(S) implementation with respect to those of SRF filters.
type algorithms considered here, it is observed that the error on the Kalman gain is always higherthan the error on the state error covariance matrix. This is partly due to the extra calculationGk (Rke )1/2 needed for the Kalman gain, where the condition number of (Rke )1/2 determines theloss of accuracy.Test 4 - Fig.5.2b: (P0|1 = 0, (A) = 1.0 and (R) = 1.0)For this case inc.P0 = B.Q.B T is positive definite, causing the transformations used in each recursion to be unitary. From the experimental results in Fig.5.2b we observe that the error on P isvery small, while the error on K is much higher than for the SRCF calculations. Furthermore, theerrors on K with the CSRF increase very slowly because the coefficient k becomes very close to 1.Generally, the CSRF is less reliable than the SRCF/SRIF combination. For zero initial conditionsof the state error covariance matrix maximal reliability can be achieved with the CSRF. Therefore,for situations where n >> m, the CSRF may be preferred because of its increased computationalefficiency despite its loss of accuracy. This property is obviously only valid for the time-invariantcase.
causes the error on P to be much higher (a factor 103 ) for the SRIF than for the SRCF. As in test2, the large value of (R) again causes a great loss in the accuracy of the Kalman gain calculationin the SRCF. In this test we analyzed the deterioration of the error covariance matrix by the SRIFimplementation by (fairly unrealistic) large condition numbers. The effect of a high (A k ) mayinfluence the accuracy of the SRIF considerably.Test 6 - Fig.5.3b:For this test, the measurement error statistics were taken from real flight-test measurement calibrations resulting in Q = diag{8.106 , 5.105 , 5.108 } and R = diag{5.102 , 2.101 }. In Fig.5.3bthe simulated error tot x on the state calculations is plotted for both filter implementations. Here,the error level with the SRIF is significantly higher than that for the SRCF, while P is computedwith roughly equal accuracy. This is due to the high condition number of Tk in the calculation ofthe filtered state with the SRIF.
5.4
In this section we compare the different filter implementations based on the error analysis and thesimulation examples.We first look at the time-varying case (whence excluding the CSRF). According to the errorbounds of Theorem 5.1, it appears that the SRCF has the lowest estimate for the local errorsgenerated in a single step k. The accumulated errors during subsequent steps is governed by thenorms k for all three filters in a similar fashion (at least for the error on the estimate) thisof course under the assumption that a symmetrized version of the CKF or the stabilized CKFis considered. From these modifications, the implementation computing only the upper (or lower)137
triangular part of the state error covariance matrix is the most efficient. The experiments withthe realistic flight path reconstruction problem indeed demonstrate that the CKF, the SRCF andthe SRIF seem to yield a comparable accuracy for the estimates x k+1|k or xk+1|k+1 , unless someof the influential parameters in the error bounds of Theorem 5.1 become critical. This is e.g.true for the SRIF which is likely to give worse results when choosing matrices A k , Rk or Qk thatare hard to invert. As far as Rk or Qk are concerned, this is in a sense an artificial disadvantagesince in some situations the inverses Rk1 and Q1k are the given data and the matrices Rk and Qkhave then to be computed. This then would of course disadvantage the SRCF. In [104] it is shownthat the problems of inverting covariances can always be by-passed as well for the SRIF as for theSRCF. The problem of inverting Ak , on the other hand, is always present in the SRIF.For the computational cost, the SRCF/SRIF have a marginal advantage over the CKF whenn is significantly larger then m and p (which is a reasonable assumption in general), even whencomputing the upper (or lower) triangular part of P with the CKF. Moreover preference shouldgo to the SRCF (resp. SRIF) when p < m (resp. p > m), with slightly preference for the SRCFwhen p = m. As is shown in [98], condensed forms or even the CSRF can sometimes be used inthe time-varying case as well, when e.g. only some of the matrices are time-varying or when thevariations are structured. In that case the latter two may yield significant savings in computingtime. Similarly, considerable savings can be obtained by using sequential processing [10] whendiagonal covariances are being treated (which is often the case in practice).For the time-invariant case, the same comments as above hold for the accuracy of the CKF,SRCF and SRIF. The fourth candidate, the CSRF, has in general a much poorer accuracy thanthe other three. This is now not due to pathologically chosen parameters, but to the simple factthat the accumulation of rounding errors from one step to another is usually much more significantthan for the three other filters. This is particularly the case when the signature matrix is notthe identity matrix, which may then lead to divergence as shown experimentally.As for the complexity, the Hessenberg forms of the SRCF and the SRIF seem to be the mostappealing candidate, except when the coefficient n1 + n2 in table 5.1 for the CSRF is much smallerthan n. This is e.g. the case when the initial covariance P0|1 is zero, in which case the CSRFbecomes the fastest of all four filters. Although the Schur implementations of the SRCF andSRIF are almost as fast as the Hessenberg implementations, they also have the small additionaldisadvantage that the original state-space transformation U for condensing the model to Schurform is more expensive than that for the other condensed forms and that the (real) Schur form isnot always exactly triangular but may contain some 2 2 bumps on the diagonal (correspondingto complex eigenvalues of the real matrix A). Finally, the c-Hess. form of the SRIF (given intable 5.1) requires a more complex initial transformation U , since it is constructed from the pair(A1 , A1 B) which also may be numerically more delicate due to the inversion of A.As a general conclusion, we recommend the SRCF, and its observer-Hessenberg implementationin the time-invariant case, as the optimal choice of KF implementation because of its good balanceof reliability and efficiency. Other choices may of course be preferable in some specific cases becauseof special conditions that would then be satisfied.
138
Chapter 6
POLYNOMIAL VERSUSSTATE-SPACE MODELSWe have seen that there are two major classes of models for which a number of numerical algorithmshave been developed. These models are state-space models
Ex = Ax + Buy= Cx + Du
(6.1)
D()y = N ()u.
(6.2)
Several algorithms were already discussed in previous chapters and it appeared clearly thatpolynomial models have the advantage of speed over the state-space models. The main reason forthis is the number of parameters in the model. For a same transfer function of a given degreen, a polynomial model typically has much less free parameters than a corresponding state-spacemodel. E.g., for a SISO systems a polynomial model will have 2n parameters versus (n + 1) 2 forthe state-space model. This is a factor of roughly n2 less parameter for the polynomial model. Fora m m transfer function of degree n the corresponding numbers are roughly 2mn parametersversus (n + m)2 , which already gives a smaller advantage for polynomial models. Also when usinge.g., condensed forms these ratios have to be divided by 2. The same ratio was also observed inthe complexity of SISO polynomial algorithms versus SISO state-space algorithms: the complexityis typically an order n smaller for polynomial algorithms. On the other hand, it was also observedthat algorithms for polynomial models may suffer from numerical instabilities whereas there existnumerically stable algorithms for most problems formulated in state-space. This chapter analyzesthese differences in more detail and tries to answer the question when to favor a particular type ofmodel.139
6.1
A system
System Sx(t)
y(t) =
with m inputs and p outputs can be represented in essentially four different ways:1) Rational transfer functiony(t) = R()u(t)
(6.3)
D()y(t) = N ()u(t)
(6.4)
(6.5)
(6.6)
2) Polynomial fraction
3) Generalized state-space
4) state-space
The corresponds between these models are found from the transfer function of each model:R() = D 1 ()N () = H(E F )1 G + J
= C(I A)1 B + D.
(6.7)
All these models are mathematically equivalent in the sense that they describe the same object,namely the system S. There also exist transformation methods to derive any of the above fourmodels from the others ([65]). But from a numerical point of view the models are clearly notequivalent. This follows quite easily from the types of transformations typically used in algorithmsdealing with these different models.There are essentially two such sets of transformations1) Unimodular transformationP () =
kX
P i i ;
detP () = c 6= 0
140
(6.8)
2) Invertible transformationsT;
detT 6= 0.
(6.9)
The first group of transformations is typically used for rational and polynomial models, the secondgroup is used for state-space and generalized state-space models. Both these transformation sets,in fact, have a multiplicative group structure, which means that if M is a member of this groupthen:M G M 1 GM1 , M2 G M1 M2 G.
(6.10)
When one has a transformation group then one can always define equivalence classes and canonicalforms. These canonical forms play a fundamental role in many analysis and design problems andare therefore worth recalling. As related to the four different models we had, we briefly describefour canonical forms for rational matrices R(), polynomial matrices P (), pencils E F andmonic pencils I A. Under unimodular transformations M () and N (), every rational matrixR() can be transformed to the quasidiagonal form (Smith McMillan form):
e ()1
M ()R()N () =
er ()fr ()
0mr,nr
(6.11)
Similarly, every polynomial matrix D() can be transformed to a similar form (Smith form):
e1 ()
.0M ()D()N () = (6.12).
er ()00mr,nr
.. ..Lk = .. 1{z|k+1
(6.13)
.}
Similarly, constant transformations T 1 , T can be used to reduce the pencil I A to its quasidiagonal form :
i 1
.. ..
..1}.
(6.14)T (I A)T = diag{Iki
. 1 i141
It is interesting to notice that with respect to the models (6.3)-(6.6) these canonical forms all revealthe polar structure of the transfer function, via the zeros of fi () in (6.11), the zeros of ei () in(6.12), the generalized eigenvalues of E F in (6.13), and the eigenvalues of A in (6.14). It iseasily seen indeed that these are the values for which the transfer function (6.7) is unbounded.
6.2
Stabilized Transformations
The above canonical forms seem equivalent to each other in the sense that they define the sameinvariants of the system (the poles in this case). When including numerical considerations, thestory is quite different. The group of constant invertible transformations has a subgroup of unitarytransformations:U,
U H U = I det U 6= 0.
(6.15)
This group is known to possess good properties in terms of error propagation. As a consequenceof this, one can define modified canonical forms which essentially contain the same information asthe Kronecker form and the Jordan form but which can be obtained using unitary transformationsonly. These forms are, of course, the generalized Schur form of a pencil E F and the Schur formof a pencil I A, as presented in Chapter 5. Notice that the generalized Schur form in its mostgeneral form was, in fact, presented in Chapter 3 in connection to the computation of the zeros ofa system.In this section we show via a simple example that the class of unimodular transformationsis unstable with respect to error propagation. Moreover, from the constraints of the algorithmconsidered, it appears to be impossible to stabilize these transformations. But the same problemcan be solved using constant transformations and there of course we can restrict ourselves to unitaryones, which will stabilize the computations.The problem considered is that of finding the zeros of a polynomial matrix of first order. Let
0 0 1 0 0P () = P0 + P1 = 1 0 + 0 1 0 0 10 0 1
(6.16)
(6.17)
are just the eigenvalues of P0 . We know there are stable algorithms for computing these eigenvalues, and moreover these eigenvalues are well conditioned when is small (since then P 0 is close toa diagonal matrix). We now show that the algorithm to construct the Smith form is unstable forthis algorithm. The first step of the Smith decomposition algorithm permutes a nonzero elementof minimum degree to the (1, 1) position (here we perform a permutation of rows 1 and 2)
+100 .M1 (P0 + P1 ) = 0
142
Then we perform column and row operations to reduce the degree of the other elements in row 1and column 1:
00 M2 ()M1 (P0 + P1 )N2 () = 0 ( + 1)/0
1where
10 01 ( + 1)/ 010 .M2 () = / 1 0 , N2 () = 000 1001This is repeated until the element in (1, 1) divides all others and the rest of row 1 and column 1is zero. Then the same procedure is repeated on the smaller dimensional matrix obtained afterdeleting row 1 and column 1:
1 M3 M2 ()M1 (P0 + P1 )N2 () = 00 ( + 1)/
0 M4 ()M3 M2 ()M1 (P0 + P1 )N2 ()N4 () =0 0
00(+1)(1)+2
M4 () =
,12( + 1)/ 1
N4 () =
1 ( 1)/ .1
( + 1)( 1)+ = ( + 1)( 1) + 32
which is indeed the characteristic polynomial of the original pencil. But the algorithm to obtainthis form involved divisions by very small elements and this algorithm apparently does not showhow this could be avoided. When goes to zero, it is easy to see that it becomes unstable for thisreason.
6.3
We saw in Section 2.2 that to any SISO system d1 ()n() in polynomial form there exists arealization that is easily derived from the coefficients of the polynomial d() and the first n samples143
of the impulse response. A much simpler form is in fact given directly in terms of the coefficientsof n() and d() in case degree n() < degree d():
001 ..
....
..b= . A=
(6.18) 0 .
011d0 d1 . . . dn1c = [ n 0 n1...nn1 ]d=[ 0 ]A proof of this follows from the following identity:
11
..
1n1d0dn2 + dn1Rewriting this we find
...n1
00...d()
.. 1 d () = (I A)1 . = (I A)1 b
0 1
(6.19)
(6.20)
(6.21)
(6.22)
Ar =
Cr
Im...
.0D0 . . . Dn2= [ N0 . . . Nn2 Nn1
, Br = . , 0 Im Dn1Im],Dr = [ 0pm ] .
(6.23)
(6.24)
where the inverse D 1 () occurs at the right of N (). By duality, one shows that for realizing theleft product D 1 ()N () instead, one needs the dual formulas
0D0N0
.. .. Ip . . .
,A` = B=,
.(6.25) Nn2 .
.0Dn2 Nn1IpDn1C` = [ 0 . . . 0 I p ] ,D` = [ 0pm ] .144
When D() is not a monic polynomial then one can not find simple state-space formulas forD1 ()N () but instead it is easy to find a generalized state-space realization C g (Eg Ag )1 Bg +Dg = D1 ()N ():
IpD0N0
.... .. Ip
.. . ,Ag Eg = B=
,g
.(6.26) Nn1 . . I D
pn1NnIpDn1Cg = [ 0 . . . 0 I p ] ,Dg = [ 0pm ] .where now N () and D() are arbitrary polynomial matrices.Exercise 6.1Prove that the above equations (6.26) satisfy Cg (Eg Ag )1 Bg + Dg = D1 ()N () by usingsimilar arguments as in (6.19)-(6.21).Notice that the realizations (6.18), (6.22), (6.24) and not necessarily minimal. Minimality ofthese realizations can be shown to be equivalent to coprimeness of the polynomials or polynomialmatrices. In the case of matrices, one defines right and left coprimeness, which are not necessarilyequivalent (see [114], [65]). Extraction of minimal realizations from these non-minimal ones can bedone in a stable manner by using staircase forms both for state-space and generalized state-spacerealizations [141, 133].
6.4
In this section we show a few fast algorithms using polynomial models and analyze their numericalreliability. In the case that they are unstable, alternative slower algorithms are discussed.A first very classical algorithm for scalar polynomials is the Euclidean algorithm for finding thegreatest common division g() of two polynomials a() and b():a() = a0 + a1 + + ak k(6.27)b() = b0 + b1 + + bk k .The algorithm is based on the remainder theorema() = b()q() + r()deg r() < deg b().
(6.28)
Any polynomial dividing a() and b() clearly divides as well r() and conversely, any polynomialdividing b() and r() divides as well a(). Hencegcd(a, b) = gcd(b, r)
(6.29)
but meanwhile we are dealing with polynomials b() and r() of smaller degree. This is appliedrecursively as followsa1 () := a(); b1 () := b(); i = 1145
while ri () 0
ri () := ri () bi ()qi ();
(6.30)
When r() = 0 we clearly have gcd(a, b) = b(), which yields the stopping criterion. This algorithmhas complexity O(n2 ). In order to show this we look at the generic case, i.e., for randompolynomials a() and b(). For such polynomials the degree of ri () decreases by 1 at each step,and each polynomial division involves a quotient qi () of degree 1:(i)
ai () = bi ()(q0 + q1 ) + ri (),
(6.31)
i.e., ai () has degree (k i + 1) and bi () has degree (k i). The number of flops involved incomputing ri () in (6.31) is easily checked to be 2(k i), and since this is performed at most ksteps, we have a total complexity ofkXi=1
2(k 1) = k 2 + o(k)
(6.32)
flops. When the quotients happen to be of higher degree one shows that the complexity does infact not exceed this simple bound.RemarkSince g() is the gcd of a() and b() we havea() = a()g();
b() = b()g()
(6.33)
where gcd(a, b) = 1. Since a() and b() are now coprime, it is well known [5] that there exist
(6.34)
a() c()b() d()
g()0
[1] =
a()b()
(6.35)
where the left polynomial matrix has determinant 1. This is nothing but the Smith form of the2 1 polynomial matrix [a(), b()]T .The above connection seems to indicate that, just as the Smith decomposition, this algorithmmust be unstable in general. This is indeed the case and polynomials of relatively low order146
(namely 6th order) were constructed where all 16 digits get corrupted during the calculations ofthe Euclidean algorithm [4].The fact that the gcd algorithm is O(n2 ) can also nicely be interpreted in terms of the 2k 2kmatrix
S2k
a0 a1 . . . b0 b1 . . .
0 a 0 a1
= 0 b0 b1 .. . . . . ...
0 ... 00 ... 0
akbk
. . . ak
. . . bk0
.. .. ..... 0
a 0 a1 . . . ak b0 b1 . . . bk
(6.36)
which is also known as the Sylvester matrix (up to a row permutation). Notice that this is in fact ablock Toeplitz matrix. If the gcd g() has degree ` > 0 then this matrix S2k has the factorization:
0 a0 a1
... ak
a0 a1 . . . ak b0 b1 . . . bk
g0 . . . g`...0.. . . . ....0 ... 0
0 . . . g`
0 ..... .......g0
(6.37)
where the inner dimension of this factorization is 2k `. This identity is easily checked from thepolynomial equations (6.33), and it implies that the nullity (or rank defect) of S 2k is at least `.In [38], [5] it is shown that is actually equal to `. This result again links the gcd problem to that ofthe rank of a matrix and therefore also to the singular values of a matrix. It then follows that thegcd of random polynomials is generically 1 (or its degree 0) since S 2k has generically full rank2k. The gcd problem should thus be rephrased as follows: given two polynomials a() and b(),how close are they to having a nontrivial gcd g() of degree larger than 0? This is answered bylooking at how close S2k is to the matrices of lower rank and hence in values singular values of S2k .The Euclidean algorithm in fact amounts to a fast Gaussian elimination on S 2k yielding thedecomposition (6.36). It is unstable because no pivoting is allowed in the algorithm and it does notcompute singular values as in fact desired. The singular value decomposition on the other hand isslow, namely of the order of 80 k 3 on the 2k 2k matrix S2k . Rank revealing factorizations of lowercomplexity than the SVD approach were considered in [4] but the problem of finding a reliable andfast algorithm for estimating how close a() and b() are to having a nontrivial gcd is still open.Let us point out here that computing the roots a() and b() and comparing those, does not solvethis problem since roots may be badly conditioned.147
RemarkThe gcd problem is equivalent to that of finding the uncontrollable part of a corresponding realization
1a0b0
. ....(6.38)
, B = .. ..1 ak1bk1where we assumed deg b() < deg a() and a() monic. The corresponding closeness problem hereis to find how close this (A, b) is to an uncontrollable one.
A second problem involving polynomials for which now there exist a fast and reliable algorithm,is that of spectral factorization. Here one starts from a polynomial (which is positive real):z() = z0 + z1 + + zk k
(6.39)
(6.40)
(6.41)
(6.42)
(6.43)
This problem is known to be equivalent to that of Riccati equations. The function () has zerosthat are symmetric with respect to the unit circle just as the eigenvalue problem of the discrete timeRiccati equation. The positive realness condition (6.43) guarantees that thee always exist a solutionr() to (6.41). In fact r() is the polynomial that groups all the stable zeros of () = ().In [146] a fast algorithm was developed to construct r(). It starts from an initial guess r 0 () thatis an arbitrary stable polynomial. Then it iterates as follows:ri+1 () =
ri () + si ()2
(6.44)
wheresi ()ri () + ri ()si () = 2().
(6.45)
(6.46)
and equating() = (ri () + ())(ri () + ())
(6.47)
we find() = ri ()ri () + ()ri () + ri ()() + ()().
(6.48)
Now this is a quadratic equation in () but when we assume () to be small (i.e., having smallcoefficients), then we can approximate this well by deleting the quadratic term and solving for acorrection i () at step i:.i ()ri () + ri ()i () = () ri ()ri () = ().
(6.49)
This is obviously a Newton step for solving (6.48), and it is the same as (6.44), (6.45) by substitutingsi () = ri () + 2i ().
(6.50)
The advantage of (6.45) over (6.49) is that the right hand side in (6.45) does not have to becomputed at each step. What can we say about the complexity of this scheme? First of all thecomplexity of one iteration step is O(k 2 ) where k is the order of the polynomials z(), ri () andSi (). This follows from the fact that the linear equation (6.45) has a structure related to that ofToeplitz matrices (see [146], [76]). The number of steps involved in the iterative process is typicallyvery low and independent of k (say 4 or 5 steps). The reason for this is that the Newton iterationis quadratically convergent (see [76]). So the overall algorithm is still O(n 2 ).The numerical accuracy of the algorithm this time is quite satisfactory. The reason for this isthat the Newton correction i () or si () is computed at each step from the residual ()for the current approximate solution solution ri (). In other words, even if i () is not computedvery accurately, this is not crucial since the next Newton step will be to evaluate () first andcompute an additional correction from there on. It turns out that the fast solver for (6.45) mayindeed suffer from loss of accuracy, but the iterative algorithm in a sense absorbs these errors.This of course does not guarantee that accurate results are always obtained. Indeed, the spectralfactorization problem may be poorly conditioned in which case any algorithm will yield poor results.Because of the link of this problem to that of Riccati equations it is known that the spectralfactorization problem has a bad condition number when some of the zeros of () are close tothe unit circle. Because of symmetry, () then also has almost double zeros which have to beseparated in r() and r (). It is well known that the Newton Raphson scheme, which is in fact aspecial case of this algorithm also will have problems.We note here that both the gcd problem and spectral factorization problem could have beensolved as well by just using a root finder. For the gcd of a() and b() one would just computethe roots of these two polynomials and check if there are any common ones. Obviously, this willnot work in practice since roots may be sensitive to perturbations. For the spectral factorizationproblem one could just find the roots of the polynomial k . () and choose the stable ones togo in the factor r(). This approach would destroy the symmetry in this problem and may givenan incorrect degree of r() if some of the roots are close to the unit circle again. So the abovealgorithm in general is more reliable.149
6.5
Conclusion
In this chapter we showed that for polynomial models you typically tend to have a compacterrepresentation of your model and therefore also faster algorithms.This is typically the case for SISO system where the model and the design/analysis algorithmsinvolve only two polynomials. These algorithms are then usually linked to root finding or to thePade, Schur or Euclidean algorithm. Each of these is O(k 2 ) in complexity versus O(k 3 ) for acomparable algorithm in state-space form. The numerical stability of these algorithms on the otherhand is often questionable and has to be analyzed carefully. We showed here that the Euclideanalgorithm is unstable and showed the same for the Padealgorithm earlier. But ideas of iterativerefinement or look ahead schemes may salvage these algorithms without sacrificing their speed. Anexample of this is the look ahead Padescheme.For polynomial matrices the advantages are less obvious as far as complexity is concerned andstability problems are worse. Therefore we recommend to use state-space realizations instead. E.g.for the simple problem of finding the zeros of a polynomial matrix P (), the state-space approachis still the only reliable method around [139].
150
Bibliography[1] B. D. O. Anderson and J. B. Moore. Optimal Filtering. Prentice-Hall, Englewood Cliffs, NJ, 1979.[2] E. Anderson, Z. Bai, C. Bischof, J. Demmel, J. Dongarra, J. DuCroz, A. Greenbaum, S. Hammarling,A. McKenney, S. Ostrouchov, and D. Sorenson. LAPACK Users Guide. SIAM, Philadelphia, PA,1992.[3] G. S. Axelby, A. J. Laub, and E. J. Davison. Further discussion on the calculation of transmissionzeros. Automatica, 14:403405, 1978.[4] P. Bailey. A theoretical analysis of greatest common divisor algorithms. Masters thesis, University ofIllinois, Urbana, IL, 1993.[5] S. Barnett. Polynomials and Linear Control Systems. Dekker Inc., New York, NY, 1983.[6] R. Barrett, M. Berry, T. Chan, J. Demmel, J. Donatoand J. Dongarra, V. Eijkhout, R. Pozo,C. Romine, and H. van der Vorst. Templates for the solution of linear systems: building blocksfor iterative methods. SIAM, NEED VOLUME(NEED NUMBER):NEED PAGES, NEED MONTH1993.[7] R. H. Bartels and G. W. Stewart. Solution of the matrix equation AX + XB = C. Communicationsof the ACM, 15(9):820826, September 1972.[8] R. Bellman. Some inequalities for the square root of a positive definite matrix. Linear Algebra and itsApplications I, pages 321324, 1968.[9] P. Benner, V. Mehrmann and H. Xu. A numerically stable, structure preserving method for computingthe eigenvalues of real Hamiltonian or symplectic pencils. Numer. Math. 78:329358, 1998.[10] G. J. Bierman. Factorization Methods for Discrete Sequential Estimation. Academic Press, New York,NY, 1977.[11] G. J. Bierman and C. L. Thornton. Numerical comparison of Kalman filter algorithmsorbit determination case study. Automatica, 13(2335), 1977.[12] D. L. Boley. On Kalmans procedure for the computation of the controllable/observable canonicalform. SIAM J. Control & Optimization., 18(6):624626, November 1980.[13] R. Byers. Numerical condition of the algebraic Riccati equation. Contemp. Math. 47:3549, 1985.[14] C. Brezinski. History of continued fractions and Pade approximants. Springer-Verlag, Berlin, 1991.[15] H. Brezinski and O. Pade, editors. Librairie Scientifique et Technique A. Blanchard, Paris, 1984.[16] A. Bultheel. Error analysis of incoming and outgoing schemes for the trigonometric moment problem.In Van Rossum and de Bruin, editors, Lecture notes in Mathematics, pages 100109. Springer-Verlag,Berlin, 1980.[17] S. Cabay and R. Meleshko. A weakly stable algorithm for pade approximants and the inversion ofhankel matrices. SIAM Matr. Anal. & Appl., 14:735765, 1993.
151
152
[40] J. D. Gardiner, A. J. Laub, J. J. Amato, and C. B. Moler. Solution of the Sylvester matrix equationAXB T + CXD T = E. ACM Trans. Math. Software, 18:223231, 1992.[41] W. M. Gentleman and H. T. Kung. Matrix triangularization by systolic arrays. In Proceedings of theSPIE, Real Time Signal Processing IV, volume 298, pages 1926, 1981.[42] W. M. Gentleman. Least squares computation by Givens transformations without square roots. JIMA,vol 12, pages 329336, 1973.[43] G. H. Golub and W. Kahan. Calculating the singular values and pseudo-inverse of a matrix. SIAM J.Numer. Anal., 2:205224, 1965.[44] G. H. Golub, S. Nash, and C. Van Loan. A Hessenberg-Schur method for the problem AX + XB = C.IEEE Trans. Automat. Control, AC-24(6):909913, December 1979.[45] G. H. Golub and C. Reinsch. Singular value decomposition and least squares solutions. Numer. Math,14:403420, 1970.[46] G. H. Golub and C. Van Loan. Matrix Computations, 2nd ed. Johns Hopkins University Press,Baltimore, MD, 1989. First Edition.[47] G. H. Golub and J. H. Wilkinson. Note on the iterative refinement of least squares solution. Numer.Mathematik, 9:139148, 1966.[48] G. H. Golub and J. H. Wilkinson. Ill-conditioned eigensystems and the computation of the Jordancanonical form. SIAM Rev., 18:579619, 1976.[49] G. Golub, B. Kagstrom, and P. Van Dooren. Direct block tridiagonalization of single-input singleoutput systems. Systems & Control Letters, 18:109120, 1992.[50] W. Gragg and A. Lindquist. On the partial realization problem. Linear Algebra & Applications,50:277319, 1983.[51] E. Grimme, D. Sorensen, and P. Van Dooren. Mode reduction of large, sparse systems via an implicitlyrestarted Lanczos method. Submitted to the 1994 American Control Conf., Baltimore, MD, 1993.[52] M. T. Heath, A. J. Laub, C. C. Paige, and R. C. Ward. Computing the singular value decompositionof a product of two matrices. SIAM Journal of Science Stat. Computer, 7(4):11471159, October 1986.[53] D. Heller. A survey of parallel algorithms in numerical linear algebra. SIAM Review, 20(4):740777,October 1978.[54] P. Henrici. Essentials of Numerical Analysis. Wiley, New York, NY, 1982.[55] G. Hewer and C. Kenney. The sensitivity of the stable Lyapunov equation. SIAM J. Contr. Optim.26:321344, 1988.[56] B. L. Ho and R. E. Kalman. Effective construction of linear state-variable models from input/outputfunctions. Regelungstechnik, 14:545548, 1966.[57] R. A. Horn and C. R. Johnson. Matrix Analysis. Cambridge University Press, 1985.[58] R. A. Horn and C. R. Johnson. Topics in Matrix Analysis. Cambridge University Press, 1991.[59] A. S. Householder. The Theory of Matrices in Numerical Analysis. Dover, New York, NY, 1964.[60] I. M. Jaimoukha and E. M. Kasenally. Oblique projection methods for large scale model reduction.To appear, 1993.[61] A. H. Jazwinski. Stochastic Processes and Filtering Theory. Academic, New York, NY, 1970.[62] R. L. Johnson. Numerical Methods: A Software Approach. Wiley, New York, NY, 1982.
153
[63] D. Kahaner, C. Moler, and S. Nash. Numerical Methods and Software. Prentice Hall, Englewood Cliffs,NJ, 1989.[64] T. Kailath. Some new algorithms for recursive estimation in constant linear systems. IEEE Transactionon Information Theory, IT-19(6):750760, 1973.[65] T. Kailath. Linear Systems. Prentice-Hall, Englewood Cliffs, NJ, 1980.[66] R. E. Kalman. A new approach to linear filtering and prediction problems. Trans. ASME. (J. BasicEng.), 92D:3445, March 1960.[67] P. G. Kaminski, A. Bryson, and S. Schmidt. Discrete square root filteringa survey of curren techniques. IEEE Trans. Automat. Control, AC-16:727736, December 1971.[68] J. Kautsky, N. K. Nichols, and P. Van Dooren. Robust pole assignment in linear state feedback. Int.J. Control, 41(5):11291155, 1985.[69] C. Kenney and G. Hewer. The sensitivity of the algebraic and differential Riccati equations. SIAM J.Contr. Optim. 28:5069, 1990.[70] G. Klein and B. Moore. Eigenvalue-generalized eigenvector assignment with state feedback. IEEEAut. Contr., AC-22:140141, 1977.[71] V. C. Klema and A. J. Laub. The singular value decomposition: Its computation and some applications.IEEE Trans. Automat. Control, AC-25(2):16476, April 1980.[72] E. G. Kogbetliantz. Solutions of linear equations by diagonalization of coefficient matrix. Quart. Appl.Math., 13:123132, 1956.[73] M. M. Konstantinov, P. H. Petkov, and N. D. Christov. Synthesis of linear systems with desiredequivalent form. J. Computat. Appl. Math., 6:2735, 1980.[74] M. M. Konstantinov, P. H. Petkov, and N. D. Christov. Sensitivity analysis of of the feedback synthesisproblem. IEEE Trans. Aut. Contr., 42:568573, 1997.[75] M. Konstantinov, P. Petkov, and D. Gu. Improved perturbation bounds for general quadratic matrixequations. Numer. Func. Anal. Optim., 20:717736, 1999.[76] V. Kucera. Discrete Linear Control: The Polynomial Equation Approach. John Wiley, New York, NY,1979.[77] I. D. Landau. Adaptive Control: The Model Reference Approach. Marcel Dekker, New York, NY, 1979.[78] C. L. Lawson and R. J. Hanson. Solving Least Squares Problems. Prentice Hall, Englewood Cliffs, NJ,1974.[79] R. E. Lord, J. S. Kowalik, and S. P. Kumar. Solving linear algebraic equations on a MIMD computer.In Proceedings of the 1980 Int. Conf. on Parallel Proc., pages 205210, 1980.[80] D. G. Luenberger. Observers for multivariable systems. IEEE Trans. Automat. Control, AC-11:190197, 1966.[81] F. T. Luk. A rotation method for computing the QR factorization. SIAM J. Sci. Stat. Comput.,7:452459, 1986.[82] J. Makhoul. Linear prediction: a tutorial review. Proc. IEEE, 63:561580, 1975.[83] T. Manteuffel. Adaptive procedure for estimating parameters for the nonsymmetric Tchebychev iteration. Numer. Math., 31:183208, 1978.[84] R. S. Martin and J. H. Wilkinson. Similarity reduction of a general matrix to Hessenburg form. Numer.Math, 12:349368, 1968.
154
[85] J. L. Massey. Shift register synthesis of BCH decoding. IEEE Trans. Inf. Th., IT-15:122127, 1969.[86] V. Mehrmann. The Autonomous Linear Quadratic Control Problem. Lecture Notes in Control andInformation Sciences. Springer-Verlag, Heidelberg, 1991.[87] V. Mehrmann and H. Xu. An analysis of the pole placement problem I. Electr. Trans. Numer. Anal.,4:89105, 1996.[88] V. Mehrmann and H. Xu. An analysis of the pole placement problem II. Electr. Trans. Numer. Anal.,5:7797, 1997.[89] J. Mendel. Computational requirements for a discret Kalman filter. IEEE Trans. Automat. Control,AC-16(6):748758, 1971.[90] W. Miller and C. Wrathall. Software for Roundoff Analysis of Matrix Algorithms. Academic Press,New York, NY, 1980.[91] G. Miminis and C. C. Paige. An algorithm for pole assignment of time invariant linear systems. Int.J. Contr., 35:341345, 1982.[92] G. S. Miminis and C. C. Paige. A direct algorithm for pole assignment of time-invariant multi-inputlinear systems using state feedback. Automatica, 24:343356, 1988.[93] P. Misra and R. V. Patel. Numerical algorithms for eigenvalue assignment by constant and dynamicoutput feedback. IEEE Trans. Automat. Contr., 34:579588, 1989.[94] J. J. Modi. Parallel Algorithms and Matrix Computations. Oxford University Press, Oxford, England,1988.[95] C. Moler and C. Van Loan. Nineteen dubious ways to compute the exponential of a matrix. SIAMReview, 20(4):801836, October 1978.[96] C. B. Moler and G. W. Stewart. An algorithm for generalized matrix eigenvalue problems. SIAMJournal of Numerical Analysis, 10(2):241256, April 1973.[97] M. Moonen, B. De Moor, L. Vandenberghe, and J. Vandewalle. On- and off-line identification of linearstate-space models. Int. J. Contr., 49:219232, 1989.[98] M. Morf and T. Kailath. Square-root algorithms for least squares estimation. IEEE Trans. Automat.Control, AC-20:487497, August 1975.[99] C. Mullis and R. Roberts. Synthesis of minimum roundoff noise fixed point digital filters. IEEE Trans.Circuits and Systems, CAS-23:551562, 1976.[100] C. Oara, R. Stefan and P. Van Dooren. Maximizing the stability radius. In Proceed. Americ. Contr.Conf., TP06-5, pages 30353040, 2001.[101] A. M. Ostrowski. On the spectrum of a one-parametric family of matrices. Journal fur die Reine undAngewandte Mathematik, 193:143160, 1954.[102] C. C. Paige. Properties of numerical algorithms related to computing controllability. IEEE Trans.Automat. Control, AC-26(1):130138, February 1981.[103] C. C. Paige. Practical use of the symmetric Lanczos process with reorthogonalization. BIT, 10:183195,1970.[104] C. C. Paige. Covariance matrix representation in linear filtering. Special Issue of ContemporaryMathematics on Linear Algebra and its Role in Systems Theory, AMS, 1985.[105] T. Pappas, A. J. Laub, and N. R. Sandell, Jr. On the numerical solution of the discrete-time algebraicRiccati equation. IEEE Trans. Automat. Control, AC-25(4):631641, August 1980.
155
[106] B. Parlett. Reduction to tridiagonal form and minimal realizations. SIAM J. Matrix Anal. Appl.,13:567593, 1992.[107] B. N. Parlett. The Symmetric Eigenvalue Problem. Prentice-Hall, Englewood Cliffs, NJ, 1980.[108] L. Pernebo and L. M. Silverman. Model reduction via balanced state space representations. IEEETrans. Automat. Control, AC-27(2):382387, April 1982.[109] P. Petkov, N. Christov and M. Konstantinov. Computational Methods for Linear Control Systems.Prentice-Hall, Englewood Cliffs, NJ, 1991.[110] J. R. Rice. A theory of condition. SIAM J. Numer. Anal., 3:287310, 1966.[111] J. R. Rice. Matrix Computations and Mathematical Software. McGraw-Hill, New York, NY, 1981.[112] J. R. Rice. Numerical Methods, Software, and Analysis. McGraw-Hill, New York, NY, 1983.[113] J. Rissanen. Recursive identification of linear systems. SIAM J. Control, 9:420430, 1971.[114] H. Rosenbrock. State-space and multivariable theory. Wiley, New York, NY, 1970.[115] Y. Saad. Numerical methods for large scale problems. Manchester Univ Press, Manchester UK, 1992.[116] A. P. Sage and C. C. White. Optimum systems control. Prentice Hall, Englewood Cliffs, 1977.[117] A. H. Sameh and D. J. Kuck. On stable parallel linear system solvers. J. Assoc. Comput. Mach.,25:8191, 1978.[118] L. M. Silverman. Representation and realization of time-variable linear systems. PhD thesis, ColumbiaUniversity, New York, NY, 1966. Dept. El. Eng.[119] V. Sima. Algorithms for Linear Quadratic Optimization. Marcel Dekker Inc. New York, 1996.[120] B. T. Smith, J. M. Boyle, J. J. Dongarra, B. S. Garbow, Y. Ikebe, V. C. Klema, and C. B. Moler.Matrix Eigensystem RoutinesEISPACK Guide, chapter 6. Springer-Verlag, New York, 2nd edition,1976. Lecture Notes in Control and Information Sci.[121] D. C. Sorensen. Implicit application of polynomial filters in a K-step Arnoldi method. SIAM J. MatrixAnal. Appl., 13:357385, 1992.[122] G. W. Stewart. Error and perturbation bounds associated with certain eigenvalue problems. SIAMReview, 15:727764, 1973.[123] G. W. Stewart. Introduction to Matrix Computations. Academic Press, New York, NY, 1973.[124] G. W. Stewart. Algorithm 506 - HQR3 and EXCHNG: Fortran subroutines for calculating and orderingthe eigenvalues of a real upper Hessenberg matrix. ACM Trans. Math. Software, 2:275280, 1976.[125] G. W. Stewart. On the perturbation of pseudo-inverses, projections, and linear least squares. SIAMRev., 19:634662, 1977.[126] G. W. Stewart. Rand degeneracy. SIAM J. Numer. Anal., 5:403413, 1984.[127] G. W. Stewart and J. G. Sun. Matrix Perturbation Theory. Academic Press, New York, NY, 1990.[128] J. Stoer and R. Bulirsch. Introduction to Numerical Analysis. Springer-Verlag, New York, NY, 1980.[129] E. C. Y. Tse, J. V. Medanic, and W. R. Perkins. Generalized Hessenberg transformations for reducedorder modeling of large-scale systems. Int. J. Control, 27(4):493512, April 1978.[130] A. van der Sluis. Stability of the solution of linear least squares problems. Numerische Mathematik,23:241254, 1975.[131] P. Van Dooren. The computation of Kroneckers canonical form of a singular pencil. Lin. Alg. Appl.,27:103141, 1979.
156
[132] P. Van Dooren. Computing the eigenvalues of a polynomial matrix. In Proceedings of the IBM-NFWOSymposium, pages 213223, Brussels, Belgium, December 1979.[133] P. Van Dooren. A generalized eigenvalue approach for solving Riccati equations. SIAM J. Sci. Stat.Comput., 2(2):121135, June 1981. Erratum in Vol.4, No. 4, Dec. 83.[134] P. Van Dooren. Deadbeat control, a special inverse eigenvalue problem. BIT, 24:681699, December1984.[135] P. Van Dooren. Reduced order observers: A new algorithm and proof. Systems & Control Lett.,4:243251, July 1984.[136] P. Van Dooren. Comments on minimum-gain minimum-time deadbeat controllers. Systems & ControlLetters, 12:9394, 1989.[137] P. Van Dooren. Numerical aspects of system and control algorithms. Journal A, 30:2532, 1989.[138] P. Van Dooren. Upcoming numerical linear algebra issues in systems and control theory, September1992.[139] P. Van Dooren and P. Dewilde. The eigenstructure of an arbitrary polynomial matrix: Computationalaspects. Lin. Alg. & Appl., 50:545580, 1983.[140] P. Van Dooren and M. Verhaegen. On the use of unitary state-space transformations. In B. N.Datta, editor, Linear Algebra and its Role in Linear Systems Theory, chapter 47, pages 447463. AMSContemporary Mathematics Series, Providence, RI, 1985.[141] P. M. Van Dooren. The generalized eigenstructure problem in linear system theory. IEEE Trans.Automat. Control, AC-26(1):111129, February 1981.[142] C. F. Van Loan. The sensitivity of the matrix exponential. SIAM J. Numer. Anal., 14:971981, 1977.[143] G. Verghese, P. Van Dooren, and T. Kailath. Properties of the system matrix of a generalized statespace system. Int. J. Control, 30(2):235243, October 1979.[144] M. Verhaegen and P. Van Dooren. Numerical aspects of different Kalman filter implementations. IEEETrans. Automat. Control, AC-31:907917, October 1986.[145] M. Verma. Synthesis of infinity-norm optimal linear feedback systems. PhD thesis, University ofSouthern California, December 1985.[146] Z. Vostry. New algorithm for polynomial spectral factorization with quadratic convergence. Kybernetika, 11:415422, 1975.[147] J. H. Wilkinson. Rounding Errors in Algebraic Processes. Princeton Hall, Englewood Cliffs, NJ, 1963.[148] J. H. Wilkinson. The Algebraic Eigenvalue Problem. Oxford, England, Clarendon Press, 1965.[149] J. H. Wilkinson and C. Reinsch. Handbook for Automatic Computation , volume II. Springer-Verlag,New York, NY, 1971.[150] W. M. Wonham. On a matrix equation of stochastic control. SIAM J. Control, 6:681697, 1968.[151] D. Youla and N. Tissi. N-port synthesis via reactance extration, Pt. I. IEEE Int. Conv. Rec., 14:183208, 1966.[152] H. Zeiger and A. McEwen. Approximate linear realizations of given dimension via Hos algorithm.IEEE Trans. Automat. Control, AC-19:153156, 1974.
157
|
https://fr.scribd.com/document/275737129/PVDnotes
|
CC-MAIN-2019-39
|
refinedweb
| 43,966
| 65.22
|
SKWebServiceController provides a barebones networking layer to interact with services returning JSON or images. Check out the SampleProject in the workspace to see some usage examples.
Installation
Cocoapods
Instalation is supported through Cocoapods. Add the following to your pod file for the target where you would like to use SKWebServiceController:
pod 'SKWebServiceController'
Initialization
Initialization requires only a base URL. All requests, except for getImages, will append the supplied endpoint information onto this base URL. The most common implementation is likely to subclass this controller and provide the baseURL. If you have multiple baseURLs, they will each require a separate WebServiceController object. The most common implementation would include a singleton to access the WebServiceController object.
import SKWebServiceController class MyWebServiceController: WebServiceController { static let shared = MyWebServiceController() init() { super.init(baseURL: "") } }
Optionally, a dictionary of default parameters can be passed in. These values are appended to every URL as query parameters after the endpoint.
WebServiceController
The WebServiceController subclass will be used to perform requests. There are methods exposed that facilitate these requests. Each of these requests takes an endpoint and a
RequestConfiguration object to handle header fields and parameters. Additionally, each method returns a URLSessionDataTask object to allow the request to be cancelled midflight.
JSON Methods
These methods are used to interact with endpoints that send and receive JSON. All requests have a
JSONCompletion object that is executed when the request is complete.
Performs a delete request on the provided endpoint.
Get
Performs a get request on the provided endpoint.
Performs a post request on the provided endpoint. This method has an optional json parameter. This object must be a valid JSON object. This will be converted to data and sent with the request.
Put
Performs a put request on the provided endpoint. This method has an optional json parameter. This object must be a valid JSON object. This will be converted to data and sent with the request.
Image Methods
There is currently a single method for getting an image from a URL. This method has an
ImageCompletion object that is executed when the request is complete.
Get Image
Unlike the other methods that take an endpoint string and build the URL dynamically, this method takes the full URL of the remote image. When the method is complete, the image or an error will be returned through the
ImageCompletion object.
RequestConfiguration
The
RequestConfiguration object allows headers and parameters to be set on a per request basis. IIf the same header appears in the RequestConfiguration and the URLSessionConfiguration object, the RequestConfiguration header takes precedence.
Latest podspec
{ "name": "SKWebServiceController", "version": "0.1.0", "license": "MIT", "summary": "A barebones network controller.", "homepage": "", "authors": { "Sean Kladek": "[email protected]" }, "source": { "git": "", "tag": "0.1.0" }, "platforms": { "ios": "9.0" }, "source_files": "Source/*.swift", "pushed_with_swift_version": "3.0" }
Sat, 29 Jul 2017 03:00:04 +0000
|
https://tryexcept.com/articles/cocoapod/skwebservicecontroller
|
CC-MAIN-2017-34
|
refinedweb
| 465
| 51.44
|
General cleanups as part of the libcaps userland threading work.
1: /* 2: * $FreeBSD: src/sys/i386/i386/mplock.s,v 1.29.2.2 2000/05/16 06:58:06 dillon Exp $ 3: * $DragonFly: src/sys/i386/i386/mplock.s,v 1.11 2003/12/04 20:09:31 dillon Exp $ 4: * 5: * Copyright (c) 2003 Matthew Dillon <dillon@backplane.com> 6: * All rights reserved.: * 17: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20: * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR: * DragonFly MPLOCK operation 30: * 31: * Each thread as an MP lock count, td_mpcount, and there is a shared 32: * global called mp_lock. mp_lock is the physical MP lock and contains either 33: * -1 or the cpuid of the cpu owning the lock. The count is *NOT* integrated 34: * into mp_lock but instead resides in each thread td_mpcount. 35: * 36: * When obtaining or releasing the MP lock the td_mpcount is PREDISPOSED 37: * to the desired count *PRIOR* to operating on the mp_lock itself. MP 38: * lock operations can occur outside a critical section with interrupts 39: * enabled with the provisio (which the routines below handle) that an 40: * interrupt may come along and preempt us, racing our cmpxchgl instruction 41: * to perform the operation we have requested by pre-dispoing td_mpcount. 42: * 43: * Additionally, the LWKT threading system manages the MP lock and 44: * lwkt_switch(), in particular, may be called after pre-dispoing td_mpcount 45: * to handle 'blocking' on the MP lock. 46: * 47: * 48: * Recoded from the FreeBSD original: 49: * ---------------------------------------------------------------------------- 50: * "THE BEER-WARE LICENSE" (Revision 42): 51: * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you 52: * can do whatever you want with this stuff. If we meet some day, and you think 53: * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp 54: * ---------------------------------------------------------------------------- 55: */ 56: 57: #include <machine/asmacros.h> 58: #include <machine/smptests.h> /** GRAB_LOPRIO */ 59: #include <machine/apic.h> 60: 61: #include "assym.s" 62: 63: /* 64: * YYY Debugging only. Define this to be paranoid about invalidating the 65: * TLB when we get giant. 66: */ 67: #undef PARANOID_INVLTLB 68: 69: .data 70: ALIGN_DATA 71: #ifdef SMP 72: .globl mp_lock 73: mp_lock: 74: .long -1 /* initialized to not held */ 75: #endif 76: 77: .text 78: SUPERALIGN_TEXT 79: 80: /* 81: * Note on cmpxchgl... exchanges ecx with mem if mem matches eax. 82: * Z=1 (jz) on success. A lock prefix is required for MP. 83: */ 84: NON_GPROF_ENTRY(cpu_get_initial_mplock) 85: movl PCPU(curthread),%ecx 86: movl $1,TD_MPCOUNT(%ecx) /* curthread has mpcount of 1 */ 87: movl $0,mp_lock /* owned by cpu 0 */ 88: NON_GPROF_RET 89: 90: /* 91: * cpu_try_mplock() returns non-zero on success, 0 on failure. It 92: * only adjusts mp_lock, it does not touch td_mpcount. Callers 93: * should always increment td_mpcount *before* trying to acquire 94: * the actual lock, predisposing td_mpcount to the desired state of 95: * the lock. 96: * 97: * NOTE! Only call cpu_try_mplock() inside a critical section. If 98: * you don't an interrupt can come along and get and release 99: * the lock before our cmpxchgl instruction, causing us to fail 100: * but resulting in the lock being held by our cpu. 101: */ 102: NON_GPROF_ENTRY(cpu_try_mplock) 103: movl PCPU(cpuid),%ecx 104: movl $-1,%eax 105: lock cmpxchgl %ecx,mp_lock /* ecx<->mem if eax matches */ 106: jnz 1f 107: #ifdef PARANOID_INVLTLB 108: movl %cr3,%eax; movl %eax,%cr3 /* YYY check and remove */ 109: #endif 110: movl $1,%eax 111: NON_GPROF_RET 112: 1: 113: subl %eax,%eax 114: NON_GPROF_RET 115: 116: /* 117: * get_mplock() Obtains the MP lock and may switch away if it cannot 118: * get it. This routine may be called WITHOUT a critical section 119: * and with cpu interrupts enabled. 120: * 121: * To handle races in a sane fashion we predispose TD_MPCOUNT, 122: * which prevents us from losing the lock in a race if we already 123: * have it or happen to get it. It also means that we might get 124: * the lock in an interrupt race before we have a chance to execute 125: * our cmpxchgl instruction, so we have to handle that case. 126: * Fortunately simply calling lwkt_switch() handles the situation 127: * for us and also 'blocks' us until the MP lock can be obtained. 128: */ 129: NON_GPROF_ENTRY(get_mplock) 130: movl PCPU(cpuid),%ecx 131: movl PCPU(curthread),%edx 132: incl TD_MPCOUNT(%edx) /* predispose */ 133: cmpl %ecx,mp_lock 134: jne 1f 135: NON_GPROF_RET /* success! */ 136: 137: /* 138: * We don't already own the mp_lock, use cmpxchgl to try to get 139: * it. 140: */ 141: 1: 142: movl $-1,%eax 143: lock cmpxchgl %ecx,mp_lock 144: jnz 2f 145: #ifdef PARANOID_INVLTLB 146: movl %cr3,%eax; movl %eax,%cr3 /* YYY check and remove */ 147: #endif 148: NON_GPROF_RET /* success */ 149: 150: /* 151: * Failure, but we could end up owning mp_lock anyway due to 152: * an interrupt race. lwkt_switch() will clean up the mess 153: * and 'block' until the mp_lock is obtained. 154: */ 155: 2: 156: call lwkt_switch 157: #ifdef INVARIANTS 158: movl PCPU(cpuid),%eax /* failure */ 159: cmpl %eax,mp_lock 160: jne 4f 161: #endif 162: NON_GPROF_RET 163: #ifdef INVARIANTS 164: 4: 165: cmpl $0,panicstr /* don't double panic */ 166: je badmp_get2 167: NON_GPROF_RET 168: #endif 169: 170: /* 171: * try_mplock() attempts to obtain the MP lock. 1 is returned on 172: * success, 0 on failure. We do not have to be in a critical section 173: * and interrupts are almost certainly enabled. 174: * 175: * We must pre-dispose TD_MPCOUNT in order to deal with races in 176: * a reasonable way. 177: * 178: */ 179: NON_GPROF_ENTRY(try_mplock) 180: movl PCPU(cpuid),%ecx 181: movl PCPU(curthread),%edx 182: incl TD_MPCOUNT(%edx) /* pre-dispose for race */ 183: cmpl %ecx,mp_lock 184: je 1f /* trivial success */ 185: movl $-1,%eax 186: lock cmpxchgl %ecx,mp_lock 187: jnz 2f 188: /* 189: * Success 190: */ 191: #ifdef PARANOID_INVLTLB 192: movl %cr3,%eax; movl %eax,%cr3 /* YYY check and remove */ 193: #endif 194: 1: 195: movl $1,%eax /* success (cmpxchgl good!) */ 196: NON_GPROF_RET 197: 198: /* 199: * The cmpxchgl failed but we might have raced. Undo the mess by 200: * predispoing TD_MPCOUNT and then checking. If TD_MPCOUNT is 201: * still non-zero we don't care what state the lock is in (since 202: * we obviously didn't own it above), just return failure even if 203: * we won the lock in an interrupt race. If TD_MPCOUNT is zero 204: * make sure we don't own the lock in case we did win it in a race. 205: */ 206: 2: 207: decl TD_MPCOUNT(%edx) 208: cmpl $0,TD_MPCOUNT(%edx) 209: jne 3f 210: movl PCPU(cpuid),%eax 211: movl $-1,%ecx 212: lock cmpxchgl %ecx,mp_lock 213: 3: 214: subl %eax,%eax 215: NON_GPROF_RET 216: 217: /* 218: * rel_mplock() releases a previously obtained MP lock. 219: * 220: * In order to release the MP lock we pre-dispose TD_MPCOUNT for 221: * the release and basically repeat the release portion of try_mplock 222: * above. 223: */ 224: NON_GPROF_ENTRY(rel_mplock) 225: movl PCPU(curthread),%edx 226: movl TD_MPCOUNT(%edx),%eax 227: #ifdef INVARIANTS 228: cmpl $0,%eax 229: je badmp_rel 230: #endif 231: subl $1,%eax 232: movl %eax,TD_MPCOUNT(%edx) 233: cmpl $0,%eax 234: jne 3f 235: movl PCPU(cpuid),%eax 236: movl $-1,%ecx 237: lock cmpxchgl %ecx,mp_lock 238: 3: 239: NON_GPROF_RET 240: 241: #ifdef INVARIANTS 242: 243: badmp_get: 244: pushl $bmpsw1 245: call panic 246: badmp_get2: 247: pushl $bmpsw1a 248: call panic 249: badmp_rel: 250: pushl $bmpsw2 251: call panic 252: 253: .data 254: 255: bmpsw1: 256: .asciz "try/get_mplock(): already have lock! %d %p" 257: 258: bmpsw1a: 259: .asciz "try/get_mplock(): failed on count or switch %d %p" 260: 261: bmpsw2: 262: .asciz "rel_mplock(): mpcount already 0 @ %p %p %p %p %p %p %p %p!" 263: 264: #endif 265:
|
http://www.dragonflybsd.org/cvsweb/src/sys/i386/i386/Attic/mplock.s?f=h;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.11
|
CC-MAIN-2014-10
|
refinedweb
| 1,320
| 69.01
|
How to get video preview from QProcess to fill a rectangle in qml
Hi!
I have a c++ class, where I am initiating QProcess in detached mode. This process launches a python script to get raspberry pi camera preview.
How can I get that preview and show it in a rectangle element?
The c++ function is a void type. Should it be some other type? You can make a QString function to return a QString, but there is no QProcess type.
I would appreciate any help. Thanks
@Kachoraza you should provide more details about your runtime environment, i.e.
is the python script running on the RPi device, or is just connecting remotely?
the python script is running on the pi.yes the python script is running on the pi locally.
@Kachoraza and what about the Qt application using QProcess?
it is also running locally on the pi
@Kachoraza so what about driving the Pi camera directly from your QML app? just for instance this guide
thanks. I will check it
I tried to access the camera through Camera element and VideoOutput element. Camera status is 2, which I cannot understand.
Camera {
id: mycamera
Component.onCompleted: { console.log(cameraStatus); mycamera.start() console.log(cameraStatus); } }
I tried it on pi and on ubuntu as well
@Pablo-J-Rogina I am trying to get camera preview with the following code, but all I have is a white window. Can you please see what am I doing wrong here. I have tried it on pi and ubuntu with no errors, but similar result. Thanks in advance
import QtQuick 2.9
import QtQuick.Window 2.3
import QtMultimedia 5.9
import QtQuick.Controls 2.2
Window {
id: window
width: 640
height: 480
property alias window: window
property alias videooutput: videooutput
visible: true
property Camera camera: Camera {
id: camera
captureMode: Camera.CaptureViewfinder
cameraState: Camera.ActiveState
Component.onCompleted: {
camera.start()
if(cameraState === Camera.ActiveState){
console.log("Camera ready")
}
}
}
VideoOutput {
id: videooutput
anchors.fill: parent
source: camera
focus: visible
enabled: true
Component.onCompleted: {
console.log(camera.cameraState)
}
}
}
|
https://forum.qt.io/topic/93936/how-to-get-video-preview-from-qprocess-to-fill-a-rectangle-in-qml/8
|
CC-MAIN-2019-43
|
refinedweb
| 340
| 60.92
|
I have the following Java code
public class Base {
private static boolean goo = true;
protected static boolean foo() {
goo = !goo;
return goo;
}
public String bar = "Base:" + foo();
public static void main(String[] args) {
Base base = new Sub();
System.out.println(base.bar);
}
}
public class Sub extends Base {
public String bar = "Sub:" + foo();
}
Base:false
Sub:true
...which shows base having two variables with the same name!
Yup!
base is a reference to a
Sub instance, and that
Sub instance has two
bar fields. Let's call them
Base$bar and
Sub$bar:
+------------------------+ base--->| Sub instance | +------------------------+ | Base$bar: "Base:false" | | Sub$bar: "Sub:true" | +------------------------+
Java allows for the same name being used at different levels in an instance's type hierarchy. (It has to: Frequently these are private fields, and so a subclass may not even know that the superclass has one with the same name.)
Those two different fields in the instance have different values:
Base$bar has the value
Base:false because it's initialized based on the first-ever call to
foo, which flips
goo (which starts as
true) and using the flipped result.
Sub$bar has the value
Sub:true because it's initialized from a second call to
foo, so
goo is flipped again and the updated value is used. There is only one instance created, but
foo is called twice.
Which one you see when you access
bar depends on the type of the reference you have to the instance. Because
base is declared of type
Base, when you do
base.bar you access the
Base$bar field in the
Sub instance. If you had a
Sub reference to the instance, you'd use
Sub$bar instead:
System.out.println(base.bar); // "Base:false" System.out.println(((Sub)base).bar); // "Sub:true"
|
https://codedump.io/share/pi7NkmQLqj6S/1/initializing-an-instance-variable-in-both-parent-and-child
|
CC-MAIN-2017-04
|
refinedweb
| 297
| 70.84
|
Kubernetes: Certificates, Tokens, Authentication and Service Accounts
Daniel Albuschat
・9 min read
Mostly for personal/learning experiences, I have created quite a few Kubernetes clusters, such as the one on my Raspberry Pi rack. I also created two clusters for a production and a staging environment on ultra-cheap cloud servers from Hetzner Cloud. Luckily, none of those environments where serious business.
Disclaimer: I'm not a Kubernetes expert, nor am I a security expert, so make sure that you second-source the information you find on this post before you rely on them. I just wanted to publish the experience and insights that I made during this trip - thanks!
Why was that lucky?
Because I accidentally leaked the certificates for my admin access to the staging cluster. I was trying to set up a CI/CD pipeline for an open source project using CircleCI. While I was testing out the steps one by one, I dumped the content of
${HOME}/.kube/config that has been created from a BASE64-encoded environment variable, like described on this blog post. That was fatal, though, since a) the job logs of open source projects are publicly visible and b) jobs and their logs can not be deleted manually, I had to reach out to the support for this. Ouch!
So let's dig into what happened here.
Creating a cluster
First of all, I created the cluster manually using
kubeadm, following the official docs. Doing so, I created a cluster with RBAC enabled and a
kube-config has been created for me that includes a user that is identified by a certificate.
Accessing the cluster
After
kubeadm created the cluster successfully, it instructs you what to do to access your cluster:
The
admin.conf that kubeadm creates includes a user identified by a certificate:
- name: kubernetes-admin user: client-certificate-data: <BASE64 ENCODED X509 CERTIFICATE> client-key-data: <BASE64 ENCODED PRIVATE KEY FOR THE CERTIFICATE>
Following these instructions is your only way to access this cluster using
kubectl as of now, so you should go ahead and do this now. After you copied the
admin.conf, you have
cluster-admin access. You are
root, so to say.
How is that?
What
kubeadm did is that it created a new CA (Certificate Authority) root certificate that is the master certificate for your cluster. It looks something like this:
Certificate: Data: Version: 3 (0x2) Serial Number: 0 (0x0) Signature Algorithm: sha256WithRSAEncryption Issuer: CN = kubernetes Validity Not Before: May 19 11:11:04 2019 GMT Not After : May 16 11:11:04 2029 GMT Subject: CN = kubernetes Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: <REDACTED> Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Key Usage: critical Digital Signature, Key Encipherment, Certificate Sign X509v3 Basic Constraints: critical CA:TRUE Signature Algorithm: sha256WithRSAEncryption <REDACTED>
So... it doesn't really contain much besides the info that it is a CA and it's CN (= Common Name) is Kubernetes. That's because this cert only acts as a root for other certs that are used for different purposes on the cluster. You can have a look at
/etc/kubernetes/pki to take a peek at some of the certs that are used in your cluster and have been signed by the CA:
daniel@kube-box:~# ls /etc/kubernetes/pki/ -1 apiserver.crt apiserver-etcd-client.crt apiserver-etcd-client.key apiserver.key apiserver-kubelet-client.crt apiserver-kubelet-client.key ca.crt ca.key etcd front-proxy-ca.crt front-proxy-ca.key front-proxy-client.crt front-proxy-client.key sa.key sa.pub
It is possible to allow access to clients that authenticate themselves using certificates that are trusted by the CA. This is enabled by passing this
ca.crt to
kube-controller-manager in the
--client-ca-file parameter. This is what the docs have to say about it:
--client-ca-file string If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate.
Back to your
kube-config: The certificate that is included in BASE64 in your
admin.conf is signed by that exact CA. This is why it is trusted by the cluster. Let's have a look at the certificate:
grep 'client-certificate-data: ' ${HOME}/.kube/config | \ sed 's/.*client-certificate-data: //' | \ base64 -d | \ openssl x509 --in - --text Certificate: Data: Version: 3 (0x2) Serial Number: 3459994011761527671 (0x30045e38cc064b77) Signature Algorithm: sha256WithRSAEncryption Issuer: CN = kubernetes Validity Not Before: May 12 10:54:39 2019 GMT Not After : May 11 10:54:42 2020 GMT Subject: O = system:masters, CN = kubernetes-admin Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: <REDACTED> Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Key Usage: critical Digital Signature, Key Encipherment X509v3 Extended Key Usage: TLS Web Client Authentication Signature Algorithm: sha256WithRSAEncryption <REDACTED>
What does this cert tell us (and the cluster)?
a) It is issued and trusted by our
kubernetes cluster
b) It identifies the Organisation (
O)
system:masters, which is interpreted as a group by kubernetes
c) It identifies the Common Name (
CN)
kubernetes-admin, which is interpreted as a user by kubernetes
In other words: This certificate logs in as the user
kubernetes-admin with the group
system:masters. This is the reason why you don't need to provide the group name in the
kube-config, and why you can change the user's name at will in the
kube-config, without this changing the actual user that is being logged in.
Where are the permissions defined?
In RBAC-enabled clusters, permissions are defined in
Roles (per namespace) or
ClusterRoles (for all namespaces). These permissions are then granted to objects using
RoleBindings and
ClusterRoleBindings. So what you have to look for are
RoleBindings and
ClusterRoleBindings that grant permissions to the group
system:masters or the user
kubernetes-admin. You can do this by having a look at the output of
kubectl -A=true get rolebindings && kubectl -A=true get clusterrolebindings
The default setup that
kubeadm created for me yielded one hit for that search, the
ClusterRoleBinding named
cluster-admin, which grants permissions to a
ClusterRole with the same name. Here's the definition:
kind: ClusterRole metadata: name: cluster-admin rules: - apiGroups: - '*' resources: - '*' verbs: - '*' - nonResourceURLs: - '*' verbs: - '*' ---: Group name: system:masters
So there we have it! The group
system:masters, which the certificate authorizes as, grants '*' permissions to all resources using all verbs, hence full access.
Unvalidated assumption: I think that users and groups in this case are only defined in the certificates, and new users can be
created by issuing a new certificate with the CommonName set to the desired username and the Organisation set to the desired group. This username and group can then, without further ado, be used in
ClusterRoleBindings and
RoleBindings. I did not take the time to validate this, though, which would be possible by issuing a new certificate using
openssl, signed with the cluster's CA. It'd be great if someone could confirm or debunk this assumption in a comment!
The mystery
So I got this far and found out how the user and group are identified and how permissions are granted to this user and group. My guess then was that when I delete the
ClusterRoleBinding, or rather remove the group
system:masters from it, that the certificate should not have access to the cluster anymore. If I did that, and it had the expected result, I would lose all access to the cluster and would have successfully logged me out for good. So I first added a
serviceaccount and created a
kube-config that logged in using a token for that
serviceaccount and verified that the access worked. We will see later how to do this. Then, after setting the safety net in place, I removed the
system:masters subject from the
ClusterRoleBinding. To my surprise, this did not lock the user out. I could still fully access the cluster using the old
kube-config… maybe someone can explain this behaviour in a comment?
Alternative 1: Replace the CA
One sure-as-hell way to make the leaked certificate useless is to replace the CA in the cluster. This would require a restart of the cluster, though. And it would require to re-issue all the certificates that we have seen above, and maybe some more. I rated the possibility to totally fuck everything up and waste multiple hours on the trip at about 99%, so I abandoned the plan. :-)
Alternative 2: Rebuild the whole cluster
Luckily, it was a staging cluster, so I had plenty of freedom. Before starting my investigations, I powered off all nodes. Then, after not finding a proper solution to only make the leaked certificate useless, I killed the whole cluster using
kubeadm reset rm -rf /etc/kubernetes rm -rf /var/lib/kubelet
And recreated from scratch with kubeadm. (Which is so great, by the way!!)
Then I went ahead and made a few dozen more commits reading 'NOT printing the content of the kube-config anymore', 'Getting CI/CD to work', 'Maybe now it works', 'Uhm what?', 'That gotta work', 'fuck CI/CD', … :-)
Lessons learned: Use service-accounts with tokens
(Or other authentication methods like OpenID, as recommended in this awesome post.)
So my lesson learned is to do what I've seen at the big managed kubernetes providers: Use a service-account and it's access token for authorization. Here I'll show how to set up a super-user that uses a token instead of a cert:
kubectl -n kube-system create serviceaccount admin
To grant super-user permissions, the easiest way is to create a new
ClusterRoleBinding to bind this service-account to the
cluster-admin
ClusterRole:
kubectl create clusterrolebinding add-on-cluster-admin \ --clusterrole=cluster-admin \ --serviceaccount=kube-system:admin
Use your new service-account
Your admin user is now ready and armed. Now we need to log in with this user. I assume that you have the
admin.conf in
${HOME}/.kube/conf. We now want to add the new user, identified by it's token, and add a new context that uses this user:
TOKENNAME=`kubectl -n kube-system get serviceaccount/admin -o jsonpath='{.secrets[0].name}'` TOKEN=`kubectl -n kube-system get secret $TOKENNAME -o jsonpath='{.data.token}' | base64 -d` kubectl config set-credentials admin --token=$TOKEN kubectl config set-context admin@kubernetes --cluster kubernetes --user admin
Now go ahead and try your new, shiny service-account:
kubectl config use-context admin@kubernetes kubectl -n kube-system get all
If this went well, you should go ahead and delete the certificate-based user and the corresponding context:
kubectl config unset users.kubernetes-admin kubectl config delete-context kubernetes-admin@kubernetes
Yay! Now we have a
kube-conf that only includes token-based access. This is great, because it is very easy to revoke that token if this config might be leaked or published.
How to invalidate a leaked token
This is easy! Just delete the secret that corresponds to the user's token. We already saw how to find out which is the correct secret:
kubectl -n kube-system get serviceaccount/admin -o yaml
You will see a field "name" in the "secrets" array. This is a name of a secret that holds this service-account's token. Now go ahead and simply delete it:
kubectl -n kube-system delete secrets/token-admin-xyz123
Then wait a few seconds, and try to access your cluster:
dainel@kube-box:~# kubectl -n kube-system get all error: You must be logged in to the server (Unauthorized)
Wohoo!
But how do you regain access? Well, if you're on your master node, simply copy the
admin.conf back to your
${HOME}/.kube/conf and repeat the steps from "Use your new service-account". Kubernetes will have created and assigned a new token by now.
I hope that this helped, and I'd love to hear feedback, errata, etc. in the comments!
Also make sure to read the VERY comprehensible and awesome post "Kubernetes Security Best-Practices" by Peter Benjamin.
And a big thank you to Andreas Antonsson, vaizki and Alan J Castonguay, who have helped me on the official Kubernetes Slack channel to get a better understanding of what is going on.
Why is Linux Not More Popular on the Desktop?
Picture taken from wikipedia. There are issues when it comes to Linux being mo...
You're Unvalidated Assumption is correct. Kubernetes does not have a database to store usernames, so you can refer to any arbitrary username you want in the Subject of your certificate, k8s will make authorization decisions based on role/bindings given that username.
Oh this is so helpful! I am experimenting with Kubernetes - trying out different auth/custom CA cert scenarios. Thanks for sharing your experience :)
Thanks!
I have been told by multiple sources, however, that using Service Account tokens isn't a silver bullet and not recommended, either O_o
The reason is that the tokens are "ephemeral", whatever that means. I have yet to find out when/why they will be recreated. I personally don't see the disadvantage to certs, though, since you should totally periodically roll your credentials anyways, so I'd suggest to do this with certs, too. But it turns out, as described in the article, that rolling (and therefore invalidating the old) certs is a huge PITA.
It's all still a mystery to me.
|
https://dev.to/danielkun/kubernetes-certificates-tokens-authentication-and-service-accounts-4fj7?utm_campaign=Up%20%26%20Running%20Weekly&utm_medium=email&utm_source=Revue%20newsletter
|
CC-MAIN-2019-35
|
refinedweb
| 2,254
| 51.58
|
In order to promote the use of graph data structures for data analysis, I’ve recently given talks on dynamic graphs: embedding time into graph structures to analyze change. In order to embed time into a graph there are two primary mechanisms: make time a graph element (a vertex or an edge) or have multiple subgraphs where each graph represents a discrete time step. By using either of these techniques, opportunities exist to perform a structural analysis using graph algorithms on time; for example - asking what time is most central to a particular set of relationships.
Graphs are primarily useful to simplify modeling and querying, but they are also useful for visual analytics. While visualizing static graphs with time embedded as a structure requires only standard graph techniques, visualizing dynamic graphs requires some sort of animation or interaction. We are currently exploring these techniques in the District Data Labs dynamic graphs research group. Towards that research, we are proposing to use D3 and SVG for interaction and visualization.
As time moves forward graph elements (vertices and edges) will change, either being added to the graph or removed from them. To support visual analytics, particularly with layouts that will change depending on the nodes that get added (like force directed layouts), these transitions must not be sudden, but instead give visual clues as to what’s going on in the layout. The most obvious choice is to use opacity or size to fade in and out during the transition. However, this does not give the user any sense of how long the node has been on the screen, or how long it has left.
Therefore, I’m interested in creating vertices that have timers associated with them. Inspired by raftscope, I want to create vertices that have a timer that indicates how long they’ve been on the screen. Here is my initial attempt:
The code to do this uses JavaScript with jQuery as well as CSS but no other libraries. To make this work for graphs, we’ll have to find a way to implement this vertex type in D3. But for now, we can just look what’s happening.
First I added an SVG element to the body of my HTML:
<html> <head> <title>Vertex Timer Test</title> </head> <body> <svg id="timer-vertex" xmlns="" version="1.1" xmlns: </svg> </body> </html>
Then add some simple styles with CSS so that you don’t have to manually set them on every single element:
svg { width: 100%; height: 120px; } svg .vertex text { text-anchor: middle; dominant-baseline: central; text-align: center; fill: #FEFEFE; } svg .vertex circle { fill: #003F87; } svg .vertex path { fill: none; stroke: #CF0000; }
For the rest of the work, we’re going to manually add SVG elements with JavaScript, updating their attributes with computed values. To make this easier, a simple function will allow us to create SVG elements in the correct namespace:
function SVG(tag) { var ns = ''; return $(document.createElementNS(ns, tag)); }
We can now use this function to quickly create the elements of our vertex: the circle representing the node, the text representing the label, and the arc representing the timer. First, let’s find the center of the SVG so that we know where to place the vertex, and define other properties like its radius.
// Set the constant arc width var ARC_WIDTH = 6; // Select the svg to place the vertex into var svg = $("#timer-vertex"); // Define the vertex center point and radius vertexSpec = { cx: svg.width() / 2, cy: svg.height() / 2, r: 30, }
Before we can add all of the elements, we need to define the method by which we create the arc. To do this we’re going to create a
path that follows an arc. Creating paths with SVG means defining a
d attribute, which contains a series of commands and parameters that define the shape of the path. The first command is the “move to” command,
M, that specifies where the path begins, e.g.
M50 210 places a point at the coordinates
(50, 210). We then define the arc with the
A command. The
A command is complex, you have to define the x and y radius, axis rotation, sweep flags and an endpoint. However, it is powerful.
In the next snippet we will use the
arcSpec function to create the
d attribute for our path. It returns a string from the spec defining the vertex (the center and radius) as well as the fraction of the circle we want represented on the arc. It also uses another helper function,
circleCoord to determine where points around the circle are located.
function circleCoord(frac, cx, cy, r) { var radians = 2 * Math.PI * (0.75 + frac); return { x: cx + r * Math.cos(radians), y: cy + r * Math.sin(radians), }; } function arcSpec(spec, fraction) { var radius = spec.r + ARC_WIDTH/2; var end = circleCoord(fraction, spec.cx, spec.cy, radius); var s = ['M', spec.cx, ',', spec.cy - radius]; if (fraction > 0.5) { s.push('A', radius, ',', radius, '0 0,1', spec.cx, spec.cy + radius); s.push('M', spec.cx, ',', spec.cy + radius); } s.push('A', radius, ',', radius, '0 0,1', end.x, end.y); return s.join(' '); }
Now that we have these two helper functions in place, we can finally define our elements:
svg.append( SVG('g') .attr('id', 'vertex-1') .attr('class', 'vertex') .append(SVG('a') .append(SVG('circle') .attr('class', 'background') .attr(vertexSpec)) .append(SVG('path') .attr('class', 'timer-arc') .attr('style', 'stroke-width: ' + ARC_WIDTH) .attr('d', arcSpec(vertexSpec, 1.0))) ) .append(SVG('text') .attr('class', 'vlabel') .text('v1') .attr({x: vertexSpec.cx, y: vertexSpec.cy})) );
This is simply a matter of appending various SVG elements together to create the group of shapes that together make up the vertex.
Now to animate, I’ll simply recompute the path of the ARC for a smaller fraction of the vertex at each time step. To do this I’ll use a function that updates the path, then uses
setTimeout to schedule the next update once it’s complete:
function updateArcTimer(elems, spec, current) { var amt = current - 0.015; if (amt < 0) { amt = 1.0; } elems.attr('d', arcSpec(spec, amt)); setTimeout(function() { updateArcTimer(elems, spec, amt) }, 100); }
Playing around with the delay between update (100 ms in this example) and the amount of the arc to reduce (0.015 in this example) changes how fast and smooth the timer is. However, making it too granular can cause weird jitters and artifacts to appear. Kick this function off right after creating the vertex as follows:
updateArcTimer($(".timer-arc"), vertexSpec, 1.0);
Future work for this project will be to implement this style vertex with D3, and the ability to set timers with a meaningful time measurement. I’d also like to look into other styles, for example the circle fill emptying out (like a sand timer) at the rate of the timer or the halo of the vertex flashing slowly or more quickly as it moves to the end of the timer. Importantly, these elements should also be able to be paused and hooked into other update mechanisms, such that sliders or other interactive functionality can be used. Finally, I’m not sure how edges will interact with the timer halo, but it is also important to consider.
|
https://bbengfort.github.io/2016/11/svg-timer-vertex/
|
CC-MAIN-2021-17
|
refinedweb
| 1,213
| 62.88
|
Hi,
I am trying to use matplotlib to visually explore some data. I started
from the "event_handling example code: data_browser.py" example, but
wanted to go a bit further. The idea is to have two plots and an image
linked together. The first plot represents a measure calculated from
an image region at different times of the day. Selecting one of this
measures shows the corresponding image, and some other measure calculated
from the individual pixels. Further on, selecting in the image or the
second plot should highlight the corresponding point in the plot or pixel
on the image, respectively (That is, the first plot is linked to the image,
and the image and the second plot are linked together).
My problem is that on the function being called upon and event, I always
get events generated by the image, even when the moused was clicked on one of
the other plots. The plots behave ok.
The coded below is a simplified functional version (the measures here are
trivial, and I haven't included the actions when the user selects the image or
the second plot), which exhibits this behavior. What I see when executing this
code is for example:
Actions (click on) Results (from the print statement on the
onpick() function)
plot1 plot1
image2
image2 image2
plot3 plot3
image2
Am I doing something wrong? I am new to both python and matplotlib, so if you
see something that could be done in a better way, please tell me.
Jorges
----- Test code -----
import os
import sys
import glob
import re
import fnmatch
import Image as im
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.stats
class LCRBrowser():
"""
Permits to visualize log chromaticity ratios and related things for
analysing static images taken at throughout a period of time
"""
def __init__(self, data):
# Initialize instance attributes
self.lcr = np.asarray(map((lambda x: x['lcr']), data))
self.lcr_ind = np.asarray(map((lambda x: x['lcr_ind']), data))
self.img = np.asarray(map((lambda x: x['img']), data))
self.lastind = 0
# Initial drawing and picking init
self.fig = plt.figure()
self.ax1 = self.fig.add_subplot(311)
self.ax2 = self.fig.add_subplot(312)
self.ax3 = self.fig.add_subplot(313)
self.plot1, = self.ax1.plot(self.lcr, 'o', picker=5)
self.selected, = self.ax1.plot([self.lcr[0]], 'o', ms=12, alpha=0.4,
color='yellow', visible=False)
self.img2 = self.ax2.imshow(self.img[0], visible=True, picker=2,\
interpolation='nearest')
self.plot3, = self.ax3.plot(self.lcr_ind[0][:], 'o', visible=True, picker=5)
print type(self.plot3)
self.fig.canvas.mpl_connect('pick_event', self.onpick)
self.fig.canvas.draw()
def onpick(self, event):
x2 = event.mouseevent.ydata
if event.artist == self.plot1:
print 'plot1\n'
N = len(event.ind)
if not N: return True
distances = x2-self.lcr[event.ind]
indmin = distances.argmin()
dataind = event.ind[indmin]
self.lastind = dataind
elif event.artist == self.img2:
print 'img2\n'
elif event.artist == self.plot3:
print 'plot3\n'
else:
print 'didn\'t detect artist'
print str(event.artist)
return True
self.update()
def update(self):
if self.lastind is None: return
ind = self.lastind
self.img2.set_data(self.img[ind])
a = self.lcr_ind[ind][:]
self.plot3.set_data((range(len(a)), a))
self.fig.canvas.draw()
def main():
results = []
for name in range(5):
img = np.random.rand(5,4,3)
lcr = sp.stats.gmean(np.mean(np.mean(img, 0), 0))
lcr_ind = sp.stats.gmean(img, 2).reshape(-1,1)
result = {'lcr': lcr, 'lcr_ind':lcr_ind, 'img':img}
results.append(result)
LCRBrowser(results)
if __name__ == '__main__':
main()
----- code end -----
|
https://discourse.matplotlib.org/t/picking-and-events-question/11352
|
CC-MAIN-2019-51
|
refinedweb
| 602
| 52.26
|
Indentation-based syntax
From Nemerle Homepage
This was one of the open projects.
Enabling
There are two ways of enabling the indentation syntax. One is to use the -i compiler option. This enables it for all the files passed to the compiler.
The other is to use #pragma indent at the top of the file (comments and whitespace before are OK, anything else is NOT!).
The algorithm
We maintain a stack of indentation strings. Whenever a new, non-empty line is processed we check if:
- its indentation is the same as the one on the top of the stack, in which case we add a semicolon to close the previous line
- otherwise the indentation has the top-one as prefix, in which case we push it on the stack and add an open brace
- otherwise, if the new indentation is somewhere on the stack, we pop elements looking for it and generate a close brace for each indentation popped
- otherwise it is an error
Exceptions
When the line ends with backslash, in which case it is effectively merged with the next one.
When the line ends with ; or the next one begins with {, the ; is not added.
Inside [], () and {} the indentation processing is off.
Further reading
Most of the comments in Python: Myths about Indentation also applies to our indentation syntax.
Example
using System.Console [Qux] \ class FooBar public static Main () : void WriteLine ("Hello") static Foo (x : int) : void if (x == 3) def y = x * 42 Foo (x) else [x].Map (fun (x) { x * 2 }) static Bar () : int def foo = 2 \ + 7 \ * 13 foo
is translated to:
using System.Console; [Qux] class FooBar { public static Main () : void { WriteLine ("Hello") } static Foo (x : int) : void { if (x == 3) { def y = x * 42; Foo (x) } else { [x].Map (fun (x) { x * 2 }) } } static Bar () : int { def foo = 2 + 7 * 13; foo } }
Alternative clauses in a match
If you use alternative clauses in a match, to match multiple cases to one result,
match (s) { | "a" | "aa" => 1 | "b" | "bb" => 2 | _ => 0 }
in indententation based syntax :
match (s) | "a" | "aa" => 1 | "b" | "bb" => 2 | _ => 0
it won't compile, you need to use line continuation ('\')
match (s) | "a" \ | "aa" => 1 | "b" \ | "bb" => 2 | _ => 0
or just use standard syntax with { .. } for this specific match:
match (s) { | "a" | "aa" => 1 | "b" | "bb" => 2 | _ => 0 }
|
http://nemerle.org/Indentation-based_syntax
|
crawl-001
|
refinedweb
| 393
| 63.93
|
The Data Science Lab, called biases).
The process of finding the values for the weights is called training the network. You obtain a set of training data which has known input values, and known, correct output values, and then use some algorithm to find values for the weights so that computed output values, using the training inputs, closely match the known, correct output values in the training data. There are many training algorithms. Back-propagation is the most common.
Model overfitting can occur when you train a network too much. The resulting weight values create a neural network that has extremely high accuracy on the training data, but when presented with new, previously unseen data (test data), the trained neural network has low accuracy. Put another way, the trained neural network is too specific to the training data and doesn't generalize well.
The most common form of neural network dropout randomly selects half of a neural network's hidden nodes, at each training iteration, and programmatically drops them -- it's as if the nodes do not exist. Although it's not at all obvious, this technique is an effective way to combat neural network overfitting. Neural network dropout was introduced in a 2012 research paper (but wasn't well known until a follow-up 2014 paper). Dropout is now a standard technique to combat overfitting, especially for deep neural networks with many hidden layers.
A good way to see where this article is headed is to take a look at the screenshot of a demo program, in Figure 1. The demo program creates a synthetic training dataset with 200 items. Each item has 10 input values and four output values. The first item's input values are (-0.8, 1.0, 6.8, -0.5, 0.1, 1.4, -5.0, 0.2, 2.1, 4.7). These are the predictor values, often called features in machine learning terminology. The four corresponding output values are: (0, 0, 1, 0).
The values-to-be-predicted (often called the labels) represent one of four categorical values. For example, the labels could represent the color of a car purchased and the features could represent normalized values such as buyer age, buyer income, buyer credit rating and so on. Suppose the four possible car color values are "red", ""white", "black" and "silver". Then (1, 0, 0, 0) represents "red"; (0, 1, 0, 0) is "white"; (0, 0, 1, 0) is "black"; and (0, 0, 0, 1) is "silver".
Behind the scenes, the demo also creates a 40-item set of test data that has the same characteristics as the 200-item training dataset.
The demo creates a 10-15-4 neural network classifier, that is, one with 10 input nodes, 15 hidden processing nodes and four output nodes. The number of input and output nodes is determined by the shape of the training data, but the number of hidden nodes is a free parameter and must be determined by trial and error.
Using back-propagation training without dropout, with 500 iterations and a learning rate set to 0.010, the network slowly improves (the mean squared error gradually becomes smaller during training). After training completes, the trained model has 98.00 percent classification accuracy on the training data (196 out of 200 correctly predicted). But the model achieves only 70.00 percent accuracy (28 out of 40 correct) on the previously unseen test data. It appears that the model may be overfitted.
Next, the demo resets the neural network and trains using dropout. After training, the model achieves 90.50 percent accuracy (181 out of 200 correct) on the test data, and 72.50 percent accuracy (29 out of 40 correct) on the test data. Although this is just a demonstration, this behavior is often representative of dropout training -- model accuracy on the test data is slightly worse, but accuracy on the test data, which is the metric that's most important, is slightly better.
This article assumes you have a reasonably solid understanding of neural network concepts, including the feed-forward mechanism and the back-propagation algorithm, and that you have at least intermediate level programming skills. But I don't assume you know anything about dropout training. The demo is coded using Python version 3, but you should be able to refactor the code to other languages such as Python version 2 or C# without too much difficulty.
Program Structure
The demo program is too long to present in its entirety here, but the complete program is available in the accompanying download. The structure of the demo program, with a few minor edits to save space, is presented in Listing 1. Note that all normal error checking has been removed, and I indent with two space characters, rather than the usual four, to save space. The backslash character is used in Python for line continuation.
I used Notepad to edit the demo but most of my colleagues prefer one of the many nice Python editors that are available, including Visual Studio with the Python Tools for VS add-in. The demo begins by importing the numpy, random and math packages. Coding a neural network from scratch allows you to freely experiment with the code. The downside is the extra time and effort required.
# nn_dropout.py
# Python 3.x
import numpy as np
import random
import math
# helper functions
def showVector(v, dec): . .
def showMatrix(m, dec): . .
def showMatrixPartial(m, numRows, dec, indices): . .
def makeData(genNN, numRows, inputsSeed): . .
class NeuralNetwork: . .
def main():
print("Begin NN dropout demo ")
print("Generating dummy training and test data \n"))
dummyTrainData = makeData(genNN, numRows=200,
inputsSeed=11)
dummyTestData = makeData(genNN, 40, 13)
print("Dummy training data: ")
showMatrixPartial(dummyTrainData, 4, 1, True)
numInput = 10
numHidden = 15
numOutput = 4
print("Creating a %d-%d-%d neural network \
classifier" % (numInput, numHidden, numOutput) )
nn = NeuralNetwork(numInput, numHidden, numOutput,
seed=2)
maxEpochs = 500 # from 300, 500
learnRate = 0.01
print("Setting maxEpochs = " + str(maxEpochs))
print("Setting learning rate = %0.3f " % learnRate)
print("Starting training without dropout")
nn.train(dummyTrainData, maxEpochs, learnRate,
dropOut=False)
print("Training complete")
accTrain = nn.accuracy(dummyTrainData)
accTest = nn.accuracy(dummyTestData)
print("Accuracy on train data no dropout = \
%0.4f " % accTrain)
print("Accuracy on test data no dropout = \
%0.4f " % accTest)
nn = NeuralNetwork(numInput, numHidden, numOutput,
seed=2)
dropProb = 0.50
learnRate = 0.01
print("Starting training with dropout ( %0.2f ) " \
% dropProb)
maxEpochs = 700 # need to train longer?
nn.train(dummyTrainData, maxEpochs, learnRate,
dropOut=True)
print("Training complete")
accTrain = nn.accuracy(dummyTrainData)
accTest = nn.accuracy(dummyTestData)
print("Accuracy on train data with dropout = \
%0.4f " % accTrain)
print("Accuracy on test data with dropout = \
%0.4f " % accTest)
print("End demo ")
if __name__ == "__main__":
main()
# end script
The demo program begins by generating the synthetic training and test data:)
The approach used is to create a utility neural network with random, but known weight and bias values between -9.0 and +9.0, then feed the network random input values:
dummyTrainData = makeData(genNN, numRows=200,
inputsSeed=11)
dummyTestData = makeData(genNN, 40, 13)
print("Dummy training data: \n")
showMatrixPartial(dummyTrainData, 4, 1, True)
Notice that the same utility neural network is used to generate both training and test data, but that the random input values are different, as indicated by the inputSeed parameter values of 11 and 13. Those seed values were selected only because they gave a representative demo.
Next, the neural network classifier is created:
numInput = 10
numHidden = 15
numOutput = 4
print("Creating a %d-%d-%d neural network \
classifier" % (numInput, numHidden, numOutput) )
nn = NeuralNetwork(numInput, numHidden, numOutput, seed=2)
I cheated a bit by specifying 15 hidden nodes, the same number used by the data-generating neural network. This makes training easier. The seed value passed to the neural network constructor controls the random part of the dropout process and the order in which training item are processed. The value specified, 2, is arbitrary.
Next, the network is trained without using dropout:
maxEpochs = 500
learnRate = 0.01
nn.train(dummyTrainData, maxEpochs, learnRate, dropOut=False)
print("Training complete")
The NeuralNetwork class exposes dropout training via a parameter to the train method. Dropout is used here with standard back-propagation, but dropout can be applied to all training algorithms that use some form of gradient descent, such as back-propagation with momentum, back-propagation with regularization and the Adam and Nesterov algorithms.
After training completes, the accuracy of the model is computed and displayed:
accTrain = nn.accuracy(dummyTrainData)
accTest = nn.accuracy(dummyTestData)
print("Acc on train data no dropout = %0.4f " % accTrain)
print("Acc on test data no dropout = %0.4f " % accTest)
The classification accuracy of the model on the test data is the more important of the two metrics. It gives you a very rough estimate of prediction accuracy of the model when presented new data, which is the ultimate goal of a classifier.
Next, the neural network is reset and trained, this time using dropout:
nn = NeuralNetwork(numInput, numHidden, numOutput, seed=2)
dropProb = 0.50
learnRate = 0.01
maxEpochs = 700
nn.train(dummyTrainData, maxEpochs, learnRate, dropOut=True)
print("Training complete")
Notice that with dropout, the maximum number of training iterations is increased from 500 to 700. In general, when using dropout, training will be slower and require more iterations than training without dropout.
The demo concludes by computing and displaying the classification accuracy of the dropout-trained model:
accTrain = nn.accuracy(dummyTrainData)
accTest = nn.accuracy(dummyTestData)
print("Acc on train data with dropout = %0.4f " % accTrain)
print("Acc on test data with dropout = %0.4f " % accTest)
print("End demo ")
In this demo, using dropout slightly improved the classification accuracy on test data. However, even though using dropout often helps, in some problem scenarios using dropout can actually yield a worse model.
Understanding Dropout
The dropout mechanism is illustrated in the diagram in Figure 2. The neural network has three input nodes, four hidden nodes and two output nodes and so does not correspond to the demo program. In back-propagation, on each training iteration, each node-to-node weight (indicated by the blue arrows) and each node bias (indicated by the green arrows) are updated slightly.
With dropout, on each training iteration, half of the hidden node are randomly selected to be dropped. Then the drop nodes essentially don't exist, so they don't take part in the computation of output node values, or in the computation of the weight and bias updates. In the diagram, if hidden nodes are 0-indexed, then hidden nodes [1] and [2] are selected as drop nodes on this training iteration.
Drop nodes aren't physically removed, instead they are virtually removed by having any code that references them ignored. In this case, in addition to hidden nodes [1] and [2], the six input-to-hidden weights that terminate in the drop nodes are ignored. And the four hidden-to-output node weights that originate from the drop nodes are ignored.
What Figure 2 does not show is that after training, each input-to-hidden node weight, and each hidden-to-output node weight is divided by 2.0 (or equivalently, multiplied by 0.50). The idea here is that during training, there are effectively only half as many weights as there are in the final neural network. So during training, each weight value will be, on average twice as large as they should be. Dividing by 2.0 approximately restores the correct magnitudes of the weights for the full network. The exact math behind this idea is quite subtle and outside the scope of this article.
It's probably not obvious to you why dropout reduces overfitting. In fact, the effectiveness of dropout is not fully understood. One notion is that dropout essentially selects random subsets of neural networks, and then averages them together, giving a more robust final result. Another notion is that dropping hidden nodes helps prevent adjacent nodes from co-adapting with each other, again leading to a more robust model.
Implementation Issues
There are several approaches to implementing neural network dropout. The demo selects random nodes and then just ignores all occurrences of those nodes. For example, at the top of the training iteration loop, the demo code selects drop nodes like this:
if dropOut == True:
for j in range(self.nh): # each hidden node
p = self.rnd.random() # [0.0, 1.0)
if p < 0.50:
self.dNodes[j] = 1 # mark as drop node
else:
self.dNodes[j] = 0 # not a drop node
The code checks the value of the Boolean dropOut parameter, then marks each hidden node as a dropout node or not, with probability equal to 0.50. Notice that using this approach, even though on average half of the hidden nodes will be selected as drop nodes, it's possible that on one iteration no nodes will be selected, or that all nodes will be selected. An alternative design that I have never seen used is to mark drop nodes in a way so that exactly half are selected each iteration.
When implementing class methods train and computeOutputs, the demo examines every reference to a hidden node and then checks if the node is currently a drop node or not. If the node is a drop node, it is skipped, otherwise the node is processed as usual. For example, in method computeOutputs, the part of the code that computes the pre-activation sum of products of the output nodes is:
for k in range(self.no): # each output node
for j in range(self.nh): # each hidden node
if dropOut == True and self.dNodes[j] == 1: # skip?
continue
oSums[k] += self.hNodes[j] * self.hoWeights[j,k]
oSums[k] += self.oBiases[k]
An alternative approach, which I've seen used in several machine learning libraries, is instead of skipping over drop nodes, to set their values to 0.0. Then on the forward pass through the network, all the key terms zero-out. However you still must skip over drop nodes on the backwards pass during training.
Wrapping Up
There are several types of dropout. In addition to dropping hidden nodes, it's possible to drop input nodes. And instead of randomly dropping nodes with probability equal to 0.50, you can drop fewer or more nodes. For example, you can drop with probability equal to 0.20, or drop with probability equal to 0.80. If so, you have to be careful to modify the final network weight values accordingly. Suppose you drop nodes with probability equal to 1/5 = 0.20. That means on average the training network has 80 percent of the weights of the full network, in other words the trained weights will be slightly too large. So, you'd multiply all weights by 0.80 (or equivalently, divide by 1.25) to reduce their magnitudes slightly.
There are several techniques, other than dropout, that you can use to combat neural network overfitting. Common techniques include:
If you're new to neural networks, all these options can seem a bit overwhelming, but if you explore them one at a time, eventually the larger picture becomes clear.
Printable Format
I agree to this site's Privacy Policy.
|
https://visualstudiomagazine.com/articles/2018/02/01/neural-network-dropout.aspx
|
CC-MAIN-2019-35
|
refinedweb
| 2,527
| 55.84
|
03 February 2012 10:47 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
For ethylene, demand is projected to hit 38m tonnes by 2015, representing an annual growth of 5.1% for the duration of China’s 12th five-year plan, covering the period from 2011-2015, the report stated.
Its propylene demand, on the other hand, is expected to grow at an annual rate of 5.4% to 28m tonnes by 2015, according to the report.
The country’s actual output of the product is projected to be slightly lower than capacity, at 24.3m tonnes for ethylene and at 21.6m tonnes for propylene by 2015, the report showed.
In end
|
http://www.icis.com/Articles/2012/02/03/9529108/chinas-annual-olefins-demand-to-grow-5-through-2015.html
|
CC-MAIN-2015-14
|
refinedweb
| 112
| 67.15
|
Introduction to C++ Aggregation
Aggregation is a type of association that is used to represent the “HAS-A” relationship between two objects. This is a subclass for a relation type association. Where the association is loosely coupled that exists between two classes where a relation exists, but aggregation restricts some situations of associations. This type of relation is like a whole/Part relationship type where one class owns another class thus one class object is a part of another class object. But the lifetime of a part class does not depend on the lifetime of the whole class neither whole class can exist without an object of part class.
For Example – There are two classes Address and Person, Each Person has an address.
Syntax:
Aggregation is a way to represent HAS-A relation between the objects of 2 individual classes.. It is a subtype of association type of relation but more restrictive.
Class PartClass{ //instance variables //instance methods } class Whole{ PartClass* partclass; }
Explanation: In the above syntax, the Whole class represents the class that is a container class for other Part class that is contained in the object of the whole class. Here each object of Whole class holds a reference pointer to the object of the Part class.
For example – BUS HAS-A Engine. Here Bus is a container class. Part class is a class whose object is contained within the objects of a container class. An object of the Part class can be referred in more than 1 object of Whole class and also a lifetime of a contained class object does not depend on the lifetime of the existence of the object of a container class.
How does Aggregation work in C++?
Aggregation is a relation type that helps to represent Has-A relation between objects of 2 individual classes in the program. It Is a subform of association relation and is more restrictive as compared to the association. It helps to make our code more readable and understandable to represent the relation in the programming language, in the same manner, it is explained in our day to day lives.
Here object of one class is referred to using a pointer variable present in the container class object.
Example: Person has Address is represented using two classes Person and Address. Since as we can see, Address has a Person is meaningless thus Person is container class and Address is a class whose object is contained within the container class object.
Here we can also see, the lifetime of an object of address class does not depend on the lifetime of the object of Person class. Thus objects are not tightly coupled. Also, one address can easily be associated with more than a Person since more than 1 person can live on the same address. Thus the object of address class can be associated with more than one object of Person class.
In this way, one can easily establish HAS-A relation between objects of 2 classes.
Example of C++ Aggregation
Let us try to illustrate the implementation of the aggregation type of relation between 2 classes Person and address using a C++ program.
Code:
#include <iostream> #include<string.h> using namespace std; class Address { public: inthouseNo; string colony,city, state; Address(inthno, string colony, string city, string state) { this->houseNo = hno; this->colony=colony; this->city = city; this->state = state; } }; class Person { private: Address* address; public: string name; Person(string name, Address* address) { this->name = name; this->address = address; } void display() { cout<< name<< " "<< " "<< address->houseNo<<" "<<address-> colony<<" " <<address->city<< " "<<address->state<<endl; } }; int main(void) { Address add1= Address(868 ,"Mahavir Colony","Jahagirpuri","New Delhi"); Person p1 = Person("Raj",&add1); Person p2 = Person("Seema",&add1); p1.display(); p2.display(); return 0; }
Output:
Explanation: Here Person has instance variable name which tells the name of the person and a pointer variable to address class object. Address class object has variables such as House, street, city, and state. Here we have 2 persons Raj and Seema living on the same address thus share the same address object add1.
Advantages of C++ Aggregation
- Aggregation helps establishing a relation between objects of 2 individual classes where one is Whole class and the other is a part class. It is used to code ‘HAS-A’ relation between objects of two classes where once object of the part class can be associated with more than 1 object of Whole class and does not have existence dependency on it.
- This type of relation is a special form of relation named as association where objects does not have any dependency on each other and show bidirectional relation between objects of different classes.
- Aggregation type of relation represents uni-directional relation between objects of 2 classes like car and garage where car is a part of garage same car can be parked in any other garage as well. Thus defines its one direction relation.
- It also helps to improve the reusability of the code. Once objects have been created, any Whole class object is capable of holding a reference to the object of any of the Part class.
- It also helps to improve the readability of the code as the relation between 2 classes can be made more understandable once it is in the form of HAS-A relation the same we interpret them in our day to day life. such as Bus HAS-A Engine and Department HAS-A Teacher.
Conclusion
Aggregation is a type of relation between objects of two individual classes. It represents the ‘HAS-A’ type of relation where one is part class and the other is the whole class, where reference variable pointing to the part class object is present in the object of the whole class. Here a lifetime of a part class object is independent of the lifetime of the whole class object.
Recommended Article
This is a guide to the C++ Aggregation. Here we discuss the Introduction of C++ Aggregation and its different Advantages along with Examples and its Code Implementation. you can also go through our suggested articles to learn more –
|
https://www.educba.com/c-plus-plus-aggregation/
|
CC-MAIN-2022-40
|
refinedweb
| 1,013
| 50.46
|
Connect to AVS with HTTP/2
The Alexa Voice Service (AVS) exposes an HTTP/2 endpoint and supports AVS-initiated directives, which enable your device to access available Alexa features. The following sections show you how to create and maintain an HTTP/2 connection with AVS.
Prerequisites
Before you create an HTTP/2 connection, you must obtain a Login with Amazon (LWA) access token and choose an HTTP/2 client library.
Obtain a Login with Amazon (LWA) access token
To access AVS, your device must obtain a LWA access token, which grants your device access to the AVS APIs on behalf of the user. To learn about the available authorization options and the steps to obtain an LWA access token, see Authorize an AVS Device
You must send the LWA access token to AVS in the header of each event. If authentication fails for any reason the connection with AVS closes. For more details abut structuring this header, see the HTTP/2 Message Syntax Reference.
The following example shows a sample header. In addition to your access token, include a boundary term in the header of each event sent to AVS. The boundary term separates different parts of a multipart message, such as JSON and binary audio. For examples showing how to use a boundary term, see the HTTP/2 Message Syntax Reference.
:method = POST :scheme = https :path = /{{API version}}/events authorization = Bearer {{YOUR_ACCESS_TOKEN}} content-type = multipart/form-data; boundary={{BOUNDARY_TERM_HERE}}
deviceSerialNumber, which is passed in scope data during authorization.
Choose an HTTP/2 client library
The following table shows the HTTP/2 client libraries that you can use with AVS.
For a complete list of implementations, see GitHub.
libcurl, your device must make a
GETrequest to
/pingevery five minutes to maintain the connection. For details, see Ping and Timeout later in this topic.
Open and close event and downchannel streams
This section describes the different expected lifecycles for the event stream and downchannel stream.
Open and close an event stream
The device sends each new event on its own stream. Typically, these streams close after AVS returns the appropriate directives and corresponding audio attachments to your device.
Handle requests sequentially. Send new requests when AVS begins responding to your previous request. AVS begins responding after the previous request returns headers.
The following steps show how an event stream opens and closes:
- Your device opens a stream and sends a multipart message consisting of one JSON-formatted event and up to one binary audio attachment. For more details, see Structuring an HTTP/2 Request.
- AVS returns multipart messages consisting of one more JSON-formatted directives and corresponding audio attachments on the same stream, potentially before streaming is complete. The URL attribute that follows
cid:in a
Playor
Speakdirective also appears in the header of the associated audio attachment.
- After receiving a response from AVS, the device closes the event stream.
Open and close a downchannel stream
In parallel, AVS might send directives to your device on the downchannel. Primarily, use the downchannel for AVS-initiated directives.
The following steps show how a downchannel stream opens and closes:
- The device makes a
GETrequest to the directives path within 10 seconds of creating a connection with AVS.
- This stream sends your device AVS-initiated directives and audio attachments, such as timers, alarms, and instructions originating from the Amazon Alexa app. Unlike an event stream, the downchannel doesn't instantly close and is should remain open in a half-closed state from the device and from AVS for prolonged periods of time.
- When the downchannel stream closes, your device must immediately establish a new downchannel to make sure that your device can receive AVS-initiated directives.
Create an HTTP/2 connection
When a user turns on your device, create a single HTTP2 connection with AVS. This connection handles all directives and events, including anything that AVS sends to your device on the downchannel stream. For more details about connection management, see server-initiated disconnects.
For your device to maintain a connection with AVS, you must meet two requirements:
- Create the downchannel stream.
- Synchronize the device component states with the appropriate AVS interfaces, such as
SpeechRecognizer,
AudioPlayer,
Alerts,
Speaker,
SpeechSynthesizer.
RecognizerStateis only required if your device uses Cloud-Based Wake Word Verification.
To create an HTTP/2 connection
Create a downchannel stream by having your device make a
GETrequest to the appropriate
/{{API version}}/directiveswithin 10 seconds of opening the connection with AVS. The request should look like the following example.
:method = GET :scheme = https :path = /{{API version}}/directives authorization = Bearer {{YOUR_ACCESS_TOKEN}}
Following a successful request, the downchannel stream remains open in a half-closed state from the device and open from AVS for the duration of the connection. Long pauses could occur between AVS-initiated directives.
To synchronize the states of the device's components with AVS, make a
POSTrequest to the appropriate
/{{API version}}/eventson a new event stream on the existing connection without opening a new connection, and then close the event stream when your device receives a directive response.
The following example shows a device components to Alexa. See Context for details. ], "event": { "header": { "namespace": "System", "name": "SynchronizeState", "messageId": "{{STRING}}" }, "payload": { } } } --{{BOUNDARY_TERM_HERE}}--
After synchronizing state, your device can to use this connection to send the following events and receive directives:
Send events to and receive directives from AVS.Note: Each event and its associated response are sent on a single event stream. When the response is received, the stream should be closed.
Receive directives on the downchannel stream.
Maintain the HTTP/2 connection
Use pings and timeouts to keep the HTTP/2 connection between your device and AVS open. If the server disconnects you, reconnect to AVS by following the instructions in the next section.
Ping and timeout
Your device must perform one of the following actions to prevent the connection from closing:
- Send a
PINGframe to AVS every 5 minutes when the connection is idle.
- Make a
GETrequest to
/pingevery 5 minutes when the connection is idle.
Sample request
:method = GET :scheme = https :path = /ping authorization = Bearer {{YOUR_ACCESS_TOKEN}}
On a failed
/ping, close the connection, and create a new connection.
libcurl, your device must make a
GETrequest to
/pingevery five minutes to maintain the connection.
Server-initiated disconnects
When the server initiates a disconnect, your device should follow the following sequence:
- Open a new connection and route any new requests through it.
- Close the old connection after processing all open requests and closing their corresponding streams.
- Maintain a connection to any stream URL established before the disconnect occurred, such as Amazon Music or Audible. A stream playing before a server-initiated disconnect occurs should continue to play as long as bytes are available.
If the device's attempt to create a new connection fails, the device should try again with an exponential back-off.
|
https://developer.amazon.com/it-IT/docs/alexa/alexa-voice-service/manage-http2-connection.html
|
CC-MAIN-2022-05
|
refinedweb
| 1,135
| 53.31
|
Ok, sorry for not blogging for so long, but I have to work, date etc. :-D
I hope this is the start of a series of small, but informative blog entries about new features available in Tiger, especially the ones a hundred people haven't mentioned before me :-D
To begin with, I'll show you how to use the new nanoTime() method in System. An important thing to notice is that nanoTime()'s return and currentTimeMillis's are not necessarily related to each other - meaning they don't have to use the same reference to zero. This example also uses the new static import feature. I am not saying I like it or not. That's what I expect you to say.
System
nanoTime()
currentTimeMillis
Here's the code:
import static java.lang.System.*;
public class Nano {
public static void main(String[] args) {
long time = 0;
long newTime;
long smaller = 9999999999999L;
for (int i = 0; i < 100000; i++) {
time = nanoTime();
newTime = nanoTime();
smaller = Math.min(smaller, newTime - time);
}
out.println("Smallest nano interval measured: " + smaller);
out.println("Current time millis: " + currentTimeMillis());
out.println("Nano time: " + nanoTime());
}
}
Save it in Nano.java and compile it with:
Nano.java
javac -source 1.5 Nano.java
Then run it normally with:
java -cp . Nano
My results (P4, 1GB RAM, Windows 2000 Pro) are:
Smallest nano interval measured: 1116
Current time millis: 1076038988125
Nano time: 8736336585045
This method is intended to be used as a way to measure performance, for instance. Here, I just tried to get its precision in my current box configuration.
Please let me know if you get smallest nano intervals in your platform/configuration. See you soon ;-)
Linux
Here on Gentoo Linux, I get a smallest time of 1000 nanoseconds every time.
I think when you use static import like you did, it looks bad, but I think if you static import specific methods of static utility classes like Math or SwingConstants, it can make the code look less cluttered. (I don't consider System a class whose static imports look nice.)
Posted by: keithkml on February 05, 2004 at 09:28 PM
In the words of Mermaidman...
EEEEEEvvvvviiiiilllll
Posted by: robertx on February 06, 2004 at 06:52 AM
Behavior on My Linux Box
The smallest nano second interval that I was able to measure was 1000 every time on my Linux box too. I'm using Red Hat 9.0.
Also, I have mixed feelings about the static import. I do think it would be a mistake to statically import * from a class, too much chance for ambiguous method references. However, I like being able to statically import System.out so that shortens the calls to out.println(...). It does look like it could introduce more problems than it solves in terms of code maintainability.
Warren
Posted by: wthomp6984 on February 06, 2004 at 08:28 AM
static import is not for this.
i thought static import should not be used like this. It looks "ok" only in constants and math libraries. Even then, i think statics are more evil than blessing..
Posted by: ahmetaa on February 06, 2004 at 12:12 PM
Timer resolution?
We don't have J2SE 1.5 on Mac OS X yet, so I wrote my own nanoTime() method (below) using Sun's performance measurement class.
One thing I've noticed is that I obtain 2x better clock resolution when I compute elapsed CPU time directly from clock ticks because the conversion from ticks to nanoseconds requires one multiply and one divide (before the compiler optimizes my code).
Could someone please test the program below under Java 1.5 and tell me how the resolution of my nanoTime() method compares with the new System.nanoTime() method? Set the BEST variable to false and change the 2 timer.nanoTime() calls in getResolution() to System.nanoTime().
Currently, with BEST = true, I am getting a time resolution of 440 nanoseconds on Mac OS X (old 400 MHz G3 iMac).
Thank you!
Craig
[code]
// Test Sun's performance measurement clock
import sun.misc.Perf;
import java.text.DecimalFormat;
public class TestTimer
{
HiResTimer timer;
public TestTimer()
{
long before, after, cputime; // CPU timing variables
DecimalFormat sci = new DecimalFormat("##0.###E0");
timer = new HiResTimer();
System.out.println("Counter frequency : " + sci.format(timer.getFrequency()) + " Hz (ticks/sec)");
System.out.println("Time per clock tick : " + timer.getTickTime() + " nanoseconds");
System.out.println("Counter resolution : " + timer.getCounterResolution() + " clock ticks");
System.out.println("Avg. counter resolution: " + timer.getAvgCounterResolution() + " clock ticks");
System.out.println("Time resolution : " + timer.getResolution() + " nanoseconds");
System.out.println("Sleeping for 3 seconds . . .");
before = System.currentTimeMillis(); // timer.milliTime();
snooze();
after = System.currentTimeMillis(); // timer.milliTime();
cputime = after - before;
System.out.println("Sleep time of 3 seconds measured as: " + cputime + " milliseconds");
System.out.println("Sleeping again for 3 seconds . . .");
before = timer.nanoTime(); // System.nanoTime();
snooze();
after = timer.nanoTime(); // System.nanoTime();
cputime = after - before;
System.out.println("Sleep time of 3 seconds measured as: " + cputime + " nanoseconds");
System.out.println("Sleeping yet again for 3 seconds . . .");
before = timer.getTicks();
snooze();
after = timer.getTicks();
cputime = timer.nsFromTicks(after - before);
System.out.println("Sleep time of 3 seconds measured as: " + cputime + " nanoseconds from ticks");
}
// Sleep 3 seconds
private final void snooze()
{
try
{
Thread.sleep(3000);
}
catch ( Exception x )
{
x.printStackTrace();
}
}
public static void main(String[] args)
{
new TestTimer();
}
// Inner class for high-rez timing measurements
public class HiResTimer
{
private Perf hiResTimer;
private long freq;
private int LOOPS;
private boolean BEST;
public HiResTimer()
{
hiResTimer = Perf.getPerf();
freq = hiResTimer.highResFrequency();
LOOPS = 1000000;
BEST = true; // Toggle for clock ticks ns
}
// return current time in milliseconds
public long milliTime()
{
return (hiResTimer.highResCounter() * 1000L / freq);
// return (hiResTimer.highResCounter() / ((freq + 500L) / 1000L));
}
// return current time in nanoseconds
public long nanoTime()
{
return (hiResTimer.highResCounter() * 1000000000L / freq);
}
// return the current clock ticks
public long getTicks()
{
return hiResTimer.highResCounter();
}
// return the number of clock ticks per second
public long getFrequency()
{
return freq;
}
// return the number of nanoseconds per clock tick
public long getTickTime()
{
return (1000000000L/freq);
}
// convert clock ticks to nanoseconds
public long nsFromTicks(long ticks)
{
return (ticks * 1000000000L / freq);
}
// Error expected in measured elapsed time (in nanoseconds)
public long getResolution()
{
long before = 0L;
long after = 0L;
long smallest = Long.MAX_VALUE;
if (BEST)
{
// Compute using clock ticks
for (int i=0; i ns
}
else
{
// Compute using nanoseconds
for (int i=0; i<LOOPS; ++i)
{
before = nanoTime(); // System.nanoTime();
after = nanoTime(); // System.nanoTime();
smallest = Math.min(smallest, after - before);
}
return (smallest);
}
}
public long getCounterResolution()
{
long before = 0L;
long after = 0L;
long smallest = Long.MAX_VALUE;
for (int i=0; i<LOOPS; ++i)
{
before = hiResTimer.highResCounter();
after = hiResTimer.highResCounter();
smallest = Math.min(smallest, after - before);
}
return smallest;
}
// Avg error expected in measured elapsed time (in clock ticks)
public long getAvgCounterResolution()
{
long before = 0L;
long after = 0L;
long dt = 0L;
// Warm up JIT/HotSpot compiler
// for (int i=0; i<LOOPS; ++i)
// before = hiResTimer.highResCounter();
for (int i=0; i<LOOPS; ++i)
{
// before = after = hiResTimer.highResCounter();
// while (before == after)
// after = hiResTimer.highResCounter();
before = hiResTimer.highResCounter();
after = hiResTimer.highResCounter();
dt += (after - before);
}
return Math.round((double)dt/LOOPS);
}
} // End HiResTimer inner class
} // End TestTimer class
[/code]
Posted by: mattocks on February 06, 2004 at 07:25 PM
Re: Timer resolution?
Sorry, browser mangled part of the code. Try again:
// Test Sun's performance measurement clock
if (BEST)
{
// Compute using clock ticks
for (int i=0; i ns
}
else
{
// Compute using nanoseconds
for (int i=0; i
Posted by: mattocks on February 06, 2004 at 07:32 PM
Re: Measuring nanos
I copied and pasted your code and ran it and I got 0 for the smallest interval. But the nanoTime() consitently returned a number with three zeros at the end. So like others I would say the smallest interval is 1000. I am running Redhat Fedora Core1 on a P4 2.4 Ghz.
Posted by: dann on February 06, 2004 at 08:23 PM
Ew
You've managed to find the worst possible way to use static import. Congratulations.
Posted by: gafter on February 08, 2004 at 12:36 PM
Please have a minimum standard
Guys,
Please have a minimum standard while posting the content. You do not want to post "cheezy" stuff and lose name (both the Author and the website).
When i looked at this post, I was expecting a through performance comparison between various versions of the Sun JDK over different platforms.
I hope this "series" does not continue. Sorry if I am being rude, but this is outrageous.
Dushy
Posted by: dushy13 on February 08, 2004 at 05:06 PM
Re: Please have a minimum standard
Have I ever said the code looked fine? No, I clearly said: I am not saying if it's good or not. And do you know why I wrote this code? I wanted to get reactions from Java developers about static import. Expect to see even more hideous uses of this new feature, because, as I say, everything that compiles eventually shows in source code.
Sorry if you were looking for a performance comparison, but there's nothing nowhere that indicates that this post is about it.
This series is about playing with the Tiger, exploring things other articles on the web don't - such as bad uses of static import. I am not here to say this code is good, as I said. This is something I expected you to say. However, as most of you got the impression I liked the way this code is written, let me make it clear: this code sucks. The nanoTime() stuff is cool, the static import is not. Not at all. It's ugly, smelly and would probably never hire someone who writes this code of code.
Hope you get the intent better ;-) Keep on ranting - or not - about it.
Posted by: mister__m on February 09, 2004 at 02:37 AM
|
http://weblogs.java.net/blog/mister__m/archive/2004/02/playing_with_th.html
|
crawl-002
|
refinedweb
| 1,627
| 58.69
|
Hi Lakmal, On Tue, Oct 11, 2016 at 2:44 PM, Lakmal Warusawithana <lak...@wso2.com> wrote:
Advertising
> Further thinking on implementation for k8s, we need to improve in 3 places. > > 1.) Need to introduce min=0 for autoscaling policies > kubectl autoscale rc foo --min=0 --max=5 --inflight-request-count=80 > > 2.) Have to config auto scaler for use load balancing factor > (inflight-request-count) - K8S have extension in Auto scaler > > 3.) Improve load balancer for hold first request (until service running) > Do you mean load balancers like nginx, haproxy? Or can we get this done with gateway itself without worrying about load balancers being used? thank you. > > On Tue, Oct 11, 2016 at 2:24 PM, Imesh Gunaratne <im...@wso2.com> wrote: > >> On Mon, Oct 10, 2016 at 8:01 PM, Sanjeewa Malalgoda <sanje...@wso2.com> >> wrote: >> >>> >>> When we do container based deployment standard approach we discussed so >>> far was, >>> >>> - At the first request check the tenant and service from URL and do >>> lookup for running instances. >>> - If matching instance available route traffic to that. >>> - Else spawn new instance using template(or image). When we spawn >>> this new instance we need to let it know what is the current tenant and >>> data sources, configurations it should use. >>> - Then route requests to new node. >>> - After some idle time this instance may terminate. >>> >>> If we were to do this with a container cluster manager, I think we >> would need to implement a custom scheduler (an entity similar to HPA in >> K8S) to handle the orchestration process properly. Otherwise it would be >> difficult to use the built-in orchestration features such as auto-healing >> and autoscaling with this feature. >> >> By saying that this might be a feature which should be implemented at the >> container cluster manager. >> >> *Suggestion* >>> If we maintain hot pool(started and ready to serve requests) of servers >>> for each server type(API Gateway, Identity Server etc) then we can cutoff >>> server startup time + IaaS level spawn time from above process. Then when >>> requests comes to wso2.com tenants API Gateway we can pick instance >>> from gateway instance pool and set wso2.com tenant context and data >>> source using service call(assuming setting context and configurations is >>> much faster). >>> >> >> I think with this approach tenant isolation will become a problem. It >> would be ideal to use tenancy features at the container cluster manager >> level. For an example namespaces in K8S. >> >> Thanks >> >>> >>> *Implementation* >>> For this we need to implement some plug-in to instance spawn process. >>> Then instead of spawning new instance it will pick one instance from the >>> pool and configure it to behave as specific tenant. >>> For this each instance running in pool can open up port, so load >>> balancer or scaling component can call it and tell what is the tenant and >>> configurations. >>> Once it configured server close that configuration port and start >>> traffic serving. >>> After some idle time this instance may terminate. >>> >>> This approach will help us if we met following condition. >>> (Instance loading time + Server startup time + Server Lookup) *>* >>> (Server Lookup + Loading configuration and tenant of running server from >>> external call) >>> >>> Any thoughts on this? >>> >>> Thanks, >>> sanjeewa. >>> -- >>> >>> *Sanjeewa Malalgoda* >>> WSO2 Inc. >>> Mobile : +94713068779 >>> >>> <>blog >>> : >>> <> >>> >>> >>> >> >> >> -- >> *Imesh Gunaratne* >> Software Architect >> WSO2 Inc: >> T: +94 11 214 5345 M: +94 77 374 2057 >> W: TW: @imesh >> lean. enterprise. middleware >> >> > > > -- > Lakmal Warusawithana > Director - Cloud Architecture; WSO2 Inc. > Mobile : +94714289692 > Blog : > > > _______________________________________________ > Architecture mailing list > Architecture@wso2.org > > > -- Manjula Rathnayaka Technical Lead WSO2, Inc. Mobile:+94 77 743 1987
_______________________________________________ Architecture mailing list Architecture@wso2.org
|
https://www.mail-archive.com/architecture@wso2.org/msg12215.html
|
CC-MAIN-2018-09
|
refinedweb
| 586
| 56.25
|
Using the coordinator pattern in iOS apps lets us remove the job of app navigation from our view controllers, helping make them more manageable and more reusable, while also letting us adjust our app's flow whenever we need.
This is part 1 in a series of tutorials on fixing massive view controllers:
View controllers work best when they stand alone in your app, unaware of their position in your app’s flow or even that they are part of a flow in the first place.. This is a pattern I learned from Soroush Khanlou – folks who’ve heard me speak will know how highly I regard Soroush and his work, and coordinators are just one of many things I’ve learned reading his blog.
That being said, before I continue: I should emphasize this is the way I use coordinators in my own apps, so if I screw something up it’s my fault and not Soroush’s!
Prefer video? The screencast below contains everything in this article and more – subscribe to my YouTube channel for more like this.
Let’s start by looking at code most iOS developers have written a hundred or more times:
if let vc = storyboard?.instantiateViewController(withIdentifier: "SomeVC") { navigationController?.pushViewController(vc, animated: true) }
In that kind of code, one view controller must know about, create, configure, and present another. This creates tight coupling in our application: you have hard-coded the link from one view controller to another, so and might even have to duplicate your configuration code if you want the same view controller shown from various places.
What happens if you want different behavior for iPad users, VoiceOver users, or users who are part of an A/B test? Well, your only option is to write more configuration code in your view controllers, so the problem only gets worse.
Even worse, all this involves a child telling its navigation controller what to do – our first view controller is reaching up to its parent and telling it present a second view controller.
To solve this problem cleanly, the coordinator pattern lets us decouple our view controllers so that each one has no idea what view controller came before or comes next – or even that a chain of view controllers exists.
Instead, your app flow is controlled using a coordinator, and your view communicates only with a coordinator. If you want to have users authenticate themselves, ask the coordinator to show an authentication dialog – it can take care of figuring out what that means and presenting it appropriately.
The result is that you’ll find you can use your view controllers in any order, using them and reusing them as needed – there’s no longer a hard-coded path through your app. It doesn’t matter if five different parts of your app might trigger user authentication, because they can all call the same method on their coordinator.
For larger apps, you can even create child coordinators – or subcoordinators – that let you carve off part of the navigation of your app. For example, you might control your account creation flow using one subcoordinator, and control your product subscription flow using another.
If you want even more flexibility, it’s a good idea for the communication between view controllers and coordinators to happen through a protocol rather than a concrete type. This allows you to replace the whole coordinator out at any point later on, and get a different program flow – you could provide one coordinator for iPhone, one for iPad, and one for Apple TV, for example.
So, if you’re struggling with massive view controllers I think you’ll find that simplifying your navigation can really help. But enough of talking in the abstract – let’s try out coordinators with a real project…
Start by creating a new iOS app in Xcode, using the Single View App template. I named mine “CoordinatorTest”, but you’re welcome to use whatever you like.
There are three steps I want to cover in order to give you a good foundation with coordinators:
Like I said above, it’s a good idea to use protocols for communicating between view controllers and coordinators, but in this simple example we’ll just use concrete types.
First we need a
Coordinator protocol that all our coordinators will conform to. Although there are lots of things you could do with this, I would suggest the bare minimum you need is:
start()method to make the coordinator take control. This allows us to create a coordinator fully and activate it only when we’re ready.
In Xcode, press Cmd+N to create a new Swift File called Coordinator.swift. Give it this content to match the requirements above:
import UIKit protocol Coordinator { var childCoordinators: [Coordinator] { get set } var navigationController: UINavigationController { get set } func start() }
While we’re making protocols, I usually add a simple
Storyboarded protocol that lets me create view controllers from a storyboard. As much as I like using storyboards, I don’t like scattering storyboard code through my project – getting all that out into a separate protocol makes my code cleaner and gives you the flexibility to change your mind later.
I don’t recall where I first saw this approach, but it’s straightforward to do. We’re going to:
Storyboarded.
instantiate(), which returns an instance of whatever class you call it on.
instantiate()that finds the class name of the view controller you used it with, then uses that to find a storyboard identifier inside Main.storyboard.
This relies on two things to work.
First, when you use
NSStringFromClass(self) to find the class name of whatever view controller you requested, you’ll get back YourAppName.YourViewController. We need to write a little code to split that string on the dot in the center, then use the second part (“YourViewController”) as the actual class name.
Second, whenever you add a view controller to your storyboard, make sure you set its storyboard identifier to whatever class name you gave it.
Create a second new Swift file called Storyboarded.swift, then give it the following protocol:
import UIKit protocol Storyboarded { static func instantiate() -> Self } extension Storyboarded where Self: UIViewController { static func instantiate() -> Self { // this pulls out "MyApp.MyViewController" let fullName = NSStringFromClass(self) // this splits by the dot and uses everything after, giving "MyViewController" let className = fullName.components(separatedBy: ".")[1] // load our storyboard let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) // instantiate a view controller with that identifier, and force cast as the type that was requested return storyboard.instantiateViewController(withIdentifier: className) as! Self } }
We already have a view controller provided by Xcode for this default project. So, open ViewController.swift and make it conform to
Storyboarded:
class ViewController: UIViewController, Storyboarded {
Now that we have a way to create view controllers easily, we no longer want the storyboard to handle that for us. In iOS, storyboards are responsible not only for containing view controller designs, but also for configuring the basic app window.
We’re going to allow the storyboard to store our designs, but stop it from handling our app launch. So, please open Main.storyboard and select the view controller it contains:
Storyboardedprotocol to work.
The final set up step is to stop the storyboard from configuring the basic app window:
That’s all our basic code complete. Your app won’t actually work now, but we’re going to fix that next…
At this point we’ve created a
Coordinator protocol defining what each coordinator needs to be able to do, a
Storyboarded protocol to make it easier to create view controllers from a storyboard, then stopped Main.storyboard from launching our app’s user interface.
The next step is to create our first coordinator, which will be responsible for taking control over the app as soon as it launches.
Create a new Swift File called MainCoordinator.swift, and give it this content:
import UIKit class MainCoordinator: Coordinator { var childCoordinators = [Coordinator]() var navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } func start() { let vc = ViewController.instantiate() navigationController.pushViewController(vc, animated: false) } }
Let me break down what all that code does…
childCoordinatorsarray to satisfy the requirement in the
Coordinatorprotocol, but we won’t be using that here.
navigationControllerproperty as required by
Coordinator, along with an initializer to set that property.
start()method is the main part: it uses our
instantiate()method to create an instance of our
ViewControllerclass, then pushes it onto the navigation controller.
Notice how that
MainCoordinator isn’t a view controller? That means we don’t need to fight with any of UIViewController’s quirks here, and there are no methods like
viewDidLoad() or
viewWillAppear() that are called automatically by UIKit.
Now that we have a coordinator for our app, we need to use that when our app starts. Normally app launch would be handled by our storyboard, but now that we’ve disabled that we must write some code inside AppDelegate.swift to do that work by hand.
So, open AppDelegate.swift and give it this property:
var coordinator: MainCoordinator?
That will store the main coordinator for our app, so it doesn’t get released straight away.
Next we’re going to modify
didFinishLaunchingWithOptions so that it configures and starts our main coordinator, and also sets up a basic window for our app. Again, that basic window is normally done by the storyboard, but it’s our responsibility now.
Replace the existing
didFinishLaunchingWithOptions method with this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // create the main navigation controller to be used for our app let navController = UINavigationController() // send that into our coordinator so that it can display view controllers coordinator = MainCoordinator(navigationController: navController) // tell the coordinator to take over control coordinator?.start() // create a basic UIWindow and activate it window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = navController window?.makeKeyAndVisible() return true }
If everything has gone to plan, you should be able to launch the app now and see something.
At this point you’ve spent about 20 minutes but don’t have a whole lot to show for your work. Stick with me a bit longer, though – that’s about to change!
Coordinators exist to control program flow around your app, and we’re now in the position to show exactly how that’s done.
First, we need some dummy view controllers that we can display. So, press Cmd+N to create a new Cocoa Touch Class, name it “BuyViewController”, and make it subclass from
UIViewController. Now make another
UIViewController subclass, this time called “CreateAccountViewController”.
Second, go back to Main.storyboard and drag out two new view controllers. Give one the class and storyboard identifier “BuyViewController”, and the other “CreateAccountViewController”. I recommend you do something to customize each view controller just a little – perhaps add a “Buy” label to one and “Create Account” to the other, just so you know which one is which at runtime.
Third, we need to add two buttons to the first view controller so we can trigger presenting the others. So, add two buttons with the titles “Buy” and “Create Account”, then use the assistant editor to connect them up to IBActions methods called
buyTapped() and
createAccount().
Fourth, all our view controllers need a way to talk to their coordinator. As I said earlier, for larger apps you’ll want to use protocols here, but this is a fairly small app so we can refer to our
MainCoordinator class directly.
So, add this property to all three of your view controllers:
weak var coordinator: MainCoordinator?
While you’re in
BuyViewController and
CreateAccountViewController, please also take this opportunity to make both of them conform to the
Storyboarded so we can create them more easily.
Finally, open MainCoordinator.swift and modify its
start() method to this:
func start() { let vc = ViewController.instantiate() vc.coordinator = self navigationController.pushViewController(vc, animated: false) }
That sets the
coordinator property of our initial view controller, so it’s able to send messages when its buttons are tapped.
At this point we have several view controllers all being managed by a single coordinator, but we still don’t have a way to move between view controllers.
To make that happen, I’d like you to add two new methods to
MainCoordinator:
func buySubscription() { let vc = BuyViewController.instantiate() vc.coordinator = self navigationController.pushViewController(vc, animated: true) } func createAccount() { let vc = CreateAccountViewController.instantiate() vc.coordinator = self navigationController.pushViewController(vc, animated: true) }
Those methods are almost identical to
start(), except now we’re using
BuyViewController and
CreateAccountViewController instead of the original
ViewController. If you needed to configure those view controllers somehow, this is where it would be done.
The last step – the one that brings it all together – is to put some code inside the
buyTapped() and
createAccount() methods of the
ViewController class.
All the actual work of those methods already exists inside our coordinator, so the IBActions become trivial:
@IBAction func buyTapped(_ sender: Any) { coordinator?.buySubscription() } @IBAction func createAccount(_ sender: Any) { coordinator?.createAccount() }
You should now be able to run your app and navigate between view controllers – all powered by the coordinator.
I hope this has given you a useful introduction to the power of coordinators:
I have a second article that goes into more detail on common problems people face with coordinators – click here to read my advanced coordinators tutorial.
If you’re keen to learn more about design patterns in Swift, you might want to look at my book Swift Design Patterns.
And finally, I want to recommend once again that you visit Soroush Khanlou’s blog, khanlou.com, because he’s talked extensively about coordinators, controllers, MVVM, protocols, and so much more:.
|
https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps?utm_campaign=Revue%20newsletter&utm_medium=Newsletter&utm_source=Swiftly%20Curated
|
CC-MAIN-2019-30
|
refinedweb
| 2,272
| 51.89
|
Node-PG database layer built with MoSQL
Paul Dirac was a theoretical physicist who made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. Dirac.js is a flexible and extendable database layer for Node Postgres.
Dirac.js is built on top of MoSQL, whose primary goal is to provide SQL query construction, but maintain value consistently throughout. This library extends that goal allowing you to reflect on the overall state of your database and retrieve your table structure in semantic JSON.
Dirac provides you with a decent foundation to start a postgres project with. It allows you to easily group all of your table logic and schema into one file and keep things generally dry and well-namespaced.
High-level single-query relationships helpers:
var options =// order.user -> {}// Make the user object available as a sub-json fieldone: table: 'users' alias: 'user'// order.restaurant -> {}table: 'restaurants' alias: 'restaurant'// order.restaurant.hours -> []// Within the restaurant object, fetch their hours in a json arraymany: table: 'restaurant_hours' alias: 'hours'// order.items -> []many: table: 'order_items' alias: 'items'// order.items[].price|options// Technically, just applies a left-joinmixin: table: 'restaurant_items'columns: 'price' 'options'// order.items[].tags -> [string]// Pull item tags into an array of stringspluck: table: 'restaurant_item_tags'column: 'name'alias: 'tags';diracdalsorders;
Register a new table with dirac:
var dirac = ;dirac;
Connect to your database, sync, and query:
dirac;// ordirac;// Tell dirac to use all of the schemas in `/tables`dirac;// Creates new tables, performs non-destructive schema changesdb; // Optionally pass { force: true } to do a complete wipe// You do not need to supply a callback.// You can start querying right away since node-pg// queues queries until readydiracdalsusers;// If the first parameter to findOne isn't an object, we assume we're querying by id// Dirac wraps the value in an object like this: { id: 57 }diracdalsusers;// Update user 57, set name = 'poop' returning "users".*diracdalsusers;// delete from users where name = "poop" returning *diracdalsusers;
Dirac has two namespaces:
The Root namespace is for top-level non-table specific methods while the Databasse namepace is for table specfic methods
Connect to Postgres
Arguments:
connStror
host,
port, and
database
pg.defaults
Options:
connectionString
Drops all tables registered in dirac.
Arguments:
(error)
Registers a new table or view with dirac. Will not actually create the table until
dirac.sync() is called. Alternatively, you could call:
dirac.dals.table_name.createIfNotExists() to manually add it. However,
sync will resolve table dependencies and it will also save the database state so dirac can reason about your current table structure.
Arguments:
Example:
// Register tabledirac;// Register Viewdirac;
Perform non-destructive syncs:
Options:
Pass a function to dirac to be called whenever
dirac.init is called. Useful for initializing before/after filters and adding database-wide properties to all schemas.
Arguments:
Example:
/*** db/middleware/created-at.js*/var utils = ;// Middleware automatically adds created_at/updated_at fields to schemasmodule{return {utils;// Adds fields to a DALvar {var schema = diracdals dal schema;// Add createdAt if it's not already thereif !optionscreatedAtname in schemaschema optionscreatedAtname = optionscreatedAt;// Add updatedAt if it's not already thereif !optionsupdatedAtname in schemaschema optionsupdatedAtname = optionsupdatedAt;};// Before filter adds updatedAt = 'now()' to the update queryvar {// Updates may be on values or updatesvar values = 'values' in $query ? $queryvalues : $queryupdates;values optionsupdatedAtname = 'now()';;};// Registers before filters to update updatedAtvar {diracdals dal ;};// Add fields to each DALObject// Add filters to each DALObject};};
/*** db/index.js*/var middleware =createdAt:;dirac;// DAL registration// ...// ...// After init is called, all functions specified in use are calleddirac;
Explicitly create a DALs table. You don't really need to use this unless you're adding new DALs, even then, you should just call
sync
Save an entry in the dirac_schemas table of the current DAL state in memory. This happens everytime you call
sync
Sets dirac's instance of MoSQL. Useful if you're already using MoSQL in your project.
All table interfaces are accessed through the
dirac.dals namespace. Each table is defined as an instance of Dirac.Dal.
Select documents in
table_name.
$query object is the
where property of a MoSQL object.
options is everything else.
Arguments:
function( error, results ){ }
Example:
// Query where conditionvar $query =rating: $gte: 35high_score: $lt: 5000name: $in: 'Bob' 'Alice' 'Joe' 'Momma';// Other options for the queryvar options =columns:'*' // users.*// Get average user high_scoretype: 'average' // Name of the functionas: 'average_score' // Name of the columnexpression: 'users.high_score' // Function argumentoffset: 50limit: 25order: column: 'id' direction: 'desc'group: 'id' 'name';diracdalsusers;
Identical to find only it adds a
limit: 1 to the options and will return an object rather than an array. Substitute an ID for $query.
Arguments:
function( error, result ){ }
Removes a document from the database. Substitute an ID for $query.
Arguments:
function( error, result ){ }
Update documents in the database. Substitute an ID for $query.
Arguments:
function( error, result ){ }
Insert a doument
Arguments:
function( error, result ){ }
Add a before filter to the DAL. Before filters are like middleware layers that get run before validationdiracdalsbooks;
Add an after filter to the DAL. After filters are like middleware layers that get run after castingdiracdalsbooks;
Transactions can be made by created a transaction object via
dirac.tx.create(). Normally, every query by default uses a pool client and releases it per request. You do not want to release a client back into the pool in the middle of a transaction, because that would be very, very bad.
For transactions, dirac allows you to access the same client to execute multiple queries until you commit or rollback.
Example:
var tx = diractx;tx;
This can be rather unwieldy so you could use a control library or abstract this further:
var async =var tx = diractx;async;
If you need to apply explicit table locks
to a transaction, you can use
.lock(mode) per table:
async;
To query the following
BEGIN;LOCK TABLE users IN ACCESS EXCLUSIVE MODE;UPDATE "users" set "users"."name" = 'Billy';COMMIT;
Creates a new
tx object which accesses the same pg.Client for transactional queries.
Invokes a
begin statement
Invokes the
commit statement and releases the
tx client. Subsequent queries will throw an error.
If you run into an error you can
rollback and release the client. Subsequent queries will throw an error.
All dirac.dals are available under the
tx object.
Example
var tx = diractx;txusers;txrestaurants;
Often times, you'll need to create custom functions that operate within its own transaction or part of an outside transaction. This is trivial to support and is outlined in the following example:
Suppose we want to create a function that atomically deletes existing user groups and saves new ones.
var tx = tx;tx;// Create a usertxusers;
How the DAL method would look:
name: 'users'schema: ...{// If this function is called within the context of an// existing transaction, the client/transaction object// will be available under `this.client`var tx = thisclient || diractx;async;}
Dirac exposes mongo-sql and pg instances through
dirac.db.
This way your database layer can reuse the same connection pool
and data access configurations.
The mongo-sql instance
Replaces the mosql object
Arguments
The node-pg instance
Replaces the node-pg object
Arguments
// Customizing pg so we parse timestamps into moment objectsvar pg = ;var dirac = ;var timestampOid = 1114;var {return ;}pgtypes;// Now abstractions such as dirac can reuse the same pg.diracdb;
Directory layout:
- my-app/- db/- tables/- table_1.js- table_2.js- table_3.js- index.js
index.js:
/*** db.js**/var dirac = ;var config = ;// Tell dirac to use all of the schemas in `/tables`dirac;dirac;// Get our database schemas up to date// This will add any tables and columnsdirac;// Expose dals on base db layer so I can do something like:// db.users.findOne( 7, function( error, user){ /* ... */ });for var k in diracdals moduleexports k = diracdals k ;
table_1.js:
/*** table_1.js* Export a JavaScript object containing the* table.name, table.schema**/moduleexports =name: 'table_1'schema:id: type: 'serial' primaryKey: truename: type: 'text'content: type: 'text'last_updated:type: 'date'withoutTimezone: truedefault: 'now()';
One of the nicest parts about dirac is its robust querying DSL. Since it's built on top of MoSQL, we get to take advantage of a fairly complete SQL API.
Find a single user by id:
diracdalsusers;
Find a user, join on groups and aggregate into array:
var options =columns:// Defaults to "users".*'*'// Columns can have sub-queries and expressions like this array_agg functiontype: 'array_agg' expression: 'groups.name' as: 'groups'// Specify all joins herejoins:groups:type: 'left'on: 'user_id': '$users.id$'// select "users".*, array_agg( groups.name ) as "groups" from "users"// left join "groups" on "groups"."user_id" = "users"."id"//// Now the user object will have an array of group namesdiracdalsusers;
Sub-Queries:
You can put sub-queries in lots of places with dirac/MoSQL
var options =// Construct a view called "consumers"with:consumers:type: 'select'table: 'users'where: type: 'consumer'var $query =name: $ilike: 'Alice'id:$in:type: 'select'table: 'consumers'columns: 'id';diracdalsusers;
Dirac has the following built-in middleware modules:
The relationships middleware allows you to easily embed foreign data in your result set. Dirac uses the schemas defined with
dirac.register to build a dependency graph of your schemas with pivots on foreign key relationships. It uses this graph to build the proper sub-queries to embed one-to-one or one-to-many type structures.
Relationships Directives
Full Blown Example:
var dirac = ;// Make sure to call relationships before registering tablesdirac;dirac;dirac;// Embed Order Items as an array on the order// Embed user and restaurant as json objectsvar options =many: table: 'order_items'alias: 'items'// Automatically do the left join to get item optionsmixin: table: 'order_item_options'one: table: 'restaurants'alias: 'restaurant'table: 'users'alias: 'user'// Automatically pull out just an array of group names// that apply to the user objectpluck: table: 'groups' column: 'name';diracdalsorders;
This is all done with a single query to the database without any result coercion.
The relationships middleware is applicable to writes, using the
returning statement:
// Pull in the restaurant and user objects after updatingvar options =one: table: 'restaurants'alias: 'restaurant'table: 'users'alias: 'user'// Automatically pull out just an array of group names// that apply to the user objectpluck: table: 'groups' column: 'name';dborders;
Applies a one-to-one relationship on the query:
// orders (id, user_id, ...)// users (id, ...)diracdalsorders// [{ id: 1, user: { ... } }, { id: 2, user: { ... } }]
Applies a one-to-many relationship on the query:
// users (id, ...)// orders (id, user_id, ...)diracdalsusers// { id: 32, orders: [{ id: 1, user_id: 32, ... }, { id: 2, user_id: 32, ... }] }
Like Many, but maps on a single field:
// users (id, ...)// groups (id, user_id, name, ...)diracdalsusers// { id: 32, groups: ['client', 'cool-guys'] }
Like One, but mixes in the properties from the target into the source (basically a more abstract join).
// Useful for junction tables// user_invoices (id, user_id, ...)// user_invoice_orders (id, user_invoice_id, order_id, ...)// orders (id, ...)dbuser_invoices// { id: 1, orders: [{ id: 1, user_invoice_id: 1, user_id: 1, restaurant_id, order_id }, ... ] }
|
https://www.npmjs.com/package/dirac
|
CC-MAIN-2016-40
|
refinedweb
| 1,790
| 54.93
|
>>.'"
One year (Score:5, Insightful)
from "no company" to "company delivers a product to customers" is not bad at all.
Re: (Score:2)
Here we have some people using other peoples money and a attitude of "right to succeed" despite seemingly having a rather ordinary product. Stop whining.
But i guess they got their name on slashdot.
Just like regular corporation Stockholders. If you do not have results by the next quarter, they throw you to the wolves.
Re: (Score:2, Funny)
Just like regular corporation Stockholders. If you do not have results by the next quarter, they throw you to the wolves.
So what mental illness causes people to randomly capitalize nouns that are not proper nouns?
It's Related to the mental Defect that causes people to comment on Stupid typos.
Re: (Score:2)
Man, if you could have made those caps into a vulgar term, you would have been gold.
Re: (Score:2)
Man, if you could have made those caps into a vulgar term, you would have been gold.
I see what you mean! I'll work on that.
Anyhow, the real reason I tend to hit the shift key is from long years and hours of working with titles for videos and PowerPoints. So I used a lot of title case typing. And it slips in everyonce in a while, even when AC's decide it is a mental illness. Hey, I am - but not for that reason.
Re: (Score:2)
Re: (Score:2)
Concentration (Score:4, Insightful)
That's why China already owns the USA's ass in manufacturing. There are too many holes in the manufacturing capability now while in China the place to make that other thing is just down the road - like it used to be in the USA.
Re: (Score:2)
Re:Concentration (Score:5, Interesting) [igg.me] If you want a cheap laser cutter.
Re: (Score:1)
Re: (Score:2)
no, you are going "100% sourced in USA" from a guy who gets M140 diodes and the rest of the stuff from china.
Re: (Score:3)
I get parts from the open market and build something that is more than the sum of its parts. The PCBs are made here (But, where is the copper mined? where is the solder mask stuff made? etc.), assembled here (but where does the solder come from?), the machining is done here (but who mined the alluminium and made the extrusions, and where?), and the plastic parts are printed here (but where does the
Re: (Score:2)
Re: (Score:1)
That's why China already owns the USA's ass in manufacturing.
China Owns America's ass in manufacturing because their Guvmint heavily subsidizes it.
Re: (Score:1)
How? and why? Their manufacturing accounts for something like 80% of GBP, what would they subsidize it with?
They keep their currency artifically low & they allow for huge inbalance in trade by buying gazxillons of dollar bonds. But you do realize you have to pay them eventually. Sooner or later China finishes preparing (they buy tons of gold right now), and say "check". You believe that USA will be able to pay all that bonds? Riiiight.
Re: (Score:2)
Re:Concentration (Score:4, Insightful)
and because environmental and human safety does NOT MATTER in china. people die? who cares. air can't be breathed? who cares. but hey, they are selling walmart shit to us and so, wow, go china, go!
;(
Re: (Score:2)
Please stop spouting bullshit like this. Where did you read it, Huffington Post? China isn't like what you think it is. Frankly, it's racist to say that people can't care about the environment because they're Chinese. There are protests all the time and these things do have an effect.
You can't expect people to take what you're saying seriously if your argument is "Walmart blaaarrrgh!"
Re: (Score:2)
China doesn't care about its people because it has too many of them. Life is cheap, much like India. It has nothing to do with race and everything to do with culture.
They have way too many living beings so no one cares what happens to a few.
Re: (Score:2)
Re: (Score:3)
There are too many holes in the manufacturing capability now while in China the place to make that other thing is just down the road - like it used to be in the USA.
Manufacturing is coming back to the Americas (North/Central/South) specifically because of problems mentioned in TFA
But Sparseâ(TM)s manufacturing partners there initially had trouble making the die-cast metal parts to the right tolerances, and there was a high rejection rate for units with the silver finish.
âoeI really care about making things perfect, and it takes a certain amount of time to solve things when the problems crop up and the information has to filter up the supply chain,â Owen says. âoeIt can take you a week to see if they are shipping the same part you presented to them.â
Problems like those can still happen with local manufacturing, but they get noticed and resolved in days, not weeks.
Re: (Score:2)
Once again, an example of my point. A concentration of industry and the designers having access to the process line/s makes a massive difference. Selling the farm to China, Mexico etc removes those advantages.
Re: (Score:2)
We're still number 2 in the world in manufacturing, so perhaps its a bit of an exaggeration to say they "own us" in that category. The idea that our manufacturing sector is in shambles is a myth.
While some is treading water plenty is a shambles (Score:2)
Re: (Score:2)
Pick a field outside of the military (or even inside the military with rocket engines coming from Russia) and it is a shambles, especially with computer and electronic equipment.
mac pro made in america. moto made in america. model s made in america. prediction, 10 years more than half of apple's stuff will be made in america.
Re: (Score:2)
As I wrote, treading water
:(
Hopefully that outlier will become a trend and hopefully it will take less than ten years while some electronics industry still exists in the USA to take up the work.
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:1)
Fifteen years from now those Chinese made parts will be manufactured in Africa and SE Asia.
Shame the light itself sucks (Score:2)
For all the marketspeak and fancy looks they're still asking $140 for a 200 lumen light. That's about a half step above terrible. The light I use, which is pretty much the minimum brightness I would consider safe as a "see" and not a "be seen" light, is 900 lumens.
Re: (Score:2)
In fact, they charge money for a device making light, who needs that? We have a fusion reactor in the center of our solar system that delivers us with light. So why pay money for something you get for free?
(Sorry had to make this stupid comparison)
Its about the marketing, not about the hard numbers. Do the people buy apple hardware because there is no cheaper alternative, or the storage-capacity is the cheapest?
When you buy a device, you not just buy the specs, you purchase a bunch of things, as the brand,
No cheaper alternative compatible with purchases (Score:2)
Do the people buy apple hardware because there is no cheaper alternative
Correct. There is no cheaper alternative to play books, videos, and apps with Apple DRM, except perhaps an as-is previous-generation device from a pawn shop. And when the iPhone and iPod touch first came out, iTunes Plus hadn't landed yet, and people wanted a phone compatible with their library of FairPlay DRM purchases from what was then called the iTunes Music Store. Finally, the iPhone arrived roughly a year before the HTC Dream, and the iPod touch had a four year lead over Samsung's Galaxy Player, givin
Re: (Score:2)
You jest, but my bike's headlight is a Harbor Freight LED flashlight that I got for free (with a coupon).
Re: (Score:2)
What 900 lumen light are you using?
I've got a couple 900 lumen lights and they're bright enough that if I shine them at cars the drivers are mildly upset about the brightness. It's like hitting them with high beams (although not covering as much area as a headlight).
I agree 200 lumens and the down-facing output is strange. I expect this is for urban riders who mostly use the streetlights to see.
Re: (Score:2)
One of the older magicshines I've had for a while. 900 lumens is closer to a regular headlight than highbeams, which can be into the thousands of lumens over a much larger area. As for bothering people... it's a headlight, it's SUPPOSED to be that bright. That's why you angle them down a bit.
Re: (Score:2)
It's a years old model at this point. It WAS one of the top end magicshines at the time, now it's probably midrange compared to the thousand plus lumen multi-lights they've got. Bright side of mine though is the controls are much simpler and I get much better battery life. You can find them pretty much all over ebay.
Re: (Score:2)
Fixed battery?! USB charger?! (Score:3)
I was thinking "looks good", until I saw that this setup uses a dual-headed USB charger that sure looks designed for indoor use only. I'm fine with a fixed battery in my cell phone, tablet, and even laptop, but my bike a) lives outdoors and b) need to accept a spare battery because working lights can be a life-or-death matter.
Nice design, but seriously deficient function.
Re: (Score:2)
Who sells C sells by the late hour?
^see what I did there?
;-)
Yes. You misspelled "cells".
Re: (Score:2)
Line up suppliers beforehand, and use their flex (Score:5, Informative)
The good thing is that my supply chain was already in place, so all I had to do was increase quantities. I did, however, have to design a simple machine (a jig, basically) to semi-automate a task I had intended to do by hand. [igg.me] if anyone cares.
Re: (Score:2)?... [youtube.com] This is what I use for the machining.?... [youtube.com] This is how I get the 3D printer to just keep going (I am going to be selling this as a kit too).
This is an integral part of engineering a product to me - you can't just make a prototype and send the drawings "off in the cloud" to be made. I mean, I guess you can, but then how can you be sure that it was made well? Se
Trivial hardware is still challenging (Score:5, Insightful).
No. Hardware is Silicon Valley's founding religion. Software came later and now real hardware startups can not get funding. Sparce's experience shows that even if your development is trivial (no significant R&D) and you don't do any of the manufacturing yourself, it can still be a bumpy road to selling product.
I see no evidence that this is improving. All that has happened is that ambitious hardware startups no longer happen and people are getting excited over hobby scale development that didn't use to make the news. Well, to be fair, Kickstarter has allowed "super hobby" scale developments to take off that used to fall into a no-man's land. They were too small to form a viable business around and yet too big for a couple of guys to pull off in their spare time. Still, this is nowhere near a hardware renaissance. The promise land is not just some distance away. There is little evidence that we are going there.
Set good expectations (Score:2)
I've backed a bunch of projects on Kickstarter and Indiegogo. A few completed in the time they expected, most didn't. It didn't bother me that they were late, it bothered me they didn't take this kind of stuff into account when setting expections with the backers.
Re: (Score:1)
IMHO It's not that hard. (Score:1)
Re: (Score:1)
Our hardware (also software heavy) start up was recently acquired for an exponent of our annual gross revenue.
What does that mean? Exponents go negative, so you're basically saying that it was acquired for the annual gross revenue multiplied by a numer between epsilon and infinity.
Re: (Score:1)
Re: (Score:2)
Our hardware (also software heavy) start up was recently acquired for an exponent of our annual gross revenue.
hopefully the gross revenue was >> 0 and the exponent was > 1
Hardware is Silicon Valley's new religion (Score:3)
uhm, who writes this tripe?
SILICON VALLEY has always been about hardware.
where do you think the word 'silicon' comes from?
sheesh.
#include <stopped_reading_there.jpg>
Re: (Score:2)
I hadn't thought about it when reading the submission and web page link. But that is true, isn't it?
Thanks for cracking me up.
:^)
Re: (Score:2)
Silicon Valley is great if you can do something consumer facing and very, very easy. There are great designers in Silicon Valley, but the old-school infrastructure and blue collar understanding is gone. The people who are really good at hardware have moved to different places in the country.
If you want to do anything with any amount of technical difficulty, go to San Diego, Boston, Austin, etc.
I don't think that it's strictly consumer-facing/easy vs. other stuff; but 'shovelling software' vs. other stuff. Yes, the valley is host to a plague of idiotic mobile-social-app-centric-nonsense-startup-wankery; but part of what makes setting up yet another stupid company to deliver worse-than-worthless drivel so fast, cheap, and relatively frictionless is the presence of actual real work, done by adults, in areas like refining the hell out of datacenter operation.
You certainly aren't going to have a go
Real Potholes (Score:2)
I misread that. I was hoping this was a startup that had some innovative, cheap way to repair potholes. Some of us have to deal with [cleveland.com] some really awful potholes [google.com] even in June, well past the end of winter [wikipedia.org].
Re:Real Pothole Repair (Score:2)
The can do the job. One-person operation. No need to leave the cab to patch a pothole. A patching job takes only a few minutes. Good quality patches. Requires a skilled operator who's good with a complex joystick, controlling air jets, asphalt conveyors, and rollers. [pythonmfg.com]
Do web design, and want to do something useful? Contact the company, in Saskatchewan, and offer to redesign their 2009 web site with bad layout, non-streaming video, and a lack of testimonials.
A more ambitious plan would be to use compute
This product turns a profit??? (Score:1)
Wow... Hipster bicycle wanks are even bigger suckers than Hipster cult of the Mac wanks...
Oh... Wait. My bad - subset of the same Hipster wank crowd. Carry on.
Re: (Score:2)
Besides that, how "theft-proof" is it really, if the thief just have to be able to take the seat/post out of the frame? A couple of my bikes, back when I still rode bikes, had the quick-set levers on the top of the upright tube, to make it easy to set the height of the seat. This light would make stealing my seat worth $70 more.
As for bikes without the quick-set levers, a set of tools to adjust that same opening isn't that hard to come by, or difficult to use.
Re: (Score:2)
That's what locking skewers [amazon.com] (link is an example, not a suggestion) are for.
Re: (Score:2)
i's crossed and t's dotted (Score:2)
'We had all the t's crossed and all the i's dotted and still there was a big daily surprise,' says industrial designer Colin Owen...
I'll assume Mt. Owen is just inexperienced, and not outright delusional. There are no inherent problems with hardware manufacturing supply lines that experienced managers can't compensate for. If one vendor flakes, you buy from the second or third source you already lined up. In advance, because you are not stupid/inexperienced/delusional.
Re: (Score:2)
Better still, some of them come with a full set of adapters that will fit pretty much any plug anywhere. I didn't understand why that was such a problem either.
Everyone is wrong again. (Score:1)
The fact that people here are surprised by these "unexpected difficulties" is highly telling.
In the virtual world - which is all the data within any properly functioning computer - one thing is made true by design which isn't true of the real world.
It's very, very simple! *Entropy is conserved*.
IE: Within the computer, things stay exactly where they're left. Nothing degrades, bits stay exactly as they are. (abeit RAID 5 may "lose" one every ~100TB or so).
What this means, is that the second law of thermodyna
Advert -- nothing to do with Silicon Valley (Score:5, Informative)
The summary made it sound like an electronic hardware startup, and the difficulties behind competing with the bigwigs like IBM, AMD, Intel, Cisco, Apple, etc.
No, it's click-bait.
As nice as a bicycle headlamp is (that will still be stolen -- thieves don't use normal tools, and they're usually supporting a drug habit), the article didn't even talk about manufacturing in Silicon Valley, or even San Francisco (which is 45 miles north), and they had no unoriginal issues with certifications in other countries. I'm voting this article down. Re-submit with an accurate summary next time.
A bicycle light - pathetic (Score:5, Insightful)
Too many of these supposed "high tech hardware startups" are producing the kind of crap that came from China two decades ago and Japan four decades ago. Bicycle lights. iPhone cases. Even the Raspberry Pi and the Arduino are just PC boards stuck under systems on a chip made in China. This is not high tech.
There were some guys at TechShop last year making a plastic gizmo for attaching an iWhatever to a an auto dashboard. They had a big "Made in Silicon Valley" poster. I felt they were embarassing Silicon Valley.
We need to do better than this.
Re: (Score:2)
What you are witnessing is the completely unqualified wealthy class getting more than their share of opportunity, simply because they are wealthy.
What you are witnessing is the completely broke poor class trying to break into the wealthy class that has absolutely no interest in penny-ante plastic trash. The wealthy class pays people to pay people to pay people to make shit like that bicycle light. They do not bother to even read the reports, let alone participate.
Re: (Score:3)
The point of the Pi and Arduino is not so much the hardware as the support and community. The hardware for both is trivial, especially the Pi which is literally the minimal reference design from the datasheet. Before they came along the was no standard low cost platform for Linux and microcontroller development that was as easy as Lego to get started with.
These days hardware is usually the easy part, it's what you do with it that counts.
Re: (Score:1)
I agree that we need to do better, but the funding for hardware startups isn't there. The risks are perceived as being too great, and long gone are the days when someone builds an Apple I in their garage. I thought the Novena laptop was a good step in the right direction, but that clearly demonstrates the challenges involved when competing with hardware designed at scale. Software is just so much more accessible and cheaper to build.
That's normal (Score:2)
the biggest hiccups were very localized and unpredictable.
What a surprise.
The things you anticipate are those that you predicted and prepared for. It is always the unpredicted ones which cause hiccups.
In the end, you cannot prepare for all eventualities, but you must budget for a number of them that will hit you, even when you cannot say precisely in advance what or when they will be. If you don't, your project will come in late and over budget.
Blatant Slashvertisment (Score:3)
TFA is 20 full-screen pictures of their product, and page after page of copy about how awesome the product is. Only barely a mention of some minor hiccups, that get treated as an industry problem, rather than the realities of an incompetent start-up that simply didn't know WTF it was doing.
And frankly, $140 for a set of 'sleek' bicycle lights makes me want to go on a killing spree.
Buy a couple 3-mode SK68 lights for $5/ea. Brighter than you could ever want, with high/low/strobe, and multiple zoom settings:... [amazon.com]
Some $2 bike mounts:... [amazon.com]
And if you don't want to cut-out some red cellophane to fit, you can get a kit with red lens for the tail light:... [amazon.com]
Batteries and Charger, < $13:... [amazon.com]... [amazon.com]
Re: (Score:2)
Only barely a mention of some minor hiccups, that get treated as an industry problem, rather than the realities of an incompetent start-up that simply didn't know WTF it was doing.
I tend to agree with you on that one. The PSU was refused certification in the EU three times? How the hell is that even possible? The damn things use a USB charger, I cannot believe you can't just buy one off the shelf in bulk at a decent price that has already been through all the international certification process.
|
https://tech.slashdot.org/story/14/06/06/2357244/sparses-story-illustrates-the-potholes-faced-by-hardware-start-ups?sdsrc=prev
|
CC-MAIN-2017-04
|
refinedweb
| 3,698
| 72.16
|
0
New to the forum and C. I am trying to write a function that will allow me to remove a certian string from and exisiting one. The below program I wrote by using examples in an text book and online. I understand it at a basic level, but I'm pretty lost when it comes to figuring out how the difference array work with one another. Could any one give me some help in getting this going, and maybe point me in the direction of a good piece that explains this in idiot language.
Thanks
#include <stdio.h> void removeString (char string[], char remove[]) { int index, source, numchar[81]; for(index = 0; index < 80, index++;) { numchar[index]= 0; } index = 0; while(remove[index]) { numchar[remove[index]] = 1; index++; } index = source = 0; do { if(! numchar[string[index]]) { string[source++] = string[index]; } } while(string[index++]); } int main (void) { char string[] = "Hello World"; char remove[] = "World"; char result = 0; removeString(string, remove); printf ("The Result is %s\n", result); }
|
https://www.daniweb.com/programming/software-development/threads/321911/remove-string-function-in-c
|
CC-MAIN-2017-26
|
refinedweb
| 167
| 69.31
|
Now that you have an overview of the data model and targets that are available, we'll next look at some example interactions to see how the targets are populated.
We'll use 'Emma' as an example member who starts by writing a post. Her contacts engage on her post and we'll look at how the target namespaces are populated for each interaction.
Example activities
A member posts a share
Emma is writing and sharing an update about her plans:
This is the share as seen on her contacts' timeline:
When Emma posts this share it creates an interaction. PYLON receives the interaction and populates targets with attributes of the share. The following targets and namespaces are populated:
A member engages with the share
Charlie is one of Emma's contacts, he chooses to like her post. The like is seen on other member's timelines like this:
The like creates a new interaction that is received by PYLON. Attributes of the like, and the post being liked are used to populate targets and namespaces as follows:
A member comments on the share
Hugo comments on Emma's post, this creates a new interaction. The main difference between Charlie's like and Hugo's comment is that a comment has content.
Targets are populated with the content of the comment and the root share activity.
A member likes the comment
Next Charlie likes Hugo's comment.
Now we have a chain of activities. The targets are populated with details of Charlie's like and Emma's root share, but not with the intermediate comment from Hugo.
A member shares an external article
The previous examples used the share of a post. In the next examples we'll look at the extra information available when the share is of an article.
Emma is going to share an external article. She does this by including a link in her post.
LinkedIn follows the link and collects metadata about the page from the <meta> tags on the page. In this example, LinkedIn have used the title, description, image and URL tags in the share.
<meta property="og:title" content="Apple's iPhone 7 ditches traditional headphone socket - BBC News" /> <meta property="og:type" content="article" /> <meta property="og:description" content="Apple confirms that its new iPhone will not feature a traditional headphone socket." /> <meta property="og:site_name" content="BBC News" /> <meta property="og:locale" content="en_GB" /> <meta property="article:author" content="BBC News" /> <meta property="article:section" content="Technology" /> <meta property="og:url" content="" /> <meta property="og:image" content="" />
The usual user member targets are populated (with Emma's details), and now the article areas of the namespace can be populated with details of the external article. However, with external articles the article author is not knowable so this namespace remains unpopulated.
A member shares a LinkedIn article
If Emma had chosen to share an article on LinkedIn then the
li.all.articles.author.* targets would be have been populated with demographic details of the author of the article.
Example events
Carrying on from the example above we'll now look at events in the same way.
A member clicks on a shared article
Charlie clicks on Emma's External Article share, generating a click event.
The click has created a new interaction that is received by PYLON. Attributes of the click, and the article being clicked are used to populate targets as follows:
A member views an external article
Now Charlie has clicked the share, he is viewing the content. This generates an article view event.
Note that not all content on all domains will trigger an article view event.
Targets for the event are populated as follows:
A member views a LinkedIn article
Again, if Emma had chosen to share an article on LinkedIn then the
li.all.articles.author.* targets would be have been populated with demographic details of the author of the article.
A member expands a share or comment
As well as the events described above, there is also the 'expand' click type. This event occurs when a member clicks a 'show more' link on a newsfeed activity or comment.
For this event the value of
li.subtype is 'click|expand'. The same targets are populated as for the click event as described above.
Article view without a preceding click event
An article view event can be received without a corresponding click event when someone clicks on a link to a LinkedIn article from outside of LinkedIn.
In this case
li.subtype will equal
article|view.
Because the article has been posted on LinkedIn the targets in the
li.all.articles.author.* namespaces will be populated, as the author is known.
Next steps...
Now that you have an in-depth undestanding of the target and namespaces, next you'll learn how to configure identities which you'll use to run your analysis queries.
|
http://dev.datasift.com/docs/products/pylon-lei/howto/developer-guide/example-linkedin-interactions
|
CC-MAIN-2017-26
|
refinedweb
| 816
| 53.51
|
JavaScript, in particular Node.js, has been frequently associated with callback hell . If you’ve written code that deals with a lot of async I/O, you’re probably familiar with this pattern:
export default function getLikes () { getUsers((err, users) => { if (err) return fn(err); filterUsersWithFriends((err, usersWithFriends) => { if (err) return fn(err); getUsersLikes(usersWithFriends, (err, likes) => { if (err) return fn (err); fn(null, likes); }); }); }); }
It turns out, this code can be much easier and safer to write.
I’ll show you how
Promise combined with
async /
await enables this, but also some of the lessons we’ve learned from using these new features in production.
Let’s start with the pitfalls of the example above.
Error handling is repetitive
In a great majority of cases, you want to just pass the error along .
In the example above, however, you repeat yourself many times. It’s also easy to miss a
return and only discover it (with non-obvious debugging) when the error actually occurs.
Error handling in unspecified
When errors occur, most popular libraries will invoke the callback with an
Error parameter, or in the success case use
null instead.
Unfortunately this is not always the case. You might get
false instead of
null . Some libraries omit it altogether. If several errors occur, you might even get multiple callbacks! Which leads us to…
Scheduling is unspecified
Does the callback fire immediately? or on a different microtask ? or on a different tick? Sometimes? Always?
Who knows! Reading your own code certainly won’t tell you. Reading the library’s documentation might tell you, if you’re lucky.
It’s possible that the callback will fire more than once without you expecting it. Once again, this will almost certainly result in code that’s extremely hard to debug .
In certain cases, the code might continue to run but not doing quite what it should. In others, you might get a stack trace that doesn’t exactly make the root cause obvious.
The solution to these problems is the standarization on
Promise .
Promises present a clear contract and API to you. While we might disagree on whether the details and API of this contract are the best ones, they’re strictly defined.
Thus, the lack of specification we mentioned above is not a concern when you’re dealing with code that uses
Promise .
This is what the equivalent to
setTimeout would look like using
Promise :
function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } sleep(100) .then(() => console.log('100ms elapsed')) .catch(() => console.error('error!'));
Promises can be in two settled states: resolved and rejected. As seen above, you can set up a pair of callbacks two obtain the resolved value and the rejected value.
The fact that we pass callbacks to a promise shows that we often deal with somewhat of a false dichotomy. Obviously, promises need callbacks to do anything meaningful. The real comparison is then between promises and the callback pattern that the JavaScript community has informally agreed upon.
Promises represent a single value. Unlike the callback pattern above, you can’t get an error followed by success for the a certain invocation. Or get a value and an error later on.
You can think of
resolve as the
Promise equivalent of
return and
reject as
throw . As we’ll see later on, this semantic equivalency is syntactically realized by the
async and
await keywords.
As far as scheduling goes, the
Promise spec has settled on always invoking callbacks "at a future time" (i.e.: the next microtask). This meants the behavior of a
Promise is consistently asynchronous every time you call
then or
catch , whether it’s already been settled or not.
If we write our initial example with this API it would look as follows:
export default function getUsers () { return getUsers() .then(users => filterUsersWithFriends) .then(usersWithFriends => getUsersLikes); }
This already looks much better! That said, if our logic were to change, refactoring the code gets complicated very quickly.
Imagine that in the code above, a particular type of failure of
filterUsersWithFriends needs to be handled differently:
export default function getUsers () { return new Promise((resolve, reject) => { getUsers().then(users => { filterUsersWithFriends(users) .then(resolve) .catch((err) => { resolve(trySomethingElse(users)); }); }, reject) }); }
No amount of chaining "convenience" can save us. Let’s look at the solution.
The future: async and await
As it’s been known for a while in the C# and F# world , there’s an elegant solution to our problems:
export default async function getLikes () { const users = await getUsers(); const filtered = await filterUsersWithFriends(users); return getUsersLikes(filtered); }
For this to work, we just need to make sure that the functions that perform I/O that we depend on (like
getUsers ) return a
Promise .
Not only is it easier to read (as the chaining example was), but now the error handling behavior is the exact same as regular synchronous JavaScript code.
That is, when we
await a function, errors (if any) are surfaced and
throw n. If our
getLikes function is invoked, errors bubble up by default. If you want to handle a particular error differently, just wrap your
await invocation with
try /
catch .
This will increase your productivity and correctness as you won’t be writing (or worse, ignoring!)
if (err) return fn(err) everywhere.
How certain are we of this future?
Promiseis already in all modern mobile and desktop browsers and Node.js 0.12+
async/
awaithas been almost completely implemented in V8 , Edge and Firefox .
We’ve been using these features at ▲ ZEIT for many months now and have been extremely happy and productive with them.
I recently published a guide to transpiling with Babel and Node 6, which due to its great support for ES6 now only needs two transformation plugins and exhibits great compilation performance.
If you want support for the browser or older versions of Node, I suggest you also include the
es2015 preset. This will compile to a state machine instead of generators.
In order to maximize your usage of this feature, you’ll want to use modules from the ecosystem that expose
Promise instead of just a callback.
- Some modules already do both.
node_redis, for example, exposes
Promiseif you suffix
Asyncto the methods it exposes.
- Some modules exist to wrap existing modules with
Promise. You can usually identify these by their prefix or suffix
thenor
promise. Examples:
fs-promise,
then-sleep.
In addition to these, Node is considering returning
Promise s directly in the standard library. You can follow that discussion here .
I also need to stress that this syntax doesn’t make
Promise go away from your codebase. In fact, you must have a thorough understanding of them, which you’ll frequently need .
A common example where
Promise makes an appearence is code that requires multiple values as part of a loop, which are requested concurrently:
const ids = [1, 2, 3]; const values = await Promise.all(ids.map((id) => { return db.query('SELECT * from products WHERE id = ?', id); }));
Notice also that in the example presented above (
async getLikes() ), I opted to
return getUserLikes() instead of
return await getUserLikes() .
Since the goal of the
async keyword is to make the function return a
Promise , those two snippets are therefore equivalent.
This means that the following code:
async function getAnswer () { return 42; }
…is perfectly valid and equivalent to its sync counter-part
const getAnswer = () => 42 with the exception that when invoked with
await it will resolve in the next microtask . When called without
await , it will return a
Promise .
The boulevard of broken Promises
Earlier I mentioned the
Promise spec set out to solve a host of problems we would frequently run into with callbacks.
I’ll cover some of the problems that have remained or have been now introduced, and some behaviors that were left unspecified but are critical for our needs.
Debugging difficulties
When you use a
Promise and don’t attach an error handler, in many environments you might never find out about the error.
This is the equivalent to ignoring the
err parameter in the callback pattern, with the difference that a
TypeError is likely to occur when you try to access the value you’re interested in.
In the callback pattern, while you can manage to ignore
err , you’re likely to find out with a crash later on when the error does occur.
Ignoring errors is normally quite difficult to do with
async and
await , however. The exception would be the entry point of your asynchronous code:
async function run () { // your app code… } run().catch((err) => { // make sure to handle the error! });
Fortunately, there are workarounds and a potential definitive solution to this problem:
- Chrome and Firefox warn about unhandled rejections in the developer tools.
- Node.js emits
unhandledRejection, with which you can log manually. I recommend you read this discussion about the implications of unhandled rejections for backend systems.
- Top-level support for
awaitin the future would make the manual
Promiseinstantiation and catching unnecessary!
Finally, I mentioned earlier that
Promise s will be resolved once, unlike callbacks that could fire multiple times unexpectedly.
The problem is that once again,
Promise s will swallow subsequent resolutions and more concerningly, rejections. There might be errors that are never logged!
The original
Promise spec left out the semantics of cancelling the ongoing asynchronous retrieval of a value.
As fate would have it, browser vendors went on to implement them as the return value of functions that have historically needed cancelation, like HTTP requests.
Namely, with
XMLHttpRequest you can call
abort on the resulting object, but with the new and shiny
fetch … you can’t.
TC39 is now considering the addition of a third state: cancelled. You can read more about the stage 1 proposal here .
While retro-fitted to
Promise s, cancellation is a fundamental property of the next abstraction we’ll cover: the
Observable .
Earlier in the post it became evident that waiting on a
Promise to resolve is somewhat equivalent to a function doing some work and returning a value synchronously.
The
Observable is a more general (and therefore more powerful) abstraction that represents a function invokation that can return several values.
Unlike
Promise ,
Observable objects can return synchronously (same tick) or asynchronously.
These design decisions make an
Observable suitable for a wider range of usecases.
In the spirit of our earlier examples, here’s how
Observable can work with
setInterval to give us a value over time:
function timer (ms) { return new Observable(obv => { const i = 0; const iv = setInteval(() => { obv.next(i++); }, ms); return () => clearInterval(iv); }); }
As I mentioned earlier,
Observable covers a broader spectrum of possibility. From this lense, a
Promise is simply an
Observable that returns a single value and completes:
function delay(ms) { return new Observable(obv => { const t = setTimeout(() => { obv.next(); obv.complete(); }, ms); return () => clearTimeout(t);c }); }
Notice that the value returned in the setup of the
Observable is a function that performs cleanup. Such a function is executed when no subscriptions are left:
const subscription = delay(100).subscribe(); subscription.unsubscribe(); // cleanup happens
This means that
Observable also fills another missing gap in
Promise : cancelation. In this model, cancelation is simply a consequence of the cease of observation .
With this said, a lot of asynchronous work can be expressed with only the
Promise subset just fine. As a matter of fact, a great portion of the core library of Node.js only needs that (the exceptions being
Stream and some
EventEmitter ).
What about
async and
await ? One could implement an operator that restricts the behavior of a given
Observable to that of a
Promise (which libraries like RxJS already have ) and
await it:
await toPromise(timer(1000));
This example shows us the generalization in action: the
timer function is just as useful as
delay , but also works for intervals!
async and
await will enable significant improvements in your codebases.
Our open-source library micro is a great example of how the request / response cycle can be made a lot more straightforward.
The following microservice responds with a
JSON encoded array of users a database.
If any of the handlers throw, the response is aborted with
err.statusCode .
If unhandled exceptions occur, a 500 response is produced and the error logged.
export default async function (req, res) { await rateLimit(req); const uid = await authenticate(req); return getUsers(uid); }
As mentioned, proposals have been made for ES6 modules to admit a top-level
await . For Node.js this would mean being able to write code like this:
import request from 'request'; const file = await fs.readFile('some-file'); const res = await request.post('/some-api', { body: { file } }); console.log(res.data);
and then run it without any wrappers (and straight-forward error handling)!
▲ node my-script.mjs
Simultaneously,
Observable continues to make progress within TC39 to become a first-class construct of the language.
I believe these new primitives for managing concurrency and asynchrony will have a very profound impact on the JavaScript ecosystem. It’s about time .
- A litmus test for callback hell: does a Ryu performing Hadouken fit in your indentation?
- The pattern can be summarized as follows: the callback is invoked once, on a different tick, with an
Errorobject as the first parameter in the case of an error, or
nulland the intended value as the second. However, deviations from this implicit agreement are commonly encountered in the ecosystem. Some libraries omit the error object and emit an
errorevent somewhere else. Some callbacks fire with multiple values. Et ceter » Async and Await
评论 抢沙发
|
http://www.shellsec.com/news/24614.html
|
CC-MAIN-2016-44
|
refinedweb
| 2,246
| 55.24
|
Interview Tips - Java Interview Questions
Interview Tips Hi,
I am looking for a job in java/j2ee.plz give me interview tips. i mean topics which i should be strong and how to prepare. Looking for a job 3.5yrs experience
hi sir - Java Beginners
the details sir,
Thanks for ur coporation sir Hi Friend,
Please visit the following link: sir Hi,sir,i am try in netbeans for to develop the swings,plz
GUI Tips
Java NotesGUI Tips
[Beginning of list of GUI tips -- needs much more]
Program structure
main can be in any class, but it's often
simplest to understand if it's in a separate class.
main should do very little work roseindia - Java Beginners
hi roseindia what is object? A Blue print of class Hi deepthi,
Objects are the basic run time entity or in other words....
Thanks.
Amardeep,... - Struts
Hi... Hello Friends,
installation is successfully
I... write the classpath and send classpath command Hi,
you set path = C:\j2sdk1.5\bin;
and JAVA_HOME=C:\j2sdk1.5;
Thanks Check this.... - Java Beginners
Hi Check this.... Hi Sakthi here..
Run This Code..
Hi sakthi
Your code is not visible here, can u send again please..
Thanks... - urgent want to write code in java for change password please provide the code
change password have three field old_pwd,new_pwd,con_pwd
Thanks Hi Friend,
Create a database table login[id friends
i am using ur sending code but problem is not solve my code is to much large i am this code please check it and solve its very urgent
Hi ragini,
First time put the hard code after... Hello Friend
I want to some code please write and me
I want to add dynamic row value in onChange event created dynamic... and send me..... its very urgent Hi friend,
Plz specify the technology
hi - Java Beginners
hi hi sir,Thanks for ur coporation,
i am save the 1 image,Thanks for ur coporation,
i am save the 1 image... that image is rendered to my frame,that's my question Hi Friend...("Frame in Java Swing");
f.getContentPane().setLayout(null);
l=new JLabel
hi - Java Beginners
hi hi sir,i am", "
Hi.. - Java Beginners
Hi.. Hi,
I hv some page within jsps folder
this is admin.jsp
this page create some link left side if i am clicking create user then admin_create_user.jsp page should be open within admin.jsp but this is open in another how i make a program if i take 2 dimensional array in same program & add each row & column & make other dimensional array by the help of switch case & also i do subtraction & search dialognal element in this. Hi ...CHECK - Java Beginners
Hi ...CHECK Hi Da..sakthi Here
RUN THIS CODE
-----
package bio;
import java.lang.*;
import java.awt.*;
import java.awt.Color;
import... ");
Screen.showMessage(" DON WORRY WE'ILL ROCK ");
}
}
}
Hi
Hi... - Java Beginners
Hi... Hi friends
I want to make upload file module please help...please write the using mvc1 rule
I have three field emp_id,name,file...; Hi Friend,
Try the following code:
1)page.jsp:
Display file
Hi.. - Java Beginners
Hi.. Hi friends,
I want to display two calendar in my form,one is dislay successfully but another is not please tell me how display second... is successfully but date of birth is not why...
Hi Friend,
Try,when i am enter a one value in jtextfield the related values to that value (which is already existed in database) is came to my... phone no sir Hi Friend,
Try the following code:
import
Hi...doubt on Packages - Java Beginners
..Explain me. Hi friend,
Package javax.mail
The Java Mail API allows...Hi...doubt on Packages Does import.javax.mail.* is already Existing Package in java..
I have downloaded one program on Password Authentication
Hi Friend.. Doubt on + - Java Beginners
}
}
Hi friend,
Tips and Tricks
Tips and Tricks
... in Java
Java provides a lot of fun while programming. This article shows you how... and keyboard related operation through java code for the purposes of test automation, self
Tips & Tricks
Tips & Tricks
Here are some basic implementations of java language, which you would... screen button on the keyboard, same way we can do it through java programming
Hi .Again me.. - Java Beginners
Hi .Again me.. Hi Friend......
can u pls send me some code......
REsponse me.. Hi friend,
import java.io.*;
import java.awt....://
Thanks. I am sending running code
Hi..Date Program - Java Beginners
Hi..Date Program Hi Friend...thank for ur Valuable information...
Its displaying the total number of days..
but i WANT TO DISPLAY THE NUMBER OF DAYS BY EACH MONTH...
Hi friend,
Code to solve the problem
Hi ..doubt on DATE - Java Beginners
Hi ..doubt on DATE Hi Friend...Thank u for ur valuable response..
IS IT POSSIBLE FOR US?
I need to display the total Number od days by Each month...
WAIT I WILL SHOW THE OUTPUT:
---------------------------------
ENTER
Hi Friend..IS IT POSSIBLE? - Java Beginners
Hi Friend..IS IT POSSIBLE? Hi Friend...Thank u for ur valuable response..
IS IT POSSIBLE FOR US?
I need to display the total Number od days by Each month...
WAIT I WILL SHOW THE OUTPUT
Hi..Again - Swing AWT
hi sir,how to set a title for jtable plz tell me sir Hi... information, visit the following link:
Thanks
hi plzz reply
hi plzz reply in our program of Java where we r using the concept of abstraction Plz reply i m trying to learn java ...
means in language of coding we r not using abstraction this will be used only for making ideas
hi - Date Calendar
hi sir,i am do the project on swings,i want a datepicker in java,how to use datepicker in my swings application,plz provide a example for to use...
ThanQ Hi Friend,
Try the following code
Hi..How to Display Days by month - Java Beginners
Hi..How to Display Days by month Hi Friend....
I have a doubt... to students....
..Thank u ..
Hi Prabhu g
I am sending... to you in solving your query regarding javadate.
Hi Friend ..Doubt on Exceptions - Java Beginners
Hi Friend ..Doubt on Exceptions Hi Friend...
Can u please send some Example program for Exceptions..
I want program for ArrayIndexOutOfbounds
OverFlow Exception..
Thanks...
Sakthi Hi friend,
Code
hi sakthi prasanna here - Java Beginners
hi sakthi prasanna here import java.lang.*;
import java.awt....) {
e.printStackTrace();
}
// TODO: handle exception
}}}
Hi friend...://
Thanks
|
http://www.roseindia.net/tutorialhelp/comment/93666
|
CC-MAIN-2013-48
|
refinedweb
| 1,073
| 77.13
|
Bitstreams produced by Quartus (in ttf format) are not suitable to be directly burned on the flash since their nibble encoding is reverse.How come Altera (Intel) chip can't be burned with firmware produced by Altera's (Intel's) software? Where can I read about this?
__attribute__ ((used, section(".fpga_bitstream_signature")))
const unsigned char signatures[4096] = {
#include "signature.h"
};
__attribute__ ((used, section(".fpga_bitstream")))
const unsigned char bitstream[] = {
#include "app.ttf"
};
Hello, what differences does the VHDL code/commands I write for a Xilinx have, comparing to the VHDL I am going to write for the MKRVidor4000?FPGA is synthesized with Quartus Prime. They plan to use premade images for several usecase. If I remember right there was plan to do some web integration for fpga build.
Hi.Also that's pretty slow if you have lite version NIOS II e. Recommend to use HW acceleration for H lines and BMP copy
Apparently, the port of Adafruit GFX for VidorBistream needs some adjustments.
The code for filling the primitives will mostly use writeVLine() function, while SDRAM would much prefer the horizontal lines.
I think you have to call build_all.sh in project folder. you have to add scripts folder to path env variable.Well, the whole idea of 'update_fw.sh' is to update the data to be put in on-chip ram, without recompiling the entire fpga project.
$ I:/Downloads/VidorBitstream/TOOLS/scripts/build_all.sh
2019.06.12.12:10:48 Info: Saving generation log to I:/Downloads/VidorBitstream/projects/MKRVIDOR4000_template_mbox/build/MKRVIDOR4000_template_mbox_lite_sys/MKRVIDOR4000_template_mbox_lite_sys_generation.rpt
2019.06.12.12:10:48 Info: Starting: <b>Create HDL design files for synthesis</b>
2019.06.12.12:10:48 Info: qsys-generate I:\Downloads\VidorBitstream\projects\MKRVIDOR4000_template_mbox\build\MKRVIDOR4000_template_mbox_lite_sys.qsys --synthesis=VERILOG --output-directory=I:\Downloads\VidorBitstream\projects\MKRVIDOR4000_template_mbox\build\MKRVIDOR4000_template_mbox_lite_sys\synthesis --family="Cyclone 10 LP" --part=10CL016YU256C8G
2019.06.12.12:10:48 Info: Loading build/MKRVIDOR4000_template_mbox_lite_sys.qsys
2019.06.12.12:10:48 Info: Reading input file
2019.06.12.12:10:48 Info: Adding JTAG_BRIDGE_0 [JTAG_BRIDGE 1.0]
2019.06.12.12:10:48 Info: Parameterizing module JTAG_BRIDGE_0
2019.06.12.12:10:48 Info: Adding clk [clock_source 18.1]
2019.06.12.12:10:48 Info: Parameterizing module clk
2019.06.12.12:10:48 Info: Adding flash_clk [clock_source 18.1]
2019.06.12.12:10:48 Info: Parameterizing module flash_clk
2019.06.12.12:10:48 Info: Adding flash_spi [tiny_spi 1.0]
2019.06.12.12:10:48 Info: Parameterizing module flash_spi
2019.06.12.12:10:48 Info: Adding mb [MAILBOX 1.0]
2019.06.12.12:10:48 Info: Parameterizing module mb
2019.06.12.12:10:48 Info: Adding nina_spi [tiny_spi 1.0]
2019.06.12.12:10:48 Info: Parameterizing module nina_spi
2019.06.12.12:10:48 Info: Adding nios2_gen2_0 [altera_nios2_gen2 18.1]
2019.06.12.12:10:48 Info: Parameterizing module nios2_gen2_0
2019.06.12.12:10:48 Info: Adding onchip_memory2_0 [altera_avalon_onchip_memory2 18.1]
2019.06.12.12:10:48 Info: Parameterizing module onchip_memory2_0
2019.06.12.12:10:48 Info: Adding pex_pio [PIO 1.0]
2019.06.12.12:10:48 Info: Parameterizing module pex_pio
2019.06.12.12:10:48 Info: Adding qspi [arduino_generic_quad_spi_controller2 18.1]
2019.06.12.12:10:48 Warning: qspi: Component type <b>arduino_generic_quad_spi_controller2</b> is not in the library
2019.06.12.12:10:48 Info: Parameterizing module qspi
2019.06.12.12:10:48 Info: Adding sam_pio [PIO 1.0]
2019.06.12.12:10:48 Info: Parameterizing module sam_pio
2019.06.12.12:10:48 Info: Adding sam_pwm [PWM 1.0]
2019.06.12.12:10:48 Info: Parameterizing module sam_pwm
2019.06.12.12:10:48 Info: Adding sdram [altera_avalon_new_sdram_controller 18.1]
2019.06.12.12:10:48 Info: Parameterizing module sdram
2019.06.12.12:10:48 Info: Adding sysid_qsys_0 [altera_avalon_sysid_qsys 18.1]
2019.06.12.12:10:48 Info: Parameterizing module sysid_qsys_0
2019.06.12.12:10:48 Info: Adding timer_0 [altera_avalon_timer 18.1]
2019.06.12.12:10:48 Info: Parameterizing module timer_0
2019.06.12.12:10:48 Info: Adding wm_pio [PIO 1.0]
2019.06.12.12:10:48 Info: Parameterizing module wm_pio
2019.06.12.12:10:48 Info: Building connections
2019.06.12.12:10:48 Info: Parameterizing connections
2019.06.12.12:10:48 Info: Validating
2019.06.12.12:10:49 Info: Done reading input file
2019.06.12.12:10:51 Error: MKRVIDOR4000_template_mbox_lite_sys.qspi: Component <b>arduino_generic_quad_spi_controller2 18.1</b> not found or could not be instantiated
2019.06.12.12:10:51 Info: MKRVIDOR4000_template_mbox_lite_sys.sdram: SDRAM Controller will only be supported in Quartus Prime Standard Edition in the future release.
2019.06.12.12:10:51 Info: MKRVIDOR4000_template_mbox_lite_sys.sysid_qsys_0: System ID is not assigned automatically. Edit the System ID parameter to provide a unique ID
2019.06.12.12:10:51 Info: MKRVIDOR4000_template_mbox_lite_sys.sysid_qsys_0: Time stamp will be automatically updated when this component is generated.
2019.06.12.12:10:51 Warning: MKRVIDOR4000_template_mbox_lite_sys.JTAG_BRIDGE_0: Interrupt sender <b>JTAG_BRIDGE_0.irq</b> is not connected to an interrupt receiver
2019.06.12.12:10:51 Warning: MKRVIDOR4000_template_mbox_lite_sys.flash_spi: Interrupt sender <b>flash_spi.irq</b> is not connected to an interrupt receiver
2019.06.12.12:10:51 Warning: MKRVIDOR4000_template_mbox_lite_sys.nina_spi: Interrupt sender <b>nina_spi.irq</b> is not connected to an interrupt receiver
2019.06.12.12:10:51 Warning: MKRVIDOR4000_template_mbox_lite_sys.JTAG_BRIDGE_0: <b>JTAG_BRIDGE_0.event</b> must be connected to an Avalon-MM master
2019.06.12.12:10:51 Error: MKRVIDOR4000_template_mbox_lite_sys.qspi.avl_mem: Data width must be of power of two and between 8 and 4096
2019.06.12.12:10:51 Info: MKRVIDOR4000_template_mbox_lite_sys: Generating <b>MKRVIDOR4000_template_mbox_lite_sys</b> "<b>MKRVIDOR4000_template_mbox_lite_sys</b>" for QUARTUS_SYNTH
2019.06.12.12:10:53 Info: Interconnect is inserted between master JTAG_BRIDGE_0.avalon_master and slave mb.mst because the master has address signal 32 bit wide, but the slave is 9 bit wide.
2019.06.12.12:10:53 Info: Interconnect is inserted between master JTAG_BRIDGE_0.avalon_master and slave mb.mst because the master has waitrequest signal 1 bit wide, but the slave is 0 bit wide.
2019.06.12.12:10:53 Info: Interconnect is inserted between master JTAG_BRIDGE_0.avalon_master and slave mb.mst because the master has readdatavalid signal 1 bit wide, but the slave is 0 bit wide.
2019.06.12.12:10:55 Error: null
2019.06.12.11:59:41 Info: Adding qspi [arduino_generic_quad_spi_controller2 18.1]Did you apply patches to Quartus? You need to do it once.
2019.06.12.11:59:41 Warning: qspi: Component type <b>arduino_generic_quad_spi_controller2</b> is not in the library
Info: Quartus Prime Shell was successful. 0 errors, 352 warnings
Info: Peak virtual memory: 4626 megabytes
Info: Processing ended: Sat Jun 22 02:28:30 2019
Info: Elapsed time: 00:06:33
Info: Total CPU time (on all processors): 00:00:05
create ram + flash app.ttf
Jun 22, 2019 2:28:30 AM - (INFO) elf2flash: args = --input=build/software/MKRVIDOR4000_graphics/MKRVIDOR4000_graphics_lite.elf --output=build/output_files/MKRVIDOR4000_graphics_lite.flash --base=0x008E0000 --end=0x008FFFFF --verbose --save
Jun 22, 2019 2:28:30 AM - (FINE) elf2flash: Starting
Jun 22, 2019 2:28:30 AM - (FINE) elf2flash: Done
projects
ip
cp: omitting directory './ip/GFX/arduino/Vidor_GFX/examples'
cp: omitting directory './ip/QUAD_ENCODER/arduino/VidorEncoder/examples'
cp: omitting directory './ip/NEOPIXEL/arduino/VidorNeopixel/examples'
cp: omitting directory './ip/MIPI_RX_ST/arduino/VidorCamera/examples'
Ok, now I'm really confused. I did a really basic test to see that my app.ttf is loaded correctly:This is exactly what I've been trying to solve, I cleared (keep the file but delete all the contents) both app.ttf and signature.h and nothing changed
1) Installed precompiled VidorGraphics from Library Manager
2) Flashed the QR example to the board - QR recognition works
3) Built the *VidorPeripherals* app.ttf from source (e.g: NOT the VidorGraphics app.ttf)
4) Put my custom-built *VidorPeripherals* app.ttf into the *VidorGraphics* precompiled library's folder (overwriting the precompiled app.ttf for *VidorGraphics*)
5) Once again flashed the QR example to the board
6) QR recognition is STILL WORKING?!
But - I flashed the sketch using the wrong app.ttf (VidorPeripherals), which should not contain the necessary things for camera + QR recognition??
So why is QR recognition still working? Has the app.ttf not been flashed to the FPGA at all?
Can someone please describe how they got the VidorBitstream workflow to work correctly? Am I missing something obvious?
Hi,Hello, I'm also having the same problem. I tried multiple app.ttf (even with app.ttf with no contents), the results are all the same. I'm pretty confused as the code does try to read app.ttf and signature but the contents don't matter.
Thanks for the updated files, the Quartus patches seem to work fine now!
I am having problems running the example files however (starting with a slightly modified bare example that should set an output pin to 1 lighting up an LED). If I merely create an Arduino library (as is suggested in the github readme), the Arduino IDE complains that FPGA is defined twice (once in the VidorFPGA.cpp file in the VidorPeripherals library and once in my test library). I can comment out the offending lines in either of the libraries, but I am not certain how to figure out which app.ttf gets loaded in the end.
I have not yet managed to turn the output LED on through code written in Quartus. It seems to me that no matter what app.ttf I try to load, the example sketches from VidorPeripherals (setting outputs to on and off) seem to work. This indicates to me that I am always just loading the pre-compiled FPGA code, am I misunderstanding something?
I have also tried running the blinking example sketch written by Philippe which was posted here earlier and while Quartus indicates that everything compiles fine, the LED connected to port 6 never blinks. Is there a way for me to debug whether I have a problem with my FPGA? (The VidorPeripheral examples work!)
EDIT: Turns out I had screwed up something during my early debugging attempts, restoring the bootloader (according to the other thread) fixed my issue.
I have not tried flashing an empty app.ttf, but it sounds like storage isn't cleared before the new bitstream is written to it... Could it be that flashing an empty file causes *nothing* to be written, which leaves the old bitstream in place? Whereas flashing a new (potentially smaller) bitstream might still leave old data around, but it will never be read, and so it won't matter?This feels like a dead sub-forum, the mods' last post is since May, and many questions left unanswered. I don't feel very safe pushing on with my project.
Could an Arduino employee please confirm whether it is possible to build a working camera or QR example from the VidorBitstream source?
That would be super helpful, so that we know whether to press on or not.
Thanks!
I will try to look these. I just updated my computer so I have to reinstall all tool chains.Thanks, I appreciate any help!
Also that Arduino team radio silence is not what I like.
At least Vidor4000 have moved to normal branch. Earlier it was only in Beta devices.
Also remember you can only use one FPGA image at time.
IMO:
I think currently Vidor is ok for basic FPGA learning with Quartus Lite and USB Blaster sketch.
I would recommend to use serial or SPI for data transfer to FPGA and USB Blaster sketch for debugging FPGA.
Currently biggest problem is missing documentation of mailbox system and no select for VCCIO for banks (no LVDS in mini PCIe connector).
If I remember right boot loader need some data in .fpga_bitstream section that is outside of SAMD flash area. If it's empty it won't access to FLASH connected to FPGA.Is there any part of the code that confirms this .fpga_bitstream requirement? I don't question your claim/memory, I just want to have something I can look at and answer questions by myself.
|
https://forum.arduino.cc/index.php?action=printpage;topic=581316.0
|
CC-MAIN-2020-10
|
refinedweb
| 2,033
| 53.58
|
On 2007-09-04, Matthew Dillon <dillon@apollo.backplane.com> wrote: >:Hi. >: >:We are getting an error printed may times with each ramdisk access on >:a custom ramdisk rootfs we are creating on Dragonfly 1.10.1. >:The error is >: >: md: si_iosize_max not set! >:... >: >:Is this a bug, or is there something we are supposed to be doing >:different starting with 1.10? >: >:Regards. >:Vincent > > It's a bug. Try this patch. > > -Matt > Matthew Dillon > <dillon@backplane.com> > > Index: md.c >=================================================================== > RCS file: /cvs/src/sys/dev/disk/md/md.c,v > retrieving revision 1.17 > diff -u -p -r1.17 md.c > --- md.c 31 Jul 2007 20:04:48 -0000 1.17 > +++ md.c 4 Sep 2007 02:18:45 -0000 > @@ -373,6 +373,8 @@ DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_ > DEVSTAT_PRIORITY_OTHER); > sc->dev = disk_create(sc->unit, &sc->disk, &md_ops); > sc->dev->si_drv1 = sc; > + sc->dev->si_iosize_max = DFLTPHYS; > + > return (sc); > } > Thank you for the very fast response Matt. I thought it was appropriate to move this thread to the bugs list. I patched and recompiled the kernel, but probably will not get a chance to test it out until tomorrow. I'll let you know. In the mean time, I thought I would point out an apparent bug in cvs on Dragonfly that your patch exposed. Since it is a different topic, I will start a new thread following this posting to give you the details.
|
http://leaf.dragonflybsd.org/mailarchive/bugs/2007-09/msg00017.html
|
CC-MAIN-2013-48
|
refinedweb
| 234
| 69.58
|
Hide Forgot
I have 2 shared libraries that both define symbols of the
same name. When I import these modules into python and call
the method with the shared name, I always exectue the method
of the last module imported.
Ex: If I have 2 shared modules written in C, each with a
different module name, but both having a function called
foo, the following code breaks.
import A
import B
A.foo() #Really calls B.foo
My code that uses this was originally written and worked
with the non-redhat rpms available at
Mike
Not Found
The requested URL /python/files/python-1.5.2-2.src.rpm was not found
on this server.
Binary rpms don't do us much good... :-)
Unfortunately, the patch that I believe breaks this for you appears
to have been added to fix something else. I'm assigning this bug
to the developer who added that patch. (Matt, it's
python-1.5.2-dl-global.patch -- what's this about libtool, and why
is the patch there in the first place?)
Unfortunately I can't address this until we start using the Python 2.0 package.
|
https://partner-bugzilla.redhat.com/show_bug.cgi?format=multiple&id=6062
|
CC-MAIN-2020-34
|
refinedweb
| 194
| 75
|
.
1. Understand jQuery!
When you call 'jQuery' what happens?
The jQuery function itself is very simple:
jQuery = function (selector, context) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init(selector, context); };
Under its skin, the jQuery function (commonly referred to as the "wrapper" function) simply returns an instantiated jQuery object -- i.e. an instance of the 'jQuery.fn.init' constructor.
This is useful to know; with this information we know that each time we call 'jQuery' we're actually creating a totally unique object with a set of properties. jQuery is clever in that it gives you an object that can be treated as an array. Each of your elements (all together, commonly known as the "collection") is referenced within the object under a numerical index, just like within an array. And jQuery also gives this object a 'length' property, just as you would expect from an array. This opens up a world of possibilities. For one, it means that we can borrow some functionality from 'Array.prototype'. jQuery's 'slice' method is a good example of this -- modified from the source:
/* ... jQuery.fn.extend({ ... */ slice: function() { return this.pushStack( Array.prototype.slice.apply( this, arguments ), "slice", Array.prototype.slice.call(<WBR>arguments).join(",") ); }, /* ... */
The native 'slice' method doesn't care that 'this' is not a real array-- it'll be fine with anything that's got a 'length' property and [0], [1], [2] etc.
There are some other interesting properties within this jQuery object -- '.selector' and '.context' will, most of the time, reflect the arguments that you pass into 'jQuery(...)'.
var jqObject = jQuery('a'); jqObject.selector; // => "a"
One thing that's important to note is that jQuery will sometimes give you new jQuery objects to work with. If you run a method that changes the collection in some way, such as '.parents()', then jQuery won't modify the current object; it'll simply pass you a brand new one:
var originalObject = jQuery('a'); var anotherObject = originalObject.parents(); originalObject === anotherObject; // => false
All methods that appear to mutate the collection in some way return a brand new jQuery object -- you can still access the old object though, via '.end()', or more verbosely, via '.prevObject'.
2. Bread-and-butter Element Creation
Central to jQuery's DOM capabilities, is its element creation syntax. 1.4 brought with it an entirely new way to create your elements quickly and succinctly. E.g.
var myDiv = jQuery('<div/>', { id: 'my-new-element', class: 'foo', css: { color: 'red', backgrondColor: '#FFF', border: '1px solid #CCC' }, click: function() { alert('Clicked!'); }, html: jQuery('<a/>', { href: '#', click: function() { // do something return false; } }) });
As of 1.4 you can pass a second argument to the jQuery function when you're creating an element -- the object you pass will, for the most part, act as if you were passing it to '.attr(...)'. However, jQuery will map some of the properties to its own methods, for example, the 'click' property maps to jQuery's 'click' method (which binds an event handler for the 'click' event) and 'css' maps to jQuery's 'css' method etc.
To check out what properties map to jQuery's methods, open your console and type 'jQuery.attrFn'.
3. Serialize your Inputs
jQuery provides a method that you can use to serialize all of the inputs within one or more forms. This is useful when submitting data via XHR ("Ajax"). It's been in jQuery for a long time but it's not often talked about and so many developers don't realise it's there. Submitting an entire form via Ajax, using jQuery, couldn't be simpler:
var myForm = $('#my-form'); jQuery.post('submit.php', myForm.serialize(), function(){ alert('Data has been sent!'); });
jQuery also provides the 'serializeArray' method, which is designed to be used with multiple forms, and the 'param' helper function (under the jQuery namespace) which takes a regular object and returns a query string, e.g.
var data = { name: 'Joe', age: 44, profession: 'Web Developer' }; jQuery.param(data); // => "name=Joe&age=44&profession=<WBR>Web+Developer"
4. Animate Anything
jQuery's 'animate' method is probably the most flexible of jQuery's methods. It can be used to animate pretty much anything, not just CSS properties, and not just DOM elements. This is how you would normally use 'animate':
jQuery('#box').animate({ left: 300, top: 300 });
When you specify a property to animate (e.g. 'top') jQuery checks to see if you're animating something with a style property ('element.style'), and it checks if the specified property ('top') is defined under 'style' -- if it's not then jQuery simply updates 'top' on the element itself. Here's an example:
jQuery('#box').animate({ top: 123, foo: 456 });
'top' is a valid CSS property, so jQuery will update 'element.style.top', but 'foo' is not a valid CSS property, so jQuery will simply update 'element.foo'.
We can use this to our advantage. Let's say, for example, that you want to animate a square on a canvas. First let's define a simple constructor and a 'draw' method that'll be called on every step of the animation:
function Square(cnvs, width, height, color) { this.x = 0; this.y = 0; this.width = width; this.height = height; this.color = color; this.cHeight = cnvs.height; this.cWidth = cnvs.width; this.cntxt = cnvs.getContext('2d'); } Square.prototype.draw = function() { this.cntxt.clearRect(0, 0, this.cWidth, this.cHeight); this.cntxt.fillStyle = this.color; this.cntxt.fillRect(this.x, this.y, this.width, this.height); };
We've created our 'Square' constructor, and one of its methods. Creating a canvas and then animating it couldn't be simpler:
// Create a <canvas/> element var canvas = $('<canvas/>').appendTo('body'<WBR>)[0]; canvas.height = 400; canvas.width = 600; // Instantiate Square var square = new Square(canvas, 70, 70, 'rgb(255,0,0)'); jQuery(square).animate({ x: 300, y: 200 }, { // 'draw' should be called on every step // of the animation: step: jQuery.proxy(square, 'draw'), duration: 1000 });
This is a very simple effect, but it does clearly demonstrate the possibilities. You can see it in action here: (this will only work in browsers that support the HTML5 canvas)
5. jQuery.ajax Returns the XHR Object
jQuery's Ajax utility functions ('jQuery.ajax', 'jQuery.get', 'jQuery.post') all return an 'XMLHttpRequest' object which you can use to perform subsequent operations on any request. For example:
var curRequest; jQuery('button.makeRequest').<WBR>click(function(){ curRequest = jQuery.get('foo.php', function(response){ alert('Data: ' + response.responseText); }); }); jQuery('button.cancelRequest')<WBR>.click(function(){ if (curRequest) { curRequest.abort(); // abort() is a method of XMLHttpRequest } });
Here we're making a request whenever the 'makeRequest' button is clicked -- and we're cancelling the active request if the user clicks the 'cancelRequest' button.
Another potential usage is for synchronous requests:
var myRequest = jQuery.ajax({ url: 'foo.txt', async: false }); console.log(myRequest.<WBR>responseText);
Read more about the 'XMLHttpRequest' object and also be sure to check out jQuery's Ajax utilities.
6. Custom Queues
jQuery has a built-in queuing mechanism that's used by all of its animation methods (all of which use 'animate()' really). This queuing can be illustrated easily with a simple animation:
jQuery('a').hover(function(){ jQuery(this).animate({<WBR>paddingLeft:'+=15px'}); }, function(){ jQuery(this).animate({<WBR>paddingLeft:'-=15px'}); });
Quickly hovering over a bunch of anchors and then hovering over them again will cause the animations to queue up and occur one at a time -- I'm sure many of you have witnessed this queuing effect before. If not, check it out here:
The 'queue' method is similar to the well-known 'each' method in how it's called. You pass a function, which will eventually be called for each of the elements in the collection:
jQuery('a').queue(function(){ jQuery(this).addClass('all-<WBR>done').dequeue(); });
Passing just a function to 'queue' will cause that function to be added to the default 'fx' queue, i.e. the queue used by all animations done by jQuery. Therefore, this function will not be called until all current animations occurring on each element in the collection (in this case, all anchors) have completed.
Notice that we're adding a class of 'all-done' in the function above. As outlined, this class will only be added when all current animations are complete. We're also calling the 'dequeue' method. This is very important, as it will allow jQuery to continue with the queue (i.e. it lets jQuery know that you're finished with whatever you're doing). jQuery 1.4 provides another way of continuing the queue; instead of calling 'dequeue', simply call the first argument passed to your function:
jQuery('a').queue(function(<WBR>nextItemInQueue){ // Continue queue: nextItemInQueue(); });
This does exactly the same, although it's slightly more useful in that it can be called anywhere within your function, even within a mess of closures (that typically destroy the 'this' keyword). Of course, pre-jQuery-1.4 you could just save a reference to 'this', but that would get a bit tiresome.
To add a function to a custom queue, simply pass your custom queue's name as the first argument and the function as the second:
jQuery('a').queue('<WBR>customQueueName', function(){ // Do stuff jQuery(this).dequeue('<WBR>customQueueName'); });
Notice that, since we're not using the default 'fx' queue, we also have to pass our queue's name to the 'dequeue' method, in order to allow jQuery to continue with our custom queue.
Read more about 'queue', 'dequeue' and 'jQuery.queue'.
7. Event Namespacing
jQuery provides a way for you to namespace events, which can be very useful when authoring plugins and third-party components. If needed, the user of your plugin can effectively disable your plugin by unbinding all event handlers that it's registered.
To add a namespace when registering an event handler, simply suffix the event name with a period and then your unique namespace (e.g. '.fooPlugin'):
jQuery.fn.foo = function() { this.bind('click.fooPlugin', function() { // do stuff }); this.bind('mouseover.<WBR>fooPlugin', function() { // do stuff }); return this; }; // Use the plugin: jQuery('a').foo(); // Destroy its event handlers: jQuery('a').unbind('.<WBR>fooPlugin');
Passing just the namespace to 'unbind' will unbind all event handlers with that namespace.
Conclusion
So which ones did I miss? Any helpful features that you feel jQuery doesn't document well enough? Let's discuss in the comments!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
|
https://code.tutsplus.com/tutorials/uncovering-jquerys-hidden-features--net-9472
|
CC-MAIN-2020-45
|
refinedweb
| 1,751
| 57.37
|
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
The C++ functions or function objects that are called whenever
a part of the parser successfully recognizes a portion of the input. Say
you have a parser
P, and
a C++ function
F. You can
make the parser call
F
whenever it matches an input by attaching
F:
P[F]
The expression above links
F
to the parser,
P.
The function/function object signature depends on the type of the parser
to which it is attached. The parser
double_
passes the parsed number. Thus, if we were to attach a function
F to
double_,
we need
F to be declared
as:
void F(double n);
There are actually 2 more arguments being passed (the parser context and a reference to a boolean 'hit' parameter). We don't need these, for now, but we'll see more on these other arguments later. Spirit.Qi allows us to bind a single argument function, like above. The other arguments are simply ignored.
Presented are various ways to attach semantic actions:
Given:
namespace client { namespace qi = boost::spirit::qi; // A plain function void print(int const& i) { std::cout << i << std::endl; } // A member function struct writer { void print(int const& i) const { std::cout << i << std::endl; } }; // A function object struct print_action { void operator()(int const& i, qi::unused_type, qi::unused_type) const { std::cout << i << std::endl; } }; }
Take note that with function objects, we need to have an
operator()
with 3 arguments. Since we don't care about the other two, we can use
unused_type for these.
We'll see more of
unused_type
elsewhere.
unused_type
is a Spirit supplied support class.
All examples parse inputs of the form:
"{integer}"
An integer inside the curly braces.
The first example shows how to attach a plain function:
parse(first, last, '{' >> int_[&print] >> '}');
What's new? Well
int_ is
the sibling of
double_.
I'm sure you can guess what this parser does.
The next example shows how to attach a simple function object:
parse(first, last, '{' >> int_[print_action()] >> '}');
We can use Boost.Bind to 'bind' member functions:
writer w; parse(first, last, '{' >> int_[boost::bind(&writer::print, &w, _1)] >> '}');
Likewise, we can also use Boost.Bind to 'bind' plain functions:
parse(first, last, '{' >> int_[boost::bind(&print, _1)] >> '}');
Yep, we can also use Boost.Lambda:
parse(first, last, '{' >> int_[std::cout << _1 << '\n'] >> '}');
There are more ways to bind semantic action functions, but the examples above are the most common. Attaching semantic actions is the first hurdle one has to tackle when getting started with parsing with Spirit. Familiarize yourself with this task and get intimate with the tools behind it such as Boost.Bind and Boost.Lambda.
The examples above can be found here: ../../example/qi/actions.cpp
Phoenix, a companion library bundled with Spirit, is specifically suited for binding semantic actions. It is like Boost.Lambda on steroids, with special custom features that make it easy to integrate semantic actions with Spirit. If your requirements go beyond simple to moderate parsing, it is suggested that you use this library. All the following examples in this tutorial will use Phoenix for semantic actions.
|
http://www.boost.org/doc/libs/1_54_0/libs/spirit/doc/html/spirit/qi/tutorials/semantic_actions.html
|
CC-MAIN-2017-47
|
refinedweb
| 542
| 55.34
|
CalicoDevelopment.
Initially, connections to robots (real and simulated) will be made through the Microsoft Robotics Developer Studio (MSRDS) API [2]. This is made through a set of services defined for each robot, sensor, actuator, etc.
In addition, an alternative interface could be defined that allows direct connections to a robot, or through another API, such as Player/Stage. This may require a layer above the services, or a different set of objects. This interface could allow for models to be created in C# (or another .NET language).
Getting Started
One can program either in Visual Studio (only available on Windows) or in Mono (available on most Platforms). Mono has a development environment (called MonoDevelop), but you can also use any editor.
There is a free Visual Studio Express available from Microsoft.
Mono 1.9.1 comes with Fedora 9 and is also for free from Mono.
Mono
Download and install Mono version 1.9.1 or greater. You can then create a program, like this:
using System; // for Console public class HelloWorld { public static void Main(string[] args) { Console.WriteLine("Hello World!"); } }
Call that program hello.cs, and compile with:
gmcs hello.cs
You can run it with:
mono hello.exe
Libraries for Pyjama
If you create a Dynamically Linked Library (.DLL) then you can load the library in Python (or any language) and use it as if it were written in Python.
For example:
gmcs -target:library hello.cs
will create hello.dll which can be used in Python.
|
http://wiki.roboteducation.org/index.php?title=CalicoDevelopment&oldid=5480&printable=yes
|
CC-MAIN-2020-05
|
refinedweb
| 250
| 59.5
|
RSS Feeds
24th Annual TONERS & PHOTORECEPTORS 2007< ?:namespace prefix = o
Fess Parker’s Doubletree Resort
Santa Barbara, California
June 4 to 6
Happy New Year!
We’re Going Global and You’re Invited …
New Format! The conference starts on Monday for the first time ever and finishes on Wednesday afternoon.
New Discounts! Save $200 if you register and pay before January 31. Save $100 between February 1 and April 15.
New Registration Fee! $1,095 is the new reduced fee for 2007.
New Program! The Program for 2007 is attached. Visit for the latest updates, a list of Past Attendees, Hotel Reservation information and more.
Terry Gorka
The Tiara Group, LLC
805.659.2298 direct
805.659.1493 fax
805.340.0608 mobile
tgorka@thetiaragroup.com
Reference Link :
|
http://tonernews.com/forums/topic/webcontent-archived-15568/
|
CC-MAIN-2016-44
|
refinedweb
| 128
| 63.66
|
I
View Complete Post.
We take a look at planned support for parallel programming for both managed and native code in the next version of Visual Studio.
Stephen Toub and Hazim Shafi
MSDN Magazine October 2008 have unit test projects to test some workflows. So I have some InternalVisiblesTo in my main project so my test project can call them. But when I do workflows (.xaml) in the test project using some codeactivity also defined into the test projects, the
build doesn't see the InternalVisiblesTo attribute and I get errors like this one :
Error 1 'BugVSInternalVisiblesTo.Class1' ne contient pas de définition pour 'Method1' c:\Projects\BugVSInternalVisiblesTo\ActivityLibrary1\CodeActivity1.cs 9 41 ActivityLibrary1
Here are the steps to reproduce easily my case :
1- Create a C# Class Library project with this code :
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo ("ActivityLibrary1")]
namespace BugVSInternalVisiblesTo
{
public static class Class1
{
internal static void Method1 ()
{
}
}
}
2 : Create a new C# Workflow ActivityLibrary project named "ActivityLibra"/>
<
When I load my Visual Studio (C++ 2010 Express and / or Visual Basic 2010 Express, it's even happened with Web Developer 2010 Express and C# 2010 Express), it never seems to work properly.
As I'm sure you know, at load a start page is meant to show with a list of previously opened projects and the latest news on the product, but for me its just a solid colour of purple from the background colour of the application. If I manage to load a project
it does an initial refresh and seems fine, but when I scroll the code it doesn't refresh, the same can be said for when I goto edit the code.
I found that resizing the window and / or changing its maximized / minimized state generates a refresh and allows me to view changes, I've also found that restart my computer a few times or re-logging allows the VS collection to work fine. Interestingly
it will work, but then if I close it for more than a few hours it stops, and vise-versa.
I've re-installed both C++ 2010 Express and Visual Basic 2010 Express at least twice, I also have the latest drivers and service packs.
Any help will be appreciated, I hate coding in Notepad++ and then debugging in VS.
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
|
http://www.dotnetspark.com/links/30923-why-doesnt-visual-studio-support-msil-as.aspx
|
CC-MAIN-2018-05
|
refinedweb
| 396
| 55.88
|
Diff for Creating and distributing packages
Creating and distributing packages page describes a simple case of packaging GNU Smalltalk code, and then, secondly, at packaging code with C.
1. Creating a Package for GNU Smalltalk code
Suppose your package is contained in a single TestPack.st file:
Object subclass: TestPack [ TestPack class >> greet: aString [ ('hello %1!' % {aString}) printNl ] ]
package.xml should look like this:
TestPack TestPack.st TestPack.st
You can make a TestPack.star file and install it to the system-wide
package directory (usually /usr/share/smalltalk) using simply
gst-package package.xml
but you usually need root access for that. You can also install it just
for you:
gst-package -t ~/.st package.xml
(-t is short for --target-directory) and use it normally:
$ gst GNU Smalltalk ready st> PackageLoader fileInPackage: 'TestPack' Loading package TestPack PackageLoader st> TestPack greet: 'world' 'hello world!' TestPack st>
If you want to distribute the .star file, just create it in the current
directory:
gst-package -t. package.xml
Then, you or other people will be able to do any of
gst-package TestPack.star gst-package -t ~/.st TestPack.star
to install it (either globally or locally).
2. Creating a package with external C code
Let's assume you want to write a C binding for GNU Smalltalk that requires a custom C module; that is, using dynamic linking to a shared library is not enough. Even the smallest package of this kind will have a smalltalk code file with C call-outs defined, and a file with C source code.
Prepare the source code
For this example we will have two files: testpack.c:
#include <stdio.h> #include "gstpub.h" static VMProxy *vmProxy; void gst_testpack_print (OOP self, const char *string) { printf ("TESTPACK PRINT: [%s]\n", string); } void gst_initModule (VMProxy * proxy) { vmProxy = proxy; vmProxy->defineCFunc ("gst_testpack_print", gst_testpack_print); }
And the smalltalk side of this binding TestPack.st:
Object subclass: TestPack [ print: aString [ <cCall: 'gst_testpack_print' returning: #void args: #(#self #string)> ] ]
After putting those files into an otherwise empty directory...
~/testpackage# ls TestPack.st testpack.c
... you should create package.xml which is used by gst-package and the install scripts to determine the name of your package and the files that are going to be included in the package installation. (For a more detailed explanation of the package.xml format have a look at the GNU Smalltalk manual):
package.xml should look like this:
<package> <name>TestPack</name> <file>TestPack.st</file> <filein>TestPack.st</filein> <module>testpack</module> </package>
Creating the build environment
Now your directory should look like this:
~/testpackage# ls -l TestPack.st package.xml testpack.c
What you want now are makefiles which compile and install
testpack.c as library for GNU Smalltalk and also install
TestPack.st.
To create an skeleton automake/autoconf environment run gst-package
like this:
~/testpackage# gst-package --prepare package.xml creating configure.ac creating gst.in creating Makefile.am
Now you've got the basic automake/autoconf skeleton ready for a GNU Smalltalk
module. What you need now is to tell automake/autoconf to build testpack.c
as library.
We are going to use libtool to build the library. So insert
AC_PROG_LIBTOOL into configure.ac:
configure.ac should then look similar to this:
AC_PREREQ(2.59) AC_INIT([GNU Smalltalk package TestPack], [0.0], , gst-testpack) AC_CONFIG_SRCDIR([package.xml]) AM_INIT_AUTOMAKE AC_PROG_LIBTOOL AM_PATH_GST([2.95c], , [AC_MSG_ERROR([GNU Smalltalk not found])]) GST_PACKAGE_ENABLE([TestPack], [.]) AC_CONFIG_FILES([Makefile]) AC_CONFIG_FILES([gst], [chmod +x gst]) AC_OUTPUT
It doesn't matter if your configure.ac looks a bit different, different
versions of gst-package may produce different output. Just make sure
to insert the
AC_PROG_LIBTOOL line there.
Next you have to insert lines into Makefile.am to tell the build scripts
which C code file to use and what library to build. On the top of the Makefile.am you will maybe find some commented out example lines.
I propose to insert these lines into Makefile.am:)
So that Makefile.am looks like this:
AUTOMAKE_OPTIONS = foreign AM_CPPFLAGS = $(GST_CFLAGS)) ### -------------------------------------- ### ### Rules completed by GST_PACKAGE_ENABLE. ### ### -------------------------------------- ### DISTCLEANFILES = pkgrules.tmp all-local: clean-local:: install-data-hook:: dist-hook:: uninstall-local:: @PACKAGE_RULES@
Creating the configure script
Next we have to call the GNU autotools to prepare the configure script for you which will then produce the Makefile:
Call autoreconf like this:
~/testpackage# autoreconf -fvi configure.ac: installing `./install-sh' configure.ac: installing `./missing' Makefile.am: installing `./depcomp'
Note: If you got errors that aclocal for example couldn't find AM_PATH_GST please make sure that you installed GNU Smalltalk correctly and that aclocal can find the .m4 files that come with GNU Smalltalk. For example if you installed GNU Smalltalk to
/opt/gst/ you maybe want to add
/opt/gst/share/aclocal/ to /usr/share/aclocal/dirlist.
Later on, the makefile will make sure that the configure script and Makefiles are updated as necessary. You can also do this manually with aclocal, autoconf, automake.
Now you should have a configure script. Now run configure and make. Watch out for errors and solve them if you got some. Among other things, make will generate two important files: TestPack.star and testpack.so, holding respectively the Smalltalk and the C code for the module.
make install will complete the build.
Testing
Now the package TestPack should be installed and you should test it:
~/testpackage# gst GNU Smalltalk ready st> PackageLoader fileInPackage: 'TestPack' "Global garbage collection... done" Loading package TestPack PackageLoader st> (TestPack new) print: 'TEST' TESTPACK PRINT: [TEST] a TestPack st>
Needless to say, it is also possible and encouraged to use SUnit to build your testsuite.
Even before installation, you can use the gst script that is in the build directory, so that GNU Smalltalk looks for your module there. TODO: how to invoke gst-sunit before installation
|
http://smalltalk.gnu.org/node/74/revisions/view/99/441
|
CC-MAIN-2016-40
|
refinedweb
| 959
| 59.4
|
."
If you retagged as a 3-disk RAID 5, and it was actually a 4-disk RAID 5, and you didn't force offline disk 2, then you need to just delete it and restore from backup, as this would have ruined the original RAID 5.
do not pass go, do not wait, don't reboot till your backup finishes if the data is important.
import a spare(new if possible, both offline disks are suspect now) disk and let the array re-build. do another backup.
whatever you do if you end up looking for a new machine don't go with the low-end H310 controller, it's a joke, sustained data throughput is horrific in RAID5.
As Wi-Fi growth and popularity continues to climb, not everyone understands the risks that come with connecting to public Wi-Fi or even offering Wi-Fi to employees, visitors and guests. Download the resource kit to make sure your safe wherever business takes you!
"non foreign"
By this, do you mean you do NOT have a foreign configuration available? In CTRL-R, go to the PD MGMT screen ... what is shown there?
disk0 online
disk1 online
disk2 ready
disk3 ready
BUT, disk3 slot is empty...if I press F2 (available operations)over disk2 or disk3 I only get something like "setup Global HS". If I choose the option get message "this will not be applied to the current VD..." or very similar phrasing..... What we do next can either destroy or recover it, but it depends on how many disks and its exact configuration.
The above is what is showing on the PD MGMT screen? Have you always had that number of disks? Have you moved any disks?
Yes I remove and put back the 2 pd that did show as "missing" (disk2 and disk3) after this they continue missing and not other option was available.
Last afternoon I did order a similar HD (a WD2500YS) which will arrive on Monday. At the same time I ran to Tigerdirect and got a similar one (but for desktop) just to try.
So at this point I have the 2 original PDs (disk0 and disk1) and this desktop HD (sata 7200 rpm 250Mb) as disk2....slot fourth or disk4 is empty.
I did restart just in case but still showing:
disk0 online
disk1 online
disk2 ready*
disk3 ready
*it correctly identify the new hard-disk, it has a different model.....
Not matter what I do it seems that the VD is not able to "see" the new hard-disk, that's why my question about delete the VD and be able to reconstruct it or something...
First, is your array ONLINE and ACCESSIBLE? You can boot to it, etc.?
"....Press F1 to reboot, F2 to go to Setup...."
but your machine should boot on 2 disks, just be slow as hell. so it sounds like there's a bigger issue than a single failure and a lost hot spare.
is it possible the hot spare got pulled in previously and the Array was not 0-1-2-3?
something like 0-2-3-4 if the hot spare was already activated and two more drives failed you're screwed. restore from last backup.
my gut feeling is if the machine won't boot, you're most likely going to end up restoring the machine.
import the foreign disk, since you know what one is new, make it the hot spare. and the card should automatically make it pop into the degraded array.
I would boot to your OS disc and attempt a startup repair of the OS - see if it even recognizes an installed OS - then attempt to repair it.
IF disks 0,1,2 were in a RAID 5, and 0,1 are showing Online, BUT you cannot boot the OS (or repair it), then you might as well start your restore from backup, because the current states of disks 2,3 don't matter.
I agree with PowerEdge that this is probably going to end up a restore.
I suggest getting all the original drives onto a new controller. and attempt tp Import them as a full set. Perc controllers (I think all RAID controllers) write the info of how they're setup so you can move them to a new card in the event of failure. as it really sounds like the controller is the problem, as a RAID5 +Hotspare setup should still run (albeit slowly) with just Disk0 and Disk1
I however wouldn't attempt the OS repair, until I'd exhausted all data recovery paths, and tried a new controller.
this all depends how important the data is, and how far behind the backup schedule I was.
it's a lot of wheel spinning if there's not critical data.
disk2 is gone, it was not seen by the controller. So I have 3 of the old disks. I deleted the Disk-Group and create a new Group-Disk with a new VD (raid5 )which is able to see the 3 disks, all of them online. The disks have not be Initialed.
I did not install the new disk on slot 4 yet. I reboot and the last enter on the bios was "Error loading operating system"
Trying to do as much possible before have to restore.....another thinking is that it never was a raid5 across 3 disk and a HS. It was a raid5 across 4 disks....Why I prepare the config in this way I don't remember, I do not need that amount of space, but can't find another explanation...=> got a Raid5 on 4disk and lost 2 of them.....
any other option based on ther last entry at the BIOS?
I got an error from the controler when I tried to create a dedicated HS...I think that was the reason I did create a 4 hd R5 instead of a 3hd R5 with HS. I didn't remember this fact and assume it was a 3disk R5.
|
https://www.experts-exchange.com/questions/28329660/Perc-6-i-missing-disk.html
|
CC-MAIN-2018-22
|
refinedweb
| 1,007
| 80.31
|
When, on Windows 7, I launch a console program that should crash, I have the following cases:
Note that on Windows XP, everything works as expected (a dialog popup opens...), and I can debug the crashed program.
Is that a cygwin bug on Windows 7? A configuration problem?
I wrote the following C++ program on Visual Studio 2008, in debug (32 bits or 64 bits have the same result):
#include <cstdio>
#include <windows.h>
int main()
{
printf("It should crash now...") ;
::DebugBreak() ;
return 0 ;
}
The ::DebugBreak()has been replaced by int * p = NULL ; *p = 42 ; (which is supposed to crash with an access violation exception), with exactly the bugged results on Cygwin.
::DebugBreak()
int * p = NULL ; *p = 42 ;
Thanks !
I observed the same issue with recent versions of Cygwin. I don't yet know what's causing it, but the Windows SetErrorMode function seems to work a treat:
{
const UINT oldErrorMode = ::SetErrorMode(0);
::DebugBreak();
::SetErrorMode(oldErrorMode);
}
Just a tip: if you're using MSVC, use the __debugbreak() intrinsic function instead. It puts the break at that point in the code, rather than inside a function called from there. Some inline assembly might do this trick on other compilers.
asked
5 years ago
viewed
790 times
active
|
http://superuser.com/questions/197397/no-crash-dialog-when-a-program-crashes-on-cygwin-on-windows-7/216646
|
CC-MAIN-2016-30
|
refinedweb
| 206
| 64.51
|
To get exact fractions, use the Ratio module (import Ratio) and the Rational type which is defined there. The code you wrote below has a serious style problem that I thought I'd point out: you shouldn't use the IO monad for pure functions. You can define f as follows: f x = let t = 2 * x in if t < 1 then t else t - 1 or with guards: f x | t < 1 = t | otherwise = t - 1 where t = 2 * x Note that there isn't any problem with using pure functions from the IO monad. You can write gen as follows: gen :: Double -> IO () gen x | c == 0.0 = return () | otherwise = do putStrLn $ "Value is: " ++ show c; gen c where c = f x (writeln is called putStrLn in the standard prelude) Or syntactically closer to your original code: gen :: Double -> IO () gen x = do let c = f x putStrLn ("Value is: " ++ show c) if (c /= 0.0) then gen c else return () You don't use the c <- f x notation because (f x) is directly the value you want, not an IO action which executes to produce that value. So long as you don't put a type signature on it (causing it to get inferred), or if you give it the type signature: f :: (Num a, Ord a) => a -> a it will work with any ordered type of numbers, which allows you to load up the Ratio module in ghci (":m + Ratio") and try it with things like 1%3 (which represents one-third exactly). Hope this is useful, - Cale On 19/07/05, Dinh Tien Tuan Anh <tuananhbirm at hotmail.com> wrote: > Here's what i got > > writeln x = putStr (x++ "\n") > > f:: Double -> IO Double > f x = do > let t = 2*x > if (t<1) > then return t > else return (t-1) > > > gen :: Double -> IO() > gen x = do c<-f x > writeln ("Value is: " ++ show c) > if (c /= 0.0) > then gen c > else return () > -snip-
|
http://www.haskell.org/pipermail/haskell-cafe/2005-July/010817.html
|
CC-MAIN-2014-10
|
refinedweb
| 331
| 65.09
|
Set of Xpath 2.0 functions which you can register in lxml
Project Description
Release History Download Files
Changelog
- 0.0.4:
- Added a new function for lowering text (Mathieu Leduc-Hamel).
- 0.0.3:
- Defined default prefix ‘xp2f’.
- 0.0.2:
- Changed default namespace.
- 0.0.1:
- Added function: string-join.
Support
- Environments: Python 2.6, Python 2.7, Python 3.2, Python 3.3, Python 3.4, PyPy
Description
Set of Xpath2 functions which you can register in lxml. User register all or chosen functions and use them in own xpaths. Xpaths are accessible under default namespace: an arg1 created by concatenating the members of the $arg1 sequence using $arg2 as a separator. If the value of $arg2 is the zero-length string, then the members of $arg1 are concatenated without a separator.
- lower-case (arg1 as
xs:string) - returns an arg1 converted to lower-cased string.
Contributors
- Kamil Kujawinski
- Mathieu Leduc-Hamel (xpath functions: lower-case)
Download Files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/lxml-xpath2-functions/
|
CC-MAIN-2017-51
|
refinedweb
| 180
| 71.1
|
Analyzing US Economic Dashboard in Python
This tutorial will guide us in learning how to analyze US economic dashboard in Python.
Taking out the information from a given data & displaying it is one of the important parts of data science and people can make decisions based on the observed information. In this article, we will try to extract two of the most essential economic indicators i.e., GDP & Unemployment of US from a given data which is stored in a .csv (Comma-Separated Values) file, & then display them in a Dashboard.
You may read: how to create dataframe in Python using pandas
GDP and its implementation in Data Science
Before we proceed in bringing out the information, let us know about GDP. Gross Domestic Product (GDP) is a factor that determines how well the economy of a region is doing by measuring the market value of all the goods and services produced in a specific time period. It is often measured annually & the economy is basically country-focused.
An economy’s performance is observed by comparing the GDP of two consecutive time periods. A decrease in GDP indicates the economy is less productive which may lead to Unemployment; on the other hand, an increase in GDP suggests the economy is performing better & can achieve Sustainable Development. In this article, we will examine how changes in GDP can affect the unemployment rate by dealing with the following points:
- Define a Function that Makes a Dashboard.
- Create a dataframe that contains the GDP data and display it.
- Create a dataframe that contains the unemployment data and display it.
- Display a dataframe where unemployment was greater than 8.5%.
- Use the function make_dashboard to make a dashboard.
NOTE: Before we proceed further in coding the whole project I want to say in this article, we are accessing a .csv file through a given URL. So while working on these kinds of Data Science Projects, I will recommend to use online Python IDEs rather than installing Pandas & Bokeh packages in your devices as the latter has a tedious process & the code I’ll discuss here may show runtime error sometimes, due to lack of packages while installing them; however the same code will run perfectly in online IDEs. One such online IDE I recommend to use is JupyterLab. To install Pandas write the following command after opening the Command Prompt if you’re using Windows
python -m pip install -U pandas
or if you’re using Linux then type the following command in your terminal.
sudo pip install pandas
after that for installing Bokeh, replace pandas with bokeh from the above two commands in your respective OSes.
Define a Function that Makes a Dashboard for US economy
a) To make the dashboard, we’ll need to define a function that will help to make it. But before that, we’ll have to import both Pandas & Bokeh.
import pandas as pd from bokeh.plotting import figure, output_file, show,output_notebook output_notebook()
b) Now we’ll define the function make_dashboard with five parameters: x (for naming the x-axis), gdp_change, unemployment (name of the two parameters of the same y-axis), title (for labeling the title of the dashboard) & file_name (name of the file being saved in .html file extension).
def make_dashboard(x, gdp_change, unemployment, title, file_name): output_file(file_name) #name of the file p = figure(title=title, x_axis_label='year', y_axis_label='%') #plotting the dashboard p.line(x.squeeze(), gdp_change.squeeze(), color="firebrick", line_width=4, legend="% GDP change") #plotting the 'GDP' part p.line(x.squeeze(), unemployment.squeeze(), color="green", line_width=4, legend="% unemployed") #plotting the 'unemployment' part show(p) #displaying the entire dashboard
c) After that, we’ll provide the URL link of the .csv file which is being accessed by a dictionary named links with two key-value pairs named GDP & Unemployment. As the two will be accessed as the columns of the .csv file, the pairs will be defined under String Characters.
links={'GDP':'',\ 'unemployment':''}
NOTE: Before implementing the links in the given key values, I would suggest checking the links in your internet browser to check the CSV file so that you can verify the output easily. Once you copy & paste the links in your browser, the files will be automatically downloaded by pressing the Enter button.
Create a dataframe that contains the GDP data and display the first five rows of the dataframe
A Data frame is a two-dimensional data structure, i.e., data is aligned in rows and columns. We’ll create the GDP dataframe & for displaying the first five rows of the dataframe, we use head() function.
csv_path=links["GDP"] d1=pd.read_csv(csv_path) #defining the dataframe d1.head() #displaying first five rows of the dataframe
Output:
Create a dataframe that contains the Unemployment data and display the first five rows of the dataframe
Now we create the Unemployment dataframe & display its first five rows using similar procedures just as we made in the GDP one.
csv_path1=links["unemployment"] d2=pd.read_csv(csv_path1) #defining the dataframe d2.head() #displaying first five rows of the dataframe
Output:
Display a dataframe where unemployment was greater than 8.5%
Now if you follow the codes of the third point you’ll notice I created a dataframe named d2. With the help of this dataframe, we’ll create another one to display when the unemployment is greater than 8.5%. We’ll name this dataframe as d3.
d3=d2[d2['unemployment']>8.5] #extracting the part of the dataframe d2 to a new dataframe d3
Output:
Use the function make_dashboard to make a dashboard
Now we’ll create the dashboard.
a) First we’ll create the dataframe for x-axis we’ve created for parameter x in the function. The x-axis will be the date column of the GDP .csv file (if you’ve checked the links given while defining the links dictionary in point 1(c), you’ll get this).
csv_path1=links['GDP'] gdp_dataframe1=pd.read_csv(csv_path1) x = pd.DataFrame(gdp_dataframe1, columns=['date']) x.head()
Output:
b) Now we’ll make the y-axis. For displaying the GDP part firstly, we’ll use the first five rows of “change-current” column of GDP as we did the same for x dataframe.
csv_path2=links['GDP'] gdp_dataframe2=pd.read_csv(csv_path2) gdp_change = pd.DataFrame(gdp_dataframe2, columns=['change-current']) gdp_change.head()
Output:
c) Similarly, we’ll use the first five rows of unemployment dataframe.
csv_path3=links['unemployment'] unemploy_dataframe1= pd.read_csv(csv_path3) unemployment = pd.DataFrame(unemploy_dataframe1, columns=['unemployment']) unemployment.head()
Output:
d) Now we’ll display the title of the dashboard using title parameter used in the function.
title = "Unemployment stats according to GDP"
then we’ll save the dashboard in .html file extension under file_name parameter of the function so that the file can be displayed in the cloud for future.
file_name = "index.html"
and lastly, we’ll combine all the parameters & make the dashboard given below:
make_dashboard(x=x, gdp_change=gdp_change, unemployment=unemployment, title=title, file_name=file_name)
Output:
Dear all,
Please assist in the following issue in a code:
I use online Python EDI – Sololearn, after import library I have next comment:
No module named ‘bokeh’
Please advise. Thank you in advance.
Regards,
Tim
I think you have to find out where the module bokeh.plotting can be found. Use pip to load it into your work environment. Then from the module import the functions figure, output_file, show, output_notebook.
hello!
i have a little bit error in my code ‘make_dashboard’ is not defined’ what it’s means and how to resolve it?
csv_path=links[“GDP”]
d1=pd.read_csv(csv_path) #defining the dataframe
d1.head()
Error Msg – —————————————————————————
NameError Traceback (most recent call last)
in
—-> 1 csv_path= links[“GDP”]
2 d1=pd.read_csv(csv_path) #defining the dataframe
3 d1.head() #displaying first five rows
NameError: name ‘links’ is not defined
Run the cell containing the links dictionary to initialize the variable links. Then run the cell for creating data frame for GDP
d3=d2[d2[‘unemployment’]>8.5] #extracting the part of the dataframe d2 to a new dataframe d3
Hi Team,
In above code why d2 wrote two times in syntax? Kindly advise as I m new to python programming. I am currently pursuing IBM data science course. How to learn code & syntax writing.
Thank you for your help!
d2[‘unemployment’]>8.5 returns a column containing True and False boolean values. d2[d2[‘unemployment’]] goes through the column d2 and for every true in adds the row in d3. I hope you got it.
Good evening. please am having same problem as in number 2 and 3 above.
How do I rectify it.
Thanks
Hi., I am struggling with the syntax error as in invalid syntax in the following code.
Can you please help me figure out?
x = # Create your dataframe with column datecsv_path1=links[‘GDP’]
csv_path1=links[“GDP”]
gdp_dataframe1=pd.read_csv(csv_path1)
x = pd.DataFrame(gdp_dataframe1, columns=[‘date’])
x.head()
csv_path= links[“GDP”]
2 d1=pd.read_csv(csv_path) #defining the dataframe
3 d1.head() #displaying first five rows
HTTPError:HTTP Error 404:Not Found
The code works perfectly fine for me. The only problem is that when I execute the final statement to actually display the dataframe, the graph is completely blank. Am I doing something wrong?
hallo,
how can we create a bucket in Watson studio?
make_dashboard() got an unexpected keyword argument ‘gdp_change’
After this we need to do some other steps for the analysis.. We need Bucket name of IBM CLOUD … HELP
How to download the last output of the dashboard (plot) into your computer
csv_path1=links[‘GDP’]
gdp_dataframe1=pd.read_csv(csv_path1)
x = pd.DataFrame(gdp_dataframe1, columns=[‘date’])
x.head()
File “”, line 1
x = # Create your dataframe with column date
^
SyntaxError: invalid syntax
|
https://www.codespeedy.com/analyzing-us-economic-dashboard-in-python/
|
CC-MAIN-2020-50
|
refinedweb
| 1,620
| 65.01
|
How to: Iterate Over STL Collection with for each
Visual Studio 2005
In addition to .NEt Framework collections, the for each keyword can also be used to iterate over Standard C++ Library (STL) collections. An STL collection is also known as a container. For more information, see STL Containers.
Example
This sample uses for each in a <map>.
// for_each_stl.cpp // compile with: /EHsc #include <map> #include <iostream> using namespace std; int main() { int retval = 0; map<const char*, int>; map<const char*, int> months_30; for each( pair<const char*, int> c in months ) if ( c.second == 30 ) months_30[c.first] = c.second; for each( pair<const char*, int> c in months_30 ) retval++; cout << "Months with 30 days = " << retval << endl; }
Output
Months with 30 days = 4
This sample uses const& for an iteration variable with STL containers. You can use an & as an iteration variable on any collection of a type that can be declared as a T&.
Output
retval: 60
See Also
Referencefor each, in
Show:
|
http://msdn.microsoft.com/en-US/library/ms177203(v=vs.80).aspx
|
CC-MAIN-2014-10
|
refinedweb
| 166
| 64
|
- It gives you comprehensive access to SAP NetWeaver
- The annual license costs only €1.071 in Germany and $1,170 (+ tax) in the US
- You get developer tools, including all patches and updates issued during the term of the subscription
- You get ABAP namespace
- You have the right to commercialize (sell the applications you develop with the subscriptions) as well as the right to test and demo
- You receive access to presentations, demos and workshops from Virtual TechEd (including Virtual SAP TechEd Complete Package)
- You can test your application’s compatibility with SAP enterprise services by accessing the Enterprise Services Workplace (ES Workplace) site
- If you get it now, you’ll have a full year to learn it to impress your Valentine in 2010
- To use all your goodies, you get a full list of challenging usernames and passwords
- If you play the DVDs backwards, you may get a preview of this year’s Oscar winners
oh and it actually costs less than €2.50 a day plus tax. Can you buy a coffee for that?
So when is it going to be available in other territories? Sorry to sound like a broken record … a broken record … a broken record but it has been over 18 months and still nothing to report on other territories. (Particularly the UK)
Kind regards,
Nigel
We are not planning to roll the program out to other countries in ’09. If you are a partner and need a development license, please contact your partner manager in the UK to obtain a copy. Or you can purchase it through sales as an end customer. I apologize for any inconvenience this might cause you. Best,
Claudine
I’m a SAP BW/BI consultant from Brazil both certified NetWeaver2004s and ABAP who’s just about to move to Canada. After almost 2 years of immigration process I’m finally just about to get my visa.
I wonder if you people could give some information whether or not I will be able to buy this from Toronto, CA? I just can’t believe that I’m so close and so far away at the same time to get it.
I would appreciate any comment.
Fernando
Congrats on your move. It sounds like a big change, also in the climate that you are moving to/from.
You may want to contact the local sales team in Canada and inquire about the perpetual NW Development License. Or, if you are an SAP partner, you can purchase a partner license. Unfortunately the subscription program is not going to be available in Canada in ’09. Regards,
Claudine
The program is being discontinued. It is now availalbe only for renewal customers. There will be other licenses availalbe in the future that will be offered worldwide, including in Canada. Best,
Claudine
|
https://blogs.sap.com/2009/02/15/10-things-you-may-not-know-about-the-sap-netweaver-development-license-subscription/
|
CC-MAIN-2017-51
|
refinedweb
| 466
| 68.4
|
How Supervisors Work
In Erlang (and Elixir) supervisors are processes which manage child processes and restart them when they crash. In this post we're going to take a look at the details of how supervisors are implemented. I had a rough idea of how these they worked, but I didn't understand the specifics. I felt like learning some stuff and figured I'd share it with you <3.
For this dive it would be helpful if you understand how to use both the
gen_server and
supervisor modules before.
If you've used the Elixir equivalent then those are fine too as they just delegate down to the Erlang
modules and don't really change behaviorally.
Let's start with an example in Elixir, straight from the docs:
defmodule MyApp.Supervisor do use Supervisor def start_link do Supervisor.start_link(__MODULE__, []) end def init([]) do children = [ worker(Stack, [[:hello]]) ] # supervise/2 is imported from Supervisor.Spec supervise(children, strategy: :one_for_one) end end
In this example,
start_link is spawning the supervisor and then
init is a callback
used by the
Supervisor behaviour. Let's dig into
Supervisor. As a quick recap of behaviours,
the
use Supervisor call will expand at compile time to whatever is in that behaviour's
__using__ macro.
So, let's look at
__using__ in the
Supervisor module in the Elixir source (tangent: the Elixir source
is laid out very conventionally and I recommend you take a little time to get comfortable navigating it).
Here's the
__using__ macro at the time of writing this:
defmacro __using__(_) do quote location: :keep do @behaviour Supervisor import Supervisor.Spec end end
@behaviour is doing some checks to make sure we implement the necessary callbacks for our supervisor and
the
import statement is pulling in some extra methods into
MyApp.Supervisor from
Supervisor.Spec.
This is where the
worker and
supervise methods are both defined.
That's the gist of what the
use Supervisor statement is doing; mixing in some functions and making sure we
implement the right callbacks.
The way we'd start our supervisor is by calling
MyApp.Supervisor.start_link,
so let's dig into that. Obviously, this delegates to
Supervisor.start_link passing a reference to itself (via
__MODULE__).
Checking out the source for
Supervisor.start_link:
def start_link(module, arg, options \\ []) when is_list(options) do case Keyword.get(options, :name) do nil -> :supervisor.start_link(module, arg) atom when is_atom(atom) -> :supervisor.start_link({:local, atom}, module, arg) {:global, _term} = tuple -> :supervisor.start_link(tuple, module, arg) {:via, via_module, _term} = tuple when is_atom(via_module) -> :supervisor.start_link(tuple, module, arg) other -> raise ArgumentError, """ expected :name option to be one of: * nil * atom * {:global, term} * {:via, module, term} Got: #{inspect(other)} """ end end
The main thing we see here is that the Elixir module is delegating down to the Erlang
:supervisor module. Wait, don't run
screaming! You can follow the Erlang source, trust me :)
Grepping for
start_link you'll find an
export statement which is just exposing it outside the module, a
spec which is
just telling you what types the function expects, and the actual implementation:
start_link(Mod, Args) -> gen_server:start_link(supervisor, {self, Mod, Args}, []).
See? Already something familiar. We're just starting a
gen_server. We won't dig into how gen_server works.
The main takeaway is that supervisors are built on-top of
gen_server.
gen_server expects us to implement a bunch of callbacks.
The one we're most concerned with right now is
init. Note that even though
MyApp.Supervisor implements
init it is not the callback that will be called next.
If you look back at
start_link in the Erlang
:supervisor module you'll see that it passes the
self reference meaning that
:supervisor.init is the function we're looking for next.
Here's the source for that:
init({SupName, Mod, Args}) -> process_flag(trap_exit, true), case Mod:init(Args) of {ok, {SupFlags, StartSpec}} -> case init_state(SupName, SupFlags, Mod, Args) of {ok, State} when ?is_simple(State) -> init_dynamic(State, StartSpec); {ok, State} -> init_children(State, StartSpec); Error -> {stop, {supervisor_data, Error}} end; ignore -> ignore; Error -> {stop, {bad_return, {Mod, init, Error}}} end.
This is doing a few things. First, it's calling
Mod:init(Args) which is just calling
MyApp.Supervisor.init. Let's look at that again real quickly:
def init([]) do children = [ worker(Stack, [[:hello]]) ] # supervise/2 is imported from Supervisor.Spec supervise(children, strategy: :one_for_one) end
Remember,
worker and
supervise are helpers coming from
Supervisor.Spec. Without digging through the plumbing, I'll cut to the chase so we can focus more
on the Erlang side of things.
worker outputs a child_spec and
supervise outputs a tuple looking
like
{:ok, { {strategy, max_retries, max_seconds}, child_specs} }.
Back to
:supervisor.init. Next, very importantly, it calls
process_flag which will trap exits.
This is very important and central to how the supervisor knows when to restart a process. The TL;DR is that when a process terminates it sends an
exit signal to all of its linked processes. Calling
process_flag will trap that signal and instead send the
{'EXIT', from_pid, reason} message
to that process instead. As we'll see later, the supervisor process will use that
from_pid value to know which process died and how to
restart it.
Okay, we left off in
:supervisor.init and just started trapping exit signals. Next we initialize our state and our children. I won't go into
init_state.
Let's go into
init_children since we're not dealing with
:simple_one_for_one supervisors.
init_children(State, StartSpec) -> SupName = State#state.name, case check_startspec(StartSpec) of {ok, Children} -> case start_children(Children, SupName) of {ok, NChildren} -> {ok, State#state{children = NChildren}}; {error, NChildren, Reason} -> _ = terminate_children(NChildren, SupName), {stop, {shutdown, Reason}} end; Error -> {stop, {start_spec, Error}} end.
Oh boy, more symbols. Another quick tangent:
State#state.name is accessing the variable
State as a
state record and plucking off the
name field.
Records are more-or-less structs that are stored as ordered tuples like
{:state, "josh", [1, 2, 3]} (kind of like an enum type in other languages).
Records are just a way to decouple the position of a field from its meaning. Here's the source for the
state record defined at the top of the file:
-record(state, {name, strategy :: strategy() | 'undefined', children = [] :: [child_rec()], dynamics :: {'dict', ?DICT(pid(), list())} | {'set', ?SET(pid())} | 'undefined', intensity :: non_neg_integer() | 'undefined', period :: pos_integer() | 'undefined', restarts = [], dynamic_restarts = 0 :: non_neg_integer(), module, args}).
As you can see,
state records have a
name field, so
SupName = State#state.name is just treating the
State tuple as a
state record, plucking out whatever
field corresponds to
name, and saving that in
SupName.
Glancing over
check_startspec; this is doing some validation as well as casting the spec we received from
MyApp.Supervisor.init to a record (source)
The real meat of
:supervisor.init_children is
start_children though:
start_children(Children, SupName) -> start_children(Children, [], SupName). start_children([Child|Chs], NChildren, SupName) -> case do_start_child(SupName, Child) of {ok, undefined} when Child#child.restart_type =:= temporary -> start_children(Chs, NChildren, SupName); {ok, Pid} -> start_children(Chs, [Child#child{pid = Pid}|NChildren], SupName); {ok, Pid, _Extra} -> start_children(Chs, [Child#child{pid = Pid}|NChildren], SupName); {error, Reason} -> report_error(start_error, Reason, Child, SupName), {error, lists:reverse(Chs) ++ [Child | NChildren], {failed_to_start_child,Child#child.name,Reason}} end; start_children([], NChildren, _SupName) -> {ok, NChildren}.
Here we have a little recursion, plucking off each child and calling
do_start_child:
do_start_child(SupName, Child) -> #child{mfargs = {M, F, Args}} = Child, case catch apply(M, F, Args) of {ok, Pid} when is_pid(Pid) -> NChild = Child#child{pid = Pid}, report_progress(NChild, SupName), {ok, Pid}; {ok, Pid, Extra} when is_pid(Pid) -> NChild = Child#child{pid = Pid}, report_progress(NChild, SupName), {ok, Pid, Extra}; ignore -> {ok, undefined}; {error, What} -> {error, What}; What -> {error, What} end.
apply is Erlang's dynamic function invocation method (similar to
send in Ruby or
apply/
call in Javascript). This winds up dynamically calling
the callback defined in
Supervisor.Spec.worker. Conventionally, it calls start_link on your worker module.
Finally, it calls
report_progress which uses Erlang's unfortunately named error_logger to publish an info event
that the new process was started by the supervisor.
First breathe. Okay, let's continue.
Zooming way out, this is how a supervisor starts, traps exits, and starts children. We still haven't gotten to the real beef of how supervisors
restart their children, but we're really close!
Remember how
process_flag traps exit signals and turns them into
{'EXIT', from_pid, reason} tuples?
Also remember that supervisors are built on top of
gen_server?
Well,
gen_server handles all non-call/cast messages using
handle_info (further reading on handle_info).
This is how supervisors handle exits from a child!
handle_info({'EXIT', Pid, Reason}, State) -> case restart_child(Pid, Reason, State) of {ok, State1} -> {noreply, State1}; {shutdown, State1} -> {stop, shutdown, State1} end;
Here we see that it handles the exit message which contains the pid of the child process that exited and the reason and it feeds that into
restart_child!
Victory! We've already seen how
do_start_child works, and
restart_child is fairly similar, so I'll leave that for the curious to look up on their own.
If you're interested in how supervisors implement their shutdown strategies, take a peek at :gen_server.stop
which delegates to the supervisor's terminate callback.
So, let's sum it all up!
Elixir implements a conventional framework for writing supervisors.
That framework interfaces with Erlang's
:supervisor module which is built on top of
:gen_server.
Elixir passes configs down to the
:supervisor module which it uses to start child processes.
It manages the child processes by trapping exit signals from its children to convert the signal
into a message.
It implements the
handle_info callback which can handle the exit messages and restart the correct worker.
Finally, it's worth reiterating that it publishes reports to
:error_logger, Erlang's event manager.
Anyways, I learned a ton from this dig, and I hope you did too. If you found this post useful or have ways you think it could be clearer, then please let me know! Thanks for reading!
|
https://jbodah.github.io/blog/2016/11/18/supervisors-work/
|
CC-MAIN-2017-13
|
refinedweb
| 1,654
| 56.86
|
On 28 Sep 06, at 9:28 AM 28 Sep 06, Carlos Sanchez wrote:
> is it using maven-user? there's already all user management code there
> to avoid duplication in different applications.
>
Joakim, to the best of my knowledge used bits and pieces from Maven
User but the implementation in plexus-security package is better in
my opinion and has been worked on by more people (I've looked at it
and agree though a critique of some things in p-sec in general is
coming from me). Myself, Jesse, and Joakim were involved and the
speed with which p-sec was integrated into Continuum is a testament
to its ease of use. The user management is part of that system.
> On 9/28/06, Emmanuel Venisse <emmanuel@venisse.net> wrote:
>> +1 for the merge
>>
>> Emmanuel
>>
>> Jesse McConnell a écrit :
>> > Over the course of the past 3 weeks I've worked with joakim on the
>> > plexus-security effort to bring rbac based security to Archiva.
>> > We succeeded.
>> >
>> > Last Friday (or so) I took the continuum/trunk and created the
>> > rbac-integration branch.
>> > I wanted from to test the integration of rbac based security, using
>> > the plexus-security project, into continuum.
>> >
>> > It integrated beautifully, without a whole lot of work, in record
>> > time, and is pretty functional now ...
>> >
>> > Some of the fun things that plexus-security brings with it are:
>> >
>> > * full separation between application webapp and security
>> (lightweight
>> > integration).
>> > * proper modularization for security components (authentication,
>> > authorization, policy, system, web, etc...)
>> > * rbac (role based access control) authorization provider.
>> > * full user management war overlay (using healthy chunk of maven-
>> user
>> > to make it happen)
>> > * toggle-able guest user authorization.
>> > * forced admin account creation (through use of interceptor)
>> > * key based authentication (remember me, single sign on, new user
>> > validation emails, and password resets).
>> > * http auth filters (basic and digest).
>> > * aggressive plexus utilization.
>> > * aggressive xwork / webwork integration.
>> > * xwork interceptors for force admin, auto login (remember me),
>> > secured action, and environment checks.
>> > * secured actions for all of the /security namespace and at
>> least one
>> > continuum secured action (these are enforced by the
>> > pssSecureActionInterceptor)
>> > * all the password validation, user management stuff (again
>> maven-user
>> > origins)
>> > * continuum-security artifact containing the actual static and
>> dynamic
>> > roles, and a continuum role manager that merges permissions to the
>> > core system, user, and guest users
>> > * ifAuthorized, ifAnyAuthorized, elseAuthorized jsp tags.
>> > * placeholders for ldap authentication, authorization and user
>> details
>> > retrieval using plexus ldap components
>> > * ability to re-use Acegi for authentication
>> >
>> > I think it is very usable now, its a matter of some jsp and action
>> > work to clean up some things and hide some other knobs and buttons.
>> >
>> > I'd like to get feedback and discussion from the others here
>> about the
>> > implementation, and consider a vote to merge it to trunk after
>> that. I
>> > believe it is stable enough to move forward with.
>> >
>> > jesse
>> >
>>
>>
>
>
> --
> I could give you my word as a Spaniard.
> No good. I've known too many Spaniards.
> -- The Princess Bride
>
|
http://mail-archives.apache.org/mod_mbox/continuum-dev/200609.mbox/%3C47AB8DBF-DFD8-4465-831C-C90A1BFD9B46@maven.org%3E
|
CC-MAIN-2014-42
|
refinedweb
| 495
| 53
|
Hey ✌✌
PROBLEM TO BE SOLVED 🤷♀️🤷♀️🤷♀️🤷♀️🤷♀️:
When we use react-router-dom library for routing pages and links in the react project, the problem with it is that when clicked on an Link the next component rendered does not get started from the top of the page, instead it renders the page from the scroll height of the parent component i.e the component which holds the Link tag.
So, what we are going to do is to render the new component/page/route from top of the scroll height, not from in-between.
SOLUTION 😎😎😎😎 :
Make a new File just like other component file - Let us name it ScrollToTop.js
import React, { Component } from "react"; import { withRouter } from "react-router-dom"; class ScrollToTop extends Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { window.scrollTo(0, 0); } } render() { return <React.Fragment />; } } export default withRouter(ScrollToTop);
Now add this file as a normal component to just below the tag like this :
Top comments (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/singhanuj620/how-to-scroll-to-the-top-while-using-react-router-dom-30nd
|
CC-MAIN-2022-40
|
refinedweb
| 162
| 50.46
|
This unit testing framework consists of about 125 lines of code in a single header. It aims to be the simplest way to get started writing unit tests for C++ developers. Being simple, it is also easy to customize. Many unit testing frameworks require linking to a separate library or require jumping through several hoops just to get started. This can make it more difficult to begin writing tests.
One of the situations developers often face when they set out to write unit tests is that they're already working on a project. If the project isn't broken out into independent libraries, it can be difficult to write stand-alone unit tests. In addition, many of the core functions of a program simply can't be broken out into a separate test executable. Ideally, a developer should be able to write a set of unit tests, include it with a single function call within the program itself, and easily #define the test out later on.
#define
This may not seem like a strong approach to software engineering. However, it is generally acknowledged that testing early and often is better than the alternative. By minimizing the effort required to get started writing tests, the goal of testing early can be more easily accomplished. As the test suite grows and the project moves forward, the tests can be factored into a separate library or executable as time permits.
I started my quest by looking for existing solutions. There is a lot of interest and activity around the xUnit frameworks within the unit testing community. It originated with Smalltalk's SUnit framework, which inspired the developers of JUnit. This, in turn, inspired the creators of NUnit, CppUnit, and several other similar frameworks.
One of the things that most of these frameworks have in common is that they are built using languages that support some reflection capability. This makes it easier to assign attributes to a test function or a setup function and have it automatically included in a test run. C++ developers are not so fortunate. C++ developers must do things more manually (or resort to templates or macros). This isn't a big deal, though. It's what we expect.
Many articles have been written on unit testing in the xUnit community and the various libraries available. However, there is surprisingly little written about options for C++ developers. One such article at Games from Within offers a survey of some of the frameworks available.
For an introduction to unit testing in general, have a look at one of the comprehensive articles here at The Code Project.
After evaluating several frameworks, I decided that none of them met my basic criteria of being extremely simple to use and modify. I decided to see how hard it would be to write a framework that would fit into a single header and would consist of as few lines of code as possible. Here is a list of my basic design criteria:
The design constraint that it should not dynamically allocate any memory would allow tests to be created on the stack. This would make it easy to write a simple main program entry point and just declare and run the tests all at once without worrying about cleanup or memory leaks.
main
A consequence of these constraints was that a class would be required for each test. The alternative of using a function pointer wouldn't allow for chaining tests within a suite without allocating memory. Also, it didn't seem in the spirit of C++ to use function pointers.
To get a test up and running, three things are necessary:
We'll follow this sequence in the illustration. The sample included for download is different.
In this example, we derive our test case from the TestCase base class. TestCase, like the other components of the framework, is a struct. This helps us avoid a lot of public access specifiers.
TestCase
struct
public
Test code is added to the single test method. The TestSuite class contains any data that is shared across test cases and it is passed to every test call. The name method is used to provide meaningful output in the event of a test case failure.
test
TestSuite
name
struct TestAccountWithdrawal : TestCase
{
const char* name() { return "Account withdrawal test"; }
void test(TestSuite* suite)
{
TestAccountSuite* data = (TestAccountSuite*)suite;
data->account->Deposit(10);
bool succeeded = data->account->Withdraw(11);
T_ASSERT(succeeded == false);
T_ASSERT(data->account->Balance() == 10);
}
};
The test suite contains a group of related tests. It serves the purpose of both the test suite and test fixture in some other unit testing frameworks.
The two key methods (both optional) are setup and teardown. Each call to a test case is framed with this call pair.
setup
teardown
struct TestAccountSuite : TestSuite
{
const char* name() { return "Account suite"; }
void setup()
{
account = new Account();
}
void teardown()
{
delete account;
}
Account* account;
};
Once a test suite and at least one test case have been written, they may be added to a runner and executed.
#include <span class="code-keyword"><stdio.h></span>
#include <span class="code-string">"shortcut.h"</span>
#include <span class="code-string">"tests/account.h"</span>
int main(int argc, char* argv[])
{
TestRunner runner;
TestAccountSuite accountSuite;
TestAccountWithdrawal accountWithdrawalTest;
accountSuite.AddTest(&accountWithdrawalTest);
runner.AddSuite(&accountSuite);
runner.RunTests();
return 0;
}
One of the benefits of this lightweight system is that all test code may be kept in headers. This avoids some duplication between a separate class declaration and implementation. Because the unit test framework is implemented in a single header, only a single driver module (containing main, for example) is required.
This system also makes it easy to add tests to an existing application. For example, the tests could be called at program startup within a #ifdef DEBUG section. In release mode, no trace of the tests would exist in the application binary. This may not be the case when linking to other unit testing libraries.
#ifdef DEBUG
Obviously, this is not a long-term solution. It is a good way to get started, though. Developers can start writing tests immediately and the tests can be factored into a separate executable when time permits.
This section may be skipped. It explains a little bit about how the (very few) moving pieces work.
All test cases derive from a very basic class, called TestCase.
struct TestCase
{
TestCase() : next(0) {}
virtual void test(TestSuite* suite) {}
virtual const char* name() { return "?"; }
TestCase* next;
};
The class has a name accessor method, which is used for logging errors. The test suite uses the next pointer to chain the test cases into a linked list. The test itself is implemented in the virtual test method.
The test suite has the same structure, except that it contains a list of tests and has different methods to override: setup and teardown.
struct TestSuite
{
TestSuite() : next(0), tests(0) {}
virtual void setup() {}
virtual void teardown() {}
virtual const char* name() { return "?"; }
void AddTest(TestCase* tc)
{
tc->next = tests;
tests = tc;
}
TestSuite* next;
TestCase* tests;
};
As stated earlier, the test suite class plays the same role as the test suite and test fixture classes in other frameworks. In such frameworks, suites often play the role of a test grouping construct while the fixture provides a setup/teardown mechanism. Since ShortCUT is such a simple framework, there was no need to create this additional level of complexity. If a development team needs this feature, it may be easily added as a customization.
The test runner is the heart of the system. It, too, is very straightforward. The main routine, RunTests calls RunSuite for each suite.
RunTests
RunSuite
struct TestRunner
{
...
void RunSuite(TestSuite* suite, int& testCount, int& passCount)
{
TestCase* test = suite->tests;
while (test)
{
try
{
suite->setup();
test->test(suite);
passCount++;
}
catch (TestException& te)
{
log->write("FAILED '%s': %s\n", test->name(), te.text());
}
catch (...)
{
log->write("FAILED '%s': unknown exception\n", test->name());
}
try
{
suite->teardown();
}
catch (...)
{
log->write("FAILED: teardown error in suite '%s'\n", suite->name());
}
test = test->next;
testCount++;
}
}
...
}
The key points to note here are that, first, the log class can be implemented and set outside of the framework. This makes it easy to display results to another output target, such as a window.
log
The second point, which can be an annoyance, is that the test suites and test cases are chained together in singly-linked lists. This means that they are traversed and executed in LIFO order. This is the reverse from the order in which they were added.
It would be a simple matter to customize the framework to fix annoyances like this. I chose not to, since the goal was to make the framework as simple as possible.
The main goal of the framework was to have the absolute simplest system possible, within the design requirements and constraints. Every line of code was scrutinized for its value. In some cases, such as with the TestLog class, a few lines were added because they helped to meet a design requirement. Even though the framework would have been simpler, it would have lost basic flexibility.
TestLog
The header is about 200 lines of code. A quarter of the code is actually unnecessary. It was included as an example of how to implement custom assert functionality through exceptions and how to implement a couple of helper macros to avoid repetitive code.
The framework is useable in its basic form. It is hoped that it will form the basis of systems that are tailored to the needs of the developers who use them (instead of the other way around). It should provide enough utility to get going quickly, and its basic structure should make it easy to modify, customize, and extend going.
|
http://www.codeproject.com/Articles/17670/ShortCUT-A-Short-C-Unit-Testing-Framework?fid=386984&df=90&mpp=10&sort=Position&spc=None&select=1899323&tid=1897912
|
CC-MAIN-2016-26
|
refinedweb
| 1,618
| 63.9
|
The QWebPluginFactory class creates plugins to be embedded into web pages. More...
#include <QWebPluginFactory>
This class is not part of the Qt GUI Framework Edition.
Inherits QObject.
This class was introduced in Qt 4.4.
The QWebPluginFactory class creates plugins to be embedded into web pages.
QWebPluginFactory is a factory for creating plugins for QWebPage. A plugin factory can be installed on a QWebPage using QWebPage::setPluginFactory().
Note: The plugin factory is only used if plugins are enabled through QWebSettings.
You can provide a QWebPluginFactory by implementing the plugins() and the create() method. For plugins() it is necessary to describe the plugins the factory can create, including a description and the supported MIME types. The MIME types each plugin can handle should match the ones specified in in the HTML <object> tag.
The create() method is called if the requested MIME type is supported. The implementation has to return a new instance of the plugin requested for the given MIME type and the specified URL.
This enum describes the types of extensions that the plugin factory can support. Before using these extensions, you should verify that the extension is supported by calling supportsExtension().
Currently there are no extensions.
Constructs a QWebPluginFactory with parent parent.
Destructor.>:
Note:.
The behaviour of this function is determined by extension.
You can call supportsExtension() to check if an extension is supported by the factory.
By default, no extensions are supported, and this function returns false.
See also supportsExtension() and Extension.
This function is reimplemented in subclasses to return a list of supported plugins the factory can create.
Note: Currently, this function is only called when JavaScript programs access the global plugins or mimetypes objects.
This function is called to refresh the list of supported plugins. It may be called after a new plugin has been installed in the system.
This virtual function returns true if the plugin factory supports extension; otherwise false is returned.
See also extension().
|
http://doc.qt.nokia.com/4.6-snapshot/qwebpluginfactory.html
|
crawl-003
|
refinedweb
| 322
| 50.53
|
flutter_foreground_service 0.1.1
flutter_foreground_service: ^0.1.1
flutter_foreground_service: ^0.1.1
Foreground service for the Android platform
flutter_foreground_service #
Setup #
Step 1 #
This plugin expects your application icon to be saved as
ic_launcher.png which is the default name.
If you use the package
flutter_launcher_icons to generate a new launcher icon, make sure to name the icon
ic_launcher.png.
Step 2 #
Add the plugin to your pubspec.yaml file:
dependencies: flutter: sdk: flutter flutter_foreground_service: ^LATEST_VERSION_HERE
Replace the
LATEST_VERSION_HERE the latest version number as stated on this page.
Step 3 #
Import the package into your project
import 'package:flutter_foreground_service/foreground_service.dart';
Usage #
example tab here on pub.dev to view the plugin in action.
In essence, the following line of code will start the foreground service:
await ForegroundService().start();
To stop the service again, use the following line of code:
await ForegroundService().stop();
|
https://pub.dev/packages/flutter_foreground_service
|
CC-MAIN-2020-50
|
refinedweb
| 142
| 52.26
|
You can subscribe to this list here.
Showing
10
results of 10
* believe finally managed to build the SBCL runtime system. I say
"believe", because build now fails at a later stage. Anyway, this is
what I did.
1. bsd-os.h
changed "typedef vm_size_t os_vm_size_t;" to
"typedef size_t os_vm_size_t;"
bsd-os.c
changed "vm_size_t os_vm_page_size;" to
"size_t os_vm_page_size;"
2. OpenBSD no longer seems to use underscore in front of function
names; I changed the file x86-assem.S to reflect this:
/* Minimize conditionalization for different OS naming schemes. */
#if defined __linux__ || defined __FreeBSD__ || defined __OpenBSD__
/* (but *not* OpenBSD) */
#define GNAME(var) var
#else
#define GNAME(var) _##var
#endif
3. LISP_FEATURE_LINUX seemed to be defined somewhere. This caused the
linking to fail, so I commented out all blocks containing "#ifdef
LISP_FEATURE_LINUX". (also in the file tools-for-build/grovel_headers.c).
[I know, this is ugly]
4. #ifndef SVR4
F(swapon)
#endif
in the file "undefineds.h" caused link failure, so I commented it out, too.
Bye.
//testing for consistency of first and second GENESIS passes
diff: output/genesis-2: No such file or directory
error: header files do not match between first and second GENESIS
$
Can this be because I broke the runtime system, even if it seemed to
compile and link? Can I verify the soundness of the runtime system
somehow?
Thanks,
Tarjei
On Sun, Nov 02, 2003 at 06:00:25PM +0100, David Lichteblau wrote:
> sb-aclrepl sets some global variables which should really be specific to
> each REPL instance (in different threads). Patch attached.
Cool. I wrote a cheesy little thing that pops up a new listener in an
xterm, but it confused sb-aclrepl and I wasn't sure how to fix it. The
files are here:
wserv.c is from the ircII sources and has been slightly modified.
Zach
In 0.8.5.19 (x86 linux) I'm now seeing the compiler go off for a very
long time on some terms. It's apparently spending all its time simplifying
unions of integer types. Here's a somewhat reduced example:
(defparameter *fn*
'(lambda ()
(-
(labels ((%f16 (f16-1 f16-2)
(* 9160907 318094 f16-1 f16-1 f16-1 -1116260 f16-1)))
(logior (integer-length (%f16 -197061128 -2304))
(* -569087
48578
-961
-7589570
(%f16 41285 961254)
(%f16 -91650836 -4)
(%f16 -7420455 -29908554)
-2022
9571109)
(block b7
(if (/= -864583285 1305672)
-18782
(logandc2 -173169065 99634))))))))
;; Do
;; (compile nil *fn*)
;; to see the problem.
I'm guessing f16-1 is getting a type that's a union of four different integer
subrange types, and the types expand exponentially from there in the multiplication
terms.
The type propagator needs some sort of widening operator for
when integer types get too complicated. There's not much gained by being
precise here.
Paul
Brian Mastenbrook <bmastenb@...> writes:
> If you had been using my patched version (y'know, the one I sent to the
> list with the title "SBCL 0.8.5 with support for G5 and 10.3") you
> wouldn't have seen this issue.
Duh. I guess I should actually read before installing. Argh.
>
>
> There is a binary release linked to from that page, along with source
> compilation instructions.
M'kay, I'm snarfing that and I'll report on my success or failure.
Thanks
'james
--
James A. Crippen <james at unlambda.com> Lambda Unlimited
61.2204N, -149.8964W Recursion 'R' Us
Anchorage, Alaska, USA, Earth Y = \f.(\x.f(xx))(\x.f(xx))
On Sat, Nov 01, 2003 at 04:35:56PM +0100, Tarjei Vagstol wrote:
> I decided to try the -devel list; please let me know if this is a
> "-help"-question instead.
Since I'm going to suggest below that you try to create a patch
yourself, -devel may be more appropriate than you expected.:-)
Seriously, "can you help me with this apparent bug" fits so well on
either list that it's probably not worth trying to classify it.
> I'm trying so compile SBCL from the 0.8.5-sources on my OpenBSD
> 3.4/i386 box. GCC is 2.95.3, GNU make 3.80. I'd thought I'd bootstrap
> it with clisp.
(It's almost certainly not relevant to the current problem, but if you
encounter other problems later, note that the clisp version may be
important. I haven't thought about it for a while, and I certainly
don't remember which versions were involved, but I dimly remember that
building SBCL pushes various limitations (pretty-printer, garbage
collector...) of various versions of clisp past the breaking point.)
> However, it fails when building the runtime system, with these errors:
>
> cc -g -Wall -O3 -I. -c -o alloc.o alloc.c
> In file included from os.h:40,
> from alloc.c:22:
> target-os.h:21: syntax error before `os_vm_size_t'
> target-os.h:21: warning: type defaults to `int' in declaration of `os_vm_size_t'
> target-os.h:21: warning: data definition has no type or storage class
[snip]
> I try to change target-os.h:21 from
> typedef vm_size_t os_vm_size_t;
> to
> typedef size_t os_vm_size_t;
>
> as suggested by Hannah Schroeter. Now, the build fails on bsd-os.c:
Note that target-os.h is supposed to be a symbolic link to the
underlying file (bsd-os.h for OpenBSD, I think). Thus, when you edit
target-os.h and write out a new version, it's not intuitively obvious
what the editor's correct action should be; but that may not stop the
editor from silently trying to DWIM by e.g. overwriting the symlink
with a modified copy of the file (but leaving the original bsd-os.h
unchanged).
If that scenario is as confusing to you as it is to me, you might want
to start anew with a clean copy of the sources, edit bsd-os.h
directly, and then restart the build from scratch (which should
regenerate the target-os.h symlink from scratch).
> cc -g -Wall -O3 -I. -c -o bsd-os.o bsd-os.c
> bsd-os.c:40: syntax error before `os_vm_page_size'
> bsd-os.c:40: warning: type defaults to `int' in declaration of `os_vm_page_size'
> bsd-os.c:40: conflicting types for `os_vm_page_size'
[snip]
> I suppose this doesn't help very much. What information should I
> provide to help diagnose the problem?
No, this actually looks like a pretty good bug report. If I still had
an OpenBSD machine I would probably bestir myself to try to fix the
problem. But then, if I still had an OpenBSD machine the port might
not have rotted this much in the first place.
It looks like the system just wants to know what vm_size_t should be
for OpenBSD, and trying to replace it with size_t sounds plausible.
And even if that's not the fix, the fix is likely to be very simple, a
line or two of code along the lines of the
#ifdef __FreeBSD__
#include <osreldate.h>
#endif
or
#if defined __OpenBSD__
typedef struct sigaltstack stack_t;
hackery that you can see at the head of bsd-os.h. But even if I were
highly motivated to try to debug and fix the problem myself, it could
be hard to do so without an OpenBSD machine to do it on.
If you do find a solution, we'd probably be happy to merge a patch.
--
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Nov 1, 2003, at 9:50 PM, James A. Crippen wrote:
> I'm running Mac OS X 10.3 Darwin 7.0 on a PPC 970 (G5). The binary
> distro of 0.8.4 for Darwin crashes on startup on this system. Below is
> the error:
If you had been using my patched version (y'know, the one I sent to the
list with the title "SBCL 0.8.5 with support for G5 and 10.3") you
wouldn't have seen this issue.-
panther.html
There is a binary release linked to from that page, along with source
compilation instructions.
Brian
- --
Brian Mastenbrook
bmastenb@...
-----BEGIN PGP SIGNATURE-----
Version: PGP 8.0.3
iQA/AwUBP6Rx72nXQDi0istxEQKp8ACfXg5Pc0STv2S7JmapJZbJTil/sloAoJzE
8fEawHnqZ320Gdk7v8T8dnDJ
=MF0P
-----END PGP SIGNATURE-----
james@... (James A. Crippen) writes:
> But I'm subscribed and would be happy to help solve this if it isn't
> already fixed in CVS.
If you're subscribed, you should probably already have seen the
message last week from Brian Mastenbrook, subject "SBCL 0.8.5 with
support for G5 and 10.3 (Panther)": if not, it's in the archive at
=3D4134
Please can you try the binary/patch he points to in that mail, and
report your experiences? Thanks.
=2Ddan
=2D-=20 - Free Software Lisp/Linux distro
I'm running Mac OS X 10.3 Darwin 7.0 on a PPC 970 (G5). The binary
distro of 0.8.4 for Darwin crashes on startup on this system. Below is
the error:
This is SBCL 0.8.4, an implementation of ANSI Common Lisp.
[...]
More information about SBCL is available at <>.
*** malloc[7745]: Deallocation of a pointer not malloced: 0x800400;
This could be a double free(), or free() called with the middle of an
allocated block; Try setting evironment variable MallocHelp to see
tools to help debug
fatal error encountered in SBCL pid 7745:
no handler for signal 4 in interrupt_handle_now(..)
There's no LDB in this build; exiting.
I don't know enough about SBCL internals to figure this out on my
own. I guess I'll try compiling SBCL with OpenMCL instead of itself.
But I'm subscribed and would be happy to help solve this if it isn't
already fixed in CVS.
'james
--
James A. Crippen <james at unlambda.com> Lambda Unlimited
61.2204N, -149.8964W Recursion 'R' Us
Anchorage, Alaska, USA, Earth Y = \f.(\x.f(xx))(\x.f(xx))
|
http://sourceforge.net/p/sbcl/mailman/sbcl-devel/?viewmonth=200311&viewday=2
|
CC-MAIN-2015-48
|
refinedweb
| 1,621
| 67.35
|
Difference between revisions of "Chatlog 2013-01-17"
From Provenance WG Wiki
Latest revision as of 16:04, 24 January 2013
See original RRSAgent log or preview nicely formatted version.
Please justify/explain all edits to this page, in your "edit summary" text.
15:57:08 <RRSAgent> RRSAgent has joined #prov 15:57:08 <RRSAgent> logging to 15:57:10 <trackbot> RRSAgent, make logs world 15:57:10 <Zakim> Zakim has joined #prov 15:57:12 <trackbot> Zakim, this will be PROV 15:57:12 <Zakim> ok, trackbot, I see SW_(PROV)11:00AM already started 15:57:13 <trackbot> Meeting: Provenance Working Group Teleconference 15:57:13 <trackbot> Date: 17 January 2013 15:57:14 <Luc> Zakim, this will be PROV 15:57:14 <Zakim> ok, Luc, I see SW_(PROV)11:00AM already started 15:57:16 <Zakim> +Curt_Tilmes 15:57:27 <Luc> Agenda: 15:57:31 <pgroth> pgroth has left #prov 15:57:38 <Luc> Chair: Luc Moreau 15:57:44 <Luc> rrsagent, make logs public 15:58:44 <pgroth> pgroth has joined #prov 15:58:54 <dgarijo> dgarijo has joined #prov 15:59:00 <Zakim> + +44.238.059.aaaa 15:59:07 <Paolo> Paolo has joined #prov 15:59:13 <Luc> zakim, +44.238.059.aaaa is me 15:59:14 <Zakim> +Luc; got it 15:59:24 <Zakim> +[IPcaller] 15:59:26 <Zakim> +??P6 15:59:33 <dgarijo> Zakim, ??P6 is me 15:59:34 <Zakim> +dgarijo; got it 15:59:35 <pgroth> Zakim, [IPcaller] is me 15:59:35 <Zakim> +pgroth; got it 15:59:46 <zednik> zednik has joined #prov 15:59:54 <dgarijo> Luc, if nobody volunteers, I can be the scribe 16:00:30 <Luc> it's very kind daniel, first, let's see if we can find somebody else, 16:00:39 <Luc> zakim, who is here? 16:00:39 <Zakim> On the phone I see Curt_Tilmes, Luc, pgroth, dgarijo 16:00:40 <Zakim> On IRC I see zednik, Paolo, dgarijo, pgroth, Zakim, RRSAgent, Curt, Luc, TallTed, ivan, trackbot, stain 16:00:43 <Zakim> +[IPcaller] 16:00:54 <ivan> zakim, dial ivan-voip 16:00:54 <Zakim> ok, ivan; the call is being made 16:00:56 <Zakim> +Ivan 16:01:00 <Paolo> HI I have done it quite recently but can do it again 16:01:02 <Luc> zakim, who is noisy? 16:01:02 <Paolo> if needed 16:01:03 <Zakim> + +1.315.330.aabb 16:01:12 <Zakim> Luc, listening for 10 seconds I heard sound from the following: Ivan (2%) 16:01:14 <tlebo> tlebo has joined #prov 16:01:20 <TallTed> TallTed has changed the topic to: Provenance WG - - Agenda: 16:01:20 <tlebo> zakim, who is on the phone? 16:01:20 <Zakim> On the phone I see Curt_Tilmes, Luc, pgroth, dgarijo, [IPcaller], Ivan, +1.315.330.aabb 16:01:26 <tlebo> zakim, I am aabb 16:01:26 <Zakim> +tlebo; got it 16:01:47 <Luc> scribe: tlebo 16:01:59 <Dong> Dong has joined #prov 16:02:05 <Luc> zakim, who is noisy? 16:02:16 <Zakim> Luc, listening for 10 seconds I heard sound from the following: Ivan (56%) 16:02:26 <tlebo> (I think this IRC client has dropped me before, so I might need to hand off to someone mid-stream) 16:02:33 <pgroth> ivan has the loudest keyboard ever 16:02:37 <ivan> zakim, mute me 16:02:37 <Zakim> Ivan should now be muted 16:02:42 <ivan> :-( 16:02:48 <tlebo> :-) 16:03:04 <khalidBelhajjame> khalidBelhajjame has joined #prov 16:03:19 <Zakim> +??P41 16:03:22 <smiles> smiles has joined #prov 16:03:24 <Luc> 16:03:27 <dgarijo> 0 (I wasn't there) 16:03:28 <tlebo> proposed: approve minutes 16:03:29 <pgroth> Topic: Admin 16:03:40 <Luc> proposed: to approve last week's minutes 16:03:41 <ivan> +1 16:03:42 <tlebo> 0 (was not here) 16:03:48 <Curt> 0 (not present) 16:03:48 <Paolo> 0 (missed it) 16:03:49 <dgarijo> 0 16:03:52 <smiles> +1 16:03:56 <Dong> +1 16:03:57 <Zakim> +[IPcaller.a] 16:04:11 <Luc> resolved: last week's minutes 16:04:34 <tlebo> luc: action on Tim for cross referencing. 16:04:43 <Zakim> +??P22 16:04:46 <Zakim> +Satya_Sahoo 16:04:48 <GK> GK has joined #prov 16:04:55 <hook> hook has joined #prov 16:05:05 <satya> satya has joined #prov 16:05:05 <tlebo> tim: I'll look at the cross reference. 16:05:06 <Zakim> +[OpenLink] 16:05:06 <Zakim> + +1.818.731.aacc 16:05:12 <TallTed> Zakim, [OpenLink] is temporarily me 16:05:12 <Zakim> +TallTed; got it 16:05:15 <TallTed> Zakim, mute me 16:05:15 <Zakim> TallTed should now be muted 16:05:17 <tlebo> luc: action on himself... 16:05:26 <tlebo> luc: action on Stephan for namespaces. 16:05:40 <tlebo> zednik: have looked at identifiers 16:06:05 <tlebo> pgroth: I've done all actions on me. 16:06:22 <Zakim> +??P13 16:06:42 <Luc> topic: Implementations <LUC>Summary: Paul reviewed all implementation surveys submitted so far. While the numbers look healthy, it was noted that 7 implementation reports were submitted by Southampton. Many implementers are known to have implemented PROV but have not submitted yet. Group members are strongly reminded to submit their reports. The discussion focused on interoperability pairs. It is important to identify which application one exports provenance to or one imports provenance from. Some generic services such as the provenance validator are hopefully good candidates for interoperability with other applications. Simon and Tom agreed to test their implementations against the validator. 16:06:55 <tlebo> luc: paul went through surveys recently. 16:07:01 <pgroth> 16:07:02 <dgarijo> I've added all the remaining implementations that I had added in the wiki. Some of them today 16:07:09 <tlebo> pgroth: announced it via email 16:07:27 <TomDN> TomDN has joined #prov 16:07:32 <tlebo> ... reports from 9 organizations 16:07:58 <tlebo> ... southampton has 7 implementations. 16:08:01 <Zakim> +Ruben 16:08:13 <TomDN> Zakim, +Ruben is me 16:08:13 <Zakim> sorry, TomDN, I do not recognize a party named '+Ruben' 16:08:14 <tlebo> ... provo is good track; all constructs supported by 2 sep implementations. 16:08:21 <TomDN> Zakim, Ruben is me 16:08:21 <Zakim> +TomDN; got it 16:08:25 <SamCoppens> SamCoppens has joined #prov 16:08:33 <tlebo> ... provo needs a pair of implmeentations to exchange. 16:08:39 <TomDN> Zakim, SamCoppens is with TomDN 16:08:39 <Zakim> +SamCoppens; got it 16:08:44 <TomDN> Zakim, mute me 16:08:44 <Zakim> TomDN should now be muted 16:08:47 <GK_> GK_ has joined #prov 16:08:55 <tlebo> ... it's easy to hit that min by having SH and Kings to exchange prov. 16:08:58 <GK_> Zakim, ??p13 is me 16:08:58 <Zakim> +GK_; got it 16:09:11 <tlebo> ... for prov-n it is less satisfying. only 2 orgs: SH and weblab. 16:09:22 <tlebo> ... tom and sam have prov-n implementations. 16:09:32 <tlebo> ... but do weblab actually support it? 16:09:42 <tlebo> ... they say openRDF sesame as the library (implies prov-o) 16:09:50 <Paolo> I am going to add implementation with prov-n support 16:09:52 <Luc> q+ 16:09:55 <tlebo> ... need to rely on tom/sam implementation 16:09:55 <Paolo> (applications) 16:10:13 <tlebo> ... constraints: luc's implementation, but we need one more impl. 16:10:31 <pgroth> it's a good thing! 16:10:44 <tlebo> luc: # implementations on southampton, some on different languages. 16:10:46 <GK> GK has joined #prov 16:11:00 <tlebo> ... we can demonstrate language independence if not org independence. 16:11:15 <TomDN> Zakim, unmute me 16:11:15 <Zakim> TomDN should no longer be muted 16:11:18 <tlebo> ... TomDN implementing? isn't he using the provtoolbox? 16:11:46 <Paolo> q+ 16:11:50 <tlebo> TomDN: not really using the toolbox. 16:12:09 <pgroth> ack Luc 16:12:15 <pgroth> ace paolo 16:12:18 <pgroth> ack paolo 16:12:27 <TomDN> Zakim, mute me 16:12:27 <Zakim> TomDN should now be muted 16:12:31 <Luc> q+ 16:12:35 <tlebo> Paolo: Tom's note, if I produce prov-n w/o provtoolbox then it counts as a new implementation. 16:12:44 <pgroth> ack luc 16:13:02 <tlebo> luc: ideally, we want full independence. 16:13:13 <tlebo> ... but we made the case that prov-n is aimed at human consumption. 16:13:19 <tlebo> ... so no need for interoperability. 16:13:46 <TomDN> Zakim, unmute me 16:13:46 <Zakim> TomDN should no longer be muted 16:13:49 <tlebo> pgroth: for prov-n, does TomDN consume prov info as prov-n? 16:13:50 <Luc> prov-dm contains examples of prov-dm, consumable by prov toolbox. So it's a pair! 16:14:01 <Luc> prov-dm contains examples of PROV-N, consumable by prov toolbox. So it's a pair! 16:14:19 <tlebo> TomDN: I read it == I evaluate. It generates it == write. 16:14:23 <GK> A precedent we might look at is the "human" syntax(es) for OWL - what do they do? 16:14:39 <Luc> @TomDN, can you validate your prov-n with my validator? 16:15:12 <tlebo> TomDN: I can produce a file from my tool as prov-n. 16:15:18 <Luc> @TomDN, can you paste your prov-n into 16:15:25 <tlebo> pgroth: we want to give TomDN's prov-n to luc's validator. 16:15:33 <tlebo> ... then we have a pair. 16:15:41 <Luc> or 16:16:00 <tlebo> pgroth: tom doens't use all of the constructs. 16:16:05 <tlebo> TomDN: no. 16:16:11 <tlebo> pgroth: extend to use other constructs? 16:16:14 <tlebo> TomDN: not easy. 16:16:27 <Luc> q+ 16:16:32 <pgroth> ack Luc 16:16:47 <TomDN> Zakim, mute me 16:16:47 <Zakim> TomDN should now be muted 16:16:58 <tlebo> Luc: prov-dm doc is an example of prov-n generation. so all statements can be validated by toolbox. 16:17:02 <tlebo> .. thus an interop pair 16:17:27 <tlebo> pgroth: we need to add it to the quesionnaire 16:17:33 <TomDN> (I will provide some rationale on my questionaire answers to explain the read/write answers 16:17:48 <tlebo> pgroth: we should do it as the WG 16:17:49 <GK> q+ to suggest looking in to how was handled 16:18:01 <Zakim> -GK_ 16:18:06 <Zakim> +[IPcaller.aa] 16:18:07 <GK> Losrt my client 16:18:08 <tlebo> pgroth: we seem to have coverage on prov-n (with these steps) 16:18:23 <GK> Sorry lost connection 16:18:23 <Luc> q? 16:18:37 <Zakim> +??P13 16:18:46 <pgroth> q+ to say we need a pair for prov-o 16:18:46 <GK> zakim, ??p13 is me 16:18:47 <Zakim> +GK; got it 16:18:51 <tlebo> Luc: please submit the implementation reports. 16:18:58 <stain> Zakim, ??P13 is me 16:18:58 <Zakim> I already had ??P13 as GK, stain 16:19:08 <Zakim> -[IPcaller.aa] 16:19:19 <tlebo> GK: prov-n and interop -- find out what OWL WG did with their functional syntax. 16:19:22 <CraigTrim> CraigTrim has joined #PROV 16:19:25 <tlebo> ... it's similar role. 16:19:28 <Luc> q? 16:19:32 <ivan> unmute ivan 16:19:34 <Luc> ack gk 16:19:34 <Zakim> GK, you wanted to suggest looking in to how was handled 16:19:39 <ivan> zakim, unmute me 16:19:39 <Zakim> Ivan should no longer be muted 16:20:15 <pgroth> i think we have a solution now for prov-n 16:20:15 <tlebo> ivan: i don't remember how function syntax was handled. it was just a specification language - not a cand rec requiement to parse it. 16:20:16 <Luc> q? 16:20:38 <tlebo> ... for OWL systems, they needed to exchange RDF/XML. the ONLY one. 16:20:39 <GK> That was my guess - I think PROV-N might be presented similarly? 16:20:45 <pgroth> Tom's implementation + validator and prov-dm docs + validator 16:20:45 <Luc> q? 16:20:48 <Luc> ack pg 16:20:48 <Zakim> pgroth, you wanted to say we need a pair for prov-o 16:21:03 <tlebo> pgroth: provo coverage is fine, we need some pairs. 16:21:09 <Zakim> +??P44 16:21:15 <tlebo> ... could simon and luc make that pair? 16:21:48 <tlebo> Luc: the service is available online. anyone can paste them in to validator or translator. 16:21:52 <tlebo> ... they can just report it. 16:21:56 <smiles> Luc - Can you give the URL again? 16:22:07 <stain> Zakim: ??P44 is me 16:22:11 <stain> Zakim, ??P44 is me 16:22:11 <Zakim> +stain; got it 16:22:11 <tlebo> pgroth: a pair isn't one directional? 16:22:22 <stain> Zakim, ??P44 is also khalidBelhajjame 16:22:22 <Zakim> I don't understand '??P44 is also khalidBelhajjame', stain 16:22:25 <tlebo> pgroth: simon, dump out provo and validate it? 16:22:34 <tlebo> smiles: yes, if it takes turtle 16:22:36 <ivan> zakim, mute me 16:22:36 <Zakim> Ivan should now be muted 16:22:50 <Luc> 16:23:01 <tlebo> Luc: anybody can do that. 16:23:04 <Luc> q? 16:23:04 <pgroth> constraints 16:23:04 <GK> I think producer -> consumer (one way) is OK - it shoews two developers read spec and had some common understanding 16:23:11 <pgroth> q+ 16:23:30 <tlebo> pgroth: constraints. luc did them, pgroth is slowing working them. 16:23:41 <tlebo> ... obviously good to have more than 2 16:23:47 <tlebo> ... or even if other parts of implementations. 16:23:59 <tlebo> ... 47 unit tests away from full coverage. 16:24:16 <tlebo> ... shoiuld be able to do it. 16:24:21 <tlebo> +1 :-) 16:24:35 <tlebo> luc: Paolo was working on partial constriants 16:24:44 <Luc> Regrets: jcheney 16:24:53 <TomDN> Does your implementation need to be completely finished by Jan. 31st? 16:24:57 <tlebo> Paolo: jun and I havent' worked on it. 16:25:07 <pgroth> @TomDN it's about the report really 16:25:17 <tlebo> Luc: when? by end of month? 16:25:20 <tlebo> Paolo: not by then. 16:25:26 <pgroth> +q to ask about stardog 16:25:29 <Luc> q? 16:25:31 <TomDN> @pgroth, thanks, that's what i thought 16:25:55 <tlebo> pgroth: we knwo there are implementations out there than what is reported. 16:26:04 <tlebo> ... we should all sign up to report implementations. 16:26:22 <tlebo> ... e.g. stardog is doing it. 16:26:27 <tlebo> ... approach individually. 16:26:50 <Luc> q? 16:26:52 <Luc> ack pg 16:26:52 <Zakim> pgroth, you wanted to ask about stardog 16:26:54 <tlebo> (I tried to poke the LInkedTV via twitter yesterday -- it's not coming out till Feb) 16:27:01 <pgroth> but there's also dbpedia, and qudt, etc 16:27:04 <Luc> topic: Response to public comments <luc>Summary: the drafted response were approved. Reviewers will be contacted by Paul with the Group responses. Outstanding issues will be tackled in the coming week. 16:27:08 <tlebo> zakim, who is making noise? 16:27:09 <pgroth> simon can you mute 16:27:12 <Luc> 16:27:18 <Zakim> tlebo, listening for 10 seconds I heard sound from the following: Luc (83%), ??P41 (28%) 16:27:30 <pgroth> zakim, mute ??P41 16:27:30 <Zakim> ??P41 should now be muted 16:27:30 <GK> (There's also the possibility of submitting "third party" reports for public implemenbtations) 16:27:43 <Luc> q? 16:27:47 <pgroth> @GK i didn't no that 16:27:52 <pgroth> s/no/know 16:28:00 <Luc> q? 16:28:09 <Luc> Proposed: the group endorses the responses to issues 611 and 612 16:28:14 <TomDN> +1 16:28:17 <ivan> +1 16:28:18 <khalidBelhajjame> +1 16:28:18 <tlebo> +1 16:28:19 <satya> +1 16:28:21 <zednik> +1 16:28:23 <stain> +1 16:28:26 <Dong> +q 16:28:26 <TallTed> +1 16:28:27 <GK> @paul - I don't *know* that, but I can't see any reason why now 16:28:34 <SamCoppens> +1 16:28:36 <Luc> q? 16:28:36 <dgarijo> +0 (I haven't reviewed them yet) 16:28:38 <hook> +1 16:28:39 <smiles> +1 (noting that I sent a suggestion just before this call) 16:28:41 <GK> +0 16:28:50 <Paolo> 0 haven't reviewed in detail 16:28:53 <Luc> Resolved: the group endorses the responses to issues 611 and 612 16:28:54 <Curt> +0 (haven't reviewed) 16:29:04 <stain> @TallTed what happened to McTed over New Year? :) 16:29:13 <tlebo> luc: who to respond to reviewers? 16:29:15 <Dong> q- 16:29:15 <pgroth> sure 16:29:17 <Luc> q? 16:29:21 <tlebo> Luc: : is it paul? 16:29:25 <tlebo> pgroth: I can do that. 16:29:33 <tlebo> ... we had a question about derivation. 16:29:57 <tlebo> ... wasQUotedFrom, not derivation. 16:30:08 <dgarijo> I think it was about the name of wasQuotedFrom. 16:30:12 <tlebo> (I think it's the same mix-up that "Tim vs. Stian+Daniel" had. 16:30:13 <stain> it was about the directionality - as I originally complained about it 16:30:23 <stain> he suggested hadQuoteFrom 16:30:27 <dgarijo> yep 16:30:35 <Luc> q? 16:30:57 <pgroth> action: pgroth to respond to public comments 16:30:57 <trackbot> Created ACTION-162 - Respond to public comments [on Paul Groth - due 2013-01-24]. 16:30:58 <Dong> @Luc and Tim: I've just remember that some PROV-O examples might need to be revised in ISSUE-611 16:31:02 <tlebo> luc: wasquotedFrom, can't recall. 16:31:17 <TomDN> 16:31:27 <hook> hook has joined #prov 16:31:29 <stain> I think we need another WG discussion on email about it 16:31:57 <TallTed> stain - just unifying my nick across a few spaces (Twitter, a couple of IRC nets, etc.) ... 16:32:03 <stain> if the term was confusing in the primer.. then it's confusing all over 16:32:04 <tlebo> q+ to note that we couldn't converge last time on the naming. 16:32:15 <Zakim> - +1.818.731.aacc 16:32:44 <Zakim> + +1.818.731.aadd 16:32:56 <tlebo> ECHO 16:32:57 <pgroth> echo madness 16:33:02 <stain> zakim, who is noisy? 16:33:06 <pgroth> simon 16:33:07 <Luc> q? 16:33:13 <Zakim> stain, listening for 10 seconds I heard sound from the following: tlebo (31%) 16:33:14 <pgroth> ack tlebo 16:33:16 <Zakim> tlebo, you wanted to note that we couldn't converge last time on the naming. 16:33:38 <Zakim> -[IPcaller] 16:34:00 <smiles> @tlebo - Do you have a link to that email conversation? 16:34:01 <Luc> q? 16:34:10 <stain> but this email was from Chuck Norris - which sounds like a native speaker 16:34:11 <Luc> q? 16:34:15 <tlebo> smiles: I can dig up the ISSUE. 16:34:17 <stain> MORRIS 16:34:19 <stain> hihi 16:34:26 <smiles> OK 16:34:26 <dgarijo> @stian:lol 16:34:56 <Zakim> +??P32 16:35:15 <Luc> q? 16:35:17 <Paolo> zakim, ??P32 is me 16:35:17 <Zakim> +Paolo; got it 16:35:25 <Luc> topic: prov-dictionary <luc>Summary: As the editor's draft was just released, it was agreed that reviewers have till Wednesday to complete their review. 16:35:27 <tlebo> tlebo: I'll dig through them. thanks for the reminder 16:35:44 <TomDN> no 16:35:54 <TomDN> Zakim, unmute me 16:35:54 <Zakim> TomDN should no longer be muted 16:36:03 <tlebo> smiles: is the wasQuotedFrom naming discussion 16:36:13 <Paolo> deadline is 23rd, right? 16:36:31 <pgroth> fine with me 16:36:35 <tlebo> Luc: reviewers should give feedback by next wed. 16:36:41 <pgroth> paul 16:36:49 <smiles> @tlebo Thanks! 16:36:59 <TomDN> Paolo, Stian, James (maybe), Luc, and Paul, 16:37:02 <Luc> q? 16:37:11 <TomDN> Zakim, mute me 16:37:11 <Zakim> TomDN should now be muted 16:37:12 <Luc> topic: prov-aq <luc>Summary: All reviewers have submitted their report. The editors will produced a revised version for the next teleconference (or the following one) and vote for release will then take place. 16:37:38 <Luc> q? 16:37:41 <tlebo> GK: I've seen 4 reviews in 16:37:57 <tlebo> pgroth: tim, simon, luc, dong, stian 16:38:18 <tlebo> h! 16:38:22 <pgroth> your back 16:38:46 <tlebo> pgroth: all have reviewed. 16:38:54 <pgroth> shall i go 16:39:08 <pgroth> q+ 16:39:11 <tlebo> GK: through 1.5 sets of comments. 16:39:15 <tlebo> ... most are editorial. 16:39:25 <tlebo> ... hoping to pick out those that are more than editorial. 16:39:42 <pgroth> that's not the main issue 16:39:45 <tlebo> ... issue on REST interface vs. simple convention for URI to retrieve prov. 16:40:04 <tlebo> pgroth: everyone but stian said doc can go LC 16:40:10 <stain> q+ 16:40:17 <tlebo> ... stian has 8-9 blocking issues. 16:40:39 <Luc> q+ 16:40:44 <Luc> ack pg 16:40:46 <tlebo> ... we should concentrate on blocking issues from stian. 16:40:46 <GK> Ah, I hadn't yet looked at those blocking issues from Stian 16:41:07 <tlebo> stain: my issues: it was heavy. 16:41:16 <Luc> q? 16:41:20 <Luc> ack sta 16:41:24 <tlebo> ... as a draft, fine. but not as final technical. 16:41:25 <stain> @GK sorry about that.. 16:41:27 <Luc> ack luc 16:41:40 <tlebo> Luc: i'm fine wiht doc released as next WD. 16:41:58 <tlebo> ... I felt that feedback required changes, and so not last call. 16:42:02 <pgroth> q+ 16:42:04 <tlebo> ... we don't have notion of last call in Note. 16:42:09 <tlebo> ... we're abusing that name. 16:42:20 <Luc> q? 16:42:21 <tlebo> ... as next draft, fine. 16:42:44 <tlebo> pgroth: we should distinguish between release and not wanting to do any more to it. 16:43:08 <tlebo> ... address all comments, release a WD at a minimum. OR when we go PRec with other docs. 16:43:17 <tlebo> ... but can we get another iteration? 16:43:17 <Luc> q? 16:43:19 <hook> hook has joined #prov 16:43:22 <tlebo> ... before PR 16:43:25 <GK> @paul +1 review/revise as much as possible 16:43:32 <Luc> q? 16:43:32 <tlebo> ... we need two more itnerations on PAQ 16:43:55 <tlebo> Luc: we should be pragmatic about Notes and making it too perfect. 16:44:00 <GK> If the issues are substantive, I don't think they should be "offline" 16:44:09 <Luc> q? 16:44:30 <pgroth> @gk i was talking about scheduling 16:44:44 <GK> @paul Ah, OK. 16:44:46 <tlebo> Luc: do we vote? or do work and editors cycle? 16:44:57 <tlebo> pgroth: next week or following for WD. 16:45:01 <Luc> ack pg 16:45:11 <TomDN> (can be synced with dictionary then) 16:45:18 <tlebo> ... take off "final" terminology" 16:45:28 <Luc> q? 16:45:45 <tlebo> topic: prov-xml <luc>Summary: Stephan updated the group on recent changes made by editors. He is going to summarise these by email, on the tracker. We then discussed the namespace convention to adopted. The ideal is to align with the conventions we have adapted for the ontology, while still being compatible with the xml approach. Stephan was tasked to come up with a proposal for next teleconference. 16:46:02 <GK> Next week is likely busy for me. I'll try to complete my pass through the reviews today. 16:46:25 <tlebo> luc: namespace, schema management, etc. 16:46:44 <tlebo> zednik: some feedback on original note. extended types was confusing with prov:type. 16:46:52 <tlebo> ... made native XML type for those. 16:47:30 <tlebo> ... identifiers: work natively for XML 16:47:33 <tlebo> ... id and idref 16:47:40 <tlebo> id uses xsi:id 16:47:54 <tlebo> ... base type of idRef -- xml tooling is familiar. 16:48:12 <tlebo> .. cannot start with numbers, other constraints. 16:48:24 <tlebo> ... it's native but doesn't work with our examples or URIs. 16:48:33 <tlebo> ... alternative: anyURI or QNames 16:48:34 <pgroth> @gk see where you can get and see what needs to be debated 16:48:44 <tlebo> ... not sure which would be better. 16:48:50 <tlebo> ... also xlinks and xpointers. 16:49:06 <GK> @paul - that's my plan - I'm making notes as I go. I'll email you a copy when done. 16:49:13 <pgroth> @gk awesome 16:49:16 <ivan> q+ 16:49:23 <tlebo> ... xpointers and xlinks might let us verify references existing. 16:49:28 <ivan> ack ivan 16:49:32 <tlebo> ... the group needs to read up on xlinks/xpointers. 16:49:35 <Luc> ack iv 16:49:46 <tlebo> ivan: how widely is xlink implemented? 16:50:03 <tlebo> ... do tools really do it? xlink is an unlucky standard. 16:50:10 <Luc> q? 16:50:23 <hook> q+ 16:50:32 <tlebo> ... might not be worth adopting, could be more harm than good. 16:50:48 <tlebo> hook: xlinks ISO community uses them to reference external XML traces. 16:50:59 <tlebo> ... in bundles, can reference across bundles. 16:51:09 <tlebo> ... but good point on how much it's used. 16:51:15 <Luc> q? 16:51:22 <Luc> ack ho 16:51:31 <tlebo> ... we still need to look into xlinks. 16:51:50 <tlebo> Luc: have your changes surfaced to the WG? 16:52:00 <tlebo> ... some may want to get insight into your changes. 16:52:20 <tlebo> ... (are you using issue tracker?) 16:52:30 <Luc> q? 16:52:54 <tlebo> zednik: announced, but did not tag into ISSUE. 16:53:12 <Luc> q? 16:53:37 <tlebo> zednik: last modeling was valid. 16:53:55 <tlebo> Luc: namespace management issue 16:54:08 <tlebo> ... the namespace HTML is waiting on it. 16:54:30 <tlebo> zednik: seems like we're misusing xml namesapces. 16:54:49 <tlebo> ... the extension should have a different namespace. 16:54:58 <tlebo> ... including dictionary in new namespace 16:55:24 <tlebo> ... stian proposed an organization, but not ideal. 16:55:37 <tlebo> ... the xml schema should have different namespaces. 16:55:58 <TomDN> (didn't we vote on this a few months ago?) 16:56:03 <Luc> q? 16:56:03 <pgroth> q+ 16:56:18 <Luc> ack pg 16:56:37 <tlebo> pgroth: prov dictionary etc being in different docs doesn't mean it's not in the same thing. 16:56:54 <tlebo> ... (they are in same group, it's just broken up to aid understanding). 16:56:58 <Luc> zakim. who is noisy? 16:57:07 <Luc> zakim, who is noisy? 16:57:14 <tlebo> pgroth: from practice, developers do not like separate namespaces. 16:57:17 <Zakim> Luc, listening for 10 seconds I heard sound from the following: pgroth (90%) 16:57:30 <hook> hook has joined #prov 16:57:30 <tlebo> ... PROV namespace will included in RDFa automatically. 16:57:44 <ivan> s/RDFa/RDFa 1.1/ 16:57:57 <tlebo> Luc: is nice to have one ns 16:58:24 <tlebo> Luc: a prov-xml dictionary namespace? 16:58:37 <TomDN> then we need a prov-links namespace as well 16:58:55 <GK> IMO, if any of the XML namespaces are different from the corresponding RDF, then they should *all* be different 16:59:10 <stain> q+ 16:59:13 <GK> .. including the "core" namespace 16:59:31 <Curt> just do 2, core, and core + all extensions 16:59:51 <Luc> q? 16:59:52 <stain> exactly.. we do a single schema with only core, and one with core-everything 16:59:53 <tlebo> q+ to ask zednik where the motivation for different namespaces comes from 16:59:59 <Luc> ack st 17:00:25 <tlebo> stain: oen for core prov xml, one that is prov-everything xml schema. If you don't like either of those, then you're on your own. 17:00:26 <zednik> q+ 17:00:43 <Luc> ack tl 17:00:43 <Zakim> tlebo, you wanted to ask zednik where the motivation for different namespaces comes from 17:01:57 <Luc> q+ 17:02:27 <Curt> I'm ok with one schema with everything 17:02:46 <pgroth> q+ prov-xml is a note 17:02:57 <pgroth> i like that 17:02:57 <tlebo> q- 17:03:02 <zednik> q- 17:04:01 <tlebo> Luc: : single schema file with all terms that use one namespace, THEN half-way house of a single schema for just the core Rec terms. 17:04:03 <pgroth> q+ to say that it is a single namespace 17:04:20 <Luc> ack luc 17:04:33 <stain> I think this is mainly an artifact of XML Schema being very strict of linking schemas and namespaces - this is not a big deal in other ways to express XML schemas like Relax NG 17:05:03 <pgroth> ack pgroth 17:05:03 <Zakim> pgroth, you wanted to say that it is a single namespace 17:05:25 <tlebo> pgroth: everyone should be able to paste the namespace to a browser and get all serializations documented. 17:05:34 <khalidBelhajjame> bye 17:05:34 <Zakim> -Satya_Sahoo 17:05:36 <Zakim> -tlebo 17:05:36 <Zakim> -Paolo 17:05:37 <Zakim> -??P22 17:05:37 <Zakim> -TomDN 17:05:37 <GK> Bye 17:05:37 <SamCoppens> bye 17:05:38 <dgarijo> bbye 17:05:39 <Zakim> -stain 17:05:40 <Zakim> -[IPcaller.a] 17:05:41 <Zakim> -Curt_Tilmes 17:05:43 <Zakim> - +1.818.731.aadd 17:05:44 <Zakim> -pgroth 17:05:45 <SamCoppens> SamCoppens has left #prov 17:05:46 <Zakim> -dgarijo 17:05:46 <Zakim> -Ivan 17:05:46 <tlebo> Luc: I am done scribing? 17:05:47 <ivan> ivan has left #prov 17:05:48 <Luc> rrsagent, set log public 17:05:50 <Zakim> -??P41 17:05:53 <Zakim> -TallTed 17:05:54 <Zakim> -GK 17:06:20 <GK> GK has left #prov 17:06:31 <Luc> rrsagent, draft minutes 17:06:31 <RRSAgent> I have made the request to generate Luc 17:06:35 <Luc> trackbot, end telcon 17:06:35 <trackbot> Zakim, list attendees 17:06:36 <Zakim> As of this point the attendees have been Curt_Tilmes, Luc, dgarijo, pgroth, [IPcaller], Ivan, +1.315.330.aabb, tlebo, Satya_Sahoo, +1.818.731.aacc, TallTed, TomDN, SamCoppens, GK_, 17:06:36 <Zakim> ... GK, stain, +1.818.731.aadd, Paolo 17:06:43 <trackbot> RRSAgent, please draft minutes 17:06:43 <RRSAgent> I have made the request to generate trackbot 17:06:44 <trackbot> RRSAgent, bye 17:06:44 <RRSAgent> I see 1 open action item saved in : 17:06:44 <RRSAgent> ACTION: pgroth to respond to public comments [1] 17:06:44 <RRSAgent> recorded in # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00000527
|
http://www.w3.org/2011/prov/wiki/index.php?title=Chatlog_2013-01-17&curid=617&diff=10707&oldid=10688
|
CC-MAIN-2016-18
|
refinedweb
| 5,375
| 74.08
|
09 November 2011 17:51 [Source: ICIS news]
BARCELONA (ICIS)--Global sugar production may rise by 8.4m tonnes/year to a total of just over 173m tonnes/year in 2011/2012, driven by population and demand growth, but sugar prices are still likely to remain high, said senior commodity analyst at FO Lichts, Stefan Uhlenbrock, on Wednesday.
Uhlenbrock was speaking at the 14th Annual FO Lichts World Ethanol and Biofuels conference in ?xml:namespace>
Emerging economies such as
Good sugar crop prospects in
This is in contrast to
While sugar prices have come off the peaks of just over 36 cents/lb seen in February 2011, international sugar prices are still likely to remain high because of growing global food demand and the need to incentivise investment.
The latest world sugar price is trading around 26 cents/lb, according to Bloomberg data.
The world sugar price remains relatively high and in contrast to the low level of eight cents/lb seen in June 2007, said Uhlenbro
|
http://www.icis.com/Articles/2011/11/09/9506906/global-sugar-production-in-2011-2012-to-rise-over-173m-tonnesyear.html
|
CC-MAIN-2014-10
|
refinedweb
| 167
| 53.34
|
WPF sometimes requires us to convert one shade of a color to another. For example, we may want a button border to be a darker shade of the button background. In cases where the color value is bound to another property, one would typically calculate the darker shade as a mathematical percentage of the base color. For example, we might calculate the border color as 85% of the background color. I recently needed to perform this chore, and I was surprised to find very little on how to do the conversion without resorting to using the System.Drawing namespace.
System.Drawing
System.Drawing is a GDI namespace, and I have a very strong preference for keeping it out of my WPF applications. To me, mixing GDI and WPF is a code smell, which should be avoided in all but exceptional circumstances. So, after a bit of research, I determined how to perform the conversion in pure-WPF.
This article explains how to perform the actual color conversion. Normally, the methods shown in the attached demos would be included in an IValueConverter object that is included in the data binding of the color property. I don't cover the IValueConverter aspect of the process in this article, since there are a number of good articles on how to create an IValueConverter class. Instead, I focus on the conversion methods themselves. However, I have included a sample IValueConverter class for each set of conversions.
IValueConverter
WPF works with the System.Windows.Media namespace, which includes a Color object built around the familiar RGB color model. Actually, the WPF Color object uses an ARGB color model, as it includes an alpha channel to control transparency. The RGB color model works very well for most purposes, but it isn't well-suited to the task of calculating different shades of a color. For that task, we can use one of two color models:
System.Windows.Media
Color
Many developers assume the two models are the same, but that's not the case. To see the difference, create a new WPF application in Expression Blend and set the window background to this solid color: #FFA7BCD7. Now, change the Blend color picker for the window background from RGB to HLS (by right-clicking on one of the R-G-B-A letters in the color picker); then, drag the L slider to reduce the Luminance value to zero. As you do so, you will see the color-space cursor jog to the right, and then move straight down:
Now, reset the color value to #FFA7BCD7, and change the color model from HLS to HSB. Then, drag the B slider to reduce the brightness to zero. This time, the color space cursor will move straight down, without the jog to the right:
As you can see, there are differences in the colors that result in some cases where B (in the HSB model) and L (in the HLS model) are set to the same value.
Either color model will give good results; it really boils down to personal preference. I like the HLS model for doing percentage color adjustments, because I feel that the HSB model tends to de-saturate colors and move too quickly in the direction of dark gray. The jog to the right that the HLS model takes seems to me to produce richer shades. But naturally, there are those who disagree. If you are one of those folks, please feel free to leave a comment.
There are two demos attached to this article:
The demos are very simple console apps that perform RGB conversions to and from HLS and HSB color equivalents. Each demo contains the necessary color conversion methods and methods to construct WPF Color objects from hex values.
Note that you will not need the hex conversion methods in an IValueConverter, since WPF contains a built-in value converter that will recognize the hex passed in from XAML as a SolidColorBrush. So, in a value converter, here is how you get an RGB Color object from the value passed in to the value converter:
SolidColorBrush
var brush = (SolidColorBrush) value;
var rgbColorIn = brush.Color;
You can see the complete code in the sample IValueConverter class included with each demo.
I don't claim to be a color theorist, and unfortunately, I can't provide a line-by-line explanation of why the methods work. I have cited my sources for the algorithms, and the demos output sufficient information to allow you to verify the methods against the conversions performed by Blend. Most importantly, the demos verify that the conversion back to RGB from either HLS or HSB results in the original RGB value converted to the alternate color model.
As always, one of the reasons for posting this article is to solicit peer review from the CodeProject community. If you know of better algorithms for performing either set of conversions, your comments are welcome. Similarly, if you can flesh out the 'why this works' for either set of algorithms, your insights would be greatly appreciated. For the rest of us, hopefully, the demos will provide the C# code needed to perform a color adjustment the next time the need for one arises.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
// Black: Set HSB and return
if (max == 0.0)
{
hsbColor.H = 0.0;
hsbColor.S = 0.0;
hsbColor.B = 0.0;
hsbColor.A = a;
return hsbColor;
}
// Black: Set HSB and return
if (max == 0.0)
{
hsbColor.H = 0.0;
hsbColor.S = 0.0;
hsbColor.B = 0.0;
hsbColor.A = a / 255.0; // Should be this...
return hsbColor;
}
H
NaN
delta
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
https://www.codeproject.com/Articles/49650/WPF-Color-Conversions
|
CC-MAIN-2017-30
|
refinedweb
| 979
| 59.43
|
Using text in n++ window as input for function
- Michael Germon last edited by
Hello,
I’m not really a programmer but am working on a plugin that alleviate some repetitive formatting I need to do multiple times daily for a system. So far I have the c# code functioning as intended and I’ve added it into a template from the plugin page while making some modifications to the template.
I am at a point where I should just need to get the input for the plugin and it should be ready to start testing. Unfortunately I’m not sure how to do this. I imagine that the namespace or some other prebuilt template code is used for this but I’m having a heck of a time finding it on my own looking through everything. I’ve also tried looking for example source code in hopes of finding a plugin that does something similar but to no fruition.
I guess, for a straight example, say I open up notepad++ and type in “Hello world !” - I would like to have my plugin use that text on the window to, lets say insert a new line for every space, so the plugin would alter the text on the window from…
Hello world !
to…
Hello
world
!
This seems like it would be a basic thing for plugins to do, so my apologies, I’m afraid my lack of experience makes sifting through the template a very overwhelming task. Thank you in advance for any assistance.
- Eko palypse last edited by
the first hing to understand is that a plugin has to work with at least two core objects,
namely notepad++ and scintilla.
Scintilla is the core component which is responsible for modifying/styling the text.
Which means that in your case in order to be able to retrieve the text you need to
get a reference/instance of the scintilla object and send/call the SCI_GETTEXT method.
How this is done in C# - I don’t know.
With pythonscript plugin it is as easy as calling
editor.getText()as the plugin
provided editor being the scintilla component and getText being a wrapper around SCI_GETTEXT.
- Michael Germon last edited by
Thank you Eko! I should be able to figure it out from here.
- gurikbal singh last edited by
well where is your repository at github.com
|
https://community.notepad-plus-plus.org/topic/17051/using-text-in-n-window-as-input-for-function
|
CC-MAIN-2019-43
|
refinedweb
| 394
| 69.01
|
Apart from the fact that the question is ambiguous, what's your problem?Apart from the fact that the question is ambiguous, what's your problem?You are given a rectangle whose side lengths are integer numbers. You want to cut the rectangle into the smallest number of squares, whose side lengths are also integer numbers. Cutting can be performed with a cutting machine that can cut only from side to side across, parallel with one side of the rectangle. Obtained rectangles are cut separately.
Input Data
The input file contains two positive integers in the first line: the lengths of the sides of the rectangle. Each side of the rectangle is at least 1 and at most 100.
Output Data
The output file consist of one line on which your program should write the number of squares resulting from an optimal cutting.
Example
CUTS.IN
5 6
CUTS.OUT
5
> Here is the example:
Nevermind someone elses answer, where is your attempt?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
My first solution is divide with the little side of the rectangle, but that solution is not the optimal result. I think i have ti make it with dynamic programming with an array, but I don't know how to start it. I would like to know tha recursive algorithm which I have to use to fill the array with the solution. Than I search the optimal solution in the array...
here is the heuristic algorithm (but this is not the optima solutionl) i wrote it in Java:
i use an array to store the squares size and number of pieces.
Code:import java.util.*; import java.io.*; public class feladat{ private static int A; private static int B; private static int F; private static int C=1; private static int[] D; private static int[] E; private static void ReadIn() throws IOException{ BufferedReader in = new BufferedReader(new FileReader("in.txt")); StringTokenizer line; line = new StringTokenizer(in.readLine()); A = Integer.parseInt(line.nextToken()); B = Integer.parseInt(line.nextToken()); in.close(); D=new int[100]; E=new int[100]; } private static void Divide(int x, int y){ if(x>y){F=x; x=y; y=F;} if(x==y){D[C]=1; E[C]=x;} else if((y%x) != 0){ D[C]=y/x; E[C]=x; C++; Divide(y%x,x); } else {D[C]=y/x; E[C]=x; } } private static void POut() throws IOException{ PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter("out.txt"))); int m=0; for(int i=1; i<=C; i++){ m +=D[i]; } ki.println(m); for(int i=0; i<C; i++){ ki.println(E[C-i]+" "+D[C-i]); } out.close(); } public static void main(String[] args)throws Exception{ ReadIn(); DivideA,B); POut(); } }
So why are you posting Java code on a C++ board?
Moved.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
|
https://cboard.cprogramming.com/tech-board/84809-ceoi-1996-example-solution.html
|
CC-MAIN-2017-26
|
refinedweb
| 534
| 64.71
|
Do I use #define or const?Use Both. #defines can be included in header files and included in many files. But const variables tend to be limited to one file at a time. It's better to use const because the compiler can check them for type correctness and prevents changes to const variables.
Built In Preprocessor NamesThese four names are built into the C preprocessor. They may come in handy for tracking down bugs.
Each starts and ends with two underscores.
- __LINE__ This is an integer that has the current source file line number.
- __FILE__ This is the name of the current source code file as a string.
- __DATE__ This is the PC's current date, as a string like Aug 17 2006.
- __TIME__ This is the PC's current time in string "hh:mm:ss" format.
#include <iostream>Note that I've used __LINE__ three times, once as a #define. The output of this is
using namespace std;
int main()
{
#define c __LINE__
const int d = __LINE__;
cout << "Value of Line is " << __LINE__ << endl ;
cout << "Value of Filename is " << __FILE__ << endl ;
cout << "Value of c is " << c << endl ;
cout << "Value of d is " << d << endl ;
cout << "Today's date and time is " << __DATE__ << __TIME__ << endl ;
return 0;
}
Value of Line is 12The value of __LINE__ changed between the three uses of it.
Value of Filename is e:\cplus\c++\lesson four\ex1\ex1.cpp
Value of c is 14
Value of d is 11
Today's date and time is Feb 19 200707:14:50
On the next page : About Type Conversions
|
http://cplus.about.com/od/learning1/ss/cppexpressionsr_4.htm
|
crawl-002
|
refinedweb
| 264
| 80.21
|
hi, I found this code snippet.
Before running the code,
Add a Bezier Curve.
Copy the script into the Text Editor.
Press Alt/P to run the script.
import Blender from Blender import Object from math import pi scene=Blender.Scene.getCurrent() OBJ=Blender.Object.GetSelected()[0].name division=9 for n in range(1,division): Op=Blender.Object.New('Curve') Op.shareFrom(Object.Get(OBJ)) Op.RotZ=n*pi/(division/2) scene.link(Op) Blender.Window.RedrawAll()
Well if you think that’s cool.
With the original curve selected,
in edit mode, select 1 bezier handle or both, rotate, scale…
WOW, that’s cool!
But I have no Idea how to animate this.
As in, obviously if you got this to work,
set the keys for the edited curve so the linked objects dance.
|
https://blenderartists.org/t/help-curve-animation/430984
|
CC-MAIN-2021-10
|
refinedweb
| 135
| 60.92
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.