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
|
|---|---|---|---|---|---|
Beforehand I’ve made up our minds to place in force a slightly total raycasting engine in ClojureScript.
It became once quite a few relaxing, an intelligent expertise, and ClojureScript became once awesome.
I’ve applied shrimp labyrinth sport, and regarded as collectively with more features to the engine, corresponding to digicam shake, and wall height commerce.
However when I’ve started working on these, I rapidly understood, that I’d rob to transfer on to something more piquant, love staunch 3D rendering engine, that additionally uses rays.
Clearly, my first though became once about writing a ray-tracer1.
This approach is vast known, and gained quite a few traction neutral neutral these days.
With native hardware strengthen for ray tracing, quite a few games are using it, and there are quite a few tutorials instructing how to place in force one2.
Briefly, we solid a bunch of rays in 3D home, and calculate their trajectories, purchasing for what ray will hit and leap off.
Assorted materials delight in diversified leap properties, and by tracing rays from digicam to the provision of sunshine, we can imitate illumination.
There are additionally quite a few diversified approaches how to calculate bouncing, e.g. for world illumination, and ambient light, however I’ve felt that it is a long way a slightly complex job, for a weekend submit.
And unlike raycasting, most ray-tracers require polygonal info in uncover to work, where raycasting handiest wish to know wall initiate and terminate features.
I’ve wanted a identical technique for 3D rendering, where we specify an object when it comes to it’s mathematical representation.
Adore for sphere, we’ll gracious specify coordinate of a center, and a radius, and our rays will gain intersection features with it, providing us a adequate data to blueprint this sphere on display masks masks.
And neutral neutral these days, I’ve read a couple of identical approach, that uses rays for drawing on display masks masks, however in its put of casting infinite rays as in raycasting, it marches a ray when it comes to steps.
And it additionally uses a peculiar trick, to type this route of very optimized, due to the this reality we can use it for rendering staunch 3D objects.
I’ve made up our minds to structure this submit equally to the one about raycasting, so this will likely be every other long-read, customarily more about Fennel in arena of raymarching, however on the terminate I promise that we’ll earn something that appears to be like love this:
So, gracious as in raycasting, first we desire to attain is to know the way raymarching engine works on paper.
Raymarching basics
Raymarching could maybe even neutral additionally be illustrated equally to raycaster, excluding it requires more steps except we could maybe per chance render our image.
First, we desire a digicam, and an object to undercover agent at:
Our first step would to solid a ray, however, unlike with raycasting, we’ll solid a fraction of a ray:
We then test, if the ray intersects with the sphere.
It’s now not, so we attain yet every other step:
It’s now not intersecting yet, so we repeat again:
Oops, ray overshoot, and is now contained in the sphere.
Here’s now not undoubtedly upright option for us, as we desire for our rays to complete without prolong on the thing’s flooring, without calculating intersection level with the thing itself.
We are in a position to repair this by casting shorter ray:
Nonetheless, right here is highly inefficient!
And moreover, if we’ll commerce the angle a exiguous or transfer the digicam, we can overshoot again.
Meaning that we’ll both delight in wrong end result, or require a extraordinarily shrimp step size, which will blow up computation route of.
How we can fix this?
Distance estimation
The approach to right here is a signed distance characteristic, or a so known as Distance Estimator.
Imagine if we knew how a long way we’re from the thing at any level of time?
This would mean that we can shoot a ray of this size in any route and mute don’t hit something else.
Let’s add every other object to the scene:
Now, let’s blueprint two circles, which will signify distances from the objects, to the level from where we’ll solid rays:
We are in a position to perceive, that there are two circles, and one is bigger than every other.
This means, that if we spend the shortest righteous distance, we can safely solid ray in any route and never overshoot something else.
Shall we scream, let’s solid a ray in direction of the square:
We are in a position to perceive, that we haven’t reached the square, however more importantly we did now not overshoot it.
Now we desire to march the ray again, however what distance could maybe even neutral mute it duvet?
To answer to this ask, we desire to build up every other distance estimation from ray terminate to the objects in the scene:
But again we spend shorter distance, and march in direction of the square, then earn the gap again, and repeat the complete route of:
You might want to per chance maybe per chance also perceive that with every step the gap to the thing becomes smaller, and thus we can by no technique overshoot the thing.
Nonetheless this additionally technique, that we can accumulate quite a few undoubtedly shrimp steps, except we in the break utterly hit the thing, if we ever attain.
Here’s now not a upright suggestion, on story of it is a long way a lot more inefficient than using fastened distance, and produces too lawful outcomes, which we don’t undoubtedly need.
So in its put of marching up except we exactly hit the thing, we can march adequate times.
E.g. except the gap to the thing is sufficiently shrimp, then there’s no staunch existing proceed marching, because it is a long way obvious that we can hit the thing soon.
However this additionally technique, that if the ray goes approach the fringe of an object, we attain quite a few pricey steps of computing distance estimations.
Here’s a ray that is parallel to the aspect of the square, and marches in direction of the circle:
We attain quite a few seemingly pointless measurements, and if a ray became once closer to the square’s aspect, we would attain a lot more steps.
Nonetheless this additionally technique, that we can use this data (since we’re already computed it) to render such issues as glow, or ambient occlusion.
However more on this later.
Once ray hit an object now we delight in the complete data we desire.
Ray represents a degree on the display masks masks, and the more rays we solid the greater resolution of our image could per chance be.
And since we’re now not using triangles to signify objects, our spheres will continuously be tender, no topic how shut we’re to it, on story of there’s no polygons lively.
Here’s on the complete it.
Ray marching is slightly straightforward thought, gracious love raycaster, though it’s a exiguous more complex, as we attain wish to compute issues in 3D home now.
So let’s initiate imposing it by installing required instruments, and constructing the venture.
Conducting structure
As you respect from the title we can use two necessary instruments to earn ray-marcher, that are LÖVE, a free sport engine, and Fennel the programming language.
I’ve chosen Fennel, on story of it is a long way a Declare love language, that compiles to Lua, and I’m quite a fan of Lisps.
However we additionally desired to blueprint somewhere, and I know no GUI toolkit for Lua.
However there is LÖVE – a sport engine that runs Lua code, which is agreeable on operating on all programs, thus a perfect candidate for our job.
Installation steps could maybe even neutral vary per operating machine, so please consult with manuals3, 4.
On the time of penning this submit I’m using Fedora GNU/Linux, so for me it technique:
$ sudo dnf set up cherish luarocks readline-devel $ luarocks set up --local fennel $ luarocks set up --local readline # requires readline-devel $ export PATH="$PATH: $HOME/.luarocks/bin"
It’s better to permanently add
$HOME/luarocks/bin (or every other path, in case your installation differs) to the
PATH variable in your shell, in uncover to be in a predicament to use installed utilities without specifying fat path at any time when.
You might want to per chance maybe per chance also test if every thing is installed precisely, by operating
fennel in you repeat line.
$ fennel Welcome to Fennel 0.5.0 on Lua 5.3! Utilize (doc something) to perceive documentation. >> (+ 1 2 3) 6 >>
For other distributions installation steps could maybe even neutral fluctuate, and for Dwelling windows, I judge it’s righteous to skip the
readline section, which is utterly now not fundamental, however makes editing in a REPL a exiguous more joyful.
Once every thing is installed, let’s earn the venture itemizing, and the
necessary.fnl file, where we can write our code.
$ mkdir love_raymarching $ cd love_raymarching $ touch necessary.fnl
And that’s it!
We are in a position to ascertain if every thing works by collectively with this code to
necessary.fnl:
(fn cherish.blueprint [] (cherish.graphics.print "It undoubtedly works!"))
Now we can compile it with
fennel --compile necessary.fnl > necessary.lua, thus producing the
necessary.lua file, and speed
cherish . (dot is intentional, it signifies contemporary itemizing).
A window could maybe even neutral mute seem, with white textual speak material
It undoubtedly works! in upper left corner:
Now we can initiate imposing our raymarcher.
Scene setup
Correct as in raycaster, we desire a digicam that can shoot rays, and a few objects to undercover agent at.
Let’s initiate by rising a digicam object, that can retailer coordinates and rotation info.
We are in a position to attain so, by utilizing
var to state a variable that is local to our file, and that we can later commerce with
living5:
(var digicam {:pos [0.0 0.0 0.0] :x-rotate 0.0 :z-rotate 0.0})
For those unfamiliar with Lisps, and particularly Clojure, let me rapidly indicate what this syntax is.
Whenever you happen to respect these items, feel free to skip this section.
We initiate by utilizing a
varparticular invent, that binds a fee to a popularity love this:
(var name fee).
So if we initiate the REPL, using
fennelrepeat in the shell, and write
(var a 40), a contemporary variable
acould per chance be created.
We then can test, that it has the specified fee by typing
a, and pressing return:
We are in a position to then alter the contents of this variable by utilizing
livingparticular invent, which works love this
(living name contemporary-fee):
>> (living a (+ a 2)) >> a 42
Now to curly and square brackets.
Every thing enclosed in curly braces is a hashmap.
We are in a position to use any Lua fee as our key, and doubtlessly the most total alternative is a string, however Fennel has extra syntax for outlining keys – a colon adopted by a note:
:a.
Here’s known as a key phrase, and in Fennel it is a long way truly the identical as
"a", however we don’t wish to jot down a pair of quotes.
Nonetheless key phrases can’t possess spaces, and every other symbols.
So penning this
{:a 0 :b 2 :c :hello}in the REPL will type a contemporary desk, that holds three key fee pairs, which we can later earn with every other syntax – the dot
..
Combining it with
var, we can perceive that it works:
>> (var m {:a 1 :b 2 :c :hello}) >> (. m :b) 2
There’s additionally a shorthand for this syntax, that is, we can type
m.band earn accurate of entry to the
:bkey’s fee:
Witness that even though we’ve specified the fee for
:cas
:hello, the REPL printed it to us as
"hello".
We’re left with square brackets now, and right here is obvious straightforward vector.
It will grow and shrink, and retailer any Lua values in it:
>> [0 :a "b c" (fn [x] x)] [0 "a" "b c" #
: 0x56482230e090>]
Nonetheless Lua doesn’t undoubtedly delight in vectors or arrays, and it utilizes tables for this, where keys are simply indexes.
So the code above is a a lot like this Fennel expression
{1 0 2 "a" 3 "b c" 4 (fn [x] x)}, however we can use square brackets for comfort.
Demonstrate, that we can mix listed tables (vectors) and smartly-liked tables (hashmaps) collectively.
We are in a position to attain it as shown above, by specifying indexes as keys, or disclose a vector var and
livinga key in it to some fee:
>> (var v [0 1 :a]) >> (living v.a 3) >> v {:a 3 1 0 2 1 3 "a"}
So digicam is truly a Lua desk, that shops keys
:pos,
:x-rotate, and
:y-rotate, every storing a respective fee.
We use a vector as our arena, and two floats as our rotation angles.
Now we can type objects, however earlier than that, we desire a scene to retailer those objects:
Yep, that’s our scene.
Nothing fancy, simply an empty vector to which we can later add objects.
Now we can earn these objects, so let’s initiate with perchance doubtlessly the most fine one – a sphere.
And I’ll additionally rapidly indicate what makes raymarching diversified from other programs of rising 3D graphics.
Creating objects
What’s a sphere?
That depends on the arena, we’re working in.
Let’s commence up Blender, accumulate away the default dice, and earn sphere with Shift+a, Mesh, UV Sphere:
To me, this appears to be like nothing love a sphere, on story of it consists out of rectangles.
Nonetheless if we subdivide the flooring, we can earn more upright representation:
This appears to be like more love a sphere, however right here is mute gracious an approximation.
Theoretically, if we transfer very shut to it, we can perceive the perimeters and corners, especially with flat shading.
Also, every subdivision provides more features, and it will get more and costlier to compute:
We now wish to type these alternate-offs, on story of we don’t need very lawful spheres, when we desire staunch time processing.
However raymarching doesn’t delight in this limitation, on story of sphere in raymarching is printed by the level and radius size.
Which we can then work with by utilizing signed distance characteristic.
So let’s earn a characteristic, that can construct sphere:
(fn sphere [radius pos color] ➊ (let [[x y z] ➋ (or pos [0 0 0]) [r g b] (or coloration [1 1 1])] {:radius (or radius 5) :pos [(or x 0) (or y 0) (or z 0)] :coloration [(or r 0) (or g 0) (or b 0)] :sdf sphere-distance ➌}))
There’s quite a few stuff happening, so let’s dive into it.
Here’s a so known as constructor – a characteristic, that takes some parameters and constructs an object with these parameters applied, then returns it.
In most typed languages we would disclose a class, or structure to signify this object, however in Fennel (and hence in Lua) we can gracious use a desk.
And right here is my current section of such languages.
So we feeble
fn particular invent to earn a characteristic named
sphere, that takes three parameters:
radius, arena in home
pos, and
coloration ➊.
Then we perceive every other particular invent
let.
It’s a long way feeble to introduce domestically scoped variables, and has every other fine property – destructuring ➋.
Let’s rapidly know the system
letworks in this case.
Whenever you happen to respect how destructuring works, it is doubtless you’ll maybe per chance skip this section.
Here’s a straightforward example:
>> (let [a 1 b 2] (+ a b)) 3
We’ve launched two local variables
aand
b, which have interaction values
1and
2respectively.
Then we’ve computed their sum and returned it which means.
Here’s upright, however what if we desired to compute a sum of three vector parts multiplied by
b?
Let’s save a vector into
a:
>> (let [a [1 2 3] b 2] ??>)
There are many of programs to attain this, corresponding to
decreaseover a vector with a characteristic that sums parts, or earn values from the vector in a loop, and save those into some local variable.
Nonetheless, in case of our venture, we continuously know exactly what number of parts there could per chance be, so we can gracious accumulate these out by indexes with none roughly loop:
>> (let [a [1 2 3] b 2 a1 (. a 1) a2 (. a 2) a3 (. a 3)] ((+ a1 a2 a3) b)) 12
But, right here is highly verbose, and never undoubtedly upright.
We are in a position to type it a exiguous much less verbose by skipping local variable definitions and use values without prolong in the sum:
>> (let [a [1 2 3] b 2] (print (.. "fee of 2d ingredient is " (. a 2))) ((+ (. a 1) (. a 2) (. a 3)) b)) fee of sectond ingredient is 2 12
Nonetheless, again, this isn’t undoubtedly huge, as now we would like to repeat the identical syntax three times, and what if we desire to use 2d fee from the vector in several areas?
Adore right here, I’ve added
Lets use a neighborhood binding for this, however we don’t desire to attain this manually.
That’s where destructuring turns out to be helpful, and belief me, it is a long way a extraordinarily helpful thing.
We are in a position to specify a pattern, that is applied to our data, and binds variables for us love this:
>> (let [[a1 a2 a3] [1 2 3] b 2] (print (.. "fee of 2d ingredient is " a2)) ((+ a1 a2 a3) b)) fee of sectond ingredient is 2 12
Which works slightly love this:
Here’s a lot shorter than any of outdated examples, and enables us to use any of vector values in several areas.
We are in a position to additionally destructure maps love this:
>> (var m {:a-key 1 :b-key 2}) >> (let [{:a-key a :b-key b} m] (+ a b)) 3
And this additionally has a shorthand for when the name of the most necessary and the name of desired local binding will match:
>> (var m {:a 1 :b 2}) >> (let [{: a : b} m] (+ a b)) 3
Which is even shorter.
All this truly boils all of the system down to this roughly particular undoubtedly, however this instance mute shows the vitality of Declare’s macro machine, by which destructuring is applied.
However it will get undoubtedly wintry when we use this in characteristic kinds, as we can perceive later.
If we were to name
(sphere) now, we would earn an error, on story of we specified a fee ➌ for a key
:sdf, that doesn’t yet exist.
SDF stands for Signed Distance Goal.
That is, a characteristic, that can return the gap from given existing an object.
The space is optimistic when the level is commence air of the thing, and is unfavorable when the level is contained in the thing.
Let’s disclose an SDF for a sphere.
What’s huge about spheres, is that to compute the gap to the sphere’s flooring, we handiest wish to compute distance to the center of the sphere, and subtract sphere’s radius from this distance.
Let’s put in force this:
(local sqrt math.sqrt) ➊ (fn sphere-distance [{:pos [sx sy sz] : radius} [x y z]] ➋ (- (sqrt (+ (^ (- sx x) 2) (^ (- sy y) 2) (^ (- sz z) 2))) radius))
For efficiency causes we snort
math.sqrt as a
local variable
sqrt, that holds characteristic fee, to stay a long way from repeated desk search for.
As became once later pointed out, Luajit does optimize such calls, and there is never a repeated search for for technique calls.
Here’s mute ture for undeniable Lua, so I’m going to lend a hand this as is, however it is doubtless you’ll maybe per chance skip all these local definitions while you happen to love to please in and use programs without prolong.
And at ➋ we again perceive destructuring, however now not in the
let block, however in the characteristic argument checklist.
What truly happens right here is that this – characteristic takes two parameters, first of which is a hashmap, that can deserve to please in a
:pos key phrase linked to a vector of three numbers, and a
:radius key phrase with a fee.
2d parameter is purely a vector of three numbers.
We without prolong destructuring these parameters into a living of variables local to the characteristic physique.
Hashmap is being destructured into sphere arena vector, which is without prolong destructured to
sx,
sy, and
sz, and a
radius variable storing sphere’s radius.
2d parameter is destructured to
x,
y, and
z.
We then compute the ensuing fee by utilizing the system from above.
Nonetheless, Fennel and Lua handiest understand definitions in the uncover from the cease to the bottom, so we desire to clarify
sphere-distance earlier than
sphere.
Let’s test our characteristic by passing several features and a sphere of radius 5:
>> (sphere-distance (sphere 5) [5 0 0]) 0.0 >> (sphere-distance (sphere 5) [0 15 0]) 10.0 >> (sphere-distance (sphere 5) [0 0 0]) -5.0
Enormous!
First we test if we’re on the sphere’s flooring, since the radius of our sphere is
5, and we’ve living
x coordinate to
5 as smartly.
Next we test if we’re
10 something a long way from the sphere, and lastly we test that we’re interior the sphere, on story of sphere’s heart and our level each and every are on the initiating.
However we additionally can name this characteristic as a technique with
: syntax:
>> (local s (sphere)) >> (s:sdf [0 0 0]) -5
This works on story of programs in Lua are a syntactic sugar.
After we write
(s:sdf p) it is a long way truly equal to
(s.sdf s p), and our distance characteristic takes sphere because it’s first parameter, which enables us to use technique syntax.
Now we desire a distance estimator – a characteristic that can compute distances to all object and could maybe even neutral return the shortest one, so we could maybe per chance then safely extend our ray by this amount.
(local DRAW-DISTANCE 1000) (fn distance-estimator [point scene] (var min DRAW-DISTANCE) (var coloration [0 0 0]) (every [_ undoubtedly works, we bought the gap to 2d sphere, and it’s coloration, since the level we’ve specified became once closer to this sphere than to the opposite.
With the digicam, object, a scene, and this characteristic now we delight in all we desire to initiate taking pictures rays and rendering this on display masks masks.
Marching ray
Correct as in raycaster, we solid rays from the digicam, however now we attain it in 3D home.
In raycasting our horizontal resolution became once specified by an amount of rays, and our vertical resolution became once on the complete infinite.
For 3D right here is now not an option, so our resolution now depends on the 2D matrix of rays, in its put of 1D matrix.
Snappily math.
What number of rays we’ll wish to solid in uncover to occupy up 512 by 448 pixels?
The reply is straightforward – multiply width and height and right here’s the amount of rays you’ll need:
A shimmering
229376 rays to march.
And every ray has to attain many distance estimations because it marches a long way from the level.
Impulsively, all that micro optimizations, love locals for capabilities attain now not feel that unnecessary.
Let’s hope for doubtlessly the most fine and that LÖVE will address staunch time rendering.
We are in a position to initiate by rising a characteristic that marches single ray in the route our digicam appears to be like.
However first, we desire to clarify what we would use to specify coordinates, directions etc in our 3D home.
My first strive became once to use spherical coordinates to clarify ray route, and transfer features in 3D home slightly to digicam.
Nonetheless it had quite a few problems, especially when objects at angles diversified from 90 levels.
Adore right here’s a screenshot of me the sphere from the “front”:
And right here’s when making an strive from “above”:
And when I’ve added dice object, I’ve observed a little fish-perceive distortion terminate:
Which became once now not huge in any appreciate.
So I’ve made up our minds that I would remake every thing with vectors, and kind an ethical digicam, with “undercover agent-at” level, will compute projection plane, etc.
And to attain this now we would like to be in a predicament to work with vectors – add those, multiply, normalize, e.t.c.
I’ve desired to refresh my data on this topic, and made up our minds to now not use any existing library for vectors, and put in force every thing from scratch.
It’s now not that laborious.
Especially when we already delight in vectors in the language, and could maybe even destructure it to variables with ease.
So we desire these total capabilities:
vec3– a constructor with some helpful semantics,
vec-size– characteristic that computes magnitude of vector,
- arithmetic capabilities, corresponding to
vec-sub,
vec-add, and
vec-mul,
- and other unit vector capabilities, mainly
normalize,
dot-product, and
excessive-product.
Here’s the provision code of every of those capabilities:
(fn vec3 [x y z] (if (now not x) [0 0 0] (and (now not y) (now not z)) [x x x] [x y (or z 0)])) (fn vec-size [ excessive [[x0 y0 z0] [x1 y1 z1]] [(- (y0 z1) (z0 y1)) (- (z0 x1) (x0 z1)) (- (x0 y1) (y0 x1))])
Since we already know the way destructuring works, it’s now not laborious to perceive what these capabilities attain.
vec3, however, has some logic in it, and likewise it is doubtless you’ll maybe per chance scrutinize that
if has three outcomes.
if in Fennel is more love
cond in other lisps, meaning that we can specify as many
else if as we desire.
Therefore, calling it without arguments produces a nil size vector
[0 0 0].
If known as with one argument, it returns a vector where every coordinate is made up our minds to this argument:
(vec 3) will construct
[3 3 3].
In other instances we both specified or now not specified
z, so we can simply earn a vector with
x,
y, and both
0 or
z.
You might want to per chance maybe per chance also neutral shock, why right here is printed as capabilities, and why didn’t I applied operator overloading, so we could maybe per chance simply use
+ or
* to compute values?
I’ve tried this, however right here is highly late, since on every operation now we would like to attain search for in meta-desk, and right here is love undoubtedly late.
Here’s a immediate benchmark:
(macro time [body] `(let [clock# os.clock start# (clock#) res# ,body end# (clock#)] (print (.. "Elapsed " (1000 (- terminate# initiate#)) " ms")) res#)) ;; operator overloading (var vector {}) (living))) ;; total capabilities speed it with
lua interpreter, we’ll perceive the variation:
$ fennel --compile test.fnl | lua Elapsed 1667.58 ms Elapsed 1316.078 ms
Attempting out this with
luajit claims that this system is truly quicker, however, I’ve skilled most necessary slowdown in the renderer – every thing ran about 70% slower, basically basically based on the physique per 2d depend.
So capabilities are k, even though are a lot more verbose.
Now we can disclose a
march-ray characteristic:
(fn transfer-level [point dir distance] ➊ (vec-add level (vec-mul dir (vec3 distance)))) (local MARCH-DELTA 0.0001) (local MAX-STEPS 500) (fn march-ray [origin direction scene] (var steps 0) (var distance 0) (var coloration nil) (var now not-done? upright) ➋ (while now not-done? (let [➍ (new-distance new-color) (-> origin (move-point direction distance) (distance-estimator scene))] (when (or (< new-distance MARCH-DELTA) (>= distance DRAW-DISTANCE) (> steps MAX-STEPS) ➌) (living now not-done? untrue)) (living distance (+ distance contemporary-distance)) (living coloration contemporary-coloration) (living steps (+ steps 1)))) (values distance coloration steps))
No longer a lot, however now we delight in some issues to chat about.
First, we disclose a characteristic to transfer level in 3D home ➊.
It accepts a
level, which is a 3 dimensional vector, a route vector
dir, which could per chance maybe even neutral mute be normalized, and a
distance.
We then multiply route vector by a vector that consists of our distances, and add it to the level.
Easy and easy.
Next we disclose several constants, and the
march-ray characteristic itself.
It Defines some local vars, that have interaction preliminary values, and uses a
while loop to march given ray adequate times.
You might want to per chance maybe per chance also scrutinize, that at ➋ we created a
now not-done? var, that holds
upright fee, and then use it in the
while loop as our test.
And likewise you additionally can scrutinize that at ➌ now we delight in a test, in case of which we
living
now not-done? to
untrue and exit the loop.
So it is doubtless you’ll maybe per chance also neutral shock, why to now not use
for loop in its put?
Lua supports index basically basically based for loops.
Fennel additionally has a strengthen for these.
So why use
while with a
variable?
Because Fennel has no
spoil particular invent for some procedure.
Here’s a exiguous of rant.
You can skip it while you happen to’re now not attracted to me making unconfirmed inferences about Fennel :).
I judge that Fennel doesn’t strengthen
spoilon story of Fennel is influenced by Clojure (upright me if I’m scandalous), and Clojure doesn’t delight in
spoilboth.
Nonetheless, looping in Clojure is a exiguous of more controllable, as we spend when we desire to scuttle to subsequent iteration:
(loop [i 0] ;; attain stuff (when (< i 10) (recur (+ i 1))))
Meaning that
when
iis much less then
10I desire you to avoid losing every other iteration.
In Fennel, however, the notion that isn’t quite love this, on story of now we would like to clarify a
varexplicitly, and save it into
whiletest arena:
(var i 0) (while (< i 10) ;; attain stuff (living i (+ i 1)))
You might want to per chance maybe per chance also neutral now not perceive the variation, however I attain.
This additionally could maybe even neutral additionally be trivially expressed as a
forloop:
(for [i 0 10] (attain-stuff)).
Nonetheless, now not every break could maybe even neutral additionally be outlined as
forloop, when we don’t delight in
spoil.
And in Clojure we don’t wish to state a variable commence air the loop, since
loopdoes it for us, however the largest difference is right spoil terminate terminate
Nonetheless we can’t attain the identical in Fennel, on story of there’s no
spoil.
In this case we could maybe per chance disclose
ivar, save
some_foo() < 1000to the
whileloop test, and then use spoil when
ireaches
100, love this:
(var i 0) (while (or (< i 100) (< (some-foo) 1000)) (living i (+ i 1)))
Which is kind of love Clojure example, and likewise it is doubtless you'll maybe per chance also neutral shock why attain I bitch, however in case of
march-raycharacteristic we can’t attain this both!
Since the characteristic we name returns a couple of values, which we desire to destructure ➍ to be in a predicament to ascertain those.
Or in some loops such characteristic could maybe even neutral rely upon the context of the loop, so it must be contained in the loop, now not in the test.
So now not having
spoil, or means to manipulate when to scuttle to subsequent iteration is a necessary downside.
Yes, Clojure’s
recuris additionally exiguous, because it must also neutral mute be in tail arena, so it is doubtless you'll maybe per chance’t use it as
proceedor something love that.
However it’s mute a exiguous more highly fine break.
I’ve truly regarded as writing a
loopmacro, however apparently it’s now not as straightforward to attain in Fennel, as in Clojure, on story of Fennel lacks some in-constructed capabilities to manipulate sequences.
I mean it’s utterly doable, however requires technique too a lot work compared with defining a Boolean
varand setting it in the loop.
At ➍ we perceive syntax that I didn’t coated earlier than:
(let [(a b) (foo)] ...).
A kind of us, who familiar with Declare, and particularly Racket would be puzzled.
You perceive, in Racket, and other Procedure implementations (that allow using diversified forms of parentheses)
let has this roughly syntax:
(let [(a 1) ;; In Scheme square brackets around bindings (b 41)] ;; are replaced with parentheses (+ a b))
Or more in total,
(let ((name1 value1) (name2 value2) ...) physique).
Nonetheless in case of
march-ray characteristic, we perceive a identical invent, excluding 2d ingredient has no fee specified.
Here's again a legitimate syntax in some lisps (General Declare, as an instance), as we can type a binding that holds nothing and later
living it, however right here is now not what happens in this code, as we don’t use
foo in any appreciate:
(let [(a b) (foo)] (+ a b))
And, since in Fennel we don’t need parentheses, and simply specify bindings as a vector
[name1 value1 name2 value2 ...], every other that it is doubtless you'll maybe per chance imagine confusion could maybe even neutral happen.
You might want to per chance maybe per chance also neutral judge that
(a b) is a characteristic name that returns a
name, and
(foo) is a characteristic name that produces a
fee.
However then we by hook or by crook use
a and
b.
What's taking place right here?
However right here is fine every other roughly destructuring on hand in Fennel.
Lua has 1 smartly-liked data type, known as a desk.
Nonetheless Lua doesn’t delight in any particular syntax for destructuring, so when characteristic wants to advance several values, you've got gotten two alternatives.
First, it is doubtless you'll maybe per chance return a desk:
characteristic returns_table(a, b) return {a, b} terminate
However particular person of such characteristic will wish to earn values out of the desk themselves:
local res = returns_table(1, 2) local a, b = unpack(res) -- or use indexes, e.g. local a = res[1] print("a: " .. a .. ", b: " .. b) -- a: 1, b: 2
However right here is additional work, and it ties values collectively into an info structure, which could per chance maybe even neutral now not be undoubtedly upright for you.
So Lua has a shorthand for this - it is doubtless you'll maybe per chance return a couple of values:
characteristic returns_values(a, b) return a, b terminate local a, b = returns_values(1, 2) print("a: " .. a .. ", b: " .. b) -- a: 1, b: 2
Here's shorter, and more concise.
Fennel additionally strengthen this multivalue return with
values particular invent:
(fn returns-values [a b] (values a b))
Here's a a lot like the outdated code, however how will we use these values?
All binding kinds in Fennel strengthen destructuring, so we can write this as:
(local (a b) (returns-values 1 2)) (print (.. "a: " a ", b: " b)) ;; a: 1, b: 2
Same could maybe even neutral additionally be done with vectors or maps when defining,
local,
var, or
world variables:
(local [a b c] (returns-vector)) ;; returns [1 2 3] (var {:x x :y y :z z} (returns-draw)) ;; returns {:x 1 :y 2 :z 3} (world (bar baz) (returns-values)) ;; returns (values 1 2)
And all of this works in
let or when defining a characteristic!
OK.
We’ve outlined a characteristic that marches a ray, now we desire to shoot some!
Taking pictures rays
As with math capabilities, let’s disclose some local definitions somewhere on the cease of the file:
(local cherish-features cherish.graphics.features) (local cherish-dimensions cherish.graphics.getDimensions) (local cherish-living-coloration cherish.graphics.setColor) (local cherish-key-pressed? cherish.keyboard.isDown) (local cherish-earn-joysticks cherish.joystick.getJoysticks)
Here's slightly a lot all we’ll need from LÖVE - two capabilities to blueprint colored pixels, one characteristic to earn resolution of the window, and enter handling capabilities for keyboard and gamepad.
We’ll additionally disclose some capabilities in
cherish namespace desk (IDK the way it is a long way is called smartly in Lua, on story of it is a long way a desk that acts love a namespace) -
cherish.load,
cherish.blueprint, and others along the technique.
Let’s initiate by initializing our window:
(local window-width 512) (local window-height 448) (local window-flags {:resizable upright :vsync untrue :minwidth 256 :minheight 224}) (fn cherish.load [] (cherish.window.setTitle "LÖVE Raymarching") (cherish.window.setMode window-width window-height window-flags))
This could per chance even neutral living our window’s default width and height to
512 by
448 pixels, and living minimum width and height to
256 by
224 pixels respectively.
We additionally add title
"LÖVE Raymarching" to our window, however it indubitably is utterly now not fundamental.
Now we can living
cherish.blueprint characteristic, which will shoot 1 ray per pixel, and blueprint that pixel with acceptable coloration.
Nonetheless we desire a technique of claiming by which route we desire to shoot our ray.
To disclose the route we can first want a projection plane and a lookat level.
Let’s earn a lookat level as a straightforward zero vector
[0 0 0] for now:
Now we desire to know the way we disclose our projection plane.
In our case, projection plane is a plane that is our display masks masks, and our digicam is a few distance a long way from the display masks masks.
We additionally desire to be in a predicament to commerce our self-discipline of perceive, or FOV for rapid, so we desire a technique of computing the gap to projection, since the closer we're to projection plane, the broader our self-discipline of perceive:
We are in a position to without problems compute the gap if now we delight in an angle, which we additionally can disclose as a
var:
Now we can compute our projection distance (PD), by utilizing this system:
The put
fov is in Radians.
And to compute radians we’ll need this constant:
(local RAD (/ math.pi 180.0))
Now we can became any angle into radians by multiplying it by this fee.
At this level we know what's the gap to our projection plane, however we don’t comprehend it’s size and arena.
First, we desire a ray initiating (
RO), and we already delight in it as our digicam, so our
ro could per chance be equal to contemporary fee of
digicam.pos.
Next, we desire a scrutinize-at level, and now we delight in it as a
lookat variable, which is made up our minds to
[0 0 0].
Now we can disclose a route vector, that can specify our forward route:
And with this vector
F if we transfer our level the gap that we’ve computed previously, we’ll navigate the center of our projection plane, which we can name
C:
Closing thing we would like to know, in uncover to earn our orientation in home, is where is up and ethical.
We are in a position to compute this by specifying an upward vector and taking a excessive product of it and our forward vector, thus producing a vector that is perpendicular to each and every of those vectors, and pointing to the ethical.
To attain this we desire an up vector, which we disclose love this
[0 0 -1].
You might want to per chance maybe per chance also neutral shock why it is a long way printed with z axis unfavorable, however right here is executed so optimistic z values truly scuttle up as we undercover agent from the digicam, and ethical is to the ethical.
We then compute the ethical vector as follows:
And the up vector
U is a excessive product of
R and
F. Let’s write this down as in
cherish.blueprint:
(fn cherish.blueprint [] handiest compute these values, however attain now not use those, hence the
nil on the terminate of the
let.
However now, as we know where our projection plane is, and where our ethical and up, we can compute the intersection level, where at given
x and
y coordinates of a plane in unit vector coordinates, thus defining a route vector.
So,
for every
x from
0 to
width and every
y from
0 to
height we can compute a
uv-x and
uv-y coordinates, and gain the route vector
rd.
To gain the
uv-x we desire to type obvious it is a long way between
-1 and
1 by dividing contemporary
x by
width and subtracting
0.5 from it, then multiplying by
x/width.
For
uv-y we handiest wish to divide contemporary
y by height, and subtract
0.5:
(for [y 0 height] (for [x 0 width] (let [uv-x ((- (/ x width) 0.5) (/ width height)) uv-y (- (/ y height) 0.5)] nil))) ;; TBD
Now as now we delight in
uv-x and
uv-y, we can compute intersection level
i, by utilizing the up and ethical vectors and heart of the plane:
And in the break compute our route vector
RD:
And now we can use our
march-ray route of to compute distance and coloration of the pixel.
Let’s wrap every thing up:
(local tan math.tan) (fn cherish.blueprint [] ) (cherish-living-coloration coloration) (cherish-living-coloration 0 0 0)) (cherish-features x y))))))
Now, if we living the
scene to possess a default
sphere, and arena our digicam at
[20 0 0], we could maybe even neutral mute perceive this:
Which is upright, on story of our default sphere has white as the default coloration.
You might want to per chance maybe per chance also scrutinize, that we compute
distance and
coloration by calling
(march-ray ro rd scene), and then test if
distance is decrease than
DRAW-DISTANCE.
If right here is the case, we living pixel’s coloration to the
coloration found by
march-ray characteristic, in any other case we living it to murky.
Lastly we blueprint the pixel to the display masks masks and repeat complete route of for the next intersection level, thus the next pixel.
However we don’t wish to blueprint murky pixels if we didn’t hit something else!
Consider, that on the initiating I’ve wrote, that if we scuttle journey the thing, we attain many steps, we can use this data to render glow.
So if we alter
cherish.blueprint characteristic a exiguous, we would be in a predicament to perceive the glow around our sphere.
And the closer the delighted bought to sphere, the stronger the glow could per chance be:
;; relaxation of cherish.blueprint (let [ ;; rest of love.draw (distance color steps) (march-ray ro rd scene)] (if (< distance DRAW-DISTANCE) (cherish-living-coloration coloration) (cherish-living-coloration (vec3 (/ steps 100)))) (cherish-features x y)) ;; relaxation of cherish.blueprint
Here, I’m setting coloration to the amount of steps divided by
100, which outcomes in this glow terminate:
Equally to this glow terminate, we can earn a unsuitable ambient occlusion - the more steps we did earlier than hitting the flooring, the more advanced it is a long way, hence much less ambient light could maybe even neutral mute be in a predicament to journey.
Unfortunately doubtlessly the most convenient object now we delight in at this moment is a sphere, so there’s no technique of exhibiting this trick on it, as its flooring isn’t very advanced.
All this could per chance maybe even neutral seem pricey, and it truly is.
Unfortunately Lua doesn’t delight in staunch multithreading to run this up, and threads feature, equipped by LÖVE outcomes in even worse efficiency than computing every thing in single thread.
Nicely at leas the technique I’ve tried it.
There’s a shader DSL in LÖVE, which could per chance maybe per chance be feeble to compute these items on GPU, however right here is currently out of the scope of this venture, as I desired to place in force this in Fennel.
Talking of shaders, now, that we can blueprint pixels on display masks masks, we additionally can coloration those, and compute lighting and reflections!
Lights and reflections
Sooner than we initiate imposing lighting, let’s add two more objects - a flooring plane, and arbitrary field.
Great love sphere object, we first disclose signed distance characteristic, and then the constructor for the thing:
(local abs math.abs) (fn field-distance [{:pos [box-x box-y box-z] :dimensions [x-side y-side z-side]} [x y z]] (sqrt (+ (^ (max 0 (- (abs (- field-x x)) (/ x-aspect 2))) 2) (^ (max 0 (- (abs (- field-y y)) (/ y-aspect 2))) 2) (^ (max 0 (- (abs (- field-z z)) (/ z-aspect 2))) 2)))) (fn field [sides pos color] (let [[x y z] (or pos [0 0 0]) [x-side y-side z-side] (or sides [10 10 10]) [r g b] (or coloration [1 1 1])] {:dimensions [(or x-side 10) (or y-side 10) (or z-side 10)] :pos [(or x 0) (or y 0) (or z 0)] :coloration [(or r 0) (or g 0) (or b 0)] :sdf field-distance})) (fn flooring-plane [z color] (let [[r g b] (or color [1 1 1])] {:z (or z 0) :coloration [(or r 0) (or g 0) (or b 0)] :sdf (fn [plane [_ _ z]] (- z plane.z))}))
In case of
flooring-plane we incorporate
:sdf as a nameless characteristic, on story of it is a long way a easy one-liner.
Now, as now we delight in more objects, let’s add those to the scene and perceive if those work:
(var digicam {:pos [20.0 50.0 0.0] :x-rotate 0.0 :z-rotate 0.0}) (local scene [(sphere nil [-6 0 0] [1 0 0]) (field nil [6 0 0] [0 1 0]) (flooring-plane -10 [0 0 1])])
With this
scene and
digicam we could maybe even neutral mute perceive this:
It’s a exiguous sadistic on the eyes, however we can now not decrease than type obvious every thing works precisely.
Now we can put in force lighting.
In uncover to calculate lighting we’ll wish to know a commonplace to the flooring at level.
Let’s earn
earn-commonplace characteristic, that receives the
level, and our
scene:
(fn earn-commonplace ['s a fine trick, since we earn three more features around our genuine level, use existing distance estimation characteristic, and earn a normalized vector of subtraction of every axis from genuine level, with the gap to the contemporary level.
Let’s use this characteristic to earn commonplace for every level, and use commonplace as our coloration:
;; relaxation of cherish.blueprint (if (< distance DRAW-DISTANCE) (cherish-living-coloration (earn-commonplace (transfer-level ro rd distance) scene)) (cherish-living-coloration 0 0 0)) ;; relaxation of cherish.blueprint
Witness that in uncover to earn endpoint of our ray we
transfer-level
ro along the route
rd using the computed
distance.
We then journey the ensuing level into
earn-commonplace, and our
scene, thus computing the commonplace vector, which we then journey to
cherish-living-coloration, and it provides us this end result:
You might want to per chance maybe per chance also perceive that the
flooring-plane remained blue, and this isn’t error. Blue in our case is
[0 0 1], and since in our world, optimistic
z coordinates display masks up, we can perceive it without prolong in ensuing coloration of the plane.
The pinnacle of the dice and the sphere are additionally blue, and front aspect is inexperienced, meaning that our normals are upright.
Now we can compute total lighting.
For that we’ll want a delicate object:
Let’s earn a
coloration-level characteristic, that can accept a
level, level
coloration,
light arena, and a
scene:
(fn coloration-level [point color light scene] (vec-mul coloration (vec3 (level-lightness level scene light))))
It will also neutral seem that this characteristic’s handiest procedure is to name
level-lightness, which we can disclose a exiguous later, and return a contemporary coloration.
And right here is upright, now not decrease than for now.
Let’s earn
level-lightness characteristic:
(fn clamp [a l t] (if (< a l) l (> a t) t a)) (fn above-flooring-level [point normal] (vec-add level (vec-mul commonplace (vec3 (MARCH-DELTA 2))))) (fn level characteristic does, is straightforward.
We compute the
commonplace ➊ for given
level, then we gain a degree that is gracious above the flooring, using
above-flooring-level characteristic ➋.
And we use this level as our contemporary ray initiating to march in direction of the
light.
We then earn the
distance from the
march-ray characteristic, and test if we’ve went the complete technique to the max distance or now not.
If now not, this system that there became once a success, and we divide complete
lightness by 2 thus rising a shadow.
In the opposite case we return
lightness as is.
And
lightness is a dot product between
light-vec and
commonplace to the flooring ➌, where
light-vec is a normalized vector from the
level to the
light.
If we again alter our
cherish.blueprint characteristic love this:
;; relaxation of cherish.blueprint (if (< distance DRAW-DISTANCE) (let [point (move-point ro rd distance)] (cherish-living-coloration (coloration-level level coloration scene light))) (cherish-living-coloration 0 0 0)) ;; relaxation of cherish.blueprint
We are in a position to also neutral mute perceive the shadows:
This already appears to be like love staunch 3D, and it is a long way.
However we can attain a exiguous more, so let’s add reflections.
Let’s earn a
reflection-coloration characteristic:
(var reflection-depend 3) (fn reflection-coloration [color point direction scene light] (var [color p d i n] [color point direction 0 (get-normal point scene)]) ➊ (var now not-done? upright) (while (and (< i reflection-depend) now not-done?) (let [r (vec-sub d (vec-mul (vec-mul (vec3 (dot d n)) n) [2 2 2])) ➋ (distance contemporary-coloration) (march-ray (above-flooring-levelation (vec-mul (vec3 (level-lightness level scene light))) (reflection-coloration level route scene light)))
You might want to per chance maybe per chance also scrutinize that I’ve added
route parameter, as we desire it for computing reflections, so we additionally wish to commerce the resolution to
coloration-level in
cherish.blueprint characteristic:
;; relaxation of cherish.blueprint (if (< distance DRAW-DISTANCE) (let [point (move-point ro rd distance)] (cherish-living-coloration (coloration-level level coloration rd scene light))) ;; rd is our preliminary route (cherish-living-coloration 0 0 0)) ;; relaxation of cherish.blueprint
Let’s strive this out (I’ve brought
flooring-plane a exiguous closer to objects so we could maybe per chance better perceive reflections):
We are in a position to perceive reflections, and reflections of reflections in reflections, on story of previously we’ve living
reflection-depend to
3.
Currently our reflections are pure mirrors, as we mediate every thing at a perfect angle, and shapes seem gracious as staunch objects.
This could per chance per chance also be modified by introducing materials, that delight in diversified qualities love roughness, and by utilizing a a lot bigger reflection algorithms love Phong shading, however perchance subsequent time.
Refractions additionally kinda need materials, as refraction angle could maybe even neutral additionally be diversified, relying on what roughly material it goes through.
E.g. glass and mute pool of water could maybe even neutral mute delight in diversified refraction angle.
And a few surfaces could maybe even neutral mute mediate rays at obvious angles, and allow them to struggle through at other angles, which will additionally require obvious modifications in reflection algorithm.
Now, if we would living our
digicam,
lookat, and
light to:
(local lookat [19.75 49 19.74]) (var digicam {:pos [20 50 20] :x-rotate 0 :z-rotate 0}) (local scene [(box [5 5 5] [-2.7 -2 2.5] [0.79 0.69 0.59]) (field [5 5 5] [2.7 2 2.5] [0.75 0.08 0.66]) (field [5 5 5] [0 0 7.5] [0.33 0.73 0.42]) (sphere 2.5 [-2.7 2.5 2.5] [0.56 0.11 0.05]) (sphere 10 [6 -20 10] [0.97 0.71 0.17]) (flooring-plane 0 [0.97 0.27 0.35])])
We could maybe per chance perceive an image from the initiating of this submit:
For now, I’m slightly joyful with contemporary end result, so lastly let’s type it that it is doubtless you'll maybe per chance imagine to transfer in our 3D home.
Individual enter
We’ll be doing two diversified programs of appealing in our scene - with keyboard and gamepad.
The adaptation largely is in the reality, that gamepad can give us floating level values, so we can transfer slower or quicker relying on how we transfer the analogs.
We’ve already specified wanted capabilities from LÖVE as our locals, however to recap, we’ll need handiest two:
(local cherish-key-pressed? cherish.keyboard.isDown) (local cherish-earn-joysticks cherish.joystick.getJoysticks)
However first, we’ll wish to type modifications to our
digicam, as currently it must handiest undercover agent on the initiating.
How will we compute the undercover agent at level for our digicam so we would be in a predicament to transfer it around in a most necessary technique?
I’ve made up our minds that a upright technique could per chance be to “transfer” digicam forward a obvious amount, and then rotate this level around digicam by utilizing some angles.
Luckily for us, we’ve already specified that our
digicam has two angles
:x-rotate, and
z-rotate:
(var digicam {:pos [20 50 20] :x-rotate 255 :z-rotate 15})
And it is a long way additionally declared as a
var, meaning that we can
living contemporary values into it.
Let’s write a characteristic that can compute a contemporary
lookat level for contemporary
digicam arena and rotation:
(local cos math.cos) (local sin math.sin) (fn rotate-level [-level (vec-add pos [1 0 0]) pos digicam.x-rotate digicam.z-rotate)))
First characteristic
rotate-level will rotate one level around every other level by utilizing two levels.
It's a long way basically basically based on plane most necessary axes, however we handiest delight in two axes, so we attain now not wish to “roll”, hence we attain exiguous much less computations right here.
Next is the
forward-vec characteristic, that computes contemporary “forward” vector for
digicam.
Ahead in this case technique the route digicam is “going through”, which is basically basically based on two angles we specify in the
digicam.
With this characteristic we can put in force total movement and rotation capabilities for digicam:
(fn digicam-forward [n] (let [dir (norm (vec-sub (forward-vec camera) camera.pos))] (living digicam.pos (transfer-level digicam.pos dir n)))) (fn digicam-elevate [n] (living digicam.pos (vec-add digicam.pos [0 0 n]))) (fn digicam-rotate-x [x] (living digicam.x-rotate (% (- digicam.x-rotate x) 360))) (fn digicam-rotate-z [z] (living digicam.z-rotate (clamp (+ digicam.z-rotate z) -89.9 89.9))) (fn digicam-strafe [x] (let [z-rotate camera.z-rotate] (living digicam.z-rotate 0) (digicam-rotate-x 90) (digicam-forward x) (digicam-rotate-x -90) (living digicam.z-rotate z-rotate)))
And if we alter our
cherish.blueprint again, we’ll be in a predicament to use our computed lookat level as follows:
(fn cherish.blueprint [] (let [;; relaxation of cherish.blueprint lookat (forward-vec digicam) ;; relaxation of cherish.blueprint
Now we don’t want a world
lookat variable, and it is a long way truly adequate for us to compute contemporary
lookat every physique.
As for movement, let’s put in force a straightforward keyboard handler:
(fn address-keyboard-enter [] (if (cherish-key-pressed? "w") (digicam-forward 1) (cherish-key-pressed? "s") (digicam-forward -1)) (if (cherish-key-pressed? "d") (if (cherish-key-pressed? "lshift") (digicam-strafe 1) (digicam-rotate-x 1)) (cherish-key-pressed? "a") (if (cherish-key-pressed? "lshift") (digicam-strafe -1) (digicam-rotate-x -1))) (if (cherish-key-pressed? "q") (digicam-rotate-z 1) (cherish-key-pressed? "e") (digicam-rotate-z -1)) (if (cherish-key-pressed? "r") (digicam-elevate 1) (cherish-key-pressed? "f") (digicam-elevate -1)))
Equally we can put in force a controller strengthen:
(fn address))) (digicam-forward (2 (- lstick-y)))) (when (and lstick-x (or (< lstick-x -0.2) (> lstick-x 0.2))) (digicam-strafe (2 lstick-x))) (when (and rstick-x (or (< rstick-x -0.2) (> rstick-x 0.2))) (digicam-rotate-x (4 rstick-x))) (when (and rstick-y (or (< rstick-y -0.2) (> rstick-y 0.2))) (digicam-rotate-z (4 rstick-y))) (when (and r2 (> r2 -0.8)) (digicam-elevate (+ 1 r2))) (when (and l2 (> l2 -0.8)) (digicam-elevate (- (+ 1 l2)))))))
Correct for controller we type obvious that our
l2 and
r2 axes are from 0 to 2, since by default these axes are from
-1 to
1, which isn’t going to work for us.
Equally to this we can add means to commerce self-discipline of perceive, or reflection depend, however I’ll leave this out for individuals who attracted to making an strive it themselves.
It’s now not laborious.
As a closing piece, we desire to detect if controller became once inserted, and address keys somewhere.
So let’s add these two closing capabilities that we desire for every thing to work:
(var gamepad nil) (fn cherish.joystickadded [g] (living gamepad g)) (fn cherish.change [dt] (address-keyboard-enter) (address-controller))
cherish.joystickadded will accumulate care of awaiting save spanking contemporary controllers, and
cherish.change will question for save spanking contemporary enter once shortly.
By this moment we could maybe even neutral mute delight in a working raymarching 3D renderer with total lighting and reflections!
Closing thoughts
I’ve made up our minds to jot down this submit on story of I became once attracted to three matters:
- Fennel, a Declare love language, which is so a lot love Clojure syntax-wise, and has huge interop with Lua (on story of it IS Lua)
- LÖVE, a fine sport engine I’ve been awaiting a extraordinarily long time already, and performed some games written with it, which were quite awesome,
- and Lua itself, a fine, rapidly scripting language, with wintry notion that every thing is a desk.
Even supposing I didn’t use a lot of Lua right here, I’ve truly tinkered with it so a lot accurate through complete route of, sorting out diversified issues, studying Fennel’s compiler output, and benchmarking diversified constructs, love self-discipline earn accurate of entry to, or unpacking numeric tables versus a couple of return values.
Lua has some undoubtedly wintry semantics of defining modules as tables, and incorporating particular intending to tables through
setmetatable, which is extraordinarily straightforward to know in my perceive.
Fennel is a large alternative while you happen to don’t desire to be taught Lua syntax (which is shrimp, however, you respect, it exists).
For me, Fennel is a large language, on story of I don’t wish to address Lua syntax AND on story of I will be able to jot down macros.
And even though I didn’t wrote any macro for this venture, on story of every thing is already presented in Fennel itself, the doable of doing this price something.
Also, accurate through benchmarking diversified features, I’ve feeble self-written
time macro:
(macro time [body] `(let [clock# os.clock start# (clock#) res# ,body end# (clock#)] (print (.. "Elapsed: " (1000 (- terminate# initiate#)) " ms")) res#))
So means to clarify such issues is a upright thing.
LÖVE is a large engine, and though I’ve feeble a extraordinarily exiguous little bit of it, I mute judge that right here is a terribly wintry venture, on story of there is so a lot more in it.
Presumably some day I’ll type a sport that can label LÖVE’s fat doable.
On a downside display masks…
The following raymarching is very late.
I’ve managed to earn around 25 FPS for a single object in the scene, and a 256 by 224 pixel resolution.
Yes, right here is on story of it runs in a single thread, and does quite a few pricey computations.
Lua itself isn’t a extraordinarily rapidly language, and even though LÖVE uses Luajit - a first rate in time compiler that emits machine code, it’s mute now not rapidly adequate for obvious operations, or tactics.
Shall we scream, if we put in force operator overloading for or vectors we’ll free quite a few efficiency for constant desk lookups.
Here's an existing dilemma in Lua, because it does it’s simplest of being shrimp and embeddable, so it could per chance maybe per chance work nearly on something else, due to the this reality it doesn’t attain quite a few caching and optimizations.
However hiya, right here is a raymarching in ~350 traces of code with some wintry tips love destructuring!
I’m beautiful with outcomes.
A slightly more polished version of the code from this article is on hand at this repository, so if something else doesn’t work in the code above, otherwise you bought lost and gracious desire to play with closing end result, you respect where to scuttle 🙂
Till subsequent time, and thanks for studying!
|
https://gisttree.com/reviews/raymarching-with-fennel-and-love/
|
CC-MAIN-2020-50
|
refinedweb
| 10,442
| 58.11
|
In Web Forms, when you drag a FileUpload control on to the designer, something happens when the page is rendered which you probably don't notice. The resulting html form that wraps the entire page is decorated with an extra attribute:
enctype="multipart/form-data". The FileUpload itself is rendered as an html
input type=file. Within an MVC View, there are a number of ways to set this up. The first is with HTML:
<form action="/" method="post" enctype="multipart/form-data"> <input type="file" name="FileUpload1" /><br /> <input type="submit" name="Submit" id="Submit" value="Upload" /> </form>
Notice that the
<form> tag includes the
enctype attribute, and method attribute of
post. This is needed because the form by default will be submitted via the HTTP get method. The following approach, using the
Html.BeginForm() extension method renders the exact same html when the page is requested:
@using (Html.BeginForm("", "home", FormMethod.Post, new {<br /> <input type="submit" name="Submit" id="Submit" value="Upload" /> }
Notice the name attribute of the <input type="file"> element. We'll come back to that shortly. In the meantime, the resulting page should look rather blandly like this:
OK. So we can now browse to a local file and click the submit button to upload it to the web server. What is needed next is some way to manage the file on the server. When using a FileUpload control, you generally see code that checks to see if a file actually has been uploaded, using the FileUpload.HasFile() method. There isn't the same convenience when you are working with MVC, as you are much closer to the raw HTTP. However, a quick extension method can take care of that:
public static bool HasFile(this HttpPostedFileBase file) { return (file != null && file.ContentLength > 0) ? true : false; }
When you look at Controller class, you see that it has a Request object as a property, which is of type HttpRequestBase. This is a wrapper for an HTTP request, and exposes many properties, including a Files collection (actually a collection of type HttpFileCollectionBase). Each item within the collection is of type HttpPostedFileBase. The extension method checks the item to make sure there's one there, and that it has some content. Essentially, this is identical to the way that the FileUpload.HasFile() method works.
Putting that into use within the Controller Action is quite simple:
public class HomeController : Controller { public ActionResult Index() { foreach (string upload in Request.Files) { if (!Request.Files[upload].HasFile()) continue; string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/"; string filename = Path.GetFileName(Request.Files[upload].FileName); Request.Files[upload].SaveAs(Path.Combine(path, filename)); } return View(); } }
Multiple File Uploading
You might already be ahead of me at this point, and wondering how you might make use of the fact that Request.Files is a collection. That suggests that it can accommodate more than one file, and indeed, it can. If you change the original View to this:
@using (Html.BeginForm("", "home", FormMethod.Post, new {<br /> <input type="file" name="FileUpload2" /><br /> <input type="file" name="FileUpload3" /><br /> <input type="file" name="FileUpload4" /><br /> <input type="file" name="FileUpload5" /><br /> <input type="submit" name="Submit" id="Submit" value="Upload" /> }
you will end up with this:
The code in the controller Action already checks all file uploads, so no changes are needed for it to work with multiple file uploads. Notice that each input has a different name attribute. If you need to reference them individually, that is what you use. For example, to reference the third one, you would get at it using Request.Files["FileUpload3"].
Saving to a Database
Before you scream "Separation of Concerns!" at me, the next piece of code is purely illustrative. It features ADO.NET within a controller action. As we all know, this is simply not done. Database access code belongs to your data access layer somewhere inside the Model. However, the code should give people a starting point if they want to save uploaded files to a database. First of all, I have created a database (FileTest) and added a table: FileStore:
CREATE TABLE [dbo].[FileStore]( [ID] [int] IDENTITY(1,1) NOT NULL, [FileContent] [image] NOT NULL, [MimeType] [nvarchar](50) NOT NULL, [FileName] [nvarchar](50) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
The FileContent field is an image datatype, and is where the binary data that forms the file will be stored. The Index Action is changed to the following:
public ActionResult Index() { foreach (string upload in Request.Files) { if (!Request.Files[upload].HasFile()) continue; string mimeType = Request.Files[upload].ContentType; Stream fileStream = Request.Files[upload].InputStream; string fileName = Path.GetFileName(Request.Files[upload].FileName); int fileLength = Request.Files[upload].ContentLength; byte[] fileData = new byte[fileLength]; fileStream.Read(fileData, 0, fileLength); const string connect = @"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;"; using (var conn = new SqlConnection(connect)) { var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (@FileContent, @MimeType, @FileName)"; var cmd = new SqlCommand(qry, conn); cmd.Parameters.AddWithValue("@FileContent", fileData); cmd.Parameters.AddWithValue("@MimeType", mimeType); cmd.Parameters.AddWithValue("@FileName", fileName); conn.Open(); cmd.ExecuteNonQuery(); } } return View(); }
The revised code still loops through as many uploads as are on the web page, and checks each one to see if it has file. From there, it extracts 3 pieces of information: the file name, the mime type (what type of file it is) and the actual binary data that is streamed as part of the HTTP Request. The binary data is transferred to a byte array, which is what is stored in the image datatype field in the database. The mime type and name are important for when the file is returned to a user. We shall look at that part next.
Serving Files to the User
How you deliver files back to users will depend on how you have stored them primarily. If you have them stored in a database, you will usually stream the file back to the user. If they are stored on a disk, you can either simply provide a hyperlink to them, or again, stream them. Whenever you need to stream a file to the browser, you will use one of the overloads of the File() method (instead of the View() method that has been used so far in the preceding examples). There are 3 different return types of the File() method: a FilePathResult, FileContentResult and a FileStreamResult. The first streams a file directly from disk; the second sends a byte array back to the client, while the third sends the contents of a Stream object which has been generated and opened.
If you remember, when saving the uploaded files into a database, we sent a byte array to the FileContent field. When we need to get that back, it will be as a byte array again. If you have been keeping up, this means that we can use one of the two overloads of File() that return a FileContentResult. If you want the name of the file to be meaningful, you will use the overload that takes 3 arguments - the byte array, the mime type and the file name:
public FileContentResult GetFile(int id) { SqlDataReader rdr; byte[] fileContent = null; string mimeType = "";string fileName = ""; const string connect = @"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;"; using (var conn = new SqlConnection(connect)) { var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = @ID"; var cmd = new SqlCommand(qry, conn); cmd.Parameters.AddWithValue("@ID", id); conn.Open(); rdr = cmd.ExecuteReader(); if (rdr.HasRows) { rdr.Read(); fileContent = (byte[])rdr["FileContent"]; mimeType = rdr["MimeType"].ToString(); fileName = rdr["FileName"].ToString(); } } return File(fileContent, mimeType, fileName); }
The easiest way to invoke this method is to provide a hyperlink:
<a href="/GetFile/1">Click to get file</a>
If the files in the database are images, instead of a hyperlink, you just point to the controller action within the src attribute of an <img> element:
<img src="/GetFile/1" alt="My Image" />
We'll have a look at how to simply use the FilePathResult now. This is used to stream files directly from disk:
public FilePathResult GetFileFromDisk() { string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/"; string fileName = "test.txt"; return File(path + fileName, "text/plain", "test.txt"); }
And this is also invoked via a simple hyperlink:
<a href="/GetFileFromDisk">Click to get file</a>
The final option - FileStreamResult can be used to serve files from disk too:
public FileStreamResult StreamFileFromDisk() { string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/"; string fileName = "test.txt"; return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName); }
So what's the difference between FilePathResult and FileStreamResult and which one should you use? The main difference is that FilePathResult uses HttpResponse.TransmitFile to write the file to the http output. This method doesn't buffer the file in memory on the server, so it should be a better option for sending larger files. It's very much like the difference between using a DataReader or a DataSet. On the other hand, you might need to check the server you are hosting your site on, as a bug in TransmitFile may lead to partial delivery of files, or even complete failure. FileStreamResult is a great way of, for example, returning Chart images generated in memory by the ASP.NET Chart Controls without having to save them to disk.
|
https://www.mikesdotnetting.com/article/125/asp-net-mvc-uploading-and-downloading-files
|
CC-MAIN-2021-43
|
refinedweb
| 1,540
| 56.05
|
I've been trying to figure this out all night. I started on this sudoku program and for some reason it's in an infinite loop. Basically, I'm using Math.random() to generate integers and collecting them into a two dimensional array that is 9 X 9. Then I use a method to verify that the numbers in the array are unique by row and by column (and soon to be box) if I can figure this out. It seems to work just fine when I only check either row or column at a time, but not both. I debugged and it seems to be doing what it's supposed to be doing by breaking away from the for loop when the value equals a value already in its row or column, then it generates a new random integer, and goes back.. but I can't tell why it says it changes, but gets stuck on the same value.
public class TestSudokuLogic { public static int counter = 0; public static void main(String[] args) { //create grid int[][] grid = new int[9][9]; for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { boolean valid = false; while (!valid) { grid[row][col] = getRandomInt(); valid = checkRandomInt(grid, row, col); counter++; System.out.println(counter); } } } printArray(grid); } public static boolean checkRandomInt(int[][] grid, int row, int col) { for (int i = 0; i < col; i++) if (grid[row][col] == grid[row][i]) //checks each col in row (rows are unique 1-9) return false; for (int j = 0; j < row; j++) if (grid[row][col] == grid[j][col]) //checks each row in col (cols are unique 1-9) return false; return true; } public static int getRandomInt() { int r = 0; while(r < 1) r = (int) (Math.random() * 10); return r; } public static void printArray(int[][] a) { for (int row = 0; row < a.length; row++) { for (int col = 0; col < a[row].length; col++) System.out.print(a[row][col] + " "); System.out.println(); } } }
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/12510-im-creating-sudoku-program-somehow-infinite-loops.html
|
CC-MAIN-2015-22
|
refinedweb
| 333
| 70.02
|
Jens:
I have it partially figured out --
In the class that you're storing, you have to implement IDynamicData. When you do this, you just have to add this to your class:
public EPiServer.Data.Identity Id { get; set; }
I did this with a custom class, and it worked perfectly.
(My problem, however, is -- how do you store a primitive? I just want to store an int. Since I can't implement an interface on a primitive, is it impossible to store a primitive?)
Deane
DDS takes the approach to save an object by saving all its properties, and by default it
saves all "simple" (non-indexed) properties (not fields) that are public and has a getter and a setter.
When you pass in a List<T>, the only property that fullfills this is the Capacity property,
and the actual items in the list wont get saved.
You would need to wrap the List<T> in your own class, and then pass it to DDS save(),
something like this:
public class CommentsWrap
{
public List<Comment> Comments { get; sst; }
}
Regards,
Johan
Here is how I've done it:
public class TheList : IDynamicData public Identity Id { get; set; } #endregion public class TheItem : IDynamicData #region IDynamicData Members Regards,
{
#region IDynamicData Members
public List<TheItem> Items { get; set; }
}
{
public string MyString { get; set; }
public int MyItn { get; set; }
public Identity Id { get; set; }
}
Morten
public class TheList : IDynamicData
public Identity Id { get; set; }
#endregion
public class TheItem : IDynamicData
#region IDynamicData Members
Regards,
Yeah, you're storing objects of a class called TheList. You couldn't store your List<TheClass> directly because it lacks public properties. But you could not even store a TheList<T> if you wanted that for some reason (for example to create a generic metaclass for lists which has a property storing the actual list just like in your example). This doesn't stop at lists or list-like objects of course, it applies to all generic classes.
Hi,
I'm trying to store a generic collection in the dynamic data store but fails to do that. I have created a Comment class consisting of three string properties and a Comments class which is a generic collection (List) of data type Comment.
First I have created a pageobjectmanager:
pom = new PageObjectManager(CurrentPage);
In the page OnLoad event handler I do this:
When I store the values I do this:
pom.Save("comments", comments);
Even though the comments list has a comment when I store the value, after reloading the page its value is gone. Does anyone have a clue why this happens or do you perhaps know of any other way to store a collection in the DDS?
|
https://world.optimizely.com/forum/legacy-forums/Episerver-CMS-6-CTP-2/Thread-Container/2010/4/Generic-collection-in-Dynamic-Data-Store/
|
CC-MAIN-2022-40
|
refinedweb
| 447
| 54.46
|
Hello,
James Strachan said the following on 06.10.2006 20:49:
>> I've tried it. I've created two additional projects (attached) for the
>> solution.
It seems that this mailing list doesn't accept attachments... :-(
>> NMS project building is fine, but there are small problems
>> with activemq project - it uses Monitor.PulseAll and Monitor.Wait
>> methods not supported by compact framework. I'll try to investigate if
>> it is possible to avoid these methods usage.
>
> I wonder if there's an alternative way of doing these kinds of
> monitors / semaphores in .Net?
Yes. Possibly it could be done just with plain locks. I'm currently
trying to do so.
There is also problem with LoggingTransport - it uses
System.Diagnostics.Trace.WriteLine method which is also not supported in
compact framework. I think it could be replaced with log4net.
> BTW does .Net compact framework support threads?
Yes. But not all methods are supported.
>> And I think payload compression is still a feature that has not yet
>> been implemented in the .NET client implementation.
>>
>> But payload compression is the part of protocol specification?
>
> Yes - using GZip
So it could be implemented using System.IO.Compression for .NET 2.0
And this namespace isn't supported in compact framework and .NET 1.1 -
so SharpZipLib could be used instead...
--
Oleg
|
http://mail-archives.apache.org/mod_mbox/activemq-users/200610.mbox/%3Coj0qv3-55k.ln1@td.selfip.net%3E
|
CC-MAIN-2014-15
|
refinedweb
| 218
| 62.34
|
Closed Bug 1047483 Opened 6 years ago Closed 6 years ago
Porting DOMFile/DOMBlob to Web
IDL
Categories
(Core :: DOM: Core & HTML, defect)
Tracking
()
mozilla35
People
(Reporter: baku, Assigned: baku)
References
(Blocks 3 open bugs)
Details
(Keywords: dev-doc-needed)
Attachments
(6 files, 10 obsolete files)
No description provided.
This patch is about the porting of DOMFile/DOMBlob to WebIDL bindings. It's a big patch but I don't know how to split it in independent sub-patches. I would like to receive a review from . hbolley for any js/xpconnect/* changes . smaug for dom/browser-element/* and for nsFrameMessageManager bz, I marked you for a review, but feel free to assign it to somebody else. khuey maybe? Thanks. This patch is the first of 3 and it's only about the porting. In a separated patch I renamed nsDOMFile.h to mozilla/dom/DOMFile.h. Then in another patch I'll get rid of nsDOMBlobBuilder, integrating its methods into DOMFile.
Attachment #8466273 - Flags: review?(bzbarsky)
Comment on attachment 8466273 [details] [diff] [review] patch 1 - v1 I spoke to Boris on IRC and offered to help with his review queue. He suggested I could do the majority of the review here and pass off to Ollie or Kyle for the webidl parts requiring a DOM peer.
Attachment #8466273 - Flags: review?(bzbarsky) → review?(bkelly)
Comment on attachment 8466273 [details] [diff] [review] patch 1 - v1 I'm going to punt most of the review to bkelly, but here are some comments on the IDL: 1) .type doesn't need GetterThrows. Just return an empty string from DOMFileImplFile::GetType if there is no MIME service, just like you would if there is a MIME service that doesn't know about the file type. 2) Why does the "contentType" argument to slice not have "" as the default value? Seems like it should; please raise a spec issue if you agree that this gives the same black-box behavior as the spec doing the empty string thing in prose. 3) In the File constructor, "fileName" should be a ScalarValueString, right? 4) >+ // These constructors is just for chrome callee: s/is/are/ and s/callee/callers/? 5) The FilePropertyBag dictionary in this patch looks nothing like the one in the spec. Why not? If the spec is just wrong, raise issues as needed, I guess... 6) Need a spec issue about the prose about FilePropertyBag being confused. The dictionary is always present, and it always has a type member. 7) Is there a bug on deprecating/removing lastModifiedDate? 8) Should mozFullPath really be exposed to the web? That seems moderately fishy. r=me on the idl with those issues addressed.
Attachment #8466273 - Flags: review+
Maybe I am looking at the wrong spec, but shouldn't there also be a constructor like this on File: [Constructor(Blob fileBits, [EnsureUTF16] DOMString fileName)] Looking at this:
Welcome to the world of the W3C. You're looking at the last "officially published" draft, dated 2013-09-12. The editor's draft is linked from that and is at and was last updated 2014-07-15. Use that as your spec reference. ;)
Comment on attachment 8466273 [details] [diff] [review] patch 1 - v1 Could you ask review after bkelly has gone through this once, so that we don't both need to comment on the same issues. (This is a *huge* patch after all.)
This patch also needs to be rebased as it does not apply cleanly to mozilla-central.
Here's my attempt at rebasing:
Comment on attachment 8466273 [details] [diff] [review] patch 1 - v1 I'll ask a review to smaug and bholley when bkelly finishes its review process.
> 3) In the File constructor, "fileName" should be a ScalarValueString, right? Do we have such type?
(In reply to Andrea Marchesini (:baku) from comment #10) > > 3) In the File constructor, "fileName" should be a ScalarValueString, right? > > Do we have such type? It just landed in inbound on Friday via bug 1025183.
I'm about half done. I'll have to finish up tomorrow morning.
I'm uploading the other patches but I don't ask for a review yet.
Attachment #8466273 - Attachment description: patch 1 - v1 → patch 1 - v1 - DOMFile/DOMBlob to WebIDL
Comment on attachment 8466273 [details] [diff] [review] patch 1 - v1 Review of attachment 8466273 [details] [diff] [review]: ----------------------------------------------------------------- Overall this looks good. It would definitely be cleaner if we could use DOMFile in more places instead of converting back and forth with nsIDOMBlob. I understand this is coming in a follow-up patch, though. I think the only major question/concern I have is about DOMFile::GetParentObject(). Right now it returns nullptr in all cases which does not seem correct. I was previously concerned about using static_cast to convert between nsIDOMBlob and DOMFile, but it was explained to me in IRC this is safe as long as the XPCOM interface is builtintype and there is only one implementation. I did not review the xpconnect portions. r=me with these items addressed. ::: content/base/public/nsDOMFile.h @@ +8,3 @@ > > #include "mozilla/Attributes.h" > + Nit: Remove extra line. @@ +22,2 @@ > #include "mozilla/dom/DOMError.h" > +#include "mozilla/dom/FileBinding.h" Please move the includes for BlobBinding.h and FileBinding.h to nsDOMFile.cpp. All you need in the header here are forward includes for BlobPropertyBag and FilePropertyBag. You'll also then need to add the binding headers to cpp files that use UNWRAP_OBJECT. @@ +61,5 @@ > +/* FOLLOWUP TODO: > +1. remove nsDOMBlobBuilder.h > +2. rename nsDOMFile.h/cpp to DOMFile.h/cpp > +3. rename nsDOMFileList to DOMFileList > +*/ Can you reference bug numbers for these? @@ +77,5 @@ > NS_DECL_CYCLE_COLLECTING_ISUPPORTS > NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(DOMFile, nsIDOMFile) > > + static already_AddRefed<DOMFile> CreateDOMBlob(); > + I don't see this method referenced. It seems you've removed its only use in nsLayoutModule.cpp. Can it just be removed? @@ +152,5 @@ > + // WebIDL methods > + nsISupports* GetParentObject() const > + { > + return nullptr; > + } If I understand correctly, this should return a valid object when the File is constructed within a Window context. If thats not the case, can you document why? It seems most bindings just return the value of GlobalObject::GetAsSupports() from aGlobal passed into the constructor. @@ +196,5 @@ > + ErrorResult& aRv); > + > + virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE; > + > + uint64_t GetSize(ErrorResult& aRv); Can this be made const? The webidl binding allows it and might prevent some const_casts further up the call stack. Please double-check the const-ness of the other accessors as well. @@ +200,5 @@ > + uint64_t GetSize(ErrorResult& aRv); > + > + void GetType(nsAString& aType, ErrorResult& aRv); > + > + int64_t GetLastModified(ErrorResult& aRv); Maybe note in a comment that GetName() for the WebIDL name attribute is declared as part of NS_DECL_NSIDOMFILE above. :::. @@ +173,5 @@ > + } > + } > + > + else { > + MOZ_ASSUME_UNREACHABLE("This should not happen."); Better message please. Maybe something like "Impossible blob data type"? @@ +365,2 @@ > { > + nsCString utf8Str = NS_ConvertUTF16toUTF8(aString); I think this can be simplified to: NS_ConvertUTF16toUTF8 utf8Str(aString); ::: content/base/src/nsDOMBlobBuilder.h @@ +76,2 @@ > > + void InitializeChromeFile(DOMFile& aData, Can this be |const DOMFile& aData|? @@ +113,5 @@ > + > + void SetFromNsIFile(bool aValue) > + { > + mIsFromNsiFile = aValue; > + } Nit: Can you fix these to be spelled the same? "NsI" vs "Nsi". I don't have a preference for which is chosen. ::: content/base/src/nsDOMFile.cpp @@ +342,5 @@ > + if (rv.Failed()) { > + return rv.ErrorCode(); > + } > + > + JS::Rooted<JSObject*> date(aCx, JS_NewDateObjectMsec(aCx, value)); I think this can be simplified to avoid duplicating some code by doing something like this: ErrorResult rv; Date value = GetLastModifiedDate(rv); if (rv.Failed()) { return rv.ErrorCode(); } if (!value.ToDateObject(aCx, aDate)) { return NS_ERROR_OUT_OF_MEMORY; } return NS_OK; @@ +395,5 @@ > DOMFile::GetSize(uint64_t* aSize) > { > + ErrorResult rv; > + *aSize = GetSize(rv); > + return rv.ErrorCode(); MOZ_ASSERT(aSize) above here. @@ +423,5 @@ > DOMFile::GetMozLastModifiedDate(uint64_t* aDate) > { > + ErrorResult rv; > + *aDate = GetLastModified(rv); > + return rv.ErrorCode(); MOZ_ASSERT(aDate) above here. @@ +480,5 @@ > + } > + > + Optional<nsAString> contentType; > + if (aArgc > 1) { > + contentType = &aContentType; I believe this should be |if (aArgc > 2)|. On a related note, can you expand test_fileapi_slice.html to test the content type argument? @@ +577,5 @@ > +/* static */ already_AddRefed<DOMFile> > +DOMFile::Constructor(const GlobalObject& aGlobal, ErrorResult& aRv) > +{ > + nsRefPtr<DOMMultipartFileImpl> impl = new DOMMultipartFileImpl(); > + MOZ_ASSERT(!impl->IsFile()); The other constructors place this assert after InitializeBlob(). Why the different ordering here? @@ +616,5 @@ > + ErrorResult& aRv) > +{ > + nsRefPtr<DOMMultipartFileImpl> impl = new DOMMultipartFileImpl(aName); > + > +// TODO: read the spec about the FilePropertyBag Is this stale at this point? If not, can we get a bug number in the comment to follow-up? @@ +715,5 @@ > > + int64_t start = aStart.WasPassed() ? aStart.Value() : 0; > + int64_t end = aEnd.WasPassed() ? aEnd.Value() : (int64_t)thisLength; > + > + nsString contentType; I believe we favor nsAutoString for stack variables. @@ +907,5 @@ > + ErrorResult error; > + *aContentLength = GetSize(error); > + if (NS_WARN_IF(error.Failed())) { > + return error.ErrorCode(); > + } MOZ_ASSERT(aContentLength) above here. @@ +912,3 @@ > > nsString contentType; > + this->GetType(contentType, error); Nit: Lets drop the |this->| as this file seems to mostly not use it and you removed it from GetSize() above. @@ +912,4 @@ > > nsString contentType; > + this->GetType(contentType, error); > + if (error.Failed()) { NS_WARN_IF() here. @@ +944,1 @@ > nsString dummyString; nsAutoString here. @@ +944,3 @@ > nsString dummyString; > + GetType(dummyString, error); > + if (error.Failed()) { NS_WARN_IF() here. ::: content/base/src/nsDOMFileReader.h @@ +18,5 @@ > #include "prtime.h" > #include "nsITimer.h" > #include "nsIAsyncInputStream.h" > > +#include "nsDOMFile.h" This can be replaced with a forward declaration of DOMFile. ::: content/base/src/nsFormData.h @@ +5,5 @@ > #ifndef nsFormData_h__ > #define nsFormData_h__ > > #include "mozilla/Attributes.h" > +#include "nsDOMFile.h" This can be replaced with a forward declaration. ::: content/base/src/nsFrameMessageManager.cpp @@ +210,5 @@ > uint32_t length = blobs.Length(); > blobList.SetCapacity(length); > for (uint32_t i = 0; i < length; ++i) { > typename BlobTraits<Flavor>::BlobType* protocolActor = > + aManager->GetOrCreateActorForBlob(static_cast<DOMFile*>(blobs[i].get())); Why do you need a cast here? Shouldn't nsRefPtr<DOMFile>::get() return DOMFile* already? ::: content/base/src/nsHostObjectProtocolHandler.cpp @@ +16,5 @@ > #include "nsIMemoryReporter.h" > #include "mozilla/Preferences.h" > #include "mozilla/LoadInfo.h" > > +using mozilla; This doesn't compile. It should be |using namespace mozilla;|. That being said, I think it would be nicer to be explicit about the class you need. So I would prefer if it was |using mozilla::ErrorResult;|. This also helps minimize unified build bleed over. @@ +518,4 @@ > > if (blob->IsFile()) { > nsString filename; > + blob->GetName(filename); Why drop the NS_ENSURE_SUCCESS? Even if it always returns NS_OK today, it may not always do so. It would seem the safe thing to do would be to leave the return code checking in. ::: content/base/src/nsXMLHttpRequest.h @@ +355,3 @@ > { > mValue.mBlob = aBlob; > } Nit: Might be slightly nicer to pass a DOMFile& reference into the constructor since you already have one where this is called. Then convert to a pointer when assigning to mValue.mBlob. ::: dom/archivereader/ArchiveReader.cpp @@ +50,2 @@ > const nsACString& aEncoding) > + : mBlob(&aBlob) Rather than cast back to an XPCOM interface here (as mBlob is nsCOMPtr<nsIDOMBlob>), would it be better to just change mBlob to be nsRefPtr<DOMFile>? ::: dom/archivereader/ArchiveZipEvent.cpp @@ +85,5 @@ > } > > + nsCOMPtr<nsPIDOMWindow> window = > + do_QueryInterface(aArchiveReader->GetParentObject()); > + This variable doesn't seem to be used. Can you explain what this statement is here for? ::: dom/base/MessagePort.cpp @@ +10,5 @@ > #include "mozilla/dom/MessagePortBinding.h" > #include "mozilla/dom/MessagePortList.h" > #include "mozilla/dom/StructuredCloneTags.h" > #include "nsContentUtils.h" > +#include "nsDOMFile.h" #include "mozilla/dom/BlobBinding.h" for UNWRAP_OBJECT(Blob). ::: dom/browser-element/BrowserElementParent.jsm @@ +542,5 @@ > } > else { > debug("Got error in gotDOMRequestResult."); > + Services.DOMRequest.fireErrorAsync(req, > + Cu.cloneInto(data.json.errorMsg, this._window)); Can you explain why these clones are now necessary? ::: dom/camera/DOMCameraControl.cpp @@ +1182,2 @@ > ErrorResult ignored; > + cb->Call(*blob, ignored); Please add a MOZ_ASSERT(blob) or MOZ_ASSERT(aPicture) above this. ::: dom/canvas/ImageEncoder.cpp @@ +48,5 @@ > jsapi.Init(mGlobal); > JS_updateMallocCounter(jsapi.cx(), mImgSize); > } > > + mCallback->Call(*blob, rv); Please add a MOZ_ASSERT(blob) above this. ::: dom/contacts/ContactManager.js @@ +91,5 @@ > > _convertContact: function(aContact) { > + var contact = Cu.cloneInto(aContact, this._window); > + let newContact = new this._window.mozContact(contact.properties); > + newContact.setMetadata(contact.id, contact.published, contact.updated); Again, can you explain why these clones are now needed? They seem unrelated. ::: dom/filehandle/FileHandle.cpp @@ +626,3 @@ > ErrorResult& aRv) > { > + DOMFile& file = const_cast<DOMFile&>(aValue); If we could make DOMFile::GetSize() const, then perhaps this cast could go away. ::: dom/indexedDB/IDBObjectStore.cpp @@ +1623,5 @@ > return true; > } > > + DOMFile* domBlob = nullptr; > + if (NS_SUCCEEDED(UNWRAP_OBJECT(Blob, aObj, domBlob))) { #include "mozilla/dom/BlobBinding.h" for UNWRAP_OBJECT(Blob). ::: dom/ipc/StructuredCloneUtils.cpp @@ +9,5 @@ > #include "nsIDOMDOMException.h" > #include "nsIMutable.h" > #include "nsIXPConnect.h" > > +#include "nsDOMFile.h" #include "mozilla/dom/BlobBinding.h" for UNWRAP_OBJECT(Blob). ::: dom/webidl/Blob.webidl @@ +21,3 @@ > readonly attribute DOMString type; > > + // TODO readonly attribute boolean isClosed; Can we reference a bug so we don't lose track of this TODO? @@ +31,2 @@ > > + // TODO void close(); Reference follow-up bug. :::? ::: dom/workers/WorkerPrivate.cpp @@ +364,3 @@ > { > + DOMFile* blob = nullptr; > + if (NS_SUCCEEDED(UNWRAP_OBJECT(Blob, aObj, blob))) { #include "mozilla/dom/BlobBinding.h" for UNWRAP_OBJECT(Blob). ::: dom/workers/XMLHttpRequest.cpp @@ +2150,5 @@ > void > +XMLHttpRequest::Send(DOMFile& aBody, ErrorResult& aRv) > +{ > + JSContext* cx = mWorkerPrivate->GetJSContext(); > + mWorkerPrivate->AssertIsOnWorkerThread(); Move the assertion to the top of the method please. ::: js/xpconnect/src/ExportHelpers.cpp @@ +13,5 @@ > #include "js/StructuredClone.h" > #include "mozilla/dom/BindingUtils.h" > #include "nsGlobalWindow.h" > #include "nsJSUtils.h" > +#include "nsDOMFile.h" #include "mozilla/dom/BlobBinding.h" for UNWRAP_OBJECT(Blob).
Attachment #8466273 - Attachment description: patch 1 - v1 - DOMFile/DOMBlob to WebIDL → patch 1 - v1
Attachment #8466273 - Flags: review?(bkelly) → review+
> Can you reference bug numbers for these? These are the other patches. > Can this be made const? The webidl binding allows it and might prevent some > const_casts further up the call stack. Please double-check the const-ness > of the other accessors as well. It cannot be const because DOMFileImplFile uses nsIFile->GetFileSize() that is not const. > :::. > ::: content/base/src/nsDOMBlobBuilder.h > @@ +76,2 @@ > > > > + void InitializeChromeFile(DOMFile& aData, > > Can this be |const DOMFile& aData|? DOMFileImplFile::GetType cannot be const :/ > On a related note, can you expand test_fileapi_slice.html to test the > content type argument? with the changes suggested by bz, contentType cannot be null. And we already have this check: testSlice(fileFile, size, "", fileData, "fileFile"); is this what you meant? > @@ +518,4 @@ > > > > if (blob->IsFile()) { > > nsString filename; > > + blob->GetName(filename); blob is DOMFileImpl and GetName returns void. > ::: dom/browser-element/BrowserElementParent.jsm > @@ +542,5 @@ > > } > > else { > > debug("Got error in gotDOMRequestResult."); > > + Services.DOMRequest.fireErrorAsync(req, > > + Cu.cloneInto(data.json.errorMsg, this._window)); > > Can you explain why these clones are now necessary? DOMFile has a chrome wrapper and cloning it we create a new object for content. This probably will disappear when DOMFile::GetParentObject() returns something and not null. > :::? Actually it's not for Blob but for MediaStream. Code updated. I'm going to proceed to add something in GetParentObject(). Then interdiff. Thanks.
Bent, can you take a look of this? The issue is that DOMFile must have a parent before returning it to content. In order to do that I had to change many components. I'm asking you a review because many of those are related to IPC. In particular BlobChild/BlobParent::GetBlob() now takes a parent nsISupport object. This is used for creating a new DOMFile if needed. Sometimes I set it to null when I'm 100% sure that that blob is not returned to content. If you have better ideas, tell me. Thanks
Attachment #8467755 - Flags: review?(bent.mozilla)
Comment on attachment 8467755 [details] [diff] [review] patch 1b I asked bz to give me a review for the DOM part.
Attachment #8467755 - Flags: review?(bent.mozilla) → review?(bzbarsky)
Comment on attachment 8467755 [details] [diff] [review] patch 1b >+++ b/content/base/public/nsDOMFile.h I'm sorry this took so long. :( >+ // threads. This method has to be used in order to set the set the correct s/set the set/set/ >+++ b/content/html/content/src/HTMLCanvasElement.cpp >+ OwnerDoc()->GetWindow(), That will pass null in cases when OwnerDoc() is not in a window... but wouldn't "global" make more sense here? That should be non-null even when GetWindow() is null. Furthermore, GetWindow() returns the outer, but the owner should be an inner. We should add an assert somewhere in the blob/file code that the owner it gets passed, if it's a window, is an inner window. >+ return DOMFile::CreateMemoryFile(OwnerDoc()->GetWindow(), imgData, Similar issue here. >+++ b/content/html/content/src/HTMLInputElement.cpp >+ mFileList[i]->SetParentObject(mInput->OwnerDoc()->GetWindow()); And here. >+ DOMFile::CreateFromFile(OwnerDoc()->GetWindow(), file); And here. >+++ b/dom/devicestorage/DeviceStorageRequestParent.cpp Please document where, if anywhere, the parents of these blobs and file are set? >+++ b/dom/filesystem/* I'm assuming that you've checked that these GetWindow return values are inner windows, not outer ones? >+++ b/dom/ipc/Blob.cpp >+ nsCOMPtr<nsIDOMBlob> blob = newActor->GetBlob(nullptr); Document why nullptr is ok? Same for other places in this file. >+ // If aParent is null, this blob will not exposed to content. "will not be" >+ nsCOMPtr<nsIDOMBlob> blob =newActor->GetBlob(nullptr); Add the space after '=' while you're here, please. >+++ b/dom/ipc/Blob.h >+ // Note: If this blob is exposed to content, aParent must be a proper value. This needs some more explanation of what "proper" is, in both places. >+++ b/dom/ipc/StructuredCloneUtils.cpp >+ // Let's create a new blob in the with the correct parent. s/in the // The rest of this looks good. r=me with the above addressed.
Attachment #8467755 - Flags: review?(bzbarsky) → review+
bholley, this patch is big, and it implements the porting of DOMFile/DOMBlob to WebIDL. bz and bkelly did the first reviews but I would like to have a review from you too. In particular I would like to have a review on how I use JSCompartments, global objects, parents and and all those things. Of course, any other comment is welcome! Thanks.
Attachment #8466273 - Attachment is obsolete: true
Attachment #8467755 - Attachment is obsolete: true
Attachment #8488767 - Flags: review?(bobbyholley)
I really think you should remove all the WrapObject() calls in this patch in favor of WrapNewBindingObject, which will ensure the result is in your compartment....
:baku, will these patches change the behavior for the user (a quick look seems to confirm this, I see more attribute to the FilePropertyBag, but I'm unsure if this lead to more user-visible change). (Meanwhile I'm adding dev-doc-needed)
Keywords: dev-doc-needed
(In reply to Boris Zbarsky [:bz] from comment #22) > I really think you should remove all the WrapObject() calls in this patch in > favor of WrapNewBindingObject, which will ensure the result is in your > compartment.... Sounds like we need some documentation somewhere... doesn't exactly hint that it deals with compartments, nor does the method name itself.
(In reply to Jean-Yves Perrier [:teoli] from comment #23) > :baku, will these patches change the behavior for the user (a quick look > seems to confirm this, I see more attribute to the FilePropertyBag, but I'm > unsure if this lead to more user-visible change). You are right. The constructor of the File object is changed and I guess we need to update our documentation pages. No other changes are made.
> Sounds like we need some documentation somewhere... OK,
Comment on attachment 8488979 [details] [diff] [review] patch 1b - WrapObject >+ if (WrapNewBindingObject(cx, blob, &val)) { >+ return val.toObjectOrNull(); So if WrapNewBindingObject returns false... where will our control flow end up? Better would be: if (!WrapNewBindingObject(cx, blob, &val)) { return nullptr; } return &val.toObject(); You have this pattern in a few places. >+++ b/dom/workers/WorkerPrivate.cpp >- return result; That seems wrong. Why was this change made? r- because of that result thing...
Attachment #8488979 - Flags: review?(bzbarsky) → review-
Comment on attachment 8488767 [details] [diff] [review] patch 1 - WebIDL Review of attachment 8488767 [details] [diff] [review]: ----------------------------------------------------------------- I just skimmed large parts of this patch looking for things that I'd be more likely to have input on. This would have been much, much easier to review as a long series of incremental patches (and I probably would have had to sift through a lot less code that I had no opinion on). Please try to avoid megapatches in the future. Handwavy r=bholley with comments addressed. ::: content/base/public/nsDOMFile.h @@ +155,5 @@ > + } > + > + // Some DOMFile objects are created without a parent maybe on different > + // threads. This method has to be used in order to set the correct > + // parent before sending these objects to content. Given this, do we want to assert mParent in GetParentObject? Looking over the patch, there are lots of places where we set this to null under the assumption that it won't ever be reflected into JS. Given that, I think we need some sort of strong assertion that this holds. ::: content/base/src/nsContentUtils.cpp @@ +5998,5 @@ > + > + JS::Rooted<JSObject*> obj(aCx, blob->WrapObject(aCx)); > + if (!obj || !JS_WrapObject(aCx, &obj)) { > + return NS_ERROR_FAILURE; > + } As Boris notes, this (and things like it) should convert to WrapNewBindingObject. ::: content/html/content/src/HTMLInputElement.cpp @@ +552,5 @@ > if (mCanceled) { // The last progress event may have canceled us > return NS_OK; > } > > + // Setting the parent to the DOMFile "to"? ::: dom/base/nsGlobalWindow.cpp @@ +7913,5 @@ > > + // See if this is a File/Blob object. > + { > + DOMFile* blob = nullptr; > + if (NS_SUCCEEDED(UNWRAP_OBJECT(Blob, obj, blob)) && scInfo->subsumes) { It makes more sense to me to invert the order here and check subsumes first. ::: dom/indexedDB/ipc/IndexedDBParent.cpp @@ +1500,5 @@ > > for (uint32_t index = 0; index < length; index++) { > BlobParent* actor = static_cast<BlobParent*>(aActors[index]); > + > + // We can use null because this blob is not exposed to content. I think "exposed to content" in all of these comments isn't quite right. "content" generally means "web content", generally defined in opposition to "chrome" (System JS). So I think it would make more sense to say "...because this blob is not reflected into JS". Comments like this appear in quite a few places in this patch, and I think they should all be updated. ::: dom/workers/XMLHttpRequest.cpp @@ +1072,5 @@ > AutoSafeJSContext cx; > JSAutoRequest ar(cx); > + > + JS::Rooted<JSObject*> scope(cx, xpc::UnprivilegedJunkScope()); > + JSAutoCompartment ac(cx, scope); Hm, why do we need the junk scope, exactly? Just to find an initial scope to enter? If so, I think that's not a good reason. We should either explicitly enter the scope of the XHR's owner, or add some machinery to BindingUtils to handle to case where the caller is in a null compartment. I really want to avoid a proliferation of junk scope usage, which is why I'm going to be stubborn about uses like this one. ;-) @@ +2160,5 @@ > SendInternal(EmptyString(), Move(buffer), clonedObjects, aRv); > } > >. ::: js/xpconnect/tests/chrome/test_cloneInto.xul @@ -147,5 @@ > true, > 'hello world', > [1, 2, 3], > { a: 1, b: 2 }, > - { blob: new Blob([]), file: new File(new Blob([])) }, Er, why do the blob tests go away here? Aren't they explicitly supported with the changes in ExportHelpers.cpp?
Attachment #8488767 - Flags: review?(bobbyholley) → review+
> We should either explicitly enter the scope of the XHR's owner The problem is that it's a pain to get there. The XHR's owner is just nsISupports, iirc,, so we have to wrap it, which means we need to be in a scope, etc. > or add some machinery to BindingUtils to handle to case where the caller is in a null > compartment. What would that machinery do? Enter the junk scope? The only sane and principled thing here is to quickly get to an nsIGlobalObject and get its JS object or something, but that's a major hassle in the general case. In this case it _could_ be done, but I for one would be OK with that happening in a followup.
(In reply to Boris Zbarsky [:bz] from comment #30) > What would that machinery do? Enter the junk scope? What code do we have that requires us to be in a compartment before we're dealing with a JSObject at all?
WrapNewBindingObject promises to wrap into the caller's compartment. That means it assumes there is a caller's compartment, no?
(In reply to Boris Zbarsky [:bz] from comment #32) > WrapNewBindingObject promises to wrap into the caller's compartment. That > means it assumes there is a caller's compartment, no? It seems like that could easily be changed, right? Or we could move most of the existing code there into WrapNewBindingObjectDontWrapValue, and WrapNewBindingObject could delegate to that and add a tail call to JS_WrapValue? In general, if we don't have any JSObjects yet, it seems wrong to require us to be in "some compartment". We've had requirements like that in the past that required us to bootstrap a dummy global every time we wanted to create a Window global, and I had to work very hard to fix it.
>. I'm open to refactoring this somehow while preserving those properties, and agree it would be a good idea. I don't think we should block this bug on it, but rather should do a followup.
(In reply to Boris Zbarsky [:bz] from comment #34) > >. Right, so we do what I suggest in comment 33. Is there anything about that which doesn't satisfy the above? > I'm open to refactoring this somehow while preserving those properties, and > agree it would be a good idea. I don't think we should block this bug on > it, but rather should do a followup. It depends - what kind of SLA would the followup have? The current patch uses the JunkScope, which is governed by special rules to avoid it becoming another hiddenDOMWindow.
> Is there anything about that which doesn't satisfy the above? I'd need to write the code to make sure. > It depends - what kind of SLA would the followup have? I'll make sure I fix it before 35 branches. I just can't do it this week, and I'd much rather get this landed to unblock other things than have it blocked on me fixing up this part.
(In reply to Boris Zbarsky [:bz] from comment #36) > I'll make sure I fix it before 35 branches. I just can't do it this week, > and I'd much rather get this landed to unblock other things than have it > blocked on me fixing up this part. Sounds good to me. Thanks a lot for doing that, and let me know if you need help.
I'm going to merge this patch in patch 1 if you give me a +
Attachment #8488979 - Attachment is obsolete: true
Attachment #8494607 - Flags: review?(bzbarsky)
Comment on attachment 8494607 [details] [diff] [review] wrapObject.patch >+++ b/dom/workers/WorkerPrivate.cpp The change here is still wrong. The "return result;" needs to be after the closing curly of that block. There's even a comment that explains why! Please fix that. r=me with that fixed, but please do fix it.
Attachment #8494607 - Flags: review?(bzbarsky) → review+
> Sounds good to me. Thanks a lot for doing that, and let me know if you need > help. In the meantime, can I keep the code as it is and file a followup?
1. rebased 2. fixed the return issue 3. applied (almost) all the bholley comments (read the comments I wrote to know why) Smaug, there are not so many changes about SystemMessage API, but I changed a couple of things and I appreciate if you can spend a couple of minutes (?) reading this patch. I guess a couple of tests are broken after the merging. I'm going to fix them and in case there are big changes, I'll ask a review in a interdiff.
Attachment #8488767 - Attachment is obsolete: true
Attachment #8494607 - Attachment is obsolete: true
Attachment #8497486 - Flags: review?(bugs)
> >. In that case I have to wrap it here and then unwrap it on the other Send() just to reuse < 10 lines. I would like to avoid this. > > - { blob: new Blob([]), file: new File(new Blob([])) }, > > Er, why do the blob tests go away here? Aren't they explicitly supported > with the changes in ExportHelpers.cpp? Because comparing cloned objects fails. The previous blob is actually a different object and we don't have any way to compare the real data from JS yet. Correct?
It is not clear to me what I should review here. I know nothing about SystemMessage API, but I also don't see SystemMessage API changes in the patch.
smaug, yes, sorry, I meant FrameMessageManager. No big changes, bug an additional glance can help.
> Because comparing cloned objects fails. The previous blob is actually a > different object and we don't have any way to compare the real data from JS > yet. Correct? As far as I know, we can compare blobs by read them into array buffers via FileReader. For Example: function readAsArrayBuffer(blob) { return new Promise(function (resolve) { var reader = new FileReader(); reader.onload = function () { resolve(reader.result); } reader.readAsArrayBuffer(blob); }); } function compareArrayBuffer(bufferA, bufferB) { if (bufferA.byteLength != bufferB.byteLength) return false; var va = new Uint8Array(bufferA); var vb = new Uint8Array(bufferB); for (var i = 0; i < va.length; i++) { if (va[i] != vb[i]) return false; } return true; } var a = new Blob(['ABCDE'], {contentType:'text/plain;carset=utf-8'}); var b = new Blob(['ABCDE'], {contentType:'text/plain;carset=utf-8'}); var c = new Blob(['01234'], {contentType:'text/plain;carset=utf-8'}); readAsArrayBuffer(a).then(function (arrayA) { readAsArrayBuffer(a).then(function (arrayB) { console.log(a === b, compareArrayBuffer(arrayA, arrayB)); // logs `false true` }); }); readAsArrayBuffer(a).then(function (arrayA) { readAsArrayBuffer(c).then(function (arrayC) { console.log(a === c, compareArrayBuffer(arrayA, arrayC)); // logs `false false` }); });
>. :(
(In reply to Andrea Marchesini (:baku) from comment #40) > > Sounds good to me. Thanks a lot for doing that, and let me know if you need > > help. > > In the meantime, can I keep the code as it is and file a followup? Yes.
(In reply to Andrea Marchesini (:baku) from comment #42) > In that case I have to wrap it here and then unwrap it on the other Send() > just to reuse < 10 lines. > I would like to avoid this. I don't follow - XMLHttpRequest::Send(JS::Handle<JSObject*> aBody, ErrorResult& aRv) doesn't do any unwrapping that I see.
(In reply to Boris Zbarsky [:bz] from comment #46) > >. :( As long as it gets done in a near-ish timeframe I don't really care about exact dates.
Interdiff: 1. MOZ_ASSERT(mParent) cannot be there because for chrome code, and workers, sometimes we don't have mParent. 2. Instead SetParentObject() I think it's cleaner to create a new DOMFile.
Attachment #8498286 - Flags: review?(bzbarsky)
Attachment #8497486 - Attachment is obsolete: true
Attachment #8497486 - Flags: review?(bugs)
Comment on attachment 8498286 [details] [diff] [review] patch 1 - interdiff r=me
Attachment #8498286 - Flags: review?(bzbarsky) → review+
Comment on attachment 8467051 [details] [diff] [review] patch 2 - nsDOMFileList to FileList A simple renaming for nsDOMFileList.
Attachment #8467051 - Flags: review?(ehsan.akhgari)
Comment on attachment 8467052 [details] [diff] [review] patch 3 - nsDOMFile.h to mozilla/dom/File.h renaming nsDOMFile to File.
Attachment #8467052 - Flags: review?(ehsan.akhgari)
Comment on attachment 8467053 [details] [diff] [review] patch 4 - Remove nsDOMBlobBuilder.h Moving code in order to remove nsDOMBlobBuilder.*
Attachment #8467053 - Flags: review?(ehsan.akhgari)
Comment on attachment 8467052 [details] [diff] [review] patch 3 - nsDOMFile.h to mozilla/dom/File.h Review of attachment 8467052 [details] [diff] [review]: ----------------------------------------------------------------- ::: dom/bindings/Bindings.conf @@ +150,5 @@ > }, > > 'Blob': { > + 'nativeType': 'mozilla::dom::File', > + 'headerFile': 'mozilla/dom/File.h', I think you should be able to drop headerFile...
Attachment #8467052 - Flags: review?(ehsan.akhgari) → review+
bz, sorry for this new interdiff, but making all the tests pass took a while. Something about this interdiff: 1. hazard rooting fixed 2. lastModified and lastModifiedData return the same value. I spoke with smaug about the reason this issue appears just now. Without my patch lastModified returns JS_Now() all the time if the lastModified date is unknown. Wtih my patches we return the creation time if lastModified is unknown. This is actually better because now lastModifiedDate and lastModified return the same value. 3. JS_Now() vs PR_Now() on windows they can return different values. So I had to use JS_Now() in the constructor. There is a comment about why. After that try seems to be fully green and we can land these patches.
Attachment #8498286 - Attachment is obsolete: true
Attachment #8500573 - Flags: review?(bzbarsky)
Comment on attachment 8500573 [details] [diff] [review] patch 1 - interdiff >+ // x.getTime() < f.dateModified.getTime() This might be false with JS_Now() too, because JS_Now() times can go backwards (e.g. due to NTP adjustments and the like). If you actually need a monotonic clock, you should be using TimeStamp in C++ and peformance.now() in JS. If you're not doing that, do NOT assume a monotonic clock (e.g. in tests). >+// In our implementation of File object, lastModifiedDate is unknown only for in new objects. s/for in/for/ ? >+++ b/content/base/test/test_bug403852.html Yeah, this test is bogus because it assumes precisely that thing I said not to assume. ;) >+ // called because otherwise the static analysis thinks it can gc the >+ // JSObject via the stack. No, because the static analysis thinks dereferencing XPCOM objects can GC (because in some cases it can!), and a return statement with a JSObject* type means that JSObject* is on the stack as a raw pointer while destructors are running. Same thing in all the other copy-pasted places. r=me but please file a followup about that test or something?
Attachment #8500573 - Flags: review?(bzbarsky) → review+
Attachment #8498290 - Attachment is obsolete: true
Attachment #8500573 - Attachment is obsolete: true
Comment on attachment 8500931 [details] [diff] [review] patch 5 - FilePropertyBag doesn't have 'name' Why doesn't ChromeFilePropertyBag just extend FilePropertyBag?
Attachment #8500931 - Attachment is obsolete: true
Attachment #8500958 - Flags: review?(bugs) remote: remote: remote: remote: remote:
Test failures:
Backed out for the webplatform test failures noted in comment 64.
I believe these failures are also related? Ready to land again if this patch is ok.
Attachment #8501720 - Flags: review?(bzbarsky)
Comment on attachment 8501720 [details] [diff] [review] patch 6 - webplatform tests fix >+ [no-argument Blob constructor without 'new'] This should throw (though Web IDL hasn't been updated to say that yet, while we figure out ES6 subclassing stuff). Can you please file a bug on this test? >+ . r=me
Attachment #8501720 - Flags: review?(bzbarsky) → review+
remote: remote: remote: remote: remote: remote: I asked jgraham to file the 2 bugs for the webplatform test suite.
(In reply to Boris Zbarsky [:bz] from comment #68) > >+ . It's not clear to me why this is bogus, but I might be missing something. It looks like the test causes mutation of the array to happen as it's being converted to a WebIDL sequence. As far as I can tell from the spec, this conversion happens using an iterator over the original array, which appears to just store an index into the array and so the output sequence will reflect changes to the array made during iteration.
My apologies. I should have looked at the test more carefully; I had assumed (bad me) that it was calling the constructor and then later mutating the array. The pop() test is still incorrect: the problem is that the test is depending on the old duck-typing behavior of sequences, not the iterator behavior. For example, stepping through the pop() test: 1) We create the array iterator, which has [[ArrayIteratorNextIndex]] set to 0 to start. 2) We call next() on it, this sets [[ArrayIteratorNextIndex]] to 1. 3) We take the returned object and ToString() it. This calls pop() on the array. 4) We call next() on the iterator again, landing in 5) In step 6, index is 1. 6) In step 8 we do .length on the array, which returns 1 (because we popped the value). 7) In step 11 we detect index >= len and return an iterator result that indicates iteration is done. The output of this is a Web IDL sequence of length 1, containing the single string "PASS". But the test expects a sequence of length 2, containing the strings "PASS" and "undefined". The unshift() test is incorrect for the same reason: it assumes that length is grabbed up front, while ArrayIterator doesn't do that.
Thanks to RyanVM for pointing me at some non-unified build bustage. I pushed what is hopefully a fix:
Adding an include didn't work. Maybe I need to explicitly prefix ErrorResult with mozilla::
Or throw in "using namespace mozilla".
Status: NEW → RESOLVED
Closed: 6 years ago
Resolution: --- → FIXED
Target Milestone: --- → mozilla35
I filed bug 1087851 on comment 34.
Hi, are there any effects on site compatibility?
Flags: needinfo?(amarchesini)
(In reply to Kohei Yoshino [:kohei] from comment #77) > Hi, are there any effects on site compatibility? No. We should not have any effects on site compatibility.
Flags: needinfo?(amarchesini)
Okay, thanks.
Component: DOM → DOM: Core & HTML
|
https://bugzilla.mozilla.org/show_bug.cgi?id=1047483
|
CC-MAIN-2020-50
|
refinedweb
| 6,070
| 59.6
|
Introduction to Abstract Class in C++
An abstract class is a class that is declared with an abstract keyword which is a restricted class hence cannot be used to create objects, however, they can be subclassed. To access abstract class, it must be inherited from another class. In class implementation and inheritance, when we want to define the same functions both in the base and derived class, we use the keyword ‘virtual’ along with the base class function. This ‘virtual’ function specifies that the same function is redefined or overridden in the derived class. An abstract class is a class with pure virtual function.
Now, what is a pure virtual function? A pure virtual function is a virtual function that has no body and is assigned as 0. This type of function is implemented when we need a function but we do not currently know what its function is. This function needs to be implemented or defined in the derived class. If not, then the derived class also becomes an abstract class.
A pure virtual function is defined as follow:
virtual void func() = 0;
Examples of Abstract Class in C++
Here, we discuss the different Examples of Abstract Class in C++ with details:
Example #1
Code:
#include<iostream>
using namespace std;
class Sample_Class {
int a = 5;
public:
virtual void sample_func() = 0;
void print_func() {
cout << a;
}
};
class Derived_Class : public Sample_Class {
public:
void sample_func() {
cout << "pure virtual function is implemented";
}
};
int main() {
Derived_Class d_object;
d_object.sample_func();
}
Output:
Code Explanation: Here Sample_Class is the base class and Derived_Class is derived from the Sample_Class. A pure virtual function called sample_func() is declared in the base class. It is assigned to 0, which means it has nobody and nothing is implemented inside the function. Thus, the base class has become an abstract class as it has a pure virtual function. Initially, when the Derived_Class is derived from the base class, it also becomes an abstract class. But in the derived class, the sample_func() class is defined, which prevents the derived class from becoming an abstract class. When the derived class object is created and function is called, we will get the output printed as ‘pure virtual function is implemented’.
An abstract class cannot be instantiated, which means that we cannot create an instance or object for an abstract class. The object cannot be created because the class is not implemented fully. It is actually a base for a class that is implemented fully later on. But pointers or references can be created for an abstract class. This pointer can be used to call the derived class functions. An abstract class can have other data members and functions similar to normal class implementation along with a pure virtual function.
The above point can be explained through the below program.
Example #2
Code:
class Class1 {
int a;
public:
virtual void func1() = 0;
void func2() {
cout << "base class";
}
};
class Class2 : public Class1 {
public:
void func1() {
cout << "func1 in derived class";
}
};
int main() {
Class1 b; //---------- > this line will cause an error
//Class1 *b = new Class2(); //---------- > pointer can be created, so this line is correct
// b -> func1();
}
Output:
Here we will get an error as an object cannot be created for abstract class. Instead, 2nd and 3rd line of code can be implemented, a pointer can be created and can be used to call derived class function.
Code Explanation: Here, in the above function Class1 is the base class and as it has a pure virtual function (func1) it has become an abstract class. Class2 is derived from the parent class Class1. The func1 is defined in the derived class. In the main function, when we try to create an object of type base class we will get an error, as objects cannot be created for abstract class. Whereas when we try to create a pointer of base class type, it will be created successfully and we can point it to the derived class. This pointer can be used to call the derived class function.
An abstract class can have constructor similar to normal class implementation. In the case of the destructor, we can declare a pure virtual destructor. It is important to have a destructor to delete the memory allocated for the class. Pure virtual destructor is a destructor that is assigned to 0 but it must be defined by the same class, as destructor is not usually overridden.
Example of Constructor and Destructor for Abstract Class in C++
Here, we discuss Example of Constructor and Destructor for Abstract Class in C++ with details.
Code:
class Base {
public:
int a;
virtual void func1() = 0;
// Constructor
Base(int i) {
a = i;
}
// Pure Virtual destructor
virtual ~Base() = 0;
};
// Pure virtual destructor is defined
Base :: ~Base() {
cout << "Pure virtual destructor is defined here" << endl;
}
class Derived : public Base {
int b;
public:
// Constructor of derived class
Derived(int x, int y) : Base(y) { b = x; }
// Destructor of derived class
~Derived() {
cout << "Derived class destructor" << endl;
}
//Definition for pure virtual function
void func1() {
cout << "The value of a is " << a << " and b is " << b << endl;
}
};
int main() {
Base *b = new Derived(5,10);
b->func1();
delete b;
}
Output:
Code Explanation: Here, in the above example Base class is an abstract class with pure virtual function func1(), a constructor and a pure virtual destructor. The pure virtual function is defined in the derived class hence preventing the derived class from becoming an abstract class. The pure virtual destructor is defined by the Base class outside the class. If we want to define the member function of a class outside the class, the scope resolution operator should be used as shown in the example. A pointer of base class type is created and pointed to the derived class. When destructor is called using ‘delete’, first the derived class destructor is called and then the base class destructor is called.
Conclusion
Hence, to compile everything about an abstract class, we can say that the abstract class is a class with a pure virtual function. This pure virtual function must be defined in the derived class, if not then the derived class also becomes an abstract class. The object cannot be created for abstract class, but pointer can be created which can be pointed to the derived class.
Recommended Articles
This is a guide to Abstract Class in C++. Here we discuss the introduction to abstract class as well as the implementation of constructor and destructor in C++ along with its example. You may also look at the following articles to learn more-
|
https://www.educba.com/abstract-class-in-c-plus-plus/
|
CC-MAIN-2021-04
|
refinedweb
| 1,085
| 58.11
|
:
Code:
d2dContext->BeginDraw();
d2dContext->Clear( D2D1::ColorF( D2D1::ColorF::White ) );
If I omit the Clear instruction the background becomes black. If I use a transparent color the background is still black. I have created the second window with the style WS_TRANSPARENT..
d2dContext->BeginDraw();
d2dContext->Clear( D2D1::ColorF( D2D1::ColorF::White ) );
Hi, welcome! I'm actually having a similar problem and was just about to post! I've been trying to create a new form from my main form to highlight an area of the main form, and would need it to be semi-transparent to show the user where to look but without hiding what I'm trying to show. The problem is, no mather how I set the new form's properties, it will not show semi-transparent!!
Not sure if this will help you, but this is what I have so far:
1. What I'm doing (and it's not working) is, on the child form, set:
Code:
.AllowTransparency = true;
.Opacity = 0.5 // 50%
.BackColor = Color.Blue;
.TransparencyKey = Color.Blue; // Same as BackColor
That should show a translucent window, but it doesn't work for me.
2. Other options
MSDN article on transparent forms
Transparent borderless forms
Very basic tutorial on transparent forms
A final mention goes to this article on Forms transparent to mouse events that doesn't have much to do with optical visibility but might be helpful anyway.
Hope it helps... and if you manage to show a transparent form from another one, please let me know!
.AllowTransparency = true;
.Opacity = 0.5 // 50%
.BackColor = Color.Blue;
.TransparencyKey = Color.Blue; // Same as BackColor
Not, I have not found a complete solution yet. Just because this is a performance issue, I have decided to redraw everything. The final effect is the same, but the program can become very slow is some cases. An alternative would be to save the static part of the drawing as a bitmap, instead of repeating it every time. That optimization would be equivalent to what I was expecting from the operating system. In this moment I have already turned my attention to other details of my program. I will return to the optimization much later on.
hi world !
[ autoit ] ( Popup )
#include <GuiConstants.au3>
$Main_GUI = GUICreate("Main")
$Btn_Exit = GUICtrlCreateButton("E&xit", 10, 10, 90, 20)
GUISetState(@SW_SHOW, $Main_GUI)
$Child_GUI = GUICreate("Child", 200, 100, 10, 50);, $WS_POPUP );,$WS_EX_LAYERED
GUISetBkColor(0xfffaf0, $Child_GUI)
$Btn_Test = GUICtrlCreateButton("Test", 10, 10, 90, 20)
GUISetState(@SW_SHOW, $Child_GUI)
DllCall("user32.dll", "int", "SetParent", "hwnd", WinGetHandle($Child_GUI), "hwnd", WinGetHandle($Main_GUI))
While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE, $Btn_Exit
Exit
Case $Btn_Test
MsgBox(0, "Test", "Hit Button on Child Window")
EndSwitch
WEnd
the code is exactly what i need: a child window stuck within the parent. but i need a transparent (transparent background, not set transparency) child without borders.
but how, since $WS_EX_LAYERED does not work with child windows ?
thx
j.
View Tag Cloud
Forum Rules
|
http://forums.codeguru.com/showthread.php?524056-Child-Window-with-a-Transparent-Background&p=2068680&mode=linear
|
CC-MAIN-2017-43
|
refinedweb
| 483
| 54.22
|
Although the "Hello World!" program looks simple, it has all the fundamental concepts of C which is necessary to learn to proceed further. Lets break down "Hello World!" program to learn all these concepts.
// Hello World! Example #include <stdio.h> int main () { printf( <stdio.h>: printf("Hello, World!"); - printf() is standard character output device defined in <stdio.h> header file. It facilitates output from a program. Finally, ("Hello world!") is inserted into the printf() to get the output printed on the output device. Please note that, in C, every statement ends with semicolon (;).
Line 7: reurn 0; indicates ends of the main function.
"\n" facilitates line change while performing output operation. "\n" tells the program to start a new line.
#include <stdio.h> int main () { printf("Hello World!.\n"); printf("Learning C is fun."); return 0; }
Hello World!. Learning C is fun.
|
https://www.alphacodingskills.com/c/c-syntax.php
|
CC-MAIN-2019-51
|
refinedweb
| 142
| 73.13
|
Over~)
There are times when key-value pairs and/or files won’t meet your need for data storage. Specifically, when you’re dealing with structured data that is repeated, such as events on a calendar. For this type of information you’ll want to use a relational store. This relational store is typically a SQL database. Both Android and Windows Phone 8 support using the SQLite relational database engine. This section assumes you have familiarity working with SQLite on Android.
Installing SQLite
The first thing you’ll need to do is install the SQLite for Windows Phone apps. This can be done by downloading the SQLite for Windows Phone package
- In Visual Studio, click the Tools menu, then click Extensions and Updates
- In the tree on the left of the Extensions and Updates window, clickOnline, then click Visual Studio Gallery.
- Next, type sqlite in the search box in the upper right hand corner and press Enter.
- The SQLite for Windows Phone package should appear. Click Download.
- You will then be prompted to click Install. Do so.
- Once the package is installed you will need to restart Visual Studio
Adding a Reference to SQLite
Now that SQLite is installed you need to add a reference to it from you project.
- Right click the References folder in your Windows Phone project and click Add Reference…
- In the tree on the left hand side of the Reference Manager windows, expand the Windows Phone and the Extensions nodes.
- Then select both the SQLite for Windows Phone and click OK.
- You should now see the extension appear under the References folder for you project.
Getting Helper Classes
The last thing you’ll want to do is obtain some helper classes that make working with SQLite a bit easier. There are a number available for Windows Phone applications. The ones I prefer to use come from thesqlite-net library.
The sqlite-net library can be obtained from NuGet via the following steps
- Right click on the References folder in you Windows Phone project and click Manage NuGet Packages…
- Expand the Online node in the left hand side of the Window.
- Enter sqlite in the search box in the upper right hand side of Window and press Enter.
- Select sqlite-net and click Install.
- Two source files will be added to your project: SQLite.cs and SQLiteAsync.cs.
- If you look in your Error List you’ll see a number of errors. This is due the fact that sqlite-net is dependent on csharp-sqlite which has not been ported to Windows Phone 8.
- To work around this you’ll need to use the sqlite-net-wp8 native C++project. You’ll first need to go to the project’s repository on github and download the zip version of the repository.
- Right-click the downloaded zip file, click Properties, click Unblock, and click OK.
- Unzip the content.
- In the Solution Explorer in Visual Studio, right-click the solution and choose Add, then choose Existing Project.
- In the Add Existing Project dialog, brose to the location where you unzipped the content in step, select the Sqlite.vcxproj file, and click Open.
- You should now see the Sqlite project in your solution.
- You now need to add a reference to the Sqlite project to your Windows Phone project. Right-click the References folder of your Windows Phone project and click Add
- In the Reference Manager dialog select Solution from the tree on the left-had side, select Projects.
- Check the box next to the Sqlite project and click OK.
- The last step is to add a compiler directive to the Windows Phone project. Right-click the Windows Phone project in Solution Explorer and click Properties
- Click Build and add the following to the conditional compilation symbols text box: ;USE_WP8_NATIVE_SQLITE
- Build your solution by pressing F6. You should now see a Build succeeded message and no errors in the Error List.
Using SQLite
In the last part of this section we’ll look at how to perform some basic tasks with SQLite in your Windows Phone application.
Creating a Table
The first step you’ll need to take is to create a table that your application will use. For the sake of example, let’s say your application is storing blog posts in a SQLite table. Using the sqlite-net package you obtained in the last section, you can define the table by simply writing a class.
public class Post { [PrimaryKey] public int Id { get; set; } public string Title { get; set; } public string Text { get; set; } }
The PrimaryKey attributes come from the sqlite-net package. There are a number of attributes that the package provides that allow you to define the table’s schema.
Once the table is defined it needs to be created, which can be done like this:
private async void CreateTable() { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); await conn.CreateTableAsync<Post>(); }
The “blog” parameter in the constructor for the SQLiteAsyncConnectionclass simply specifies the path to the SQLite database.
The Post type specified in the call to the CreateTableAsync method specifies the type of table that should be created. This maps back to thePost class created earlier.
public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE Post ( Id INTEGER PRIMARY KEY, Title TEXT, Text TEXT )"); }
Inserting a Record
Now that the table is created, records can be added to it with the following code:
public async void InsertPost(Post post) { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); await conn.InsertAsync(post); }
public void insertPost(SQLiteDatabase db, String title, String text ) { ContentValues values = new ContentValues(); values.put("Title", title); values.put("Text", text); long newRowId; newRowId = db.insert("Post", null, values); }
Retrieving Records
Retrieve all records from the table with the following:
public async Task<List<Post>> GetPosts() { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); var query = conn.Table<Post>(); var result = await query.ToListAsync(); return result; }
public Cursor getPosts(SQLiteDatabase db){ String[] projection = {"Id", "Title", "Text" }; Cursor c = db.query("Post", projection, null, null, null, null, null); return c; }
Retrieve a single record from the table with the following:
public async Task<Post> GetPost(int id) { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); var query = conn.Table<Post>().Where(x => x.Id == id); var result = await query.ToListAsync(); return result.FirstOrDefault(); }
public Cursor getPost(SQLiteDatabase db, Integer id){ String[] projection = {"Id", "Title", "Text" }; String selection = "Id LIKE ?"; String[] selelectionArgs = { String.valueOf(id) }; Cursor c = db.query( "Post", projection, selection, selectionArgs, null, null, null); return c; }
Updating a Record
Updating a record requires the following code:
public async void UpdatePost(Post post) { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); await conn.UpdateAsync(post); }
public void updatePost(SQLiteDatabase db, Integer id, String title, String text ) { ContentValues values = new ContentValues(); values.put("Title", title); values.put("Text", text); String selection = "Id LIKE ?"; String[] selelectionArgs = { String.valueOf(id) }; int count = db.update("Post, values, selection, selectionArgs); }
Deleting a Record
A record can be delete with the following:
public async void DeletePost(Post post) { SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog"); await conn.DeleteAsync(post); }
public void deletePost(SQLiteDatabase db, Integer id ) { String selection = "Id LIKE ?"; String[] selelectionArgs = { String.valueOf(id) }; db.delete("Post", selection, selectionArgs); }
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/android-windows-phone-8-2
|
CC-MAIN-2017-13
|
refinedweb
| 1,195
| 64.71
|
Hide Forgot
- default install in Japanese using
- Selecting gnome desktop during the installation, everything else
default
- After the first login into gnome, the desktop is English, not Japanese
- open a gnome-terminal and check the locale, it is POSIX.
- the contents of the file /var/lib/Accounts/Service/users/mfabian are
[mfabian@localhost ~]$ cat /var/lib/AccountsService/users/mfabian
[User]
Language=
XSession=
[mfabian@localhost ~]$
- After using “system settings -> region and language” and selecting Japanese there, log out and log in again, the locale is correctly ja_JP.utf8. And the file /var/lib/AccountsService/users/mfabian now contains:
[mfabian@localhost ~]$ cat /var/lib/AccountsService/users/mfabian
[User]
Language=ja_JP.utf8
XSession=
[mfabian@localhost ~]$
Expected result:
After an installation done in Japanese, the default language of the
desktop should be Japanese already.
Created attachment 614238 [details]
first-login-after-default-install-in-japanese.png
The file /etc/sysconfig/i18n does not exist after a default install
of f18 in Japanese.
move bug to anaconda because of comment#2.
After creating /etc/sysconfig/i18n with the one line content
LANG=ja_JP.UTF-8
then gnome-session-quit and log in again, the desktop is Japanese.
Please attach /var/log/anaconda/anaconda.log and /var/log/anaconda/syslog to this bug report. Thanks.
Created attachment 614791 [details]
anaconda.log
Created attachment 614792 [details]
/var/log/anaconda/syslog
I just did a test install of a post-alpha tree and I see that /etc/sysconfig/i18n has:
LANG="ja.UTF-8"
I wonder if that setting works for you.
That won’t work, it is an incorrect setting, see:
mfabian@ari:~
$ LANG=ja:~
You see an error message because that locale doesn’t exist on Fedora.
The correct locale is ja_JP.UTF-8, when using this, there is no error message:
mfabian@ari:~
$ LANG=ja_JP.UTF-8 locale charmap
UTF-8
mfabian@ari:~
$
(In reply to comment #8)
> I just did a test install of a post-alpha tree and I see that
> /etc/sysconfig/i18n has:
>
>
> I wonder if that setting works for you.
That locale settings perfectly worked until f17. I'm wondering why the kind of this regression happens.
I tested i18n test day iso and installed in English locale and found that default locale set is en.UTF-8 which should be set as en_US.UTF-8.
Looks like installed locale is missing countrycode?
(In reply to comment #11)
> I tested i18n test day iso and installed in English locale and found that
> default locale set is en.UTF-8 which should be set as en_US.UTF-8.
>
> Looks like installed locale is missing countrycode?
Yes, without the country code it is just an invalid locale:
mfabian@ari:~
$ LC_ALL=en:~
$
(Still happens with anaconda-18.9-1.fc19.)
Discussed at 2012-09-26 blocker review meeting: . No consequences of this that would violate the Beta criteria have been identified, but it clearly violates the Final criterion "All critical path actions on release-blocking desktop environments should correctly display all sufficiently complete translations available for use". It is also accepted as NTH for Beta as it's a highly visible error for non-English users.
Firstboot crashes because of the wrong locale.
This regression is causing a lot of problems -
probably also the firewall config tool crash?
Note this bug affects even: en_US -> en.UTF-8.
Maybe this would help with the en.UTF-8 issue?
diff -u anaconda-18.10/pyanaconda/localization.py\~ anaconda-18.10/pyanaconda/localization.py
--- anaconda-18.10/pyanaconda/localization.py~ 2012-09-27 02:26:04.000000000 +0900
+++ anaconda-18.10/pyanaconda/localization.py 2012-09-27 20:50:08.077007658 +0900
@@ -268,8 +268,8 @@
def __init__(self, preferences={}, territory=None):
self.translations = {repr(locale):locale for locale in get_available_translations()}
self.locales = {repr(locale):locale for locale in get_all_locales()}
- self.preferred_translation = self.translations['en.UTF-8']
- self.preferred_locales = [self.locales['en.UTF-8']]
+ self.preferred_translation = self.translations['en_US.UTF-8']
+ self.preferred_locales = [self.locales['en_US.UTF-8']]
self.preferred_locale = self.preferred_locales[0]
self.all_preferences = preferences
So far not sure yet how to fix the general missing territory issue.
I see localization.py file is supposed to set all the needed things for a language environment. It even sets territory. something must be going wrong in that code that makes it to miss country code.
I think "data/lang-table" needs to be brought back.
The current language implementation seems to just use the "locales" in po/ which is oversimplified. GLibc does not support xx.utf8 locales at all.
This regression is making i18n and l10n testing of F18 really difficult.
jens: if this bug has consequences more severe than we thought when doing the blocker evaluation, do please explain what they are and re-propose as Beta blocker so we can look at it again...
Or maybe instead of "data/lang-table", anaconda could refer to the list of real
locales listed in "/usr/share/i18n/locales"?
Adam: I am still not sure if it fulfils the Beta blocker criteria.
Having said that if it doesn't, I really feel that the criteria need
to be updated to cover valid locales. IMHO this should even be
an Alpha blocker (alpha anaconda just hardcoded en_US.UTF-8 so
it did not have this problem fortunately, but both the i18n and l10n
testdays used post-alpha to get gnome-3.5.9x).
FWIW en.UTF-8 doesn't seem to make firstboot crash but ja.UTF-8 does iirc.
You don't have to phrase it in terms of the criteria, just specify any specific consequences of this bug that are not listed in this report yet.
One of example for consequence: Bug#860276
And possibly other applications using scripting language such as python like the above bug. particularly if they deal with localized strings.
the locale support is essential and many many applications are relying on it. the crash and not working properly isn't that surprised things if it's broken.
firewalld and firewall-config crash:
Bug 860278 - [abrt] firewalld-0.2.7-1.fc18: locale.py:539:setlocale:Error: unsupported locale setting
Created attachment 620140 [details]
screenshot showing "cannot change locale" warnings after first logging into a console
Another consequence is a flurry of "cannot change locale" warnings after first logging into a console.
Reproduced after a clean install with:
anaconda-18.10-1.fc18.x86_64
Fedora-18-Nightly-20120930.12-x86_64-Live-desktop.iso
Default Language and Keyboard were accepted.
Timezone was set to America/Los_Angeles.
Automatic partitioning was selected.
$ qemu-kvm -m 2048 -hda f18-test-2.img -cdrom ~/xfr/fedora/nightly-composes/Fedora-18-Nightly-20120930.12-x86_64-Live-desktop.iso -vga qxl -boot order=dc,menu=on.
Created attachment 620326 [details]
screenshot showing "Unspecified [ANSI_X3.4-1968]" selected as language in "System Settings:Region & Language"
Another consequence is that "Unspecified [ANSI_X3.4-1968]" is displayed as the language in the "System Settings:Region & Language" control center panel.
A partial work-around seems to be to set a specific language from "System Settings:Region & Language" and reboot. Unfortunately, firewalld still crashes and warnings are still displayed when logging into a console.
After selecting "Spanish" from "System Settings:Region & Language" and rebooting, the locale command reports:
$ cat typescript-6
Script iniciado (mar 02 oct 2012 14:26:25 EDT
)[joeblow@localhost xfr]$ locale
LANG=es_ES.utf8
LC_CTYPE="es_ES.utf8"
LC_NUMERIC="es_ES.utf8"
LC_TIME="es_ES.utf8"
LC_COLLATE="es_ES.utf8"
LC_MONETARY="es_ES.utf8"
LC_MESSAGES="es_ES.utf8"
LC_PAPER="es_ES.utf8"
LC_NAME="es_ES.utf8"
LC_ADDRESS="es_ES.utf8"
LC_TELEPHONE="es_ES.utf8"
LC_MEASUREMENT="es_ES.utf8"
LC_IDENTIFICATION="es_ES.utf8"
LC_ALL=
[joeblow@localhost xfr]$ exit
Script terminado (mar 02 oct 2012 14:26:43 EDT
)
Created attachment 620377 [details]
screenshot showing a menu of locales in "System Settings:Region & Language" control center panel
(In reply to comment #26)
>.
FWIW, in the "System Settings:Region & Language" control center panel, if you click the "+" button, you get a menu of locales (language and region).
For a work-around, there appear to be three files that must be correct and consistent: [1]
1. /var/lib/AccountsService/users/joeblow
2. /etc/sysconfig/i18n
3. /etc/locale.conf [2]
Work-around procedure:
1. Run "System Settings:Region & Language" to write file #1 above.
2. $ grep Language /var/lib/AccountsService/users/joeblow [3]
3. With a text editor, write the locale from step 2 to file #2 and file #3 above.
4. Reboot.
Test cases:
1. From a gnome terminal:
$ locale
There should not be any error messages.
2. Login to a console.
There should not be any warnings.
3. To verify that firewalld did not crash during booting:
$ ps -ef | grep firewalld
Run firewall-config to verify that it does not crash:
$ firewall-config
[1] Thanks to Mike for identifying the first two files.
[2] /etc/locale.conf does not exist on my F17 system.
[3] For the encoding, the file has "utf8", not "UTF-8"..
(In reply to comment #30)
>.
Thanks for the tip. I did a live install from a nightly in a VM:
anaconda-18.10-1.fc18.x86_64
Fedora-18-Nightly-20120930.12-x86_64-Live-desktop.iso
Which 3? There are four in Comment 29 ... :-).
Because of this bug, iok application got this bug 860159. Consider the case where applications depend on current set locale code. They are all going to get failed.
Chris,
I have not looked into source code thoroughly.
How about changing a anaconda UI a bit by adding available locales once a language is selected and let the user select his own preferred locale?
OR
I still not sure how can a locale be selected which have script modifier in it like aa_ER@saaho, de_BE@euro, ks_IN@devanagari etc.
(In reply to comment #34)
>
In fact there are no locales which don't have a territory. in that case, should fall back to POSIX IMHO.
The GNU documentation says this:
2.3.1 Locale Names
"A locale name usually has the form ‘ll_CC’. Here ‘ll’ is an ISO 639 two-letter language code, and ‘CC’ is an ISO 3166 two-letter country code."
The 'C' and 'POSIX' locales are exceptions to the 'll_CC' form:
$ locale -a | egrep '^C|POSIX'
C
POSIX
The locale files are text files in /usr/share/i18n/locales/.
(In reply to comment #35)
> (In reply to comment #34)
> > If locale is not
> > available then only like current anaconda, locale should have set like
> > LANG=es.utf8
>
> In fact there are no locales which don't have a territory. in that case,
> should fall back to POSIX IMHO.
I think falling back to en_US.UTF-8 is better in that case because
using POSIX uses ASCII encoding:
mfabian@ari:~
$ LC_ALL=POSIX locale charmap
ANSI_X3.4-1968
mfabian@ari:~
$ LC_ALL=en_US.UTF-8 locale charmap
UTF-8
mfabian@ari:~
$
Therefore, using POSIX can cause problems with display of non-ASCII stuff
in some cases:
mfabian@ari:~/tmp/test
$ LC_ALL=en_US.UTF-8 ls
täst 日本語
mfabian@ari:~/tmp/test
$ LC_ALL=POSIX ls
t??st ?????????
mfabian@ari:~/tmp/test
$
and some software then gets ASCII as the default encoding, for example
when reading files.
I think using en_US.UTF-8 is a better fallback.
(In reply to comment #32)
>.
Yes, "UTF-8" is the preferred spelling but "utf-8" or "utf8" work
as well with glibc.8 locale charmap
UTF-8
mfabian@ari:~
$ LC_ALL=en_US.UtF---8 locale charmap
UTF-8
mfabian@ari:~
When a spelling is used which does not work with glibc, an error
like this is seen:
mfabian@ari:~
$ LC_ALL=en_US.UTF:~
$
(In reply to comment #34)
> I still not sure how can a locale be selected which have script modifier in
> it like aa_ER@saaho, de_BE@euro, ks_IN@devanagari etc.
aa_ER@saaho and ks_IN@devanagari use UTF-8:
mfabian@ari:~
$ LC_ALL=aa_ER@saaho
mfabian@ari:~
$ LC_ALL=aa_ER@saaho locale charmap
UTF-8
mfabian@ari:~
$ LC_ALL=ks_IN@devanagari locale charmap
UTF-8
mfabian@ari:~
But the xx_YY@euro locales use the legacy ISO-8859-15 encoding:
mfabian@ari:~
$ LC_ALL=de_BE@euro locale charmap
ISO-8859-15
mfabian@ari:~
$
So it is not a good idea to use xx_YY@euro locales, these
are just legacy locales and should not be set as defaults,
they are useful only for special purposes.
I rather like the idea of using timezone selection to also set the locale
but I dunno if that data is available? Does pytz have locale info?
(Right, utf8 vs UTF-8 is not an issue here - either is fine.)
If there are no other possible ideas then probably
reverting back to using lang-table for now is probably
the simplest viable solution at this point?
As for F18Beta - no further new info to add.
Presumably firstboot crashing for a Japanese, etc installs
is not a blocker until after Beta?
Anyway I really really hope this can be fixed by Beta
otherwise it is not going to be good.
(In reply to comment #40)
> but I dunno if that data is available? Does pytz have locale info?
I don't think tzdata has any locale info so it will not work
and anyway as you know many countries have multiple locales.. Anyway just offering it as
an possible alternative to reverting to lang-table, which some might
still consider the safest.
(In reply to comment #42)
>.
That's true. this may makes some duplicate work and files.
BTW how are keyboard layouts being defaulted now, or is it always US layout?
Overall lang-table still seems a nice compact way to store all this info,
though if there was some upstream project that could provide all this
data with a nice API that would be ideal surely.
Anyway here is a scratch build
implementing the hack in comment 42, which seems to work for me.
After installing in Japanese with this build, firstboot now starts,
system locale is correct and locales errors gone. :)
Created attachment 620776 [details]
anaconda-18-fix-locales.patch
Here is the patch to anaconda.spec used for the above test build.
It is not beautiful but at least it works. ;)
I can convert it into a shell script that can be run from %install, if it helps.
Though thinking of kbd default handling also - maybe still better to return to lang-table?
According to the POSIX specification[1], the default locale can be "the POSIX locale or any other implementation-defined locale."
7.2 POSIX Locale
[1] The Open Group Base Specifications Issue 6
IEEE Std 1003.1, 2004 Edition
I'm going to regret this, but I'll take this bug.
re-proposing as Beta blocker. For the record, as status of this bug is complex, it's currently accepted as Final blocker and Beta NTH, but rejected as Beta blocker: I am re-proposing it as Beta blocker on the basis that it causes more effects than we were aware of when we first rejected it. Status will be updated after discussion at the blocker meeting today. may possibly be another consequence of this (still being checked).
*** Bug 860276 has been marked as a duplicate of this bug. ***
So #860276 gives us a very solid basis to accept this as a blocker: it breaks firstboot. I confirmed this myself. 'LC_ALL=es.UTF-8 firstboot' crashes, firstboot does not run at all. 'LC_ALL=es_ES.UTF-8 firstboot' runs fine. Other languages are affected, at least Japanese. So this bug causes firstboot to fail to run in several languages, breaking the".
Created attachment 621475 [details]
anaconda-18-fix-locales.patch
Ok I cleaned up my patch a little more and made a shell script for the locale file renaming. This now takes care of renaming all the translation files (even 2 not yet supported by glibc;).
However English (en) seems to be a special case in anaconda
so en.UTF-8 not fixed yet. That can probably be fixed on the python side.
But lang-table is probably still a cleaner solution.
Those wanting to install with a valid locale can try installing
into a Live instance.
Jens - thanks, but I've got something in anaconda itself for now. We'll definitely be looking for a better solution in the future, though. We really don't want to own this kind of data.
Add in a locale mapping to avoid incorrect system settings (#858591).
Thanks.
Does this mean that selecting a language implicitly sets a corresponding country in the resulting locale?
"en": "en_US"
"es": "es_ES"
"ja": "ja_JP"
Some languages are still missing and these are important languages.
Bengali(India) bn_IN
Chinese(Simplified) zh_CN
Chinese(Traditional) zh_TW
Portuguese(Brazilian) pt_BR
Serbian(Latin) sr@latin
Those don't need to be mangled, they're already good as-is.
I ran a validation test of the locales against /usr/share/i18n/locales/ in F17:
ls: cannot access /usr/share/i18n/locales/ilo_PH: No such file or directory
ls: cannot access /usr/share/i18n/locales/kk_KK: No such file or directory
ls: cannot access /usr/share/i18n/locales/tg_TG: No such file or directory
$ cat locale-list-1.txt | sed -e 's@^@/usr/share/i18n/locales/@' | xargs ls
Locales were extracted with:
#!/bin/bash
# Extract locales from language-list-1.txt
# The list is from:
#
sed -e 's/[:,]/\n/g' -e 's/[" }]//g' language-list-1.txt | grep '_'
Right.
kk_KK should be kk_KZ
tg_TG should be tg_TJ
I wonder where ilo locale gone?
Guys - if you want to be involved in development, do it on the anaconda-devel and anaconda-patches mailing list, not in bugzilla.
(In reply to comment #59)
> Guys - if you want to be involved in development, do it on the
> anaconda-devel and anaconda-patches mailing list, not in bugzilla.
On F17:
$ ls /usr/share/i18n/locales/*PH
/usr/share/i18n/locales/en_PH /usr/share/i18n/locales/fil_PH /usr/share/i18n/locales/tl_PH
Consider this a bug report, then ... :-)
This bug has caused a lot of problems and a lot of work, so any fixes deserve a lot of scrutiny.
(In reply to comment #53)
> Jens - thanks, but I've got something in anaconda itself for now. We'll
> definitely be looking for a better solution in the future, though. We
> really don't want to own this kind of data.
Thanks, glad to hear it, and good to know.
(In reply to comment #54)
> Add in a locale mapping to avoid incorrect system settings (#858591).
>
> ?id=45c8c0a28ccca8ac02b89571b4fcb192c33c2103
Thanks for the pointer. I should have looked yesterday...
is a test build of current anaconda HEAD.
I tested it from Live and the patch looks good so far.
So, great news that with 18.13 we should have working locales again.
(In reply to comment #58)
> I wonder where ilo locale gone?
It is not in glibc.
Created attachment 621937 [details]
anaconda-fix-kk-tg-locales.patch
> kk_KK should be kk_KZ
> tg_TG should be tg_TJ
Right - I had already noticed this while working on my hack.
Chris: can you please apply this patch to correct those two locales.
(In reply to comment #62)
>
> is a test build of current anaconda HEAD.
Here is an corresponding updates.img file too (untested)
if anyone wants to test with a net install or dvd.
(In reply to comment #58)
...
> I wonder where ilo locale gone?
Good question. ilo_PH was invalid in F17 too:
Bug 863450 - invalid locale ilo_PH after installing in Iloko language from F17 DVD
>Chris: can you please apply this patch to correct those two locales.
Done.
*** Bug 863510).
F18 Beta TC3 - - should include this fix. Please re-test and check. Thanks!
I checked this myself, and it looks fine. Did an install in French (with UK English keyboard layout, just for fun) - the installed system shows up in French and firstboot ran fine. Setting VERIFIED.
I verified that installing in Spanish results in a valid locale of es_ES.UTF-8 and that the desktop displays Spanish. Some messages in terminals are in Spanish and some are not. Compare "ls /tmp/foo" and "sudo foo".
It could take a while to test all of the available languages by installing ...
Tested with:
$ qemu-kvm -m 2048 -hda f18-test-1.img -cdrom ~/xfr/fedora/F18/F18-Beta/TC3/Fedora-18-Beta-TC3-x86_64-Live-Desktop.iso -usb -vga qxl -boot menu=on
I can confirm here that installation in Marathi language with US keyboard layout, set the correct locale to mr_IN.UTF-8
work around for me was 'export LC_ALL="en_US"'
It seems OK, localization is setted correctly.
Discussed at 2012-10-10 blocker review meeting: . Accepted as a blocker per", in the case of just about any non-English install firstboot fails to run.
Created attachment 626612 [details]
screenshot showing invalid locale eu.UTF-8 for Basque in 18.16
anaconda 18.16 is writing an invalid locale eu.UTF-8 for Basque.
This is the first result for a semi-automated locale validation test. It requires patching anaconda, but hopefully in a non-destructive way. When anaconda writes /mnt/sysimage/etc/sysconfig/i18n and /mnt/sysimage/etc/locale.conf, the patch appends the same strings to files in /tmp: langlist_i18n_1.txt and langlist_locale_conf_1.txt. (The strings appear to be identical, so having two is redundant.)
The main problem with this procedure is that the strings are written at the very end of the install, so a test for each language requires configuring the disk and waiting for the install to complete.
Created attachment 626660 [details]
screenshot showing six invalid locales configured by anaconda 18.16
The language menu items that do not show a country all produce invalid locales:
be
bs
eu
hy
ka
sr
Created attachment 626661 [details]
install.py.patch-1 patch to write the locale string to a file before installation
Writing out the locale string before installation speeded up checking the language menu items greatly. For each language tested, after confirming that /tmp/langlist_ksdata_1.txt had been updated, it was safe to kill anaconda and start a new test of the next language. I was lazy and only checked the languages that did not have a corresponding country in the language menu. :-)
$ diff -u install.py.ORIG-18.16 install.py.NEW-1 > install.py.patch-1
*** Bug 866108 has been marked as a duplicate of this bug. ***
Georgian gives an invalid locale.
Package: anaconda-18.16-1.fc18.x86_64
OS Release: Fedora release 18
Test results for Fedora-18-Beta-TC4-x86_64-DVD.iso (which has anaconda 18.16):
Selecting these languages results in an invalid locale:
Belarusian be
Bosnian bs
Basque eu
Armenian hy
Georgian ka
Serbian sr
These alternative languages from the language menu result in a valid locale:
Basque (Spain) eu_ES
Serbian (Serbia) sr_RS
There are no alternatives for Belarusian, Bosnian, Armenian, Georgian.
There are 74 languages in the language menu. I did not test every one ...
Tested by repeatedly running clean, minimal installs from the DVD.
Command-line:
$ qemu-kvm -m 2048 -hda f18-test-1.img -cdrom ~/xfr/fedora/F18/F18-Beta/TC4/Fedora-18-Beta-TC4-x86_64-DVD.iso -usb -vga qxl -boot menu=on -usbdevice mouse
Steve: can you please open a new bug for the cases which still give invalid locales? The main bug here - that anaconda was just completely broken regarding locale setting - is clearly addressed, and overloading the report will only lead to confusion. Since what you're seeing now is effectively a new issue - anaconda now does actually try to do locale setting properly, but in a few cases gets it wrong - filing it as a new bug is the appropriate approach.
Bug 866730 - invalid locales configured for some languages
This was fixed in 18.13 and 18.14 went stable, so closing.
|
https://bugzilla.redhat.com/show_bug.cgi?id=858591
|
CC-MAIN-2022-27
|
refinedweb
| 3,939
| 58.48
|
Best Practices for Programming MATLAB 56
Posted by Loren Shure,
I thought I would share my top goto list of things I try to do when I write MATLAB code. And checking with other MathWorks folks whose code I admire, I found they basically used the same mental list that I use. You can find blog posts on all of these topics by selecting relevant categories from the right side of The Art of MATLAB blog site.
Contents
My List of Best Practices
Clearly (at least to me), this is not everything you generally need to do. You still need to comment the code, add good help information and examples, etc. But these are the main coding practices and tools I always rely on.
- Vectorize (but sensibly).
- Use bsxfun in lieu of repmat where possible.
- When looping through an array, loop down columns to access memory in the same order that MATLAB stores the data in.
- Profile the code. I am often surprised about what is taking up the time.
- Pay attention to messages from the Code Analyzer.
- Use functions instead of scripts.
- Don't "poof" variables into any workspaces. Translation, don't use load without a left-hand side; avoid eval, evalin, and assignin.
- Use logical indexing instead of find.
- Avoid global variables.
- Don't use equality checks with floating point values.
Missing from Your List? Additions to My List?
What's on my list that you don't currently do? Do you have a major addition to my list (there can't be too many, or I won't remember to do them all!)? Let me know here.
Get the MATLAB code
Published with MATLAB® 7.13
Note
56 CommentsOldest to Newest
Here’s the biggest thing you missed:
Pay A LOT of attention to code clarity and code design. In 97% of the code you write, tiny improvements in execution speed don’t matter, and yet you (and your colleagues/coworkers) will spend 10-20 times as much time reading your code as you spent typing it.
Having recently moved to a MATLAB environment from other scientific scripting environments, I am stunned by the lackadaisical attitude MATLAB programmers seem to have to code quality from the point of view of legibility and clarity of thought expressed in code through good design. At the same time they frequently reject some well-established software engineering best practices on the grounds that they may cost microseconds in execution time.
The hardware that runs MATLAB now is roughly 100,000 times faster than when MATLAB was first released. Software development practices have changed to recognize the fact that programmer time is vastly more valuable than machine time in almost all cases. MATLAB programmers seem to be behind the curve in realizing this.
JamesL-
I agree with you on writing for clarity, esp. if the speed isn’t horribly impacted. I don’t know a tool to specifically reinforce that though – in looking for specifics, I believe profiling and vectorize sensibly cover the intent of what you are saying, but without the background you provided. Thanks for sharing.
–Loren
That’s a nice list. One more I think about:
Does the code deal with corner cases gracefully? What if a) one or more dimensions of an input array are of length 1, or b) some inputs are Inf, NaN or complex?
I have an assortment of more thoughts embedded in a more general document that’s far too long for your short list criterion:
Thorough error checking of function input parameters is one of my best practices. By using inputParser and assert(), you can provide future users some guidance at least on the form of variables that are provided as inputs.
This is true throughout the rest of the function as well. I try to explicitly check for as much a priori information as I can. When assertions fail, provide useful information regarding the assumption.
Iain-
Yes, all your items are important for creating robust code. It’s very hard to keep the list small, as you said.
–Loren
Eric-
Yes, error checking is usually important. Interestingly, I have found cases where the error that would occur without checking explicitly was quite clear.
–Loren
instead of doing,
for k=1:N,
array(k)=k;
end
implicitly pre-allocate array by
for k=N:-1:1,
array(k)=k;
end
“Use bsxfun in lieu of repmat where possible. “
This one is new to me, can you explain why, and how it’s used?
I like the pragmatic theme of today’s post, by the way.
Use unit tests (the earlier the better) and use the Profiler to make sure that every line of code gets exercised.
I’m curious why you prefer functions over scripts. I find that scripts allow me to do things that I cannot do in a function such as have access to all the data created within the script once the script has finished executing. With a function, once the function is finished, the data is gone. Sometimes that’s desirable, other times it’s not.
Loren,
thanks for a nice and suitably short list. There were a couple of best practices that I was not aware of:
2) Using bsxfun in stead of repmat. Do you have any example of when bsxfun is better than repmat? What can be gained in terms of processing time / memory usage?
10) Not checking for equality with floating point values. Could you give an example here, too? I may be guilty of doing this quite often, since the default class in Matlab is double (floating-point).
Hi Loren,
Best wishes for 2012! Very interesting post, thank you. A few comments I might add from my own experience..
Additions to Loren’s list:
1) As multi-function projects get larger & more complex, coding standards & best practices must be applied ever more rigorously.
2) When developing class hierarchies : plan on several development generations & much refactoring before stable, high-quality code is achieved.
3) Within all function M-files : use Hungarian Notation prefixes or suffixes to clarify variable types.
4) Always step through newly-written function M-files & visually check values of every single variable, via datatip, command-line, or Variable Editor.
Qualifications to Loren’s list:
7. Don’t “poof” variables into any workspaces. (unless meta-programming is an integral part of your project design; example upon request)
8. Use logical indexing instead of find. (unless you explicitly want to generate a vector of non-zero indexes)
any comments appreciated,
brad
Thanks, Loren! A valuable list which should be considered by all Matlab users and developers. Some additions – there is no reason to keep the list small:
* Documentation is required to make a working function usable.
Inputs, outputs and the applied procedure must be explained.
Because bugs are everywhere changes of the code must be accompanied by a version history. Without documentation it is impossible to reuse code for other projects.
* Create a unit-test function, which compares the output of the function with a set of known answers. Automatic unit-tests are more powerful than manual tests, because they can run reproducible after each bug fix and when a new Matlab release is used.
* Keep it simple stupid.
This is one of the rare cases, where D.E. Knuth and Conan the Barbarian agree.
I’m still amused by this line from SAVEPATH:
mlr_dirs = cellfun(@(x) ismember(1,x),strfind(dirnames,mlroot))
How funny. What about:
mlr_dirs = strncmp(dirnames, mlroot, length(mlroot));
* program time = design time + programming time + debug time + runtime
Pre-mature optimization of speed will have negative effects to the debug time. A bad design increase the programming time due to necessary refactoring. Spending an hour to save a milli-second of runtime matters, if the program runs more than 3.6e6 times.
11 Disable the Code Analyzer. The code analyzer frequently advice’s you to micro optimize your code not considering the impact on the readability. If you don’t disable it your left with the following bad options:
A Do the optimization and make your code less readable for almost no speed improvement.
B Clutter your code with %#ok
C Ignore the message and let the code be cluttered with underlines easily masking more serious errors such as syntax errors.
Two things come to mind:
1. Don’t get too buried in the code to think about the algorithm and how it can be improved. If you don’t step back, it’s all too easy to write things like sqrt(v) < r when v < r.^2 could be a lot faster if v is a big vector.
2. Try to make your code as general and reusable as possible. (Writing functions rather than scripts is an aspect of this.) This may mean splitting up big functions into smaller ones, making sure that all cases are covered, thinking about whether the arguments give the user all the control they might want, and providing good documentation always.
Loren,
in keeping with reply # 1, my main addition would be that LOTS of comments are good. When I come back to see a routine, a year later, even with lots of comments I sometimes wonder what a particular snippet was for.
And altho’ I agree that “poofing” (is that a standard term?) is not good, I do not know for sure how to do the equivalent of putting a left-hand-side in the code or on the command line when I do an “import data,” other than a comment line.
good stuff, all, and thanks
tony
My list is basically the same, except I also add:
Comment! If I vectorize for speed and it makes the code hard to read I often leave the original, non-vectorized code as a comment (highlight, ctrl+r). This gets the best of both worlds. Anyone reading the code then sees what the vectorized version was meant to do and can uncomment the simple code for debugging or whatever purpose. Other than that, spending the time to comment every step or block can save much time later when performing maintenance, even if it is me looking at my own code. Comments are free, be generous with them.
Test! Depending on how critical the code is, I will spend significant time trying to break it by doing dumb things to the code. Passing in the wrong types of variables, or doing things out of the expected order (especially important for GUIs).
Help! Always spend the time to write good, clear help. This helps the user know (remember) what the code does, even if it is me!
Don’t Mask! Pay attention when assigning variable (and function M-file) names such that built-in functions are not overwritten.
Thanks for all the great feedback. I will only address a few items, at least right now.
1) why a short list? because people need it in their heads, I believe. I don’t think most people have incorporated consulting long lists as part of most of their processes.
2) for bsxfun, please see posts in the vectorization category. At least 2 talk about bsfux.
3) similar to #2, please see the category about numerical accuracy for the issues relating to comparing floating point numbers.
4) functions generally execute more quickly than scripts because they have a contained, known workspace and can be more fully analyzed by the language machinery.
Thanks again!
–Loren
Loren-
Thanks for the thoughtful list. A blog that triggers 17 (and counting) responses is on target.
Your list concentrates on coding practices (8 of 10 items). Many of the responses suggest development practices (test, document, etc). My experience in interacting with over 100 MATLAB users a year is that they are interested in and benefit from both.
Of course you know where my favorite list is…
-Richard
This comment is not exactly “code performance” related, but the importance of clearly named variables/functions should not be overlooked. In my code I try to prefix variable names in a way that makes it immediately obvious what the variable contains. Here are some examples:
(1) Use an “n” or “m” in front of a variable name that stores the number of “things”:
i.e. nRecords = length(recordData);
[nRows,nCols] = size(dataArray);
(2) Use an “i” (or “j” or “k”) in front of a variable name that is incremented in a for-loop to make it clear what the loop is indexing through:
i.e. for iRecord = 1:nRecords
recordData{iRecord} = …;
end
(3) Use “is” as a prefix for logical arrays:
i.e. isDetected = measurementData > threshold;
isInPolygon = inpolygon(x,y,xv,yv);
(4) Use “h” in front of variables that contain handles:
i.e. hAx = axes;
hFig = get(hAx,’Parent’);
Also, it is extremely useful to attach unit identifiers to variable names to avoid (potentially disastrous amounts of) confusion. I like to use an underscore to separate the variable name from the units for clarity:
i.e. elevationAngle_deg = …
terrainHeight_ft = …
vehicleSpeed_mps = …
I love this – great post!
What is your thought on using try/catch – and where would you caution people against using it?
I have my own thoughts – but I would like yours :)
Richard, Joseph, and Sarah,
1) Thanks Richard. Indeed I was focusing primarily on actual coding and not the rest of the development process. That is, of course, a very important topic and your book addresses it well.
2) Joseph- I agree about having good naming conventions. Exactly how to agree on conventions can be difficult. I prefer MixedCase or camelCase vs. using an extra character with _ generally, for example. Others don’t share my aversion to _!
3) Sarah-
I like and think try/catch should be used in general. It didn’t make my top list because… not sure… maybe because I am not sure most people are writing code that needs to be robust to the extent of supporting a large group of users. Also, it may be richer than they often need. Sometimes simply issuing an error is enough. Only if you have to do something special after the error is try/catch *required*. If used, I believe it’s best used with the MException syntax. What do you think?
–Loren
Great post, Loren!
@Joseph, I was reading your list, and I noticed that I have the exact same convention as you have.
I agree with many of these points. The one that resonated with me was about error checking. Aside from demos, I tend to create utility functions, so I always make sure that I have solid error checking, using functions like “assert”, “inputParser”, “validateattributes”, and “validatestring”. Writing extremely detailed help is another thing I do. Especially if I’m creating a class, I make sure I format it appropriately so that the HELP/DOC commands will render it correctly.
For #7, what do you think about the following form of load which specifies what variables are appearing in the workspace?
load(‘my_file_name.mat’, ‘myVariable’); % No poof!
Great blog topic. Would love to see a future one on best practices for managing a code project in Matlab, such as many linked functions to do a complicated analysis task.
11. Organize functions into packages or classes when a work directory gets too large, or lots of “helper” functions start appearing.
For other languages, that probably wouldn’t need menition. But I see some very ugly MATLAB directories, and frequntly run into namespace collisions when using code from others.
KE-
You are still poofing the variable. You never “see” it in the file until it is used on the right hand side as a variable. So I don’t care for that usage.
–Loren
Chad-
True, but not in my top group as in my experience, most users are not making large applications.
–Loren
Excellent practices and information from everyone so far. One thing I have done in the past that I try to avoid (mainly for my sanity):
o Do not use nested functions; use a driver function and subfunctions (and please close all of the subfunctions with “end”).
This is mainly to avoid accidental workspace collisions/overwrites from parent functions. And not closing all subfunctions with “end” is a just a huge pet peeve (thanks to the indoctrination of F90).
Troy-
I don’t happen to agree with you about never using nested functions. The shared workspace, when used correctly, can massively reduce memory needs for one. Also, the nested functions can have much simpler and more intuitive apis.
My $0.02,
Loren
Hi and many thanks for this post.
Could you please explain why one should avoid eval (#7)
Best,
Eleftheria
Eleftheria-
Please see these 2 blog posts, in addition to what I mentioned – it is “unfriendly” to have new variables showing up in MATLAB when they are not created from an assignment.
–Loren
Loren:
Hm, I never considered that, but it makes sense. I guess I’ve become spoiled with 8GB of memory at work.
And I guess the last time I’ve used nested function was for one of the largest projects I’ve ever done (an incompressible, 2D CFD simulation with a 200×200 grid). I’ll consider this in the future.
– Troy Haskin
With regards post
Loren, what you ideally want is a plugin architecture like Visual Studio whereby someone can write a ReSharper addin. Possibly one of the single most productivity and code-clarity beneficial addins I have ever used. Although the “beast of Redmond” is much derided I would urge any language developer to look at the functionality and usability of their IDE.
Hi Loren,
I have 2 questions related to your ‘best practises’
N°1: why do you recommend to avoid the use of Global variables, sometimes it is very convenient?
N°2 Remark:
I have the impression that we must pre-allocate the arrays at the appropriate sizes; I have seen in some functions things like the following example where the size of the array changes at each step of the loop
array0=[0 0 1 1];
For k=1:16
array1 =[array0 array0];
end
Even if it is convenient in some processing, from a point of view of clarity and efficiency I think it is better to make a pre-allocation before the processing
array=zeros(1000,1) for instance
What is your feeling?
I loved the tip about bsxfun; I had seen it once before and forgotten the name. Thank you! Now I’ve recorded it in my own tips and tricks.
Suggestion: we need nsxfun (“n-argument singlet expansion”) as well (or extend bsxfun to more than two args). Example of desired operation:))
(I mention a separate function because bsxfun is probably heavily optimized and already published and thus not to be redefined, although when I’m coding and add a new capability to a function, as long as it’s backward compatible I don’t define a new function)
Irl-
Please contact technical support and make an enhancement suggestion. It will be much more potent coming from you than me!
–Loren
Reply to Chaowei Chen
for k=N:-1:1, array(k)=k;end,
on my computer, the run time is 1/40 of the normal for k=1:N method, thank you for this very good code practice example.
Gaston-
I find Globals make programs very hard to debug, they do not generally change the memory characteristics of a program, the program has only one “state” so you can’t make it re-entrant. Generally using a nested function to contain such variables works better as it limits the exposure to who can tamper with the variables. Another great option, if you write your own classes, is to derive one, possible from handle, depending on what you are doing.
Preallocation is a great idea in MATLAB. MATLAB can be smart in certain ways and detect sizes, but otherwise the growth of an area can be both expensive in time, and wasteful of memory. So I agree about that. For me, preallocation is so obvious to do that I wanted to put things on the list the I may not remember to do.
–Loren
A very nice article, and very good to illustrate the difference between coding standard and best practice.
Here are a few of my examples
* For non native English speakers: Name your variables in English
* In general: Name your variables so that you recognize instantly what they mean after you have not seen the code for a whole year.
* comment is divine
* do not put different variables into one vector/matrix, whatever. It will become one big messy soup until you choke in a bite and you can start over from scratch.
* Do no use try and catch constructions. If you think they code might fail, you should change the code until you are sure it will always works. Only exception is file handling (pun not intended)
* There is no need to be careful for every single byte these days, but be conscious of memory usage.
Thanks for everyone for the thoughtful comments.
–Loren
Loren —
Done! request no. 1-H8XTUR.
–Irl
Thanks, Irl!
In response to post 12. point 8. on acceptible uses of find for creating a list of indices. I find it much faster to create logical indexing and then use find on the logical index array to get the list.
%logical indices (very fast)
idxLow = X > minRange;
idxHigh = X < maxRange;
idx = and(idxLow, idxHigh);
%list of indices (very fast on logicals)
idx = find(idx);
In response to post 36 in reference to a fancy way of preallocating arrays in this manner
for k=N:-1:1, array(k)=k;end
This is cute and works because matlab must first create an array with N elements in it proceed with the rest of the loop. It would be much clearer to preallocate with acceptible preallocation functions like:
array = zeros(1,N); %Same speed as above
for k=1:N
array(k)=k;
end
array = linspace(1,N,N); %3.5 times faster
So, Loren I would add to your list a specific point opposite to vectorization; avoid using for and while loops where possible as in the example above. Do not use a For loop to create a range, use linspace instead.
Loren, a great post as always!
The tip I’d add to this list is make sure your code is formatted nicely with breaks, tabs, and clear variable names. I frequently help to resolve issues that arise because people don’t bother with formatting and the order of desired operations in complex functions gets accidentally mangled.
I typically use “if/else & error” instead of “try/catch” because I write code used by a small core of people, and if it doesn’t break entirely, I won’t hear about edge cases that are malfunctioning. When edge cases arise that I anticipate but don’t have test data to implement with, then I can solve the issue efficiently by adding the required functionality on the spot. I also try to make code noisy when it breaks.
I follow the “Rule of Repair”: When you must fail, fail noisily and as soon as possible. () I think that most people should read “the art of unix programming” when learning to program. It’s free, tremendously insightful, and fun to read.
Hans:
There are several reasons to use functions instead of scripts. First, they don’t have unintended side affects (when combining scripts, variable names can collide). Second, data and flags are explicitly passed back and forth, with temporary variables getting cleared out of memory automatically. Third, the code can be compiled more efficiently because of the variable name issue (it knows where data is coming from, rather than having to check if a variable exists already and what the type is).
Since functions define the inputs and outputs, it also easier to reuse the code, since you know where things are coming from and going to. Likewise, if you start to document things with comments, the code will have it’s own documentation. You can also encapsulate required sub-functions so that the code is easily portable across systems.
Loren,
Sometimes its diffucult to avoid globals but I understand the need to avoid them.
“Poofing” has certainly caused me problems in the past. I appreciate you listing this one. Poofing also makes it difficult for others to follow the original author’s code.
I love the Profiler but sometimes the code is so fast that profiling is unnecessary.
I must admit that my biggest surprise came from the comments.
There seems to be quite a bit of concern with regards to programming / development time. One of the main reasons to purchase MATLAB/Simulink is that programming / development time is so much less than that of other languages especially when graphics are concerned. There is really no other SW product on Earth that can do so much so easily. If there was, the MW would not have been as successful as it has been for almost 30 years.
I have developed MATLAB applications and Simulink models professionally for 16 years and it has been my experience that the actual development time is barely significant when compared to the amount of time spent on the design of the SW (what shall the SW do), drafting the SW requirements and the inevitable changes to the requirements that come during code development.
Legibility and clarity come from the author’s comments as well as from his/her code but copious comments ought not affect development time that much.
Eddie
I started writing source code in about 1972 and I have written in FORTRAN, Pascal, Basic, C, C+, and others. First, I would like to say that Matlab is the best of the high order languages that I have used. I have also written coding standards for the Air Force for FORTRAN and for Matlab in the current company where I work. What I notice mostly about the best practices listed here is that there is a lot missing. I am not going to try to list all of the standards that I follow, but a few of them might be of interest.
Naming conventions: 1) all functions begin with a capital letter; 2) all parameters and variables begin with a small letter; 3) I prefer a capital letter to separate parts of the name, the underscore just adds unneeded length; 4) select a set of standard units that are to be used throughout the code and change the input units to the standard units at the input function(s) and change the standard program units to the desired units at the output function(s). Do not change units within the program; 5) global should only contain constant values. The global values are the parameters for the model and should be set in a function that defines the meaning of the values as well as setting the value; 6) Along with the use of parameters, never use a real number inline in the code, these are referred to as magic numbers and often difficult to locate and update when changes are needed; 7) Every function should (read must) contain a header consisting of the following information: the purpose of the function, complete description of all input arguments (including units), complete description of all output arguments, the function author, and the version number and date. If the function is complex, then a reference describing the algorithm is preferred.
These are just a small part of the standards that I enforced on my programmers both here and Los Alamos National Labs regardless of the programming languages that were used at the time. There is much more, but I am not going to try to put all of this in the comment. I hope this is interesting to some one.
I find that using globals when I optimising a simulink block parameter in a function is faster though dirty. This is partly due to legacy when I was using the fmins program. I think the ideal solution today is to map the workspace. Are there any easy methods?
One more addition that came to mind this morning.
There is a often a balance between performance and memory usage, facing programmers. I have bought 24 GB of memory for an equivalent of less than a week’s rent of my apartment. The processor I have bought 3 years ago still costs more today.
If you can improve performance by using more memory… do so.
(a) Distinguish carefully — in your mind, and then in the typography — between entities that are allowed to change (dynamic objects with handles) and those that aren’t (“constants”). I generally use ALLCAPS for the constants. If you’re writing a library function for lots of other people to use, you had better not change their objects without warning them!
Lesson: All input arguments should be assumed to be constants until proven otherwise, or unless documented otherwise. For general-use functions, the fact that you don’t think of an array, a string, or a file as a constant is none of your business — it belongs to the user/caller, not to your function, unless you document that it will change. (Yes, I typically write all non-handle input arguments in ALLCAPS, for exactly this reason.)
Refinement: MATLAB will help to manage this when changing arguments that have built-in non-handle types, such as numerical arrays. But it will do so by copying the entire object, possibly exhausting memory. If you rely on this behavior (the nice semantics of MATLAB), you should probably make it clear to the person reading your code later: You are creating a copy of the array, with some different values. That will take time and use memory, and the original values of that array will no longer be available in the code, even if the code-maintainer later decides that they are needed. (Best practice: Never change the value of an input argument. Just use a local variable for the changed version of the argument.)
(b) Be careful about capitalization: Unlike MATLAB, people are NOT case-sensitive — or rather, we use it for much more sophisticated things than simply distinguishing between distinct entities.[*]
So someone trying to understand your code in 6 months may notice the difference between “a” and “A”, which have very different shapes. They may not notice the difference between “s” and “S”, nor between “YourCasedVariableName” and “YourCasedVariablename”. (BTW, in my experience, they will notice underscores.)
Lessons: Use the editor display/MLINT to flag variables that aren’t used. (Maybe you mis-capitalized something?) And don’t depend too much on subtleties like capitalization to keep things straight in the minds of people reading your code later!
[*] Notice that my surname has a capital letter in the middle of it. It does not distinguish me — legally, or any other way — from anyone who uses different capitalization. Rather, it conveys information about my heritage.
What best practices do people have about using structures?
I am reading people’s code where they set a field of a structure in one place, and then set another field of the same structure somewhere else, and then again somewhere else, and by the end of the program I have little idea which fields the structure has ended up with. So I try to pre-initialize structures that I will be building up by doing
s = struct(‘field1’,[],…
‘field2’,[],…
…
);
In general, I like the struct statement better than
s.field1 = [];
s.field2 = [];
…
s.fieldn = [];
Tom-
I don’t have any that go on my highest list, as you saw. But I have written several blog posts on aspects of structs. You might find some good tips in them
–Loren
Loren can you explain why we can’t put a function in a script? I find it convenient for initial development to have your top level main be a script but then I often want to have a function in it and am forced to make the annoying choice of functionalizing the main or putting the function in a separate file.
Jeff-
It’s simply not currently part of the MATLAB language. It’s been requested before and we understand why. It’s something we continue to consider.
The other thing you could do is put your script into a function that doesn’t require any inputs, and have the associated function be a subfunction for the same file.
–Loren
I echo Tom Pressburger’s point — about both structures and arrays (cell or otherwise). Augmenting a structure with new fields, or an array with new lengths (along one or more dimensions), multiple times scattered throughout a function is a recipe for code that is difficult to understand and difficult to maintain. If you can, define those fields or lengths at the beginning.
I am learning Simulink and it appears to violate many of these recommendations. For example, the default is to fill your workspace with every variable the model will use (this could be hundreds, with no way of tracking them). It is hard to execute a Simulink model from within a function rather than from within a script. It seems like you end up using evalin a lot when scripting. Do more experienced Simulink users find this to be the case?
@KE – Many years ago, Simulink was limited to storing data only in the base workspace. Recent releases of Simulink have addressed these issues by creating model workspaces and enabling management of all data through the Model Explorer. Executing a Simulink model from within a function can still be a little awkward, but it is possible to specify the source workspace as the ‘current’ to access variables within the function. I think these capabilities greatly improve the ability to manage data within Simulink. Most experienced Simulink users have an overall strategy for data management, and for data shared across model references, such as bus objects or global data objects, the base workspace is used.
|
https://blogs.mathworks.com/loren/2012/01/13/best-practices-for-programming-matlab/
|
CC-MAIN-2018-13
|
refinedweb
| 5,667
| 62.27
|
I’m looking to parse CSV files containing multiple tables using Python3’s
csv module.
These complex CSVs are not unlike the toy example below. My goal is to make an idiom for picking out any one table using a known header row.
Complex CSV file
toy.csv:
lists, fruits, books, forks, rope, gum 4, 2, 3, 0, 2, 2 Manhattan Produce Market id, fruit, color 1, orange, orange 2, apple, red Books id, book, pages 1, Webster’s Dictionary, 1000 2, Tony the Towtruck, 20 3, The Twelfth Night, 144 Rope id, rope, length, diameter, color 1, hemp, 12-feet, .5, green 2, sisal, 50-feet, .125, brown Kings County Candy id, flavor, color, big-league 1, grape, purple, yes 2, mega mango, yellow-orange, no
Each table is preceded by a title (except for a garbage table at the start). I save the previous row, and when I match the correct table header, I add the title as a new column.
import csv, re header = [] #doesn't need to be list, but I'm thinking ahead table = [] with open('toy.csv', 'r') as blob: reader = csv.reader(blob) curr = reader.__next__() while True: prev = curr try: curr = reader.__next__() except StopIteration: break if not ['id', ' book', ' pages'] == curr: continue else: header.append(prev) table.append(['title'] + curr) while True: try: curr = reader.__next__() if curr == []: break else: table.append(header[0] + curr) except StopIteration: break
The first part is to make an idiom which I can simply repeat for each table I want to extract. Later, I will combine the tables into one super-table filling NANs where the table headers don’t match.
[['title', 'id', ' book', ' pages'], ['Books', '1', ' Webster’s Dictionary', ' 1000'], ['Books', '2', ' Tony the Towtruck', ' 20'], ['Books', '3', ' The Twelfth Night', ' 144']]
This is my first post in Code Review (I hope I’m asking an appropriate question). The code is based on a SE post, How do I match the line before matched pattern using regular expression.
Happy to hear your suggestions to make the code more compact, idiomatic, and fit for my!
|
https://extraproxies.com/parse-one-table-out-of-csv-with-multiple-titled-tables-with-python-csv-module/
|
CC-MAIN-2022-40
|
refinedweb
| 350
| 72.05
|
On Thu, 2008-01-17 at 19:59 -0500, H. Peter Anvin wrote:> Harvey Harrison wrote:> > > > Sorry, missed that detail in ptrace.h, I notice now.> > > > Is there some better way this could be organized, would the following> > be an improvement, as opposed to two long ifdef sections?> > > > Patch will follow if you think it's a good idea.> > It is actually quite a bit easier to read.I'll send along a patch along soon, any thoughts on how to order it inthe file?> > > > > static inline unsigned long stack_pointer(struct pt_regs *regs)> > {> > #ifdef CONFIG_X86_32> > return (unsigned long)regs;> > #else> > return regs->sp;> > #endif> > }> > This one is kind of strange. In particular, the 32-bit definition isn't > exactly what one would expect. It makes me concerned that it actually > refers to two different kinds of stack pointers?This tripped up the kprobes unification as well, see the stack_addr()helper that was introduced there. Would be good to figure this outand put a big fat comment on it.kprobes.c#ifdef CONFIG_X86_64#define stack_addr(regs) ((unsigned long *)regs->sp)#else/* * "®s->sp" looks wrong, but it's correct for x86_32. x86_32 CPUs * don't save the ss and esp registers if the CPU is already in kernel * mode when it traps. So for kprobes, regs->sp and regs->ss are not * the [nonexistent] saved stack pointer and ss register, but rather * the top 8 bytes of the pre-int3 stack. So ®s->sp happens to * point to the top of the pre-int3 stack. */#define stack_addr(regs) ((unsigned long *)®s->sp)#endif> > /* still need a define here, as one is long and one is unsigned long.> > * but this is another target for unification I guess. */> > #define regs_return_value(regs) ((regs)->ax)> > Indeed...I think this comes out of Roland's patches unifying some names eip/rip,eax/rax, etc.CC'd in case he felt like more work ;-)Harvey
|
http://lkml.org/lkml/2008/1/17/518
|
CC-MAIN-2017-43
|
refinedweb
| 318
| 75
|
First time here? Check out the FAQ!
Steps to be followed to make it run:
1.Install open stack RDO with neutron enabled.
2.Create ifcfg-br-ex interface on compute node/neutron node:
3.If your open stack server (compute node/neutron node) is VM in ESXi set the promiscuous mode on ESX vSwitch.
problem solved..!
As compute node itself is a virtual machine residing on ESX server need to enable promiscuous mode on Esxi virtual switch.
Thanks
following are the links i am following to add network namespace and dkms.Then will lead to devstack installation.
pl let me knw if any other precise way to do this.
Is it because network namespace issue..? As i am using centos 6.4 + devstack setup.And found that it does not support network namespace required for smooth working of open stack neutron service.
@dheeru,
thanks for the replay, by checking above link I see it will be very useful documentation for all who are new to open stack and wants to make their things run.Waiting for it completion.
In mean time plz let me know if any other links can be followed to make this things run.
Thanks
Hi All,
I am using centos 6.4 (virtual machine installed on ESX server) to install open stack (devstack),with single node setup(All in one).
Centos on which open stack is installed have only one NIC card. (eht0).
1. I install neutron service to this setup,
2.created public and private network , and routed them together following instruction given in user guide.
3.added security rules to pas tcp/icmp traffic to the instance, and added keypair to ssh it from outer world.
4. assigned private and public (floating ip) to the open stack instance (cirros).
what i found is, i am unable to ping the instance (with both private and floating ip) from centos on which open stack is installed, neither i can ssh to it as it ends with error message 'no route to the host'
My question is i sit because of single nic card (eth0) present on my centos causing me this issue..?
Is there any workaround for this problem..?
Any feedback will be very helpful.
Thanks..
even i am facing the same issue.
any feedback will be very helpful.
While launching instance on devstack hawana (single node setup) using fedora qcow2 image,it fails to start open ssh server daemon and LSB bring up/down networking.
Allowed tcp/icmp rules in security group still not able to ping private or floating ip.
Any feedback will be helpful.
OpenStack is a trademark of OpenStack Foundation. This site is powered by Askbot. (GPLv3 or later; source). Content on this site is licensed under a CC-BY 3.0 license.
|
https://ask.openstack.org/en/users/2482/mithun/?sort=recent
|
CC-MAIN-2019-43
|
refinedweb
| 462
| 76.01
|
This project is archived and is in readonly mode.
Python freezed binary cannot use psycopg.so
Reported by Christian Bachmaier | March 25th, 2014 @ 09:13 AM
I use psycopg2 2.4.5-1buidl5 under Ubuntu 14.04 LTS x86_64. After pachting Python 3.4.0 final as described under to work again since Python 3.2 under Python 3.3 and 3.4 I can sucessfully freeze my Python cgi project to a binary with the in Python included Tool freeze.py command.
However, a freezed script hello.py containing only the one line
import psycopg2
does not operate, since it does not find the psycopg.so library. It delivers after execution:
Traceback (most recent call last): File "hello.py", line 18, in <module> import psycopg2 File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2214, in _find_and_load return _find_and_load_unlocked(name, import_) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 2203, in _find_and_load_unlocked module = _SpecMethods(spec)._load_unlocked() File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1200, in _load_unlocked self._exec(module) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1129, in _exec self.spec.loader.exec_module(module) File "/usr/lib/python3.4/importlib/_bootstrap.py", line 1336, in exec_module exec(code, module.__dict__) File "/usr/lib/python3/dist-packages/psycopg2/__init__.py", line 67, in <module> from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID._psycopg'
In Python 3.2 it helped to create a link
_psycopg.so -> /usr/lib/python3/dist-packages/psycopg2/_psycopg.cpython-32mu.so in a subdir psycopg2 of the current directory of the execution of the freezed binary.
The same issue is on Python3.4r2 under Debian Wheezy/Sid.
Daniele Varrazzo March 25th, 2014 @ 09:29 AM
It doesn't seem a psycopg bug to me: it seems a freeze problem. We just provide a
setup.pyfor the Python toolchain to build. Or is there anything we have to change in
setup.pyto support new features?
Daniele Varrazzo March 25th, 2014 @ 09:34 AM
- State changed from new to invalid
Taken a look at the above bug report. Closing as not a psycopg bug.
Christian Bachmaier May 14th, 2014 @ 06:40 AM
Adding
from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
to the top of psycopg2/__init__.py resolves the problem and the frozen binary works as expected. I had to learn this in a painful and time wasting way without any help from here or the Python bug databse :(
I am not quite sure if this is due to a flaw of Python/freeze as running in interpreted mode does not need it. At least the behaviours in interpreted and frozen mode should not be different. Or it is a bug of psycopg2. However, the above works in both modes. Other libraries like janitor or gi do already contain these lines.
Daniele Varrazzo May 16th, 2014 @ 09:29 PM
- State changed from invalid to open
from
extend_pathdocs:
"This is useful if one wants to distribute different parts of a single logical package as multiple directories"
This doesn't sound what psycopg wants to do. Could there be a way to adjust psycopg imports to make it compatible with freeze? This comment from M.-A. L. seems suggesting it is possible.
If you can fix psycopg by adjusting its imports but remaining in the realm of the canonical ways to import internal modules I'll be happy to apply the patch. If you want to see the patch applied in psycopg 2.5.x it must be compatible with everything between Python 2.5 and 3.4.
I'll leave the bug open for you but I won't be working on this problem: the ball is yours.
Christian Bachmaier May 17th, 2014 @ 05:18 AM
As far as I can tell, this is exactly as needed. Using debug outputs like
print(__path__) from pkgutil import extend_path __path__ = extend_path(__path__, __name__) print(__path__)
show that running in interpreted mode does not change the search path path of the package:
['/usr/lib/python3/dist-packages/psycopg2'] ['/usr/lib/python3/dist-packages/psycopg2']
So there is not any change for that at all. Everything stays as before.
In compiled mode path seems to be empty. See the link in my previous postings. The guys there told me that this is by design. Don't know why, this may be a bug in freeze if you are asking me. Hower running in compiled mode, the above code only adds the psycopg2 directory which contains the native so-library and which is there in interpreted mode. Then the native library can be found at runtime by a frozen binary.
[] ['/usr/lib/python3/dist-packages/psycopg2']
Other (similar built up) libraries use this code. Look at /usr/lib/python3/dist-packages/gi or .../janitor.
Fazit: The 2 lines fix the problem enitrely. There is nothing to work on, but to test with older python version and to put into the official code. Unfortunately, I can only test with 3.4 at the moment. Theoretically this should work also with older Python versions. But maybe the maintainer of psycopg have some testing installations?
Remember to use the fixed version of freeze (e.g. hg clone) as prior versions in Python 3.3 and 3.4 were broken.
Then it is easy:
$ /$HOME/cpython-xxx/Tools/freeze/freeze.py hello.py $ make $ ./hello
For your convenience I have also attached an archive with an operating version of freeze. So at least for 3.3 and 3.4 you need not to download it.
hello.py contains some code which uses psycopg2. Consiting only of a line
import psycopg2
already suffices.
Daniele Varrazzo May 19th, 2014 @ 01:59 PM
Christian, extend_path is not designed to fix freeze but for a different use case that doesn't apply to psycopg, so I'm very reluctant to add it. In the past I've been pyinstaller maintainer and I remember having no problem with psycopg. For what I (don't) know your solution may end up breaking other freeze solutions that currently work.
Please talk with freeze authors and have the issue fixed there. If we are doing our internal imports wrong I'm ready to change every single one of them, but I'm not happy to add a call to a function that I don't know what it does and the docs say it's not for our use; the fact two packages I don't know anything about do the same is not enough for me to accept it as a quality solution.
Daniele Varrazzo August 25th, 2014 @ 10:43 PM
Christian, I've taken a look at your problem.
Freeze cannot freeze psycopg just because it cannot work with C extension. This should be enough to rule out what you want to do. I've taken a look at why adding the unrelated hack of
extend_path()work: it works just because it finds an externally available
_psycopg.so, however we don't want to distribute psycopg "as multiple directories": that's not for us.
Note that using absolute or relative imports doesn't change anything. However we will likely move to relative imports as they are the right thing and we don't target Python 2.4 anymore.
In order to solve your problem you can add an import hack into your frozen application:
sys.path.insert(0, '/path/to/psycopg2') import _psycopg sys.modules['psycopg2._psycopg'] = _psycopg sys.path.pop(0) # this will now work import psycopg2
so you can ship
_psycopg.soin a separate directory together with your frozen application and make it available before
psycopg2itself.
The above hack only works with a psycopg version patched with this changeset; without it importing
_psycopgwould fail because it would try to import
psycopg2.tz.
This is the best I can do for your issue. Please acknowledge that you are trying to use a tool designed to freeze pure Python modules: if it doesn't work for psycopg2 it isn't our fault and we cannot do much. Please test the workaround above: if it works I'll try and ship the patch in the next 2.5.4 release (it still needs some testing).
Christian Bachmaier August 26th, 2014 @ 03:31 PM
Daniele, thanks.
Your code sys.path Manipulation works with the version from
cd /scratch
git clone -b freeze
cd psycopg
python3 setup.py build
and using
import sys
sys.path.insert(0, '/scratch/psycopg2/build/lib.linux-x86_64-3.4/psycopg2')
...
Please let me know from which release version on the changes will be contained.
I assume that in init.py
from pkgutil import extend_path
path = extend_path(__path__, name)
does something similar, as many other libraries (see above) use that. The advantage is that the library does the trick then and not the user programm.
However, there should be a clean way. Either this is a bug in freeze or in psycopg2. I tend to say it is in freeze as the interpreted and compiled beavior should be identical. However, the freeze guys are not very amused about my opionion (). Maybe you could open a ticket?
Please acknowledge that you are trying to use a tool designed to freeze pure Python modules
The docu (I have found) says nothing about not supporting .so-files, nor the maintainer of freeze do, if I interpret them right (see above link).
Daniele Varrazzo August 26th, 2014 @ 04:05 PM
- State changed from open to resolved
Hi Christian,
I consider the refactoring I've made to _psycopg.so generally useful and I've tested it more yesterday. If there is no surprise from the test grid (with python versions I've not tested yet) I'll release soon, in the next 2.5.4.
Have another test: I suspect if
_psycopg.sois in the same directory of the executable you don't even need the sys.path hack, but I may be wrong.
The docu (I have found) says nothing about not supporting .so-files, nor the maintainer of freeze do, if I interpret them right (see above link).
Freeze doesn't support non-pure modules at all: read its docstring:
The script should not use modules provided only as shared libraries; if it does, the resulting binary is not self-contained.
so, that's what happens. Freeze doesn't freeze the .so, but the resulting executable can still use them if it finds them, i.e. with the regular python importing machinery. It's up to you to make the .so available to the exe. I've fixed psycopg2 so that the .so can be imported outside the package and that's about what I can do to help whatever program needs pythonpath hacking. But you are really asking too much to freeze: other programs are better suited to create executables out of non-pure modules (e.g. pyinstaller).
Closing the bug. Have a nice day.
Christian Bachmaier August 26th, 2014 @ 04:15 PM
Have another test: I suspect if _psycopg.so is in the same directory of the executable you don't even need the sys.path hack, but I may be wrong.
Unfortunately, this does not work, even not if _psycopg.so is in a local subdirectory psycopg. The latter worked with python 2.7 and its freeze.
214 Python freeze does not like psycopg2 I have added a comment with an solution to the (premature...
214 Python freeze does not like psycopg2 I have added a comment with an solution to the (premature...
|
https://psycopg.lighthouseapp.com/projects/62710/tickets/201-python-freezed-binary-cannot-use-psycopgso
|
CC-MAIN-2020-50
|
refinedweb
| 1,918
| 68.26
|
Is there any shortcut to copy the path of the current directory in Total Commander?
Also, is it possible to select or highlight the address bar with a keyboard shortcut?
You can indeed copy the path of any file or folder you are viewing in any of the panes.
CTRL+P will add the current directory path to the address bar.
You can also get individual files' paths. Select the files you want to get the path from, click
Mark > Copy Names With Path To Clipboard.
Mark > Copy Names With Path To Clipboard.
You can even add a new button to the toolbar which activates this command if you use this function very often. Add a new button to the toolbar, and assign it this command: cm_CopyFullNamesToClip
cm_CopyFullNamesToClip
Another option for easy access is to map a custom keyboard shortcut to this function. This is done in
Configuration > Misc.
Configuration > Misc.
As for a shortcut to focus on the command line, there is no built in shortcut to do it, but you can again assign a new button or keyboard shortcut to the command cm_FocusCmdLine, which takes you from wherever you are straight to the command bar, selecting its whole content.
cm_FocusCmdLine
Home, then Shift+F6.
As molgar / randy-skretka said, and also Ctrl+P but use Shift+← and Shift+→ to go to command line and cut with Ctrl+X.
because that also works in Brief and Thumbnail View 'mode', not only in Full (extra: see available modes with Shift+F1).
Is there any shortcut to copy the path of the current directory in
Total Commander?
Is there any shortcut to copy the path of the current directory in
Total Commander?
Ctrl+P and then ← OR → (arrow keys) to copy the current directory to the command line and then select it for you. Then just Ctrl+C copy.
Also, is it possible to select or highlight the address bar with a
keyboard shortcut?
Also, is it possible to select or highlight the address bar with a
keyboard shortcut?
Use your Home key to put you over the [..] notation at the top of the directory listing. That's the parent directory. Then use Shift+F6 to focus on and highlight the address bar (edit it if you need to!).
shift+F6
ctrl+f6
←
→
Ctrl+F1
Shift
A good hack is using:
Configuration>Options>Misc>Redefine hotkeys.
Now you can add Control + L
and in Command select cm_EditPath
pressing Control+L will select the path just like Firefox, Explore (in windows 8), Dolphin, Nautilus, ...
I don't think there are keyboard shortcuts to either of the functions.
A list of TC hotkeys can be found here:
There is a way to create custom hotkeys for functions in TC (for all available commands) or even for custom commands. Information can be found here and here. You may be able to create your desired shortcuts there.
What about a 1-click solution? It's using Python (which is great for so many reasons):
pip install pyperclip
Write the following short script and save it as a .pyw file:
.pyw
'''
Run from TC's button with a "%P parameter (not "%p)
It will pass the current path into the clipboard
'''
import sys, pyperclip
pyperclip.copy(' '.join(sys.argv[1:]))
"%P
"%p
"
wcmicons.dll
From now on, whenever you click on that button, the full path to your current panel's directory will be copied into the clipboard!
If you want to copy only Path witout names you should assign command cm_CopySrcPathToClip to button
I think ctrl-d is what you wanted, then you can use ctrl+c to copy the path.
A solution with bat instead of python:
cmd /c echo
%P | clip
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
19905 times
active
2 months ago
|
http://superuser.com/questions/387833/copy-current-path-to-clipboard-or-select-address-bar-in-total-commander/533754
|
CC-MAIN-2016-22
|
refinedweb
| 643
| 71.95
|
workbook containing worksheet with space in name and print titles fails to open
Attempting to open a workbook that contains any worksheets with a space in the name and a print title will result in an error as below: (Python 3.5, Openpyxl 2.4)
Traceback (most recent call last): File "C:/Users/user/pythonProjects/testproject/testpy/tester.py", line 5, in <module> EngineerMetrics = ox.load_workbook("book1.xlsx", data_only=True, read_only=True) File "C:\Users\user\AppData\Roaming\Python\Python35\site-packages\openpyxl\reader\excel.py", line 245, in load_workbook parser.assign_names() File "C:\Users\user\AppData\Roaming\Python\Python35\site-packages\openpyxl\packaging\workbook.py", line 79, in assign_names rows, cols = _unpack_print_titles(defn) File "C:\Users\user\AppData\Roaming\Python\Python35\site-packages\openpyxl\workbook\defined_name.py", line 48, in _unpack_print_titles return m.group('rows'), m.group('cols') AttributeError: 'NoneType' object has no attribute 'group'
It took a little bit to isolate, attached is a workbook that will demonstrate the issue.
With a workbook containing a "Sheet 1"
def _unpack_print_titles(defn): """ Extract rows and or columns from print titles so that they can be assigned to a worksheet """ m = TITLES_REGEX.match(defn.value) # defn.value = '\\'Sheet 1\\'!$A:$A,\\'Sheet 1\\'!$1:$1' return m.group('rows'), m.group('cols')
With a workbook containing Sheet1
def _unpack_print_titles(defn): """ Extract rows and or columns from print titles so that they can be assigned to a worksheet """ m = TITLES_REGEX.match(defn.value) # defn.value = 'Sheet1!$A:$A,Sheet1!$1:$1' return m.group('rows'), m.group('cols')
Thanks for the report and the sample file. Looks like we might want remove the escaping from and titles before we extract them (Excel needs the escaping but conceals it). Or, I could just disable this feature! ;-)
I think we do have a regex that can find the titles more reliably.
Looking deeper at the problem it looks like it is related to the order of the titles with columns preceding rows here.
Fixed in 2.4 branch
This isn't really solved. I have titles with space in the first character.. could you check Charlie?
Your post yesterday actually referred to the print area and would be a separate issue. The problem will only be resolved for print titles if you're working with a checkout.
Could you explain better? I'm not a excel expert hehe
The issue tracker is not designed for chat. Please follow the procedure in the documentation for using a checkout and submit questions to the mailing list.
Issue
#709was marked as a duplicate of this issue.
I have the same error, but it is not because of a space in a title. I created fake excel sheets to test that was not the issue. Can you please advise, @charlie_x if you are recommending to checkout your branch for the fix?
@Jess_C Yes, the description is misleading and you will need to work with a checkout.
I am not sure I understand this correctly. I had opened the issue
#709, which was marked as a duplicate of this issue. It has been fixed in branch 2.4 and I have the version 2.4.0 installed and this bug definitely exists in that branch.
You are recommendation is to use a checkout of that branch, but I have deployment scripts written and I would really like to use pip instead.
Any idea when this fix would go on to the version at pip?
Hi Charlie,
I didn't see a fix for the Print Titles issue in the default branch, so I forked and submitted a pull request #150 with my hack-fix; I don't like how I handled the second SHEET_TITLE reference so I'm willing to work on it if you have a suggestion.
Removing version: 2.4.x (automated comment)
|
https://bitbucket.org/openpyxl/openpyxl/issues/690
|
CC-MAIN-2020-24
|
refinedweb
| 636
| 67.45
|
Your
I want Capture a Window ex: Internet Explorer or any software. Can you help me! Thank you!Reply
How can i use this application for sharing my desktop with other remote users?Reply
as u used win api for screen capture?what abt linux? another thing is that how i can capture remote screen?Reply
Originally posted by: V.srinivasan
Is there a way we can simulate windows action? Can I enter spcefic values into the screen, simulate mouse actions and read contents of the screen using these dlls?
please let me know
thanks
-Srini
Originally posted by: Rasha
Is it possible to send the captured image over a LAN using socket programming?? please we need to know this piece of information urgently...& if the answer is yes could u tell us how ?
& thank u in advance...:)
Use TcpClient and Tcp Server Classes in the System.Net/System.Net.Socket nbamspaces to comminicate on network serialize this image using binary formatter get the strem nd the send it on the net work vi TcpClient.Send()........... Need further help or code semple emil me at riz_ahmad@msn.com. ll these suggestion given by me keeping in mind that u know C# in general. Regards RizwanReply
It is possible in java using the Robot class. It is present in java.awt.Robot namespaceReply
|
http://www.codeguru.com/comment/get/48374610/
|
CC-MAIN-2014-52
|
refinedweb
| 222
| 68.87
|
I Done This is a service that provides daily status reports with a list of
tasks which are done, planned, or blocked. This integration allows posting
'done' entries to I Done This teams on behalf of users when they publish,
change, or close a review request, and when they publish reviews or replies.
Each posted message includes a description of what the user did, along with
details such as the review request id, summary, and url. Reviewer groups are
also added as #tags for tracking on the I Done This website. The messages are
currently hard-coded, but could become configurable in another change.
The I Done This API gives control over individual user accounts, so each user
has to provide their personal API token on their Review Board account page.
The token is validated via the API before getting encrypted and saved in the
user settings. The list of the user's teams is retrieved from the API the first
time the user needs to post, and is cached to avoid duplicate requests. The
cache expires in 24 hours, or can be deleted manually by re-saving the token.
The administrator has to add an integration configuration for each I Done This
team that posts are allowed to, along with conditions to filter which review
request activity gets posted. Multiple configurations can specify the same team
to allow alternative sets of conditions, but only one message will be posted
to each unique team.
The configuration method is not ideal, since the admin can't verify that the
team is correctly set up without using an API token of a user on that team.
Users also don't have access to the team configurations to choose or even see
which teams or review requests get posted. However, the overall goal is to keep
user settings to a minimum, and let he admin control the configuration. There
may be ways in the future to improve the user experience, for example by adding
UI notifications from the integration when posting to I Done This.
Unit tests have been added to verify all the posted message types, various
reasons for not posting, posts with multiple configurations and team ids,
functionality of the user and admin forms, and team id requests with caching.
Unit tests pass, with full coverage except icon_static_urls().
Manually tested adding integration configurations, setting the user API token,
form validation errors, and posting all message types to I Done This.
Because this is a property, the docstring should look more like it is for attributes (such as just "The icons used for the integration") instead of the docstring for a method.
Add a trailing comma.
Unlike all our other docstrings, test case descriptions shouldn't include a period, because the test runner adds an ellipsis when printing. Here and throughout this file.
Would you mind changing these to use the format strings instead of a hard-coded result? These tests are fragile to text changes.
Trailing comma. I assume the same throughout this file.
Because this is imported into other code as just
create_request, it was initially a bit confusing when I read that code. Can we rename this as
create_idt_requestso it's clear what's going on?
Change Summary:
Addressed review comments.
Moved
integration_mgr.clear_all_configs_cache()to base class for test cases -
Updated some form test cases to pass
datain the constructor and call
form.full_clean()to verify that the appropriate
clean_<field>method is called.
Checks run (2 succeeded, 1 failed with error)
<b>is deprecated. Use
<strong>instead.
The fieldset label should be marked for translation.
Here too.
Maybe use
<p>over linebreaks? Also, IDK if we use self-closing tags (they are deprecated in the HTML spec)
Missing file-level docstring.
Must inherit from
object.
unicode.formatis slow compared to using %-based interpolation (and we also don't really use the former elsewhere). You can change these to use:
format_strings = { REPLY_PUBLISHED: 'Replied to review request %(request_id)s: ' '%(summary)s %(url)s %(group_tags)s', #... }
and then interpolate with:
format_strings[entry] % { 'group_tags': group_tags, 'num_issues': num_issues, 'request_id': review_request.display_id, 'summary': review_request.summary, 'url': url, }
You may want to replace
-with
_in
group.namebecause idt doesn't like tags with dashes (but underscores work for some reason :/)
Why not just use, e.g.:
import re #... re.sub(r'\s{2,}', ' ', entry)
You can compile the regex with
re.compileso we only have to parse the regex once.
I'm not sure which is more expensive
Coalesce into
elif
Change Summary:
Addressed Barret's review comments.
Moved entry types, template strings, and formatting to
entries.py.
Changed template string formatting to use
string.Template.
Renamed
event_nameto
signal_namefor clarity, and to avoid confusion with custom event filtering (separate change).
Switched to explicit keyword arguments when calling
IDoneThisIntegration.post_entry().
Checks run (1 failed, 1 succeeded)
flake8
Sorry this took so long :( Change looks great, and I love the test coverage. Most of my stuff are small doc tweaks and other tiny suggestions.
This should be "Format".
Text like
${num_issues}should be surrounded with double backticks so it'll appear as code/literal text in docs (not that we generate them yet, but still).
Same with others in this function.
We should use
review_request_idinstead of
request_idin places. In our terminology, "Request" is the HTTP request.
I couple suggestions for formatting and optimizations:
group_names = review_request.target_groups.values_list('name', flat=True) group_tags = ' '.join( '#%s' % re.sub(r'\W', '_', group_name) for group_name in group_names )
We should also ideally precompile the regex in the module.
Let's precompile this one too.
Let's put the URL in
<code>...</code>.
We should maybe expand this to say why this might be the case (the API token may be incorrect, please check the token in your account, etc.).
You can reference by doing:
:py:mod:`rbintegrations.idonethis.entries`
Might want to explicitly disregard
Noneentries in the conditional instead of doing the lookup.
I'm generally a fan of collapsing down if statements, but given that we have these same checks within the
if review.ship_it, maybe these ones should go in an
else.
Wonder if we should just do the
build_server_urlin
post_entry, so each call site doesn't have to reepeat it.
Should be "reply".
"Return ..."
"Get" implies that it's getting it from somewhere else, and doesn't necessarily imply that it's returning it.
No need for the
settings.getif it's known to be in there.
Since it's most likely in there, you can actually do:
try: return decrypt_password(settings['api_token']) except KeyError: return None
Same as above.
"IDs"
No blank line here.
We probably should turn this into two different paragraphs, or just let it wrap, rather than forcing a line break.
|
https://reviews.reviewboard.org/r/8776/
|
CC-MAIN-2020-29
|
refinedweb
| 1,116
| 57.16
|
23 [details]
Demo project
Attached, find a test project and bindings for PSPDFKit PDF library.
The test scenario:
when using PSPDFViewController directly, all is working as expected.
However, when subclassing it, the PDF library will stop working properly.
The demo project creates a plain stupid derived class:
public class TestController : PSPDFViewController
{
public TestController(PSPDFDocument doc) : base(doc)
{
}
}
Then it is adding an instance of TestController to the UINavigationController.
If you click the index view button (top right) in the demo, you should see an overview of all pages of the PDF.
* When building the DLL using 5.2.13, you won't see anything, just page numbers.
* When building the lib uisng 5.3.6, everything is working as expected.
* When using PSPDFViewController directly instead of the derived class, it is also working in 5.2.13
I have also attached the generated binding files for easy comparison.
Created attachment 2424 [details]
Code generated for base by 5.2.13
Created attachment 2425 [details]
Code generated for base by 5.3.6
Created attachment 2426 [details]
Code generated for controller by 5.2.13
Created attachment 2427 [details]
Code generated for controller by 5.3.6
Interesting (and a bit unexpected). I do not think it's binding related as there's no "real" changes between the attached files. At least none to explain the issue (wrt subclassing). (please don't use .rtf files as attachments, they don't diff very well ;-)
It's more likely that something was fixed in 5.3.x (and I can't say what out of my head). You should be able to confirm this by using the 5.2.x build assembly with 5.3 (it should work).
Note that you won't be able to use the 5.3-built bindings on 5.2 since the string optimization (one of the binding change) depends on symbols that are not part of 5.2.x.
You should consider using 5.3.6 (and not only for this, it's full of other fixes and optimizations). It's also the last beta planned before 5.4 (stable) and it's very unlikely that a new 5.2.x release will be made before (or even after) 5.4 is released.
Sorry for the RTFs...that's what TextEdit made from the source (they compare well in Xcode's FileMerge by the way).
I'm planning to switch to 5.3.6 for the next version, so no big issue.
And yes, you're right: the 5.2.13 built DLL works in 5.3.6.
So issue resolved. If you should find out what exactly is making it work in 5.3.6, I'd like to know.
Good night!
Thanks for confirming it's not binding related (and for all the useful information :-)
We'll let you know if we find out what was the 5.2.x issue (maybe another bug report will make it easier to spot / recall).
|
https://bugzilla.xamarin.com/67/6727/bug.html
|
CC-MAIN-2021-25
|
refinedweb
| 497
| 78.35
|
pip install entrypoints
The Python entrypoints library is among the top 100 Python libraries, with more than 17,487,902 downloads. This article will show you everything you need to get this installed in your Python environment.
How to Install entrypoints on Windows?
- Type
"cmd"in the search bar and hit
Enterto open the command line.
- Type “
pip install entrypoints” (without quotes) in the command line and hit
Enteragain. This installs entrypoints for your default Python installation.
- The previous command may not work if you have both Python versions 2 and 3 on your computer. In this case, try
"pip3 install entrypoints"or “
python -m pip install entrypoints“.
- Wait for the installation to terminate successfully. It is now installed on your Windows machine.
Here’s how to open the command line on a (German) Windows machine:
First, try the following command to install entrypoints on your system:
pip install entrypoints
Second, if this leads to an error message, try this command to install entrypoints on your system:
pip3 install entrypoints
Third, if both do not work, use the following long-form command:
python -m pip install entrypoints entrypoints on Linux?
You can install entrypoints on Linux in four steps:
- Open your Linux terminal or shell
- Type “
pip install entrypoints” (without quotes), hit Enter.
- If it doesn’t work, try
"pip3 install entrypoints"or “
python -m pip install entrypoints“.
- Wait for the installation to terminate successfully.
The package is now installed on your Linux operating system.
How to Install entrypoints on macOS?
Similarly, you can install entrypoints on macOS in four steps:
- Open your macOS terminal.
- Type “
pip install entrypoints” without quotes and hit
Enter.
- If it doesn’t work, try
"pip3 install entrypoints"or “
python -m pip install entrypoints“.
- Wait for the installation to terminate successfully.
The package is now installed on your macOS.
How to Install entrypoints in PyCharm?
Given a PyCharm project. How to install the entrypoints
"entrypoints"without quotes, and click
Install Package.
- Wait for the installation to terminate and close all pop-ups.
Here’s the general package installation process as a short animated video—it works analogously for entrypoints if you type in “entrypoints” in the search field instead:
Make sure to select only “entrypoints” because there may be other packages that are not required but also contain the same term (false positives):
How to Install entrypoints in a Jupyter Notebook?
To install any package in a Jupyter notebook, you can prefix the
!pip install my_package statement with the exclamation mark
"!". This works for the entrypoints library too:
!pip install my_package
This automatically installs the entrypoints library when the cell is first executed.
How to Resolve ModuleNotFoundError: No module named ‘entrypoints’?
Say you try to import the entrypoints package into your Python script without installing it first:
import entrypoints # ... ModuleNotFoundError: No module named 'entrypoints'
Because you haven’t installed the package, Python raises a
ModuleNotFoundError: No module named 'entrypoints'.
To fix the error, install the entrypoints library using “
pip install entrypoints” or “
pip3 install entrypoints” in your operating system’s shell or terminal first.
See above for the different ways to install entrypoints.
|
https://blog.finxter.com/how-to-install-entrypoints-in-python/
|
CC-MAIN-2022-33
|
refinedweb
| 518
| 56.96
|
tensorflow::
ops:: CropAndResize
#include <image_ops.h>
Extracts crops from the input image tensor and bilinearly resizes them (possibly.
Summary() with
align_corners=True.
Arguments:
- scope: A Scope object
- image: A 4-D tensor of shape
[batch, image_height, image_width, depth]. Both
image_heightand
image_widthneed to be positive.
- boxes: 1-D tensor of shape
[num_boxes]with int32 values in
[0, batch). The value of
box_ind[i]specifies the image that the
i-th box refers to.
- crop_size: A 1-D tensor of 2 elements,
size = [crop_height, crop_width]. All cropped image patches are resized to this size. The aspect ratio of the image content is not preserved. Both
crop_heightand
crop_widthneed to be positive.
Optional attributes (see
Attrs):
- method: A string specifying the interpolation method. Only 'bilinear' is supported for now.
-
|
https://www.tensorflow.org/versions/r1.6/api_docs/cc/class/tensorflow/ops/crop-and-resize
|
CC-MAIN-2018-34
|
refinedweb
| 125
| 62.44
|
Accessing Resources from a Lambda Function
Lambda does not enforce any restrictions on your function logic – if you can code for it, you can run it within a Lambda function. As part of your function, you may need to call other APIs, or access other AWS services like databases.
Accessing AWS Services
To access other AWS services, you can use the AWS SDK (Node.js, Java, Python, C#) or Go, AWS Lambda will automatically set the credentials required by the SDK to those of the IAM role associated with your function – you do not need to take any additional steps. For example, here’s sample code using the Python SDK for accessing an S3 object.:
import boto3 import botocore BUCKET_NAME = 'my-bucket' # replace with your bucket name KEY = 'my_image_in_s3.jpg' # replace with your object key s3 = boto3.resource('s3') try: s3.Bucket(BUCKET_NAME).download_file(KEY, 'my_local_image.jpg') except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print("The object does not exist.") else: raise
Note
For convenience, AWS Lambda includes versions of the AWS SDK as part of the execution environment so you don’t have to include it. See Lambda Execution Environment and Available Libraries for the version of the included SDK. We recommend including your own copy of the AWS SDK for production applications so you can control your dependencies.
Accessing non AWS Services
You can include any SDK to access any service as part of your Lambda function. For example, you can include the SDK for Twilio to access information from your Twilio account. You can use Environment Variables for storing the credential information for the SDKs after encrypting the credentials.
Accessing Private Services or Resources
By default, your service or API must be accessible over the public internet for AWS Lambda to access it. However, you may have APIs or services that are not exposed this way. Typically, you create these resources inside Amazon Virtual Private Cloud (Amazon VPC) so that they cannot be accessed over the public Internet. These resources could be AWS service resources, such as Amazon Redshift data warehouses, Amazon ElastiCache clusters, or Amazon RDS instances. They could also be your own services running on your own EC2 instances. By default, resources within a VPC are not accessible from within a Lambda function..
Important
AWS Lambda does not support connecting to resources within Dedicated Tenancy VPCs. For more information, see Dedicated VPCs.
To learn how to configure a Lambda function to access resources within a VPC, see Configuring a Lambda Function to Access Resources in an Amazon VPC
|
https://docs.aws.amazon.com/lambda/latest/dg/accessing-resources.html
|
CC-MAIN-2018-34
|
refinedweb
| 428
| 55.44
|
A simple web server for unit testing purposes. Acts as context manager for teardown.
Project description
Mock Web Server
A simple web server for unit testing purposes. Acts as context manager for teardown.
How to develop
pip install -r requirements.txt
How to use
from mockwebserver import MockWebServer() import requests def test_requests_get(): with MockWebServer() as server: url = server.set('/path/to/page', "page content") response = requests.get(url) assert response.ok assert response.text = "page content"
How to distribute
If you need to publish a new version of this package you can use this command:
$ make build $ make dist
License
Licensed under
MIT license. View license.
Project details
Release history Release notifications | RSS feed
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/mockwebserver/
|
CC-MAIN-2021-43
|
refinedweb
| 135
| 52.46
|
Talos Vulnerability Report
TALOS-2016-0071
Network Time Protocol Skeleton Key: Symmetric Authentication Impersonation Vulnerability
January 19, 2016
Report IDs
CVE-2015-7974 (NTP, NTPsec)
CVE-2016-1567 (chrony)
CERT VU#357792
Summary
Symmetric key encryption requires a single trusted key to be specified for each server configuration. A key specified only for one server should only work to authenticate that server, other trusted keys should be refused.
Instead we observe that when symmetric key authentication is verified, there is no check that the key used is the key specified for the address, any trusted key can be used as long as the keyid references another key the systems share and that key is used to compute the MAC.
This has three implications for the client server model. A client that has multiple servers configured each with different keys could be attacked by one of its servers spoofing every other server using its own key. Even worse a server can be attacked by any of its authenticated clients in a similar manner.
Finally, being able to use any key to authenticate a packet for a client or server means that if any key in the trustedkeys list uses a weak digest algorithim (MD5), then an attacker can abuse that method instead of being restricted by the stronger keys configured.
NOTE: Code locations referenced below refer to the NTP reference implementation from.
There is no clear location in the code where this defect occurs, since it exists due to an omission. Verifying the key used matches the proper server’s key could be done in ntp_proto.c around line 803 (in 4.8.2p3) where authdecrypt is called, or it might make sense to build it into the libntp code such as the authdecrypt function itself.
Be aware that this issue could affect other ntpd modes of operation such as broadcast or active/passive peering.
Tested Versions
NTP 4.2.8p3
NTPsec a5fb34b9cc89b92a8fef2f459004865c93bb7f92
chrony 2.2
Product URLs
CVSS Score
CVSSv2: 3.6 - AV:N/AC:H/Au:S/C:N/I:P/A:P
CVSSv3: 4.2 - CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:L
Details
ntpd does not ensure that the key used to verify the authenticity of a packet actually belongs to the alleged sender of the packet.
The intended binding between keys (via keyids) and peers is indicated to ntpd through the configuration file. For example:
server ntp-server key 1
indicates that keyid 1 is a symmetric key shared with ntp-server. Packets bound for ntp-server should be authenticated under keyid 1 and, to prevent impersonation, packets from ntp-server should be authenticated using keyid 1.
Unfortunately, when receiving a packet, allegedly from ntp-sever, ntpd does not require the packet to authenticate under keyid 1. ntpd only ensures that the packet authenticates under some trustedkey known to ntpd. This allows any authenticated peer to impersonate any other authenticated peer.
We confirmed this vulnerability with the following setup. (The tests below were performed with NTP 4.2.8p3. 4.2.8p4 appears to introduce regressions which break LOCAL refclocks and symmetric associations.)
ntp-server - simulated stratum 1 server to provide time to clients
# /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 server 127.127.1.1 prefer fudge 127.127.1.1 stratum 0 # /etc/ntp.keys: 1 MD5 youllneverguess 2 MD5 you_really_wont
ntp-client - authenticates ntp-server with keyid 1 and ntp-client2 with keyid 2
# /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server key 1 minpoll 2 maxpoll 2 iburst peer ntp-client2 key 2 minpoll 2 maxpoll 2 noselect # /etc/ntp.keys 1 MD5 youllneverguess 2 MD5 you_really_wont
ntp-client2 - authenticates ntp-server with keyid 1, uses keyid 1 to talk to ntp-client
# /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server key 1 minpoll 2 maxpoll 2 iburst peer ntp-client key 1 minpoll 2 maxpoll 2 # /etc/ntp.keys 1 MD5 youllneverguess 2 MD5 you_really_wont
attacker1 (192.168.33.9) - conducts a man-in-the-middle attack using ntp-client2’s peer key (keyid 2) to impersonate ntp-server to ntp-client and shift time
attacker1 uses an ARP-spoofing attack to intercept and replay all packets between ntp-client and ntp-server. When it receives a server mode packet, it modifies the sent and recv time to be 100 years in the future. It then authenticates the packet with ntp-client2’s key (keyid 2). In this specific attack, the timestamps overflow so 100 years in the future from 2015 is 1979.
ntp-client accepts the forged replies as though they were coming from ntp-server and, eventually, steps its clock.
Do The Sender and Recipient Have to Agree on the Keyid?
According to the ntpd documentation
html/authentic.html:
The servers and clients involved must agree on the key ID, key type and key to authenticate NTP packets.
Though it doesn’t indicate precisely what “agreement” means or why, this conflicts with RFC 5905 which states:
keyid: Symmetric key ID for the 128-bit MD5 key used to generate and verify the MAC. The client and server or peer can use different values, but they must map to the same key.
This statement is problematic and only partially true. It is problematic because it does not address the binding of symmetric keys (specified by keyid) to the peers that they authenticate, allowing for impersonation between peers. It is only partially true because, in client-server modes, the server will use the keyid from the client mode packet to authenticate the incoming client mode packet as well as the outgoing server mode packet. Thus, in a benign scenario, clients and server must agree both on keyid and the key value. In symmetric modes, the statement is partially true because each peer uses the keyid specified in its peer association when generating an outgoing packet. However, in all cases, the keyid specified in an incoming packet will be used to authenticate that packet. Therefore, even in symmetric modes, if the two peers use different keyids A and B for a given symmetric association, each peer must map both keyids to the same key — the sender will use A (respectively B) to generate the authenticator for the outgoing packet and, therefore, the recipient will use A (respectively B) to authenticate the incoming packet. This is illustrated by the non-normative example code from RFC 5905:
According to receive() () the keyid in the received packet is used to look up the key to authenticate the packet.
The keyid in the received packet is used to set the peer keyid for manycast peers (), symmetric peers (), and broadcast peers.
The keyid in the received packet is also used to choose the keyid and key to authenticate the transmitted packet in fast_xmit() ()
In peer_xmit() () the keyid of the peer is used to authenticate the transmitted packet. It appears to omit setting the keyid on the transmitted packet. But, for preemptable associations, the peer keyid came from a received packet. For configured associations, it’s the value from the configuration file.
This is also borne out by the ntpd source code. When ntpd receives an incoming packet with an authenticator, it verifies the authentication under the key specified by the keyid from the incoming packet:
receive() reads the keyid from the packet:
skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
receive() then calls authdecrypt() with that keyid:
if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, has_mac)) is_authentic = AUTH_ERROR; else is_authentic = AUTH_OK;
authdecrypt() calls authhavekey() which looks up the key by keyid:
if (id == sk->keyid) { if (0 == sk->type) {
And finally, MD5authdecrypt() is called to compute and verify the digest using the key value found via the packet’s key id
But, there is never a check which verifies that the keyid from the incoming packet (skeyid) matches the keyid configured for the peer association in question (peer->keyid)
Test Case: Equal keyids Refer to Differing Key Material
To verify that the sender and recipient can’t merely use different keyids to refer to the same key material unless both have been configured to map both keyids to the same key, we configured ntp-client2 with the same keys as ntp-server and ntp-client, but we swapped the keyids on ntp-client2. This confirmed that, though ntp-client2 was using the same key material as the other two nodes, all packets from ntp-client2 would fail authentication because the other nodes did not also have the same key material mapped to the keyids sent by ntp-client2.
ntp-client can sync with ntp-server just fine
# /etc/ntp.keys 1 MD5 youllneverguess 2 MD5 you_really_wont # /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server key 1 minpoll 2 maxpoll 2 iburst peer ntp-client2 key 2 minpoll 2 maxpoll 2 ntp-client$ ntpq -c as ind assid status conf reach auth condition last_event cnt =========================================================== 1 43544 f65a yes yes ok sys.peer sys_peer 5 # ntp-server 2 43545 e01a yes no ok reject sys_peer 1 # ntp-client2
ntp-client detects that ntp-client2’s packets fail authentication. However, because ntp-client2 is also rejecting ntp-client’s packets due to bad auth, the origin timestamp doesn’t match and that check fails first before an auth check is performed. Note the
auth 2(AUTH_ERROR) on line 2 of the log snippet below.
Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): calling authdecrypt Nov 3 19:23:37 ntp-client ntpd: receive: at 698 192.168.33.11<-192.168.33.13 mode 1 keyid 00000001 len 68 auth 2 Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): big switch Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): AM_PROCPKT, regular packet Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): done with big switch Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): flip is 0, not interleaved Nov 3 19:23:37 ntp-client ntpd: (ntp_proto.c): met bogus condition (p_org is not qual to peer->aorg), test2
ntp-client2 uses the same keys but different ids.
# /etc/ntp.keys 2 MD5 youllneverguess 1 MD5 you_really_wont # /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server key 2 minpoll 2 maxpoll 2 iburst peer ntp-client key 1 minpoll 2 maxpoll 2
We can see that ntp-client2 is rejecting both the server and the peer due to bad auth.
ntp-client2$ ntpq -c as ind assid status conf reach auth condition last_event cnt =========================================================== 1 64340 c01c yes no bad reject 1 # ntp-server 2 64341 c01c yes no bad reject 1 # ntp-client
We can see this when ntp-client2 receives a packet from ntp-client:
Nov 3 19:40:29 ntp-client2 ntpd: receive: at 1438 192.168.33.13<-192.168.33.11 mode 1 keyid 00000002 len 68 auth 2 Nov 3 19:40:29 ntp-client2 ntpd: (ntp_proto.c): big switch Nov 3 19:40:29 ntp-client2 ntpd: (ntp_proto.c): AM_PROCPKT, regular packet Nov 3 19:40:29 ntp-client2 ntpd: (ntp_proto.c): done with big switch Nov 3 19:40:29 ntp-client2 ntpd: (ntp_proto.c): flip is 0, not interleaved Nov 3 19:40:29 ntp-client2 ntpd: (ntp_proto.c): digest failed Nov 3 19:40:29 ntp-client2 ntpd: event at 1438 192.168.33.11 c01c 8c bad_auth digest
Test Case: Using Different keyids That Map To The Same Key Material
This tests confirms that, as long as the sender and the recipient have the same key material configured for a given keyid, the recipient won’t enforce the binding between the keyid configured for an association and the keyid used to authenticate an incoming packet under that association.
We configure the same keys on both hosts
# /etc/ntp.keys on both hosts 1 MD5 youllneverguess 2 MD5 you_really_wont
But ntp-client uses keyid 2 to communicate with ntp-client2.
# ntp-client /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server iburst key 1 minpoll 2 maxpoll 2 peer ntp-client2 key 2
And ntp-client2 uses keyid 1 when sending packets to ntp-client.
# ntp-client2 /etc/ntp.conf keys /etc/ntp.keys trustedkey 1 2 server ntp-server iburst key 1 minpoll 2 maxpoll 2 peer ntp-client key 1
As can be seen here, both ntp-client and ntp-client2 accept the packets from their peer despite being configured to use different keyids.
ntp-client$ ntpq -c as ind assid status conf reach auth condition last_event cnt =========================================================== 1 55125 f65a yes yes ok sys.peer sys_peer 5 # ntp-server 2 55126 f03a yes yes ok reject sys_peer 3 # ntp-client2 ntp-client2$ ntpq -c as ind assid status conf reach auth condition last_event cnt =========================================================== 1 53439 f63a yes yes ok sys.peer sys_peer 3 # ntp-server 2 53440 f024 yes yes ok reject reachable 2 # ntp-client
Possible Fix
The following (untested) patch ensures that the keyid used to
authenticate the packet is the same as the keyid configured for the
corresponding peer association. If not, it sets
is_authentic to
AUTH_ERROR and skips the call to
authdecrypt().
diff --git a/ntpd/ntp_proto.c b/ntpd/ntp_proto.c index 2a15d72..01959f0 100644 --- a/ntpd/ntp_proto.c +++ b/ntpd/ntp_proto.c @@ -840,6 +840,11 @@ receive( } #endif /* AUTOKEY */ + /* Ensure that the packet actually came from the expected peer */ + if(skeyid <= NTP_MAXKEY && peer && skeyid != peer->keyid) { + is_authentic = AUTH_ERROR; + // TODO: log impersonation attempt + /* * Compute the cryptosum. Note a clogging attack may * succeed in bloating the key cache. If an autokey, @@ -847,11 +852,13 @@ receive( * again. If the packet is authentic, it can mobilize an * association. Note that there is no key zero. */ - if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, + } else if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen, has_mac)) is_authentic = AUTH_ERROR; else is_authentic = AUTH_OK; + + #ifdef AUTOKEY if (crypto_flags && skeyid > NTP_MAXKEY) authtrust(skeyid, 0);
Credit
Discovered by Matt Street of Cisco ASIG.
Timeline
2015-10-07 - Vendor Disclosure
2016-01-19 - Public Release
|
http://www.talosintelligence.com/reports/TALOS-2016-0071/
|
CC-MAIN-2017-04
|
refinedweb
| 2,351
| 53.21
|
:
- A bug needs to be fixed and you want to fix it without breaking other functionality.
- You think of a better or more efficient method of implementing a feature.
- You want to pay down some technical debt accrued by the team.
.
Testing Landscape in an ASP.NET World.
Automated Acceptance Testing
- Browse to the main page at.
- If currently logged in, click Logout.
- Verify that you are accessing the site as a guest. ("Welcome guest" should be displayed in the top right.)
- Browse to.
- Verify that you are re-directed to and prompted for.
Introducing WatiN.
Setting Up WatiN in Figure 1.
<, shown in Figure 2, change the Copy to Output Directory to "Copy if newer."
Figure 2 File Properties View
in Figure 3 , I have added to the Trusted sites list to run our simple WatiN, as well as , since we'll be using a local Webserver to host our test site.
Figure 3 Trusted Sites Screen
.
You can learn more by viewing the following video clip.
Using WatiN to Test a Local Web site
Now that we have successfully run a simple WatiN test against a remote Web site, we turn our attention to using WatiN to test ScrewTurn Wiki. We won't want to deploy ScrewTurn Wiki to a server every time we want to run our acceptance test suite using WatiN. Instead, we will use the ASP.NET Development Server (WebDev.WebServer.exe), which is better known by its code name "Cassini." It is installed with .NET Framework 2.0 and above in C:\Windows\Microsoft.NET\Framework\v2.0.50727\. Another option would be to use a local IIS instance, but the ASP.NET Development Server has the nice feature that it can be started and/or stopped by a normal user.
We want to start ASP.NET Development Server before any WatiN tests are run and stop it once testing is complete. Most test frameworks have a method for specifying code to run before and after any tests. In NUnit 2.4.8, we use the SetUpFixture attribute on a class to mark it as containing setup/teardown code for all tests in the same namespace, as shown in Figure 4.
using System.Configuration; using NUnit.Framework; namespace ScrewTurn.Wiki.Tests { [SetUpFixture] public class WebServerRunner { private WebServer webServer; [SetUp] public void StartWebServer() { var absolutePathToWebsite = ConfigurationManager.AppSettings["absolutePathToWebsite"]; webServer = new WebServer(absolutePathToWebsite, 9999); webServer.Start(); } [TearDown] public void StopWebServer() { webServer.Stop(); webServer = null; } } }
The WebServer class is a helper class that encapsulates the ASP.NET Development Server. It needs the physical path to the compiled Web site and a fixed port. We need a fixed port, such as 9999, so that we can direct WatiN to browse to in our tests.
ASP.NET Development Server on Windows Vista and Later
The ASP.NET Development Server only listens for requests on IPv4, not IPv6. If you are running Windows Vista or Windows Server 2008, requests for "localhost" will resolve to the IPv6 address of ::1 by default rather than the IPv4 address of 127.0.0.1 and the WatiN tests will fail. To resolve this issue, comment out the IPv6 localhost address in your C:\Windows\System32\drivers\etc\hosts file. This is the line with "::1 localhost".
The Start method for WebServer formats the command line arguments for WebDev.WebServer.exe and launches it using a System.Diagnostics.Process object:
public void Start() { webServerProcess = new Process(); const string webDevServerPath = @"c:\Windows\Microsoft.NET\Framework\v2.0.50727\WebDev.WebServer.exe""; string arguments = string.Format("/port:{0} /path:\"{1}\" /vpath:{2}", port, physicalPath, virtualDirectory); webServerProcess.StartInfo = new ProcessStartInfo(webDevServerPath, arguments); webServerProcess.Start(); }
At the end of the test run, the Stop method terminates the Cassini process:
NOTE: You might receive a strange error message from the ASP.NET Development Server stating that "The directory '<PATH> /vpath:' does not exist", as we see in Figure 5. This is a bug in the ASP.NET Development Server which causes it to fail if your physical path has a trailing \. To bypass this bug, simply remove the trailing slash in your configuration file or code defensively using physicalPath.TrimEnd(\\) on any physical path intended for the ASP.NET Development Server as I did in the constructor for ScrewTurn.Wiki.Tests.WebServer.
Figure 5 ASP.NET Development Server Showing Error Message
Smoke Tests
Our goal in writing acceptance tests is to ensure that end user functionality continues to work as expected, as we add features or refactor existing code for better maintainability. Before getting into complex workflows, we will write some simple smoke tests using WatiN to ensure that ScrewTurn Wiki's basic functionality is working. (A smoke test is a preliminary test designed to show simple and obvious failures, such as an error in the web.config file resulting in the site being inaccessible.) Our smoke tests include the actions of:
- Browsing to the main page
- Logging into the site
- Browsing the admin pages redirects to the login page
- Accessing a nonexistent page redirects to a page not found information page
Note that you don't have to think of everything immediately, but can gradually add tests as you build your test suite.
We'll start out with testing whether a user can log into the site as an administrator. (By default, ScrewTurn Wiki's administrative account is admin/password.) The WatiN script should be fairly self-explanatory. You are finding page elements, such as the Login link, and then performing actions, such as clicking the Login link via its Click method, as shown in Figure 6.
[Test] public void CanLogIntoSite() { using(var browser = new IE()) { browser.GoTo(""); browser.Link(Find.ByTitle("Login")).Click(); browser.TextField(Find.ByTitle("Type here your Username")).TypeText("admin"); browser.TextField(Find.ByTitle("Type here your Password")).TypeText("password"); browser.Button(Find.ByValue("Login")).Click(); var username = browser.Link(Find.ByTitle("Go to your Profile")).Text; Assert.That(username == "admin"); } }
The only slightly confusing part might be how to find the page elements. (e.g., How did I know to find the username textbox by looking for its title, "Type here your Username"?) You need your browser of choice and a tool or two, such as Internet Explorer and the Internet Explorer Developer Toolbar or Firefox and Firebug/Web Developer Toolbar.
Finding by selecting an element's title isn't recommended because it is more likely to change. For example, the text really should say "Type your username here." If we correct the grammar, however, we break the test. I wanted to create the smoke tests before modifying the site, which is why I left the text as it is. A better option for identifying page elements is by ID. (You can find elements by ID using Find.ById("id") instead of Find.ByTitle("title"). The Find class contains a wide variety of static methods for simplifying the location of page elements.) So while WatiN can automate any site, you can make your tests more robust in the face of change (and language translations) by providing IDs for elements of interest...
|
https://msdn.microsoft.com/en-us/magazine/dd744751.aspx
|
CC-MAIN-2018-51
|
refinedweb
| 1,178
| 58.69
|
Originally posted by mike hengst: so is this going in the right direction
public class Student
{
static char[] studentGrades = new char[5];
static char[] letterGrades = { 'F' , 'D' , 'C' , 'B' , 'A' };
static double[] grades = { 0.0 , 1.0 , 2.0 , 3.0 , 4.0 };
static double[] gradePoints = new double[ 5 ];
int studentNumber;
public Student()
{
int stuNum = stuNum +1;
}
public void setGrade( int index , char letterGrade )
{
// set studentGrades[ index ] = ?? // set gradePoints[ index ] = ??}
for (int i = 0;i < studentGrades[].length; ++i)
{
//setting letter grade into studentGrades array
studentGrades[i] = letterGrade;
//setting the index of the letterGrade into letterGrades array
studentGrades[i].index = letterGrades[i];
//setting gradePoints into grades
gradePoints[i].index = grades[i];
// studentGrades[i] = letterGrade;
}
}
Since studentGrades is an array of char, I would think you would want to assign a char into each array slot (defined by the array index). You could also throw in a couple of System.out.println statements to see what you're getting each time. Try compiling it (maybe even one statement at a time by commenting the others out) and see what happens. Also note that indentation (and code tags to preserve that indentation) helps readability which helps other people's ability to help you.
|
http://www.coderanch.com/t/392677/java/java/arrays
|
CC-MAIN-2014-35
|
refinedweb
| 200
| 54.83
|
Represents four segments that form a loop, and might be a tag.
More...
#include <Quad.h>
Represents four segments that form a loop, and might be a tag.
Definition at line 22 of file Quad.h.
List of all members.
Constructor.
(x,y) are the optical center of the camera, which is needed to correctly compute the homography.
Definition at line 11 of file Quad.cc.
Interpolate given that the lower left corner of the lower left cell is at (-1,-1) and the upper right corner of the upper right cell is at (1,1).
Definition at line 36 of file Quad.cc.
Referenced by interpolate01().
Same as interpolate, except that the coordinates are interpreted between 0 and 1, instead of -1 and 1.
Definition at line 36 of file Quad.h.
Referenced by AprilTags::TagDetector::extractTags().
[static]
Searches through a vector of Segments to form Quads.
Definition at line 48 of file Quad.cc.
Given that the whole quad spans from (0,0) to (1,1) in "quad space", compute the pixel coordinates for a given point within that quad.
Note that for most of the Quad's existence, we will not know the correct orientation of the tag.
Definition at line 53 of file Quad.h.
Referenced by AprilTags::TagDetector::extractTags(), interpolate(), and Quad().
Early pruning of quads with insane ratios.
Definition at line 25 of file Quad.h.
Referenced by search().
Minimum size of a tag (in pixels) as measured along edges and diagonals.
Definition at line 24 of file Quad.h.
Total length (in pixels) of the actual perimeter observed for the quad.
This is in contrast to the geometric perimeter, some of which may not have been directly observed but rather inferred by intersecting segments. Quads with more observed perimeter are preferred over others.
Definition at line 49 of file Quad.h.
[private]
Definition at line 66 of file Quad.h.
Referenced by interpolate(), and Quad().
Points for the quad (in pixel coordinates), in counter clockwise order. These points are the intersections of segments.
Definition at line 39 of file Quad.h.
Referenced by AprilTags::TagDetector::extractTags(), and Quad().
Segments composing this quad.
Definition at line 42 of file Quad.h.
|
http://tekkotsu.org/dox/classAprilTags_1_1Quad.html
|
CC-MAIN-2018-47
|
refinedweb
| 367
| 69.99
|
Today, We want to share with you Laravel Create Custom Helper Class Example.In this post we will show you Creating a Helpers file in a Laravel App, hear for Creating your own PHP helper functions in Laravel we will give you demo and example for implement.In this post, we will learn about How To Create A Custom Helper Class In Laravel MVC with an example.
Laravel Create Custom Helper Class Example
There are the Following The simple About Laravel Create Custom Helper Class Example Full Information With Example and source code.
As I will cover this Post with live Working example to develop laravel 5.7 custom helper functions, so the create custom helper in laravel 5.7 for this example is following below.
Step : 1 Create Laravel helpers.php file
app/helpers.php
<?php function getMemberProfile($id) { $data = \DB::table('users') ->select(\DB::raw('CONCAT(firstname, " ", lastname) as username')) ->where('id', $id) ->first(); return $data->username; }
Step : 2 Add app/helpers.php file in composer.json file
app/helpers.php
"autoload": { "classmap": [ ... ], "psr-4": { "App\\": "app/" }, "files": [ "app/helpers.php" //Add This Line ] },
After done this then once we are run following command.
composer dump-autoload
Step : 3 Use Custom Laravel Helper In Controller
Create a Laravel Controller
namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; class HomeController extends Controller { public function index() { $fullprofiledetails = getMemberProfile(Auth::user()->id); dd($fullprofiledetails); } }
Step : 4 Use Custom Laravel Helper In Blade File
Laravel Blade View Files
@extends('layouts.app') @section('content') <?php $fullprofiledetails = getMemberProfile(Auth::user()->id); dd($fullprofiledetails); ?> @endsection
Angular 6 CRUD Operations Application Tutorials
Read :
Create A Custom Helper Class In Laravel MVC
Summary
You can also read about AngularJS, ASP.NET, VueJs, PHP.
I hope you get an idea about Laravel Create Custom Helper Class Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.
|
https://www.pakainfo.com/laravel-create-custom-helper-class-example/
|
CC-MAIN-2022-05
|
refinedweb
| 336
| 50.12
|
Script structure
This topic describes the code layout and resource files used for DevWeb scripts in LoadRunner Developer.
main.js layout
This section describes the layout of the main.js file. This file contains the script code.
main.js can contain three types of sections: initialize, action, and finalize. These can appear more than once and are executed in the order that they appear in the script.
Tip: You can implement run logic to determine the order in which actions run during a test. For details, see Implement run logic.
The following is an example of a typical Dev.
All the elements of the SDK are within the load namespace (object), therefore the load. prefix is needed to access them.
Note: Dev.
Script resources
The following describes some of the important YAML and other files available in LoadRunner Developer for your DevWeb scripts. These files control the execution of the DevWeb engine and scripts.
Scenario resource file
The scenario.yml file defines the scenario settings when running a DevWeb script in load mode. For details, see Run scripts.
Note: This file is used for LoadRunner Developer only. When running a test in LoadRunner Professional or LoadRunner Enterprise,
Runtime settings resource file
The optional rts.yml contains the default runtime settings for test runs, for example, timeouts for HTTP connections and logger settings.
The runtime settings are specific to each Vuser. If you want to customize these settings, you can do so in a local runtime settings file that you create in the script's folder. For details, see Customizing runtime settings.
The optional parameters.yml contains the parameter descriptions for your script. This file is user-defined in the script folder.
The parameters file defines the parameters that can be used in the script and various aspects of how and when new values are retrieved.
For more information, see Parameterize values.
Transactions resource file
The optional Transaction file, transactions.yml, is only relevant for LoadRunner Cloud users.
To enable the SLA feature of LoadRunner Cloud, populate this file with a list of transaction names for which to calculate the SLA.
Note: The script must contain transactions with matching names
Format the list as shown in the following example, where two transactions are defined, named foo and bar:
- name: foo
- name: bar
The optional rendezvous.yml file is created automatically in the script directory during replay, if the main script contains rendezvous points. When a rendezvous point is reached, the Vuser stops running and waits for permission to continue.
Note: Rendezvous points are supported when running scripts in LoadRunner Professional or LoadRunner Cloud. They are not supported when executing scripts locally using LoadRunner Developer.
The rendezvous.yml file provides a list of rendezvous names, required by LoadRunner Cloud to define the rendezvous policy. The file uses the following format:
- name: foo
- name: bar
In the above example, the file contains two rendezvous points with the names foo and bar. The script must contain rendezvous with matching names for the rendezvous functionality to work in LoadRunner Cloud.
Before uploading a script to LoadRunner Cloud, you must replay the script once so that the rendezvous.yml file is included in the zip file for the script.
For details on adding the rendezvous function to your script, see the JavaScript SDK Rendezvous section.
User arguments resource file
The optional User arguments file, user_args.json, contains arguments that are used in the script for execution. These arguments are equivalent to the custom command line options used for VuGen scripts.
For API properties, see Config in the SDK documentation.
The file is in a key-value JSON format (string values):
{ "key": "value", "hello": "world" }
See also:
|
https://admhelp.microfocus.com/lrd/en/2021_R2/help/Content/DevWeb/DW-scripts.htm
|
CC-MAIN-2021-49
|
refinedweb
| 610
| 58.08
|
Dear SAP PI/PO consultants,
It has been a while(3 years) since I wrote “.Net C# SOAP Web Service Client Example for SAP PI/PO Services” .NET Core has gained popularity since then.
There is also a tendency to request REST services. However, I still think there are many valid use cases where SOAP is the better option. In order to speed up things, you can pass this blog post when you are working with .NET developers.
Prerequisites:
- .NET Core SDK is installed
Generate Web Service Client Reference Classes & add libraries
Java wsimport equivalent of .NET Core is dotnet-svcutil
dotnet tool install --global dotnet-svcutil dotnet tool list -g
Usually it adds the tools to the PATH. You may need to close & reopen the terminal. If that doesn’t work you should add this directory to Environment variable PATH:
%USERPROFILE%\.dotnet\tools
Generate client classes with a WSDL:
dotnet-svcutil calculator-v1.wsdl
Generate classes with namespace:
dotnet-svcutil SI_SEND_ORG_DATA.wsdl -n *,MDP.MyAwesomePO.WSClient
This command will create a Service Reference. You can copy the class to your project. By default, it doesn’t create sync methods but there is an option for that(–sync). You can use –help to see options.
You have to add these packages to your project:
dotnet add package System.ServiceModel.Primitives dotnet add package System.ServiceModel.Http
Don’t forget to run “dotnet restore”.
Use the Reference Classes
I like to set endpoint, username, and password programmatically. Binding configuration helps if you have to use basic authentication over HTTP.
String endpointurl = ""; BasicHttpBinding binding = new BasicHttpBinding(); //If you need HTTP with Basic Auth for internal network or dev environments. Otherwise remove these two lines: binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; EndpointAddress endpoint = new EndpointAddress(endpointurl); var wsclient = new SI_SEND_ORG_DATAClient(binding, endpoint); wsclient.ClientCredentials.UserName = "username"; wsclient.ClientCredential.Password = "password"; //Here you can use client var request = new SI_SEND_ORG_DATA(); request.field="value" var response = await wsclient.SI_SEND_ORG_DATAAsync(request);
Beware of the integer/double
Coming from Java one of the things that bit me was setting an integer value for a SOAP request.
If you have a field like xsd:integer or xsd:double that maps to .Net built-in types which don’t have null, you have to set Specified value to true.
Example:
request.FirstNumber = 2; request.FirstNumberSpecified=true;
This is a solution to differentiate between an element with 0 and no element. I’m sure you experienced this behavior while trying to send an integer with 0 value using ABAP Proxy. Because in ABAP, integer initial value is 0 and regarded as null for outbound XML processing. 🙂
See you in next blog posts!
Hi Fatih,
thanks for the blog. As a person with a C# background I really appreciate the blogs where SAP and .NET go hand-in-hand. One question: Why do you use the commandline util svcutil to generate the classes? On your first/old article you used the “Service Definition” gui from Visual Studio. As far as I know this is still available, even for .NET Core applications. Any specific reasons why you switched to the console? 🙂
Hi Raffael,
That is a good question. Yes, it may work with the GUI also!
I have a few reasons:
-I don’t use C# and Visual Studio daily. Since .Net Core came out, I prefer terminal + VS Code to poke around. So I haven’t checked Visual Studio GUI, to be honest.
-As a reader I prefer command-line tutorials. I find them expressive, concise, and easy to reproduce.
-This solution also works on Linux/Mac as a side benefit 🙂
Thanks for your contribution.
Regards, Fatih
Hi Fatih,
thanks for your response. I would say these are valid points you listed. No further questions. 😉
|
https://blogs.sap.com/2020/03/15/sap-po-soap-web-service-with-.net-core-client/
|
CC-MAIN-2020-50
|
refinedweb
| 629
| 52.46
|
0
*Note: its not a fully functional hashTable for technical purposes
My priority is to get it to store the strings properly. I approached this a different
yet similar way to my other post and I have gotten much farther! The problem now is that my output prints duplicates each and table. More confounding is why only these words don't output properly. I will provide the source so you can try it out for yourself.
I compiled with visual c++ 2008 & 05 and received same output. My next goal would be to
implement it as an ADT, but for now solving this issue is crucial.
Once again thanks for any help I receive.
#include <iostream> #include <string> #include <fstream> #include <cctype> #include <iomanip> using namespace std; //function prototypes int hashFunction(const char *key, int keyLenght, const int HTSIZE); void LinearProbing(int upindex, string words[], string item ,int noitems[]); string StringToLower(string strToConvert); int main() { string getString; //used to read the strings const int HTSIZE = 131; //Holds up to 130 words string hashTable[HTSIZE]; //stores unique words const char *cphashTable; //holds c-string value for processing int IndexStatusList[131]; //holds the number of times a word is inserted at its location ifstream DataIn; //filestream object int size = 0; //no use yet int lenght; //stores lenght of a string int hIndex; //stores the index in where to store a string //will be used as a constructor when implemented as ADT //initializes both arrays. The first for empty strings, the other for ints for(int c = 0; c < HTSIZE; c++) { hashTable[c] = " "; IndexStatusList[c] = 0; } DataIn.open("blah.txt"); //Fail Safe test if(!DataIn) { cout <<"Error opening data file\n"; } else //Sucess { while(DataIn >> getString) //Gets the first string and reads until { //there is no more data to be read lenght = static_cast<int>(getString.length()); //gets lenght of a string to be used for processing cphashTable = getString.data(); //returns a c-string copy of a string hIndex = hashFunction(cphashTable,lenght,HTSIZE); //computes the index. see def below LinearProbing(hIndex,hashTable, cphashTable, IndexStatusList); //cphashTable //getString } //tried both no difference in results } cout << "Count\t" << "Index\t" << "WORD\n"; //Title of Columns for(int i = 0; i < HTSIZE;i++) // Outputs number of occurences followed by { // the location of the word in the hashtable if(hashTable[i] != " ") // the content of that location e.g cat { cout << IndexStatusList[i] << "\t" << i << "\t" << hashTable[i] << endl ; } } return 0; } //end of main /* Def of Linear Probring Places the item, in this case a string in the appropriate location in the array. The location hIndex is calculated by the function hashFunction and then passed to this function as an argument. If the location to where hIndex points is empty in the hashTable insert the item there and update its number of currence:(parralel array) StatusListIndex. While the location is occupied find next available location by incrementing the current location to one until an available space is found. My current list is less than 130 elements so no need to worry about space at this time. Then insert item at this new location and update the IndexStatusList. You also need to check if at a certain location it is the same instance of that item, to update its IndexStatusList. Eg, cat is inserted into location 1, IndexStatusList is 1. Then another cat is found just update the IndexStatusList by one rather than inserting it in a new location. Cat still at loc 1 IndexStatusList is 2 */ void LinearProbing(int upindex, string words[], string item ,int noitems[]) { item = StringToLower(item); //i tried this in hopes of being able to compare both //strings properly but im not so sure. if(item == words[upindex]) { int inc = noitems[upindex]; //this section takes care of duplicates inc++; noitems[upindex] = inc; } else if(words[upindex] == " ") { words[upindex] = item; //if location is empty noitems[upindex] = 1; } else { while(noitems[upindex] != 0) { upindex = ((upindex + 1) % 131); //collision } words[upindex] = item; noitems[upindex] = 1; } } /* Adds the values of each character in the string then % it with HTSIZe which is to be used as hIndex. There is no distinction between lowercase and uppercase A is converted to the ascii equivalent of a ex string ab = 97+98 then lets say htsize was 3 hIndex would then be 0. */ int hashFunction(const char *key, int keyLenght, const int HTSIZE) { int sum = 0; for(int j =0; j < keyLenght ; j++) { sum = sum + static_cast<int>(tolower(key[j])); } return sum = sum % HTSIZE; } //change each element of the string to lower case string StringToLower(string strToConvert) { for(unsigned int i=0;i<strToConvert.length();i++) { strToConvert[i] = tolower(strToConvert[i]); } return strToConvert;//return the converted string }
|
https://www.daniweb.com/programming/software-development/threads/156258/hashtable-implementation-revised
|
CC-MAIN-2018-13
|
refinedweb
| 772
| 56.89
|
user control in an assembly
Discussion in 'ASP .Net' started by Steve Richter, Apr27
- Mattias Sjögren
- Nov 19, 2003
Referencing assembly from GAC using @assembly failsBrent, Jan 14, 2004, in forum: ASP .Net
- Replies:
- 1
- Views:
- 1,378
- Brent
- Jan 23, 2004
ASP.NET 2.0: What is the namespace and assembly name of generated assemblySA, Aug 9, 2004, in forum: ASP .Net
- Replies:
- 0
- Views:
- 484
- SA
- Aug 9, 2004
Assembly's manifest definition does not match the assembly reference.Horatiu Margavan via .NET 247, Aug 30, 2004, in forum: ASP .Net
- Replies:
- 0
- Views:
- 3,636
- Horatiu Margavan via .NET 247
- Aug 30, 2004
adding assembly to windows\assembly through bat fileGrant Merwitz, Sep 15, 2005, in forum: ASP .Net
- Replies:
- 3
- Views:
- 9,087
- Grant Merwitz
- Sep 15, 2005
|
http://www.thecodingforums.com/threads/user-control-in-an-assembly.101169/
|
CC-MAIN-2014-49
|
refinedweb
| 132
| 67.35
|
Hi everyone,
I’m new to netmf gadgeteer and I’m having a couple of issues with the FEZ Hydra and the CP7 display.
Before I delve in, I’ll say that I have the latest TinyCLR firmware and Tinybooter 4.2.6.2.
On my computer I have Visual Studio 2010 Express, NETMF SDK 4.2, and NETMF and Gadgeteer Package 2014 R1 installed.
And here is the major caveat… I’m building my project in visual basic. I did some searching here and didn’t find too much help for vb, though I now c# and vb get compiled into the same .net code basically. The reason I chose VB is because at my job, VB.Net 2010 is used extensively and it would really be beneficial for me to learn it. I figured this project would be a good opportunity to get two birds with one stone.
Ok, here are the two issues I’m having:
- I can’t seem to run debug mode while using the cp7. Every time the project gets deployed, the following message turns up in the debug output screen:
[quote]Using mainboard GHI Electronics FEZHydra version 1.2
Updating display configuration. THE MAINBOARD WILL NOW REBOOT.
To continue debugging, you will need to restart debugging manually (Ctrl-Shift-F5)[/quote]
Whenever I actually hit Ctrl-Shift-F5, it basically goes through the entire deploy process again and I end up with the same message, right back where I was.
I saw another topic on this issue that basically entailed including the display module library in your project, or editing and rebuilding the display module, but as a newbie I’m a bit unsure about this method, and I don’t think the project inclusion would really work since I’m using VB.
- I saw the following on the Hydra developer guide for changing the pixel clock divider to stop flickering:
Register LCDCON1 = new Register(0x00500800); LCDCON1.ToggleBits(0x2000);
Sure enough, when I use purple text, I can see flickering clear as day. Unfortunately, I’m unsure how to implement this fix in VB as “Register” doesn’t seem to be a supported type. Is this because I am failing to include the proper resource/namespace/library or something? Or would this be implemented completely differently in VB? Searching on the subject results in an inundation of hits on dealing with the “registry,” not “registers.”
Is it possible to address this through FEZConfig as well?
Thanks everyone in advance- I’m very much looking forward to learning this platform and getting to the point where I can build modules on my own.
Jon
|
https://forums.ghielectronics.com/t/fez-hydra-problems-with-cp7-display/16068
|
CC-MAIN-2019-22
|
refinedweb
| 440
| 62.58
|
Pandas – filtering records in 20 ways
Filtering records is a quite common operation when you process or analyze data with pandas,a lot of times you will have to apply filters so that you can concentrate to the data you want. Pandas is so powerful and flexible that it provides plenty of ways you can filter records, whether you want to filtering by columns to focus on a subset of the data or base on certain conditions. In this article, we will be discussing the various ways of filtering records in pandas.
Prerequisite:
You will need to install pandas package in order to follow the below examples. Below is the command to install pandas with pip:
pip install pandas
And I will be using the sample data from here, so you may also want to download a copy into your local machine to try out the later examples.
With the below codes, we can get a quick view of how the sample data looks like:
import pandas as pd df = pd.read_excel(r"C:\Sample-Sales-Data.xlsx") df.head(5)
Below is the output of the first 5 rows of data:
Let’s get started with our examples.
Filtering records by label or index
Filtering by column name/index is the most straightforward way to get a subset of the data frame in case you are only interested in a few columns of the data rather than the full data frame. The syntax is to use df[[column1,..columnN]] to filter only the specified columns. For instance, the below will get a subset of data with only 2 columns – “Salesman” and “Item Desc”:
new_df = df[["Salesman","Item Desc"]] new_df.head(5)
Output from the above would be:
If you are pretty sure which are the rows you are looking for, you can use the df.loc function which allows you to specify both the row and column labels to filter the records. You can pass in a list of row labels and column labels like below:
df.loc[[0,4], ["Salesman", "Item Desc"]]
And you would see the row index 0 and 4, column label “Salesman” and “Item Desc” are selected as per below output:
Or you can specify the label range with : to filter the records by a range:
df.loc[0:4, ["Salesman", "Item Desc"]]
You would see 5 rows (row index 0 to 4) selected as per below output:
Note that currently we are using the default row index which is a integer starting from 0, so it happens to be same as the position of the rows. Let’s say you have Salesman as your index, then you will need to do filtering based on the index label (value of the Salesman), e.g.:
df.set_index("Salesman", inplace=True)
df.loc["Sara", ["Item Desc", "Order Quantity"]]
With the above code, you will be able to select all the records with Salesman as “Sara”:
Filtering records by row/column position
Similarly, you can use iloc function to achieve the same as what can be done with loc function. But the difference is that, for iloc, you shall pass in the integer position for both row and columns. E.g.:
df.iloc[[0,4,5,10],0:2]
The integers are the position of the row/column from 0 to length-1 for the axis. So the below output will be generated when you run the above code:
Filtering records by single condition
If you would like to filter the records based on a certain condition, for instance, the value of a particular column, you may have a few options to do the filtering based on what type of data you are dealing with.
The eq and == work the same when you want to compare if the value matches:
flt_wine = df["Item Desc"].eq("White Wine")
df[flt_wine]
Or:
flt_wine = (df["Item Desc"] == "White Wine")
df[flt_wine]
Both will generate the below output:
If you run the flt_wine alone, you will see the output is a list of True/False with their index. This is how the filter works as pandas data frame would filter out the index with False value.
To get the data with the negation of certain condition, you can use ~ before your condition statement as per below:
df[~flt_wine]
#or
df[~(df["Item Desc"] == "White Wine")]
#or
df[(df["Item Desc"] != "White Wine")]
This will return the data with “Item Desc” other than “White Wine”.
And for string data type, you can also use the str.contains to match if the column has a particular sub string.
df[df["Item Desc"].str.contains("Wine")]
If you want to filter by matching multiple values, you can use isin with a list of values:
flt_wine = df["Item Desc"].isin(["White Wine", "Red Wine"])
df[flt_wine].head(5)
And you can also use data frame query function to achieve the same. But the column label with spaces in-between would cause errors when using this function, so you will need to reformat a bit of your column header, such as replacing spaces with underscore (refer to this article for more details ).
With this change in the column header, you shall be able to run the below code with the same result as above isin method.
df1 = df.query("Item_Desc in ('White Wine','Red Wine')")
df1.head(5)
There are other Series functions you can use to filter your records, such as isnull, isna, notna, notnull, find etc. You may want to check pandas Series documentation.
Filtering records by multiple conditions
When you need to filter by multiple conditions where multiple columns are involved, you can also do similar as what we have discussed in above with the & or | to join the conditions.
For filtering records when both conditions are true:
flt_whisky_bulk_order = (df["Item Desc"] == "Whisky") & (df["Order Quantity"] >= 10) df[flt_whisky_bulk_order]
The output would be :
For filtering the records when either condition is true:
flt_high_value_order = (df["Item Desc"] == "Whisky") | (df["Price Per Unit"] >= 50)
df[flt_high_value_order]
The output would be :
Similarly, the above can be done with data frame query function. Below is the example of AND condition:
df1 = df.query("Item_Desc == 'Whisky' and Order_Quantity >= 10") df1.head(5)
Below is the example of OR condition:
df1 = df.query("Item_Desc_ == 'Whisky' or Price_Per_Unit >= 10")
df1.head(5)
Filtering records by dataframe.filter
There is also another filter method which can be used to filter by the row or column label.
Below is an example that can be used to get all the columns with the name starting with “Order” keyword:
df.filter(regex="Order*", axis=1)
you shall see the below output:
Similarly, when applying to row labels, you can axis=0
df.set_index("Order Date", inplace=True) df.filter(like="2020-06-21", axis=0)
Take note that data frame query function only works on the row or column label not any specific data series.
Conclusion
Filtering records is a so frequently used operation whenever you need to deal with the data in pandas, and in this article we have discussed a lot of methods you can use under different scenarios. It may not cover everything you need but hopefully it can solve 80% of your problems. There are other Series functions you may employ to filter your data, but probably you would see the syntax still falls under what we have summarized in this article.
If you are interested in other topics about pandas, you may refer to here.
|
https://www.codeforests.com/2020/08/21/pandas-filtering-records-in-20-ways/
|
CC-MAIN-2022-21
|
refinedweb
| 1,245
| 58.01
|
MooseX::DOM - Easily Create DOM Based Objects
package RSS; use Moose; use MooseX::DOM; dom_value 'version' => '@version'; dom_nodes 'items' => ( fetch => dom_fetchnodes( xpath => 'channel/item', filter => dom_to_class('RSS::Item') ) ); # or, easy way (just get some DOM nodes) # dom_nodes 'items' => 'channel/items'; # or, create your own way to fetch the nodes # dom_nodes 'items' => ( # fetch => sub { ... } # ); no Moose; no MooseX::DOM; package RSS::Item; use Moose; use MooseX::DOM; dom_value 'title'; dom_value 'description'; dom_value 'link'; no Moose; no MooseX::DOM; sub BUILDARGS { my $class = shift; my $args = {@_ == 1? (dom_root => $_[0]) : @_}; return $args; } package main; # parse_file() is automatically created for you. my $rss = RSS->parse_file('rss.xml'); foreach my $item ($rss->items) { print "item link = ", $item->link, "\n"; print "item title = ", $item->title, "\n"; }
MooseX::DOM is a tool that allows you to define classes that are based on XML DOM.
The following DSL is provided upon calling
MooseX::DOM. When
no MooseX::DOM is used, these functions are removed from your namespace.
Declares that a method named $name should be built, using the given spec. Returns a list of nodes, or what the filter argument trasnlates them to.
If %spec is omitted, $name is taken to be the xpath to fetch.
Declares that a method named $name should be built, using the given spec. Returns the result of the fetch, whatever that may be.
If %spec is omitted, $name is taken to be the xpath to fetch.
Creates a closure that fetches some nodes
Creates a closure that transforms nodes to something else, typically an object.
The following methods are built onto your class automatically.
These methods allow you to parse a piece of XML, and build a MooseX::DOM object based on it.
Does a DOM XPath lookup. Returns a plain DOM object.
Does a DOM XPath lookup. Returns whatever value the XPath results to.
By default dom_to_class() gives your object a single DOM element to play with. This is a problem if your class is a MooseX::DOM object and it doesn't already handle single argument constructors. In such cases, a simple builtin BUILDARGS can be provided for you. Simply do
package MyObject; use Moose; use MooseX::DOM qw(BUILDARGS);
Which will install a default BUILDARGS method for your class.
Daisuke Maki
<daisuke@endeworks.jp>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See
|
http://search.cpan.org/~dmaki/MooseX-DOM-0.00999_02/lib/MooseX/DOM.pm
|
CC-MAIN-2015-48
|
refinedweb
| 399
| 65.42
|
Dipankar Sarma wrote:>Provide a rq_has_rt_task() interface to detect runqueues with>real time priority tasks. Useful for RCU optimizations.>Can you make rq_has_rt_task the slow path? Adding things like thiscan actually be noticable on microbenchmarks (eg. pipe based ctxswitching). Its probably cache artifacts that I see, but it wouldn'thurt to keep the scheduler as tight as possible.I think this should cover it.int rq_has_rt_task(int cpu){ runqueue_t *rq = cpu_rq(cpu); return (sched_find_first_bit(rq->active) < MAX_RT_PRIO);}Any good?-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
https://lkml.org/lkml/2004/1/8/96
|
CC-MAIN-2016-18
|
refinedweb
| 107
| 53.78
|
stateless function components. You also might want to know how to convert to ES6 classes and I’ve got a video and article for that as well.
Replace createClass
When replacing
React.createClass there are 2 options:
- use an ES6 class (learn how here)
- use a stateless function stateless functions – another one covers ES6 classes.
Before: createClass
Here’s the old syntax. Everything is a property of an object passed to React.createClass.> ); } });
After: Stateless Function
Here’s the same component, converted to a stateless function. It’s fewer lines of code, too! };
What changed?
- Props are passed as an argument: No more
this.props.whatever. The first argument to the function is an object containing the props. The code below uses the ES6 destructuring syntax (the
{ author }part) which pulls the named keys out of the object and stores them in variables of the same name.
- PropTypes are pulled out: Since the component is a function now, its PropTypes are a property on the function itself – instead of being a property on the object that describes the component.
- PropTypes is its own library: In React 15.5, there is no more
React.PropTypes. Instead, there’s a separate module that must be installed with
npm install prop-types, and can be imported as
import PropTypes from 'prop-types'.
Example Project
I put together an example project with 9 different components, both before and after conversion from React.createClass to stateless functions. You can download it here (no email required).
|
https://daveceddia.com/convert-createclass-to-function-component/
|
CC-MAIN-2019-35
|
refinedweb
| 250
| 66.64
|
If you want fast animation (games!), you have to use DirectX. Try filling the screen by drawing each pixel separately using GDI. Compare it with DirectX, which gives you practically direct access to the screen buffer. There's no competition!
The bad news is that DirectX involves dealing with COM interfaces. The good news is that you can encapsulate them nicely inside C++ classes. Let me show you first how to use these classes to write a simple application that displays an animated, rotating, bitmap. We'll use Windows timer to drive the animation. We'll have to:
Let's start with the WM_PAINT message. This message is sent to us when Windows needs to repaint our window. We have to stash somewhere a complete animation frame, so that we can quickly blit it to screen in response to WM_PAINT. The storage for this frame will be called the back surface.
Upon receiving the timer message, we have to paint a new frame on the back surface. Once we're done, we'll invalidate our window, so that WM_PAINT message will be sent to us.
Upon resizing the window, we have to create a new back surface, corresponding to the new window size. Then we'll draw on it and invalidate the window.
The initialization involves creating the timer, creating the World (that's where we keep our bitmap and drive the animation), creating the View, and setting the first timer countdown.
void Controller::Create (CREATESTRUCT * create) { _timer.Create (_h, 1); _world = new World (create->hInstance, IDB_RS); _view.Create (_h, _world); _timer.Set (10); }
Here's our response to WM_SIZE. We let the View know about the new size (it will create a new back surface), we call it's Update method which draws the animation frame, and we invalidate the window.
bool Controller::Size (int width, int height) { _view.Size (_h, width, height); _view.Update (); // force repaint _h.Invalidate (false); return true; }
In response to WM_PAINT, we let the View do the painting (blit the back surface to the screen). We also have to tell Windows that the painting is done--validate the uncovered area. This is done simply by constructing the PaintCanvas object.
bool Controller::Paint (HDC hdc) { _view.Paint (_h); // validate painted area PaintCanvas canvas (_h); return true; }
In response to WM_TIMER, we kill the timer, tell the World to move one frame ahead, let the View repaint the frame on the back surface, invalidate the window (so that Paint is called) and set the timeout again.
bool Controller::Timer (int id, TIMERPROC * proc) { _timer.Kill (); _world->Step (); _view.Update (); // force repaint _h.Invalidate (false); _timer.Set (10); return true; }
There is one more thing. DirectX doesn't like when a screen saver kicks in, so we have to preempt it.
bool Controller::SysCommand (int cmd) { // disable screen savers if (cmd == SC_SCREENSAVE || cmd == SC_MONITORPOWER) return true; return false; }
By the way, this is how SysCommand is called from the window procedure:
case WM_SYSCOMMAND: if (pCtrl->SysCommand (wParam & 0xfff0)) return 0; break;
Let's now have a closer look at View, which is the class dealing with output to screen. Notice two important data members, the Direct::Draw object and the Direct::Surface object.
class View { public: View (); void Create (HWND h, World * world); void Size (HWND h, int width, int height); void Update (); void Paint (HWND h); private: Direct::Draw _draw; Direct::Surface _backSurface; World * _world; int _dx; int _dy; };
I have encapsulated all DirectX classes inside the namespace Direct. This trick enforces a very nice naming convention, namely, you have to prefix all DirectX classes with the prefix Direct::.
The Direct::Draw object's duty is to initialize the DirectX subsystem. It does it in it's constructor, so any time View is constructed (once per program instantiation), DirectX is ready to use. It's destructor, by the way, frees the resources used by DirectX.
Direct::Surface _backSurface will be used by View to draw the animation upon it.
The initialization of DirectX also involves setting up the collaboration level with Windows. Here, we are telling it to work nicely with other windows, rather then taking over in the full-screen mode.
void View::Create (HWND h, World * world) { _world = world; // Set coopration with Windows _draw.SetCoopNormal (h); }
Back surface is created (and re-created) in response to WM_SIZE message. Surfaces are implemented in such a way that regular assignment operation does the right thing. It deallocates the previous surface and initializes a new one. Notice that the constructor of an OffScreenSurface takes the Direct::Draw object and the dimensions of the surface in pixels.
void View::Size (HWND h, int width, int height) { _dx = width; _dy = height; if (_dx == 0 || _dy == 0) return; _backSurface = Direct::OffScreenSurface (_draw, _dx, _dy); }
Painting is slightly tricky. We have to get access to the primary drawing surface, which is the whole screen buffer. But since we are not using the full-screen mode, we want to draw only inside the rectangular area of our window. That's why we create a Direct::Clipper, to clip anything that would fall outside of that area. The clipper figures out the correct area using the handle to the window that we are passing to it.
Next, we create the primary surface and pass it the clipper. Now we can blit the image directly from our back surface to the screen. Again, since the primary surface represents the whole screen, we have to offset our blit by specifying the target rectangle. The auxillary class Direct::WinRect retrieves the coordinates of that rectangle.
void View::Paint (HWND h) { if (_dx == 0 || _dy == 0) return; // Clip to window Direct::Clipper clipper (_draw); clipper.SetHWnd (h); // Screen surface Direct::PrimarySurface surf (_draw); surf.SetClipper (clipper); Direct::WinRect rect (h); // Blit from back surface to screen surf.BltFrom (_backSurface, &rect); }
Finally, the actual drawing is done using direct access to the back surface buffer. But first, we flood the back surface with white background. Then we construct the Direct::SurfaceBuf. This is the object that let's us set pixels directly into the buffer's memory (depending on implementation, it might be your video card memory or a chunk of your system memory). The details of our drawing algorithm are inessential here. Suffice it to say that the work of setting the pixel is done in the SetPixel method.
void View::Update () { if (_dx == 0 || _dy == 0) return; try { // white background _backSurface.Fill (RGB (255, 255, 255)); { // Get direct access to back surface Direct::SurfaceBuf buf (_backSurface); // draw bitmap within a centered square int side = 100; if (_dx < side) side = _dx; if (_dy < side) side = _dy; int xOff = (_dx - side) / 2; int yOff = (_dy - side) / 2; assert (xOff >= 0); assert (yOff >= 0); double dxInv = 1.0 / side; double dyInv = 1.0 / side; for (int i = 0; i < side; ++i) { for (int j = 0; j < side; ++j) { double u = dxInv * i; double v = dyInv * j; COLORREF color = _world->GetTexel (u, v); // draw pixel directly buf.SetPixel (xOff + i, yOff + j, color); } } } // Paint will blit the image to screen } catch (char const * msg) { ::MessageBox (0, msg, "Viewer error", MB_OK | MB_ICONERROR); throw; } catch (...) { ::MessageBox (0, "Unknown error", "Viewer error", MB_OK | MB_ICONERROR); throw; } }
Besides being able to set individual pixels quickly, DirectX also provides ways to efficiently blit bitmaps or even use GDI functions to write to a surface.
As mentioned before, all DirectDraw objects are enclosed in the Direct namespace. The fundamental object, Direct::Draw, is responsible for the initialization and the release of the DirectDraw subsystem. It can also be used to set up the cooperation level with Windows. It's easy to add more methods and options to this class, as the need arises.
namespace Direct { // Direct Draw object class Draw { public: Draw (); ~Draw () { _pDraw->Release (); } void SetCoopNormal (HWND h) { HRESULT res = _pDraw->SetCooperativeLevel(h, DDSCL_NORMAL); if(res != DD_OK) throw "Cannot set normal cooperative level"; } IDirectDraw * operator-> () { return _pDraw; } private: IDirectDraw * _pDraw; }; } // implementation file using namespace Direct; Draw::Draw () { HRESULT res = ::DirectDrawCreate (0, &_pDraw, 0); if(res != DD_OK) throw "Cannot create Direct Draw object"; }
DirectDraw is based on COM interfaces, so it makes sense to encapsulate the "interface magic" in a handy template. The Direct::IFace class takes care of reference counting, pointer dereferencing and assignment (see the assignment of surfaces above).
template<class I> class IFace { public: IFace (IFace<I> & i) { i->AddRef (); _i = i._i; } ~IFace () { if (_i) _i->Release (); } void operator = (IFace<I> & i) { if (i._i) i._i->AddRef (); if (_i) _i->Release (); _i = i._i; } I * operator-> () { return _i; } operator I * () { return _i; } protected: IFace () : _i (0) {} protected: I * _i; };
A drawing surface is an example of an interface. First we define a generic surface, then we'll specialize it to primary and off-screen surfaces.
class Surface: public IFace<IDirectDrawSurface> { friend class SurfaceBuf; protected: // Locking and unlocking the whole surface void Lock (SurfaceDesc & desc) { assert (_i != 0); HRESULT res; do res = _i->Lock (0, &desc, 0, 0); while (res == DDERR_WASSTILLDRAWING); if(res != DD_OK) throw "Cannot lock surface"; } void Unlock () { assert (_i != 0); _i->Unlock (0); } public: Surface () {} void GetDescription (SurfaceDesc & desc) { HRESULT res = _i->GetSurfaceDesc (&desc); if(res != DD_OK) throw "Cannot get surface description"; } void SetClipper (Clipper & clipper) { assert (_i != 0); HRESULT res = _i->SetClipper (clipper); if(res != DD_OK) throw "Cannot set clipper"; } void BltFrom (Surface & src, RECT * dstRect = 0, RECT * srcRect = 0) { assert (_i != 0); HRESULT res = _i->Blt (dstRect, src._i, srcRect, 0, 0); if(res != DD_OK) throw "Cannot perform a blt"; } void Fill (COLORREF color); };
When you create a surface, it has to be one of the derived ones. The primary surface lets you draw directly on your screen, the off-screen surface lets you prepare a picture off-screen in a format that can be very quickly transferred to the screen.
class PrimarySurface: public Surface { public: PrimarySurface () {} PrimarySurface (Draw & draw) { Init (draw); } void Init (Draw & draw) { SurfaceDesc desc; desc.SetCapabilities (DDSCAPS_PRIMARYSURFACE); HRESULT res = draw->CreateSurface (&desc, &_i, 0); if(res != DD_OK) throw "Cannot create primary surface"; } }; class OffScreenSurface: public Surface { public: OffScreenSurface () {} OffScreenSurface (Draw & draw, int width, int height) { Init (draw, width, height); } void Init (Draw & draw, int width, int height) { SurfaceDesc desc; desc.SetCapabilities (DDSCAPS_OFFSCREENPLAIN); desc.SetDimensions (width, height); HRESULT res = draw->CreateSurface (&desc, &_i, 0); if(res != DD_OK) throw "Cannot create off-screen surface"; } };
In order to directly access pixels in a surface, you have to lock it. The class, SurfaceBuf, encapsulates locking and unlocking in its constructor and destructor, so that you don't have to worry about it. It also provides direct access to the buffer through its SetPixel method. Notice the low-level address calculations and color formatting.
class SurfaceBuf { public: SurfaceBuf (Surface & surface) : _surface (surface) { SurfaceDesc desc; surface.Lock (desc); _pitch = desc.Pitch (); _buf = static_cast<unsigned char *> (desc.Buffer ()); _format.Init (desc); int bpp = _format.BitsPp (); if (bpp != 16 && bpp != 24 && bpp != 32) { surface.Unlock (); throw "Only high color and true color supported"; } } ~SurfaceBuf () { _surface.Unlock (); } void SetPixel (int x, int y, COLORREF color) { switch (_format.BitsPp ()) { case 16: { int offset = y * _pitch + x * 2; unsigned short * p = reinterpret_cast<unsigned short *> ( _buf + offset); *p &= _format.Mask (); *p |= static_cast<unsigned short> ( _format.ColorValue16 (color)); } break; case 24: { int offset = y * _pitch + x * 3; unsigned long * p = reinterpret_cast<unsigned long *> ( _buf + offset); *p &= _format.Mask (); *p |= _format.ColorValue24 (color); } break; case 32: { int offset = y * _pitch + x * 4; unsigned long * p = reinterpret_cast<unsigned long *> ( _buf + offset); *p &= _format.Mask (); *p |= _format.ColorValue32 (color); } break; } } private: Surface & _surface; unsigned char * _buf; int _pitch; PixelFormat _format; };
There is a separate class to deal with the formatting of color values. As you can see, depending on the bits-per-pixel setting of the video card, different color encodings are used. The surface descriptor contains bit masks that are used in this encoding. These masks vary not only between bpp settings, but also between video cards. The most complex is the encoding of the color for the 6-bit setting. In 32-bit mode the card can actually support more colors that can be packed into the standard Windows COLORREF. Here, we're not making use of it, but it would be an interesting area to experiment.
class PixelFormat { public: PixelFormat () {} PixelFormat (SurfaceDesc & desc) { Init (desc); } void Init (SurfaceDesc & desc); int BitsPp () const { return _bpp; } unsigned long Mask () const { return _mask; } unsigned long ColorValue16 (COLORREF color) { return ( (GetRValue (color) << _redShift) & (_redMask << 16) | (GetGValue (color) << _greenShift) & (_greenMask << 16) | (GetBValue (color) << _blueShift) & (_blueMask << 16)) >> 16; } unsigned long ColorValue24 (COLORREF color) { return (GetRValue (color) << 16) & _redMask | (GetGValue (color) << 8) & _greenMask | GetBValue (color) & _blueMask; } unsigned long ColorValue32 (COLORREF color) { return (GetRValue (color) << 16) & _redMask | (GetGValue (color) << 8) & _greenMask | GetBValue (color) & _blueMask; } unsigned long ColorValue (COLORREF color) { switch (_bpp) { case 16: return ColorValue16 (color); case 24: return ColorValue24 (color); case 32: return ColorValue32 (color); default: throw "PixelFormat: only 16, 24 and 32 bits supported"; } } private: int _bpp; // bits per pixel 4, 8, 16, 24, or 32 unsigned long _redMask; unsigned long _greenMask; unsigned long _blueMask; unsigned _redShift; unsigned _greenShift; unsigned _blueShift; unsigned long _mask; }; unsigned HiBitShift (unsigned val) { unsigned i = 0; while (val != 0) { val >>= 1; ++i; } return i; } void PixelFormat::Init (SurfaceDesc & desc) { DDPIXELFORMAT & format = desc.PixelFormat (); if (format.dwFlags != DDPF_RGB) throw "Direct Draw: Non-RGB formats not supported"; _bpp = format.dwRGBBitCount; _redMask = format.dwRBitMask; _greenMask = format.dwGBitMask; _blueMask = format.dwBBitMask; _mask = ~(_redMask | _greenMask | _blueMask); switch (_bpp) { case 16: _redShift = HiBitShift (_redMask) + 8; _greenShift = HiBitShift (_greenMask) + 8; _blueShift = HiBitShift (_blueMask) + 8; break; case 24: break; case 32: break; default: throw "Only 16, 24 and 32 bit graphics supported"; } }
Notice that this tutorial only scratches the surface of DirectX. There are several versions of DirectDraw. There is Direct3D for three-dimensional graphics (although it seems like Open GL might be a better platform). Sound can be dealt with using DirectSound and input devices have their DirectInput. All these subsystems can be encapsulated using similar techniques.
|
http://www.relisoft.com/Win32/direct.html
|
CC-MAIN-2013-20
|
refinedweb
| 2,312
| 55.84
|
Hello
So my problem is I've been making a bunch of flash banners(AS2.0) for a bunch of different publications. They all have different clickTags. I used to publish sets(160,300,728) for each tag but I feel there must be an easier way. I would like to use the same banner for ALL the trafficking.
Just to be clear I have 1 button instance on my banner. I just want to add multiple click tags to the banner to cover this "Non-Industry Standard" solution to flash banners.
Here are a few example of tags.
on (release){getURL(clickTag, "_blank");}
on (release){getURL(_root.clickTAG, "_blank");}
on (release) {getURL(_level0.clickTag, "_blank");}
on (release){getURL(clickTAG, "_blank");}
Do I need an if/else statement or can I fire them all off all at once and whatever the browser is set to receive it will only receive that call.
Thanks in advance for any help.
There's something like an "universal clicktag", it could help you a lot:
on (release) { function cFcTg(t) { return (t.substr(0, 7) == 'http://' || t.substr(0, 8) == 'https://'); } var fcTg = ''; var fcTt = '_blank'; var cTgM = 'clicktag'; var cTtM = 'clicktarget'; for (prop in this) { var p = prop.toLowerCase(); if (p == cTgM && cFcTg(this[prop])) fcTg = this[prop]; if (p == cTtM) fcTt = this[prop]; } if(fcTg == '' || fcTt == '_blank') for (prop in _root) { var p = prop.toLowerCase(); if (p == cTgM && cFcTg(_root[prop]) && fcTg == '') fcTg = _root[prop]; if (p == cTtM && fcTt == '_blank') fcTt = _root[prop]; } if(fcTg == '' || fcTt == '_blank') for (prop in _level0) { var p = prop.toLowerCase(); if (p == cTgM && cFcTg(_level0[prop]) && fcTg == '') fcTg = _level0[prop]; if (p == cTtM && fcTt == '_blank') fcTt = _level0[prop]; } if (cFcTg(fcTg)) getURL(fcTg, fcTt); else getURL("", fcTt); }
Although not all ad servers accept it!
Wow now thats a line a code. Yeah if it doesn't work on all servers than it really puts me back in the same place I was beforeThansk for the help. I'll keep trying to figure this out.
Thanks,
What you're trying to do, won't work anyway. Firing off 4 events at the same time, will in theory open 4 new windows... so you need to use the If statement. It's not that the code in my example doesn't work, it's way over the top, and by far the best solution I ever found to catch all the different clicktags.
But that said, in my experience, Microsoft can be very picky about this. If you do not use their example code literally, it will be rejected...
We use our own little AIR app, that's capable of changing the clicktag in multiple files.
Yeah I didn't think what I was doing would work. I'm looking for suggestions
on the best way to handle it. I don't have a way to recreate the test enviorment for the pubs I'm sending to.
Thanks for the help and the education
|
https://forums.adobe.com/message/3578300
|
CC-MAIN-2018-13
|
refinedweb
| 495
| 82.85
|
Style Guide for Packaging Python Libraries
NOTE: This is a draft proposal. Comments are welcome and encouraged.
NOTE: Also see Python/AppStyleGuide for alternative single package debian/rules., invoked via python setup.py test.
- The package has some documentation buildable by Sphinx.
Your Debian packaging uses debhelper, dh_python2, and is preferably source format 3.0 (quilt).
- debhelper v8 or newer is assumed, but v7 probably works too (not sure about earlier ones, anyway, update your package!)
The design of this document is to capture best-practices that you can cargo cult into your own packages. It will forever be a work in progress.
debian/control, so you need to watch carefully to make sure your local builds don't do this, and be sure to add the http_proxy line in your debian/rules file (see below)..
Start with a fairly straightforward debian/control file.-docs Description: Python frobnicator (Python 2) This package frobnicates a Python-based doohicky so that you no longer need to kludge a dingus to make the doodads work. . This is the Python 2 version of the package. Package: python3-foo Architecture: all Depends: ${python3:Depends}, ${misc:Depends} Suggests: python-foo-docs Description: Python frobnicator (Python 3) This package frobnicates a Python-based doohicky so that you no longer need to kludge a dingus to make the doodads work. . This is the Python 3 version of the package.
Notice the Suggests line. If the same set of documentation is available for both Python 2 and Python 3, it's best to put those files into a separate python-foo-docs package, like so:
Package: python-foo-docs
Here is a debian/rules file for you to start with. First, I'll show you the whole thing, then I'll explain it line by line.
#DH_VERBOSE=1 PYTHON2_VERSIONS=$(shell pyversions -vr) PYTHON3_VERSIONS=$(shell py3versions -vr) PYTHON_VERSIONS=${PYTHON2_VERSIONS} ${PYTHON3_VERSIONS} # Prevent setuptools/distribute from accessing the internet. export http_proxy = %: dh $@ --with python2,python3,sphinxdoc ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) test-python%: python$* setup.py test -vv override_dh_auto_test: $(foreach pyversion,${PYTHON_VERSIONS},$(pyversion:%=test-python%)) endif build-python%: python$* setup.py build override_dh_auto_build: $(PYTHON3:%=build-python%) dh_auto_build install-python%: python$* setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb override_dh_auto_install: $(PYTHON3:%=install-python%) dh_auto_install override_dh_installchangelogs: dh_installchangelogs -k foo/NEWS.rst override_dh_installdocs: python setup.py build_sphinx dh_installdocs build/sphinx/html override_dh_auto_clean: dh_auto_clean rm -rf build rm -rf *.egg-info
The file starts with the standard #! line. I like adding the (commented out when uploading) DH_VERBOSE line because it can make build problems easier to debug.
The next three lines are:
PYTHON2_VERSIONS=$(shell pyversions -vr) PYTHON3_VERSIONS=$(shell py3versions -vr) PYTHON_VERSIONS=${PYTHON2_VERSIONS} ${PYTHON3_VERSIONS}
This gives you make variables which will contain (just) the version numbers for the Python versions you are requesting your package be built against. See the manpage for details, but essentially this consults the X-Python-Version field in your debian/control file and matches it against the Python versions available for your distroversion. For example, on Wheezy, PYTHON2_VERSIONS would contain 2.6 2.7.
py3versions does the same, but for Python 3, and it uses the X-Python3-Version field in debian/control. For example, on Wheezy, PYTHON3_VERSIONS would contain 3.2. If upstream does not yet support Python 3, you can still leave this line enabled, or comment it out, but you will have to adjust some of the lines that follow.
The next line is a safety valve:
# Prevent setuptools/distribute from accessing the internet. export http_proxy =
setuptools-based setups have the annoying -- and buggy -- behavior of trying to download dependencies from PyPI when they aren't locally available. Some build environments block this (e.g. by disabling the network), but if not, then the build could appear to succeed, when in fact it's only satisfying its setup.py dependencies external to the archive. To prevent this even in local builds, where downloading may succeed, add export http_proxy = to your debian/rules file. Port 9 is the Discard Protocol, so this should safely prevent downloading even if something is actually listening on the port. Now if you are missing a dependency, even your local builds will fail early, which is a good thing!
The next line is the standard debhelper-based catch-all rule which is used to get the whole build started:
%: dh $@ --with python2,python3,sphinxdoc
What's important to note here is that both of the dh_python2 and dh_python3 helpers are being invoked, as well as the Sphinx documentation helper. If upstream does not yet support Python 3, omit the python3 helper for now. If upstream doesn't have Sphinx-based documentation, omit the sphinxdoc helper for now.
The next few lines enable the test suites to be run for each version of the package that gets built. If upstream has a test suite that passes on Debian, then it's a very good idea to enable it in your build. Testing is always a good thing, and in general (although there are exceptions), you want your build to fail if the test suite fails.
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) test-python%: python$* setup.py test -vv override_dh_auto_test: $(foreach pyversion,${PYTHON_VERSIONS},$(pyversion:%=test-python%)) endif
Things to note here.
The make conditional wrapping the rules allows you to set DEB_BUILD_OPTIONS=nocheck to temporarily disable the test suite. This can be useful while your debugging your build if the test suite takes a long time to run.
You will need to change the rule's command if the package's test suite is invoked in a way other than python setup.py test. The way it is above enables a higher level of verbose output, which again is useful for general diagnostics.
The dependencies in the override_dh_auto_test target uses PYTHON_VERSIONS to cover all versions of Python 2 and Python 3 for which your package is built.
These next few lines build the package:
build-python%: python$* setup.py build override_dh_auto_build: $(PYTHON3:%=build-python%) dh_auto_build
Note that debhelper will automatically build the Python 2 version, but does not yet know how to build Python 3 packages. Thus, the override is necessary to add dependencies that trigger the Python 3 build (first rule above). In the body of the override, the standard dh_auto_build is invoked, which will properly build the Python 2 version of the package. If upstream doesn't yet support Python 3, you can comment out both of these rules and just let the normal dh_auto_build process build the Python 2 version.
The next few lines install the package for all supported versions of Python.
install-python%: python$* setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb override_dh_auto_install: $(PYTHON3:%=install-python%) dh_auto_install
Again, this is only necessary because dh doesn't know how to install the Python 3 versions by default. It works in a similar manner as the build rules above. Like above, you can comment out all of these lines (or omit them) if upstream does not yet support Python 3.
Also note that --install-layout=deb is a Debian-only argument for setup.py. It was added to python-distribute to support Debian's dist-packages convention.
The next lines are useful if upstream has a non-standard change log that needs to be installed. In this case, the foo package has a news file that serves as its log of changes. Consult the dh_installchangelogs manpage for details about whether you need this override or not.
override_dh_installchangelogs: dh_installchangelogs -k foo/NEWS.rst
If upstream has documentation that's built by Sphinx, these next few lines will build and install them for the separate python-foo-docs package mentioned above.
override_dh_installdocs: python setup.py build_sphinx dh_installdocs build/sphinx/html
Finally, you should ensure that your package can be built twice in a row, by properly cleaning up any artifacts of your build. By default dh_clean will do most of the work, but Python packages need a little extra help, thus this override.
override_dh_auto_clean: dh_auto_clean rm -rf build rm -rf *.egg-info
Some packages produce other artifacts, or modify files in the upstream original tarball. Those are harder to clean and may produce build failures when built twice in a row.
debian/*.install files
When the same source is used to build three different binary packages (e.g. the Python 2 version, the Python 3 version, and the common documentation package), you will need debian/*.install files to get everything in the proper place for packaging. For most simple Python packages, this is fairly easy. You will not need an .install file for the documentation (TBD: explain why this works automatically), but you will for the Python 2 and Python 3 code.
Here is the debian/python-foo.install file (i.e. the Python 2 version):
usr/lib/python2*
and here is the debian/python3-foo.install file:
usr/lib/python3
Usually, that is all you need.
debian/*.pyremove
Upstream source may install some files that you don't care about including in your Debian packages. The way to handle this is by adding a debian/python-foo.pyremove file. This should work for both Python 2 and Python 3. For example:
foo/conf.py foo/README.rst foo/NEWS.rst foo*.egg-info/SOURCES.txt
TBD: better explanation of the rationale for removing these.
TODO
- describe egg related information, what should go in the binary package and what shouldn't.
|
https://wiki.debian.org/Python/LibraryStyleGuide?action=recall&rev=21
|
CC-MAIN-2015-32
|
refinedweb
| 1,556
| 64.71
|
Hello,
As a maintainer of graphics/blender, could you have a look at PR #252648:
In short, TBB version 2021 will soon be available as devel/onetbb but the port you maintain does not build correctly with it, see the following Poudriere run:
and error logs:
c++ [...] /wrkdirs/usr/ports/graphics/blender/work/blender-2.91.0/intern/cycles/bvh/bvh.cpp
In file included from /wrkdirs/usr/ports/graphics/blender/work/blender-2.91.0/intern/cycles/bvh/bvh.cpp:25:
In file included from /wrkdirs/usr/ports/graphics/blender/work/blender-2.91.0/intern/cycles/bvh/../bvh/bvh_build.h:27:
In file included from /wrkdirs/usr/ports/graphics/blender/work/blender-2.91.0/intern/cycles/bvh/../util/util_task.h:22:
/wrkdirs/usr/ports/graphics/blender/work/blender-2.91.0/intern/cycles/bvh/../util/util_tbb.h:39:14: error: no member named 'self' in namespace 'tbb::v1::task'
tbb::task::self().cancel_group_execution();
~~~~~~~~~~~^
1 error generated.
ninja: build stopped: subcommand failed.
- to disable option OPENVDB (see PR #252788)
Thanks for your contribution,
Best regards,
Ganael.
Let me quote your feedback from PR #252687:
> I'm also the maintainer for blender. I'm starting to think that being able to
> co-install the old tbb will need to be an option for a while.
I would like to avoid that situation, as much as possible. That would mean relocate tbb to a dedicated subdir and patch every remaining dependent port.
>.
It seems this is what we are seeing in the logs : cycles fail to compile. The upstream probably faces that exact same situation ; have you tried to ask for help from Blender community/devs ?
Thanks a lot,
Best regards,
Ganael.
The last bug you added as depends is missing a digit.
About to test at a patch that is meant to fix the tbb build for blender.
Fixed, thanks!
And good news for the patch :)
Created attachment 221955 [details]
maintainer update for graphics/blender
Adjust graphics/blender to build with onetbb.
Disable OPENVDB and OPENIMAGEDN until dependencies transition to onetbb
New patches combine and
Thanks a lot! I'll keep that patch for the big switch.
Patch committed, thanks!
|
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=252868
|
CC-MAIN-2021-21
|
refinedweb
| 361
| 50.02
|
Introduction:
Struts framework was launched by Apache in the year 2000. Since then struts 1 version was running very well. But to meet the current product demands and requirements, the struts 2 version was launched and thereafter, recently, Apache no longer supports struts 1 version.
There are two versions of Struts framework: struts 1.x and struts 2.x. Here ‘x’ stands for more subversions of struts.
This chapter will cover the major differences between both these versions and for detailed descriptions and examples you can refer next chapters of this tutorial.
Differences between Struts 1.x and 2.x:
The main difference between struts 1.x and struts 2.x is the configuration file. In struts 1.x version, the configuration is named as struts-config.xml where as in struts 2.x version it is named as struts.xml
In struts 1.x version, for every page, multiple tag libraries have to be included. That is, there are different tag libraries of including the functionality of HTML, Beans, Logic, etc. Whereas in struts 2.x version, only one tag library encapsulates the functions of all the individual libraries. So there is only one include statement here.
In struts 1.x :
<%@ taglib uri = "/WEB-INF/struts-html.tld" prefix = "html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix = "logic" %>
<%@ taglib uri = "/WEB-INF/struts-bean.tld" prefix = "bean" %>
In struts 2.x :
<%@ taglib uri = "/struts-tags" prefix = "s" %>
Mutual exclusion was a problem in struts 1.x version. The classes responsible for Action are supposed to look after resource allocation in a proper manner. That is, the respected operations are to be coded in thread-safe manner. In other words, either synchronized methods or synchronized blocks (from core Java) are to be used. While in struts 2.x version, thread-safety is not an issue.
In struts 1.x, the Java beans and Action classes are separately defined. That is, for each Action class, the variables used inside it are defined (using getter and setter methods) in separate beans class. While in struts 2.x version, Java beans and action classes are combined together.
Struts 1.x is servlet dependent. The reason is, the Action classes of struts 1.x version have to extend org.apache.struts.action.Action class and provide implementation of execute() method. While in case of struts 2.x framework, the Action classes have flexibility in implementing the Action interface or extending ActionSupport class. Both the interface and the class have execute() method which becomes optional to define if used by extending the ActionSupport class.
In struts 1.x:
import org.apache.struts.action.*; class calculate extends Action { //body of class public String execute() { // body of method } }
In struts 2.x:
import org.apache.struts.action.*; class calculate extends Aciton { //body of class }
OR
class calculate implements ActionSupport { //body of class public String execute() { // body of method } }
- In Struts 1.x framework, front end is totally controlled by the ActionServlet whereas, in Struts 2.x, Filters can be used as a front end controller.
- JSTL’s (JSP standard tag library) EL is used as an expression language in struts 1.x while struts 2.x used OGNL (Object Graph Notation Language) for expression language.
- In struts 1.x, validations are performed in ActionForm manually. Where as in struts 2.x version, XWork Validator is used which provides validations for some specific fields automatically.
- The main drawback of using struts 1.x framework is that all the request processors (action handlers) follow the same life cycle. While struts 2.x framework is designed in such a way that all the interceptors follow a different life cycle. That is struts 2.x actions can be customized and thus it is more flexible and feasible to use.
Easy to remember the differences between Struts 1. x and 2. x:
|
https://wideskills.com/struts/versions-struts
|
CC-MAIN-2022-27
|
refinedweb
| 641
| 62.64
|
I am trying to make some simulations of chaotic systems, for instance X(k) = 4 X(k) (1 - X(k-1)) but I noticed that for all these systems, the loss of precision propagates exponentially, to the point that after 50 iterations, all values generated are completely wrong. I wrote some code in Perl using the BigNum library (providing hundreds of decimals accuracy) and it shows how dramatic standard arithmetic fails in this context.
You can check out the context, my code, and an Excel spreadsheet that illustrates the issue, here.
I am looking for a piece of code in Python that could nicely do the job, probably using some kind of BigNum library in Python? Anyone can make recommendations, or re-write my code in Python? Alternatively, how could this be done in R?
Thank you!
Source for picture: click here.
For arbitrary precision in many programming languages, check out this reference. Not sure if it is up-to-date and correct, but could not find anything about R. Some of these packages are not truly "arbitrary precision." More on this (for Python) here.
Views: 6753
<![if !IE]>▶<![endif]> Reply to This
I don't see any way to do it in R or Python in a way that would execute quickly enough. Two possible alternatives:
Why do you need such big integers? I find that R's standard RNG -- a Mersenne twister -- or L'Ecuyer's WELL package in R work for me.
<![if !IE]>▶<![endif]> Reply
Hi David,
My goal here is to illustrate high precision computing, in a context where many scientists are not aware that their simulations are wrong after just 50 iterations (though, due to the nature of the process, it does not really matter.)
I am aware of the Mersenne twister, and yes it is very good for random number generation. Would love to see how R and Python compare in terms of high precision computing, regardless of the application. Yep, C has nice libraries too for that purpose.
Thanks,
Vincent
<![if !IE]>▶<![endif]> Reply
As for Python, someone on Reddit posted the following, with seed = 3/10:
Now, if I run that I get:
With fixed being the result using float, arbitrary being decimal.Decimal, and diff being what I believe represents the accumulated rounding error. That said I can't really run your Perl, and I'm not sure I haven't missed something transcribing your code, and since we're starting with different seeds the values in your spreadsheet bear no relation.
My comment is that over the 10,000 iterations, the difference at any given iteration, is much bigger than 0.1229, on average. The difference was computed only at iteration 10,000 in the above Python code.
<![if !IE]>▶<![endif]> Reply
Here's a Java version. You should find your own implementation of bigSqrt. This Java version diverges from the correct answer at iteration #30. I was hoping it would be better. Unfortunately Java does not have a built-in version of square root for BigDecimal.
public static void main(String[] args) {
BigDecimal pi = new BigDecimal(4 * atan2(1,1));
BigInteger bigint = new BigInteger("10").pow(50);
BigDecimal seed = pi.divide(new BigDecimal(11), MathContext.DECIMAL128);
BigDecimal z = seed;
long k;
String zp;
for (k=1; kspan>10000; k++) {
z = z.multiply(new BigDecimal("4")).multiply(new BigDecimal("1").subtract(z));
z = bigSqrt(z, MathContext.DECIMAL128);
z = new BigDecimal(bigint).multiply(z).add(new BigDecimal(".5")).setScale(0, RoundingMode.CEILING).divide(new BigDecimal(bigint));
zp = String.format("%.10f", z);
System.out.println(k);
System.out.println(zp);
}
}
<![if !IE]>▶<![endif]> Reply
Using the Apfloat Java JAR library available at, you can generate very high precision numbers in Java code (hundreds or thousands of digits or any arbitrary number of digits, computation speed will degrade as you need more precision obviously). Below is my Java code generating numbers using the well known iterative function x(k+1) = 4*x(k)*(1-x(k)). You can compare numbers using this iteration vs. the actual known kth-element solution of pseudo-code formula of sin((2^k)*init*PI)^2. The caret represents exponentiation. Interesting that the sine function degrades our precision in the estimated and actual computation since we are taking the sine of a larger and larger number for each iteration (due to the 2^k part in the formula). Here's my Java code:
public class Main {
public static void main(String[] args) {
long k;
String zp;
long prec = 30;
long highprec = 1000;
Apfloat seed = ApfloatMath.pi(prec).divide(new Apfloat(11,prec));
Apfloat estimate = seed;
Apfloat init = new Apfloat(1).divide(ApfloatMath.pi(highprec)).multiply(ApfloatMath.asin(ApfloatMath.sqrt(ApfloatMath.pi(highprec).divide(new Apfloat(11)))));
for (k=1; kspan>100; k++) {
estimate = new Apfloat(4).multiply(estimate).multiply(new Apfloat(1).subtract(estimate));
Apfloat actual = ApfloatMath.pow(ApfloatMath.sin(init.multiply(ApfloatMath.pi(highprec).multiply(ApfloatMath.pow(new Apfloat(2),new Apfloat(k,highprec))))),2);
System.out.println(k);
System.out.println(String.format("%#s", estimate));
System.out.println(String.format("%#s", actual));
}
}
}
<![if !IE]>▶<![endif]> Reply
Using Python's mpmath (arbitrary precision) library, with the seed pi/11 and 10000,20000,30000,45000 and 50000 iterations, for 1000,10000 and 100000 decimal places precision. Notice that the decimal places of the difference between 10000 and 100000 decimal-place precision results depend almost linearly on the number of iterations. As the number of iterations grow, precision is quickly destroyed.
<![if !IE]>▶<![endif]> Reply
R user here.
Browsing through an old paper lead my to look at the chaotic dynamic of $x_i = 4 * x_{i-1}*( 1 - x_{i-1})$. The paper suggests looking at the cumulative sums of $x - .5$, i.e.: $P_i = P_{i-1} + x_{i-1} - .5$, so I did, but I computed $x-.5$ in two ways. One, by using the recursion above, two, by writing the recursion of $y_i = x_i - .5$ as $y_i = -.5 + 4*(.25 - y_i^2)$. The results are different, and by plotting the cumulated processes it is clear that after a few iterations the differences are noticeable.
R has the package Rmpfr to run computations using the MPFR C library.
Below is my R snippet. Varying the precision D one see the effect of precision on the computations. Taking D=1000 gives un-discernible results for both ways of computing the dynamics for 1000 iterations.
#--------------------------------------
require("Rmpfr")
#----------- precision in bits
D = 100
#----------- number of iterations
N=1000
#----------- quadratic dynamics parameter
a=4
#----------- CHAOTIC process, and cumulative process
X=mpfr(rep(0,N), D )
X[1]=.3
P = mpfr(rep(0,N), D )
P[1] = 1000
for(i in 2:N ){ X[i] = a*X[i-1]*(1-X[i-1])
P[i] = P[i-1] + X[i-1] - .5}
#----------- CHAOTIC process centered, and cumulative process
dP = mpfr(rep(0,N), D )
dP[1] = X[1] - .5
P2 = mpfr(rep(0,N), D )
P2[1] = 1000
for(i in 2:N ){ dP[i] = a*(.25 - dP[i-1]^2) -.5
P2[i] = P2[i-1] + dP[i-1]}
#----------- PLOT
windows(8,8)
plot(1:1000, P, type='l', col='blue')
points(1:1000, P2, type='l', col='red')
#--------------------------------------------
<![if !IE]>▶<![endif]> Reply
Here is code in R. I understand that the initial value of X is X[1], and the code outputs the first few digits of X[10,000], starting with initial value 0.3.
According to a previous post, the values obtained form a (non-independent) sample drawn from the density
f(u) = 1/ ( 2* sqrt(1-u) ) .
The histogram of {X[1], ..., X[10001]} looks like a sample drawn from f.
#------------------------------
require("Rmpfr")
#--- precision in bits
D = 20000
#--- number of iterations
N = 10001
#---- CHAOTIC process
X=mpfr(rep(0,N), D )
X[1]=.3
for(i in 2:N ){ X[i] = sqrt( 4*X[i-1]*(1-X[i-1]) ) }
#------------------ Terminal points
Z = floor( .5 + 10^50*X[9999:10001] )/10^50
format(Z, digits= 10)
roundMpfr( Z, precBits = 40)
# [1] "0.2929369280" "0.9102194993" "0.5717340724"
# 3 'mpfr' number of precision 40 bits
# [1] 0.2929369280459 0.9102194993147 0.5717340723877
#------------------------- Histogram and theoretical density
u=0:100/101
windows(8,8)
hist(as.numeric(X), col='blue',
breaks=50, probability = TRUE,
xlab = 'u' , ylab = 'y (Density)' ,
main = 'Histogram of values and theoretical density')
points(u, (1-u)^(-.5)/2, type='l', col='red', lwd=3)
text(.2, 1.5, expression(y == frac(1, 2*sqrt(1-u))))
<![if !IE]>▶<![endif]> Reply
© 2020 Data Science Central ®
Badges | Report an Issue | Privacy Policy | Terms of Service
|
https://www.datasciencecentral.com/forum/topics/question-how-precision-computing-in-python?commentId=6448529%3AComment%3A674418
|
CC-MAIN-2020-34
|
refinedweb
| 1,429
| 57.77
|
Opened 12 years ago
Closed 11 years ago
Last modified 8 years ago
#6002 closed (fixed)
Better saving in newforms-admin ModelAdmin
Description
There are two very long methods in django.contrib.admin.options.ModelAdmin - save_add and save_change. They do three different things - they save objects, they log what happened and they redirect. So I propose to divide them.
Method add_view would call save_add for saving, log_add for logging and redirect_after_save for redirection. Method change_view would call save_change for saving, log_change for logging and redirect_after_save for redirection.
Methods save_add and save_change would be useful for complex saving which depends on forms and inline formsets together. (It solves #4507.)
Methods log_add and log_change could be used for example for something as AuditModelAdmin or NoLogAdmin.
Method redirect_after_save would be something as render_change_form - technical code common for adding and changing, which is not interesting very much.
I feel that now redirection is quite broken, it does not check permissions correctly. My patch fixes it too.
Attachments (5)
Change History (17)
Changed 12 years ago by
new version - after autoescape merge
comment:1 Changed 12 years ago by
This should be solved with the use of
ModelForm
once it is integrated into ModelAdmin.
comment:2 Changed 11 years ago by
Just some little addition: Add a
post_url
parameter to the proposed
redirect_after_save
method:
def redirect_after_save(self, request, new_obj, add=False, change=False, post_url="../")
Then use this to redirect when succesfully saved.
Rationale:
Consider a Menu model which contains MenuEntry models. In the admin I want to edit the Menus, MenuEntries should only be accessible through the admin view of the Menu. If a MenuEntry was edited I want to redirect to the Menu it is contained in, rather than to the MenuEntry overview. To achieve this I need to overwrite
save_change
(in newforms-admin trunk) or
redirect_after_save
(in the patch version) and duplicate the whole code of these functions. With the additional
post_url
parameter a simple wrapper would suffice.
comment:3 Changed 11 years ago by
Changed 11 years ago by
Patch cleanly applies to revision 7875
comment:4 Changed 11 years ago by
comment:5 Changed 11 years ago by
This actually really isn't critical for a merge. I am going to drop the nfa-blocker and bump to 1.0 beta. I will look at it later.
comment:6 Changed 11 years ago by
comment:7 Changed 11 years ago by
comment:8 Changed 11 years ago by
comment:9 Changed 11 years ago by
comment:10 Changed 11 years ago by
comment:11 Changed 11 years ago by
comment:12 Changed 8 years ago by
Milestone 1.0 beta deleted
new version - after autoescape merge
|
https://code.djangoproject.com/ticket/6002
|
CC-MAIN-2019-26
|
refinedweb
| 445
| 62.88
|
> To be able todo controlled shutdown/reboot of containers an s/todo/to do/ > API to talk to init via /dev/initctl is required. Fortunately > this is quite straightforward to implement, and is supported > by both sysvinit and systemd. Upstart support for /dev/initctl > is unclear. > > +++ b/src/util/virinitctl.c > @@ -0,0 +1,161 @@ > + > +/* These constants & struct definitions are taken from > + * systemd, under terms of LGPLv2+ > + * > + * initreq.h Interface to talk to init through /dev/initctl. > + * > + * Copyright (C) 1995-2004 Miquel van Smoorenburg > + */ Thankfully, compatible with our usage. > + > +#if defined(__FreeBSD_kernel__) > +# define VIR_INITCTL_FIFO "/etc/.initctl" > +#else > +# define VIR_INITCTL_FIFO "/dev/initctl" > +#endif > + > +#define VIR_INITCTL_MAGIC 0x03091969 Wonder if the original author of this code picked a birthdate. Gotta love the Easter eggs present in open source software :) > + > +/* > + * Because of legacy interfaces, "runlevel" and "sleeptime" > + * aren't in a separate struct in the union. > + * > + * The weird sizes are because init expects the whole > + * struct to be 384 bytes. > + */ > +struct virInitctlRequest { > + int magic; /* Magic number > */ 'int' is not necessarily 4 bytes; I would feel slightly more comfortable had upstream used int32_t. I know you are just copying code from an existing header (so don't change the struct itself), but wonder if we should at least add our own sanity checking: verify(sizeof(virInitctlRequest)) == 384); > + > + if ((fd = open(path, O_WRONLY|O_NDELAY|O_CLOEXEC|O_NOCTTY)) < 0) O_NDELAY is non-standard. I would spell it according to POSIX as O_NONBLOCK. > +typedef enum virInitctlRunLevel virInitctlRunLevel; > +enum virInitctlRunLevel { > + VIR_INITCTL_RUNLEVEL_POWEROFF = 0, > + VIR_INITCTL_RUNLEVEL_1 = 1, > + VIR_INITCTL_RUNLEVEL_2 = 2, > + VIR_INITCTL_RUNLEVEL_3 = 3, > + VIR_INITCTL_RUNLEVEL_4 = 4, > + VIR_INITCTL_RUNLEVEL_5 = 5, > + VIR_INITCTL_RUNLEVEL_REBOOT = 6, Should you add VIR_INITCTL_RUNLEVEL_LAST, in case we ever expand this list? I've never used messages over the socket to initctl myself, but I'm assuming your code works. ACK once you fix the nits I've pointed out above.
|
https://www.redhat.com/archives/libvir-list/2012-November/msg01453.html
|
CC-MAIN-2017-39
|
refinedweb
| 294
| 54.63
|
Dr. Noraini Mohd. Ariffin Assoc. Prof. Dr. Muhammad Akhyar Adnan Department of Accounting Kulliyyah of Economics and Management Sciences International Islamic University Malaysia
Abstract
This research study deals with the perceptions of Islamic bankers on the issue of Qardhul Hasan in Islamic banks in Malaysia. The study adopted the methodology of questionnaire survey. 13 full-fledged Islamic banks in Malaysia are used in the study. The response rate is 46.9%. The findings are divided into three sections: Knowledge and awareness about Qardhul Hasan, General Information on Qardhul Hasan, Problems of Qardhul Hasan and Differences in Perceptions among the Islamic bankers. In general, the Islamic bankers are familiar with Qardhul Hasan and they agreed that Islamic banks should offer Qardhul Hasan in order to enhance corporate social responsibility and to help needy people. Therefore, the findings could provide insights to Islamic banks in diversifying their products by offering Qardhul Hasan to the customers but with proper guidelines and policies.
Introduction Qardhul Hasan refers to an interest-free loan in the Islamic religion, which forbids loaning or borrowing money to earn interesti. The borrower is only required to repay the principal amount borrowed, but he / she may pay an additional amount at his / her absolute discretion, as a token of appreciation. This is to promote social welfare in the society. Based on that definition, it is important for Islamic banks to also provide this product in order to enhance the social welfare of the society and as part of their corporate social responsibility.
Corporate Social Responsibility (CSR) is an issue currently actively pursued by governments, corporations, civil society and international organizations in developed countries and emerging markets. The objective of the organization is not only responsible to the owners but to be also socially responsible to various stakeholders. This concern over CSR is also applicable to Islamic banks. As a business entity established within the ambit of Islamic Law (Shariah), Islamic banks are expected to be guided by an Islamic economic worldview, which based on the principle of social justice and wellbeing. Among products in Islamic banks that relate to CSR are Qardhul Hasan and Zakat. The former are zero-return loans that the Qur'an encourages Muslims to make to the needy, and where the financier is allowed to charge the borrower a service fee to cover the administrative expenses of handling the loan provided that the fee is unrelated to the loan maturity or amount. The latter is a type of religious tax that is deducted from wealth to be paid to the specified recipients (8 asnaf) as stated in Quran, surah At-Taubah verse 60.
It is interesting to observe that the Qardhul Hasan has been so far seriously neglected by many Islamic banks. Although it is always discussed [theoretically] to be one of product or services the Islamic Banks can offer, but few as later confirmed by this studyii have implemented this
particular product. This is among the important reasons why this study was conducted. We [the researchers] were eager to know from the Islamic bank operators about how their view about this product.
This study is expected to contribute at least first, general information about the Islamic banks in Malaysia which have applied the Qardhul Hasan product. Secondly, the information on how the perception of Islamic banks operators on Qardhul Hasan. Thirdly, the reasons and problems perceived by the bankers in implementing the Qardhul Hasan product.
This study aims to look into the application of Qardhul Hasan in Malaysian Islamic Banks, using the questionnaire method of data collection. In addition, the annual reports of several Islamic banks are analysed with regard to Qardhul Hasan. It is expected that due to its unique objectives, Islamic banks should provide Qardhul Hasan to customers or related stakeholders in order to enhance CSR.
The final report is organised as follows. After this introduction, the research questions and objectives are discussed. Then it follows by literature review, where Qardhul Hasan is discussed from its basic understanding, viewed from the Holy Quran, the hadith of Rasulullah (pbuh) and some related books and or articles; some previous research, (although limited) are also
discussed. The next section is the research method, where the research instrument, sample and tools of analysis are offered. It is then followed by the data analysis and findings. The report is finally concluded with conclusions, implication, research limitations and further study directions.
Research Questions and Objectives This study aims to acquire information for the following research questions: 1. What are the perceptions among bankers in Islamic banks in Malaysia on Qardhul Hasan? Objective: To elicit the perceptions on Qardhul Hasan among bankers in Islamic banks in Malaysia
2. What are the problems as perceived by Islamic bankers with regard to Qardhul Hasan? Objective: To identify the problems faced by Islamic banks with regard to Qardhul Hasan.
3. How difference is the perceptions on Qardhul Hasan in Malaysian Islamic banks? Objective: To determine any differences in perceptions on Qardhul Hasan in Malaysian Islamic Banks.
Literature Review
This section seeks to elaborate the Qardhul Hasan from various literature in order to provide the general picture related to the Qardhul Hasan. The chapter is basically divided into two general sections. First is the discussion of Qardhul Hasan with reference to some related text books, magazines or newspaper. This include the what why where when who and how questions. The second section is the discussion about more elaborated issues with reference to scientific journal publications. Some issues related the Qardhul Hasan which has been published will be reviewed to find any possible association with the current topic we are trying to study.
The Qardhul Hasan, at best should be investigated first from the main reference in Islamic literature, which is the Holy Quran, which was revealed initially on 17 Ramadhan, about fourteen centuries ago. There is at least six times the term Qardhul Hasan mentioned in the Quran. They are as follows:
1. He who will give Allah Qardhul Hasan, which Allah will double into his credit and multiply many times. [Al-Baqarah (2): 245].
Who is he that will lend to Allah a goodly loan so that He may multiply it to him many times? And it is Allah that decreases or increases (your provisions), and unto Him you shall return (2:245).
2. If you give Allah Qardhul Hasan. He will double it to your credit and he will grant you forgiveness. [Al-Taghabun (64):17] If you Allah a goodly loan (i.e. spend in Allahs cause), He will double it for you and will forgive you. And Allah is Most Ready to appreciate and to reward, Most Forbearing. (64:17).
expiate your sins and admit you to Gardens under which rivers flow (in Paradise). But if any of you after this, disbelieved, he has indeed gone astray from the Straight Path. (5:12).
4. And give Allah Qardhul Hasan, it will be increased manifold to their credit. [Al-Hadid (57): 18]
Verily, those who gave sadaqat (i.e. Zakat and alms), men and women, and lend Allah a goodly loan, it shall be increase manifold (to their credit), and theirs shall be an honourable good reward (i.e. Paradise). (57:18).
5. Who is he that will give Allah Qardhul Hasan? For Allah will increase it manifold to hiscredit. [Al-Hadid (57):11]
Who is he that will lend to Allah a goodly loan, then (Allah)increase it manifold to his credit (in repaying), and he will have (besides) a good reward (i.e. Paradise) (57:11).
6. Establish regular prayer and give regular charity and give Allah Qardhul Hasan. [AlMuzzammil (73): 20].
..and perform as-Salat and give Zakat and lend Allah a goodly loan. And whatever good you send before for yourself, you will certainly find it with Allah, better and greater in reward. And seek Forgiveness of Allah. Verily, Allah is Oft-Firgiving, Most Merciful (73:20). All Qardhul Hasan terms stated above refer basically to the loan which is trusted to Allah, where Allah had promised to return the loan with manifold rewards. It should be noted here that, one should not understand these verses literally and narrowly, as Allah is the Greatest and the Real Owner of everything in this world. Obviously He absolutely does not need any help or loan 6
from His creature. It is therefore imperative to understand that the Qardhul Hasan is among others the loan in His teachings which also include helping other Muslim brothers and sisters.
The investigation on the ahadith has also resulted at least two hadiths which deal with the Qardhul Hasan. One of them was narrated by Ibnu Majah, Ibnu Hibban and Baihaqi, and the other was narrated by Ibnu Majah and Baihaqi (Antonio, 2000, 186-87). The two hadiths strongly advise Muslims to lend something he or she has to other Muslim brothers or sisters. The value of lending something has been said to be equivalent to sadaqat practices. Interestingly, in the second hadith which refers to the miraj trip conducted by Rasulullah, he saw the statement in the paradise, where the value of lending is eighteen rewards which is much higher than the rewards of giving which only ten rewards. Based on above verses and hadiths, the ijma of ulama has confirmed the allowance and permission to Qardhul Hasan practice, as a part of social activities among the Muslims. That is why, in many textbooks related to muamalat activities such finance and banking the concept of Qardhul Hasan are repeatedly discussed and widely understood.
Literal meaning
The Qardhul Hasan consists of two words: (1) al-Qardh, and (2) al-Hasan. Al-Qardh is associated with the word qirad means to cut. It is said so, because by applying the Qardh it means that there will be a cut some of the lenders property by providing the loan to the borrower. While Hasan means a kindness. In other words, the practice of Hasan is understood as an act that benefits other persons.
Officially, from the theory of banking operation it is understood as a benevolent loan that obliges a borrower to repay the lender the principles sum borrowed on maturity of the loan (Haron & Shanmugam, 1997, 80). It is added that the borrower has the discretion to reward the lender for his loan by paying any sum over and above the amount of the capital.
Definition of Qardhul Hasan can be easily found in many text books. For example Ayub (2007, 492): says: Qardh literally to cut. It is so called because the property is cut off transferred to the borrower.
He then added: Legally, Qardh means to give anything having in the ownership of the other by the way of virtue so that the latter may avail himself of the same for his benefit with condition that the same similar amount of that thing will be paid back on demand or at the settled time. The repayment of loan is obligatory. Loans under Islamic law can be classified into Salaf and Qardh. The former being for a fixed time and the latter payable on demand. Qardh is, in fact, a particular kind of Salaf. (2007, 492) Ayub further explains that Qardhul Hasan [is] a virtuous loan. A loan with the stipulation to return the principal sum in the future without any increase; in Islamic law, all loans have to be virtuous, as seeking any benefit from loaning amounts to Riba Abdul Rahman (2006) defines Qardh as the transfer of ownership of an asset or money from the original owner to others on condition that the asset or money will be returned to the owner in the same condition/form/ value as when it first received by the other party from the owner. 8
He furthermore added as saying that Borrowing or Qardh' in Islam is a contract, which is based on the concept of mutual help (tabarru') and contemplation for others' well being especially the people in need (Al-Mughni, Ibn Qudamah, 4/353). Thus, Islam highly encourage the practise of Qardhul Hasan' as stated in the Hadith of the prophet Muhammad S.A.W (pbuh) : "One who releases his brother from difficulties, Allah will release him from the hardships in the hereafter...." (Hadith narrated by Muslim).
Other technical understanding of Qardh is offered by Bank Negara Malaysia as cited as follows: A bank will grant a benevolent loan to the applicant who wishes to pawn his valuable item. The loan will be issued under the concept of Qardhul Hasan, whereby the customer is only required to pay the amount borrowed
According to Karim (2005, 106), the Qardh is usually applied for any of the four purposes below:
1. As a bridging loan for pilgrimage, whereby a would-be pilgrim is given a loan to meet the requirement of prepayment of the travel expenses for pilgrimage. The client will have to pay in full prior to pilgrimage. 2. As cash advance from the sharia credit card, whereby a client is given the flexibility to withdraw cash from the bank via ATM. The client has to repay within a given period. 3. As a small business loan, in the case that under the banks calculation, any other financing scheme such as sale and purchase ijarah or profit sharing would over burden the client.
4. As a credit loan to the banks staff whereby the bank facilitates it to ensure that the staff can fulfill his or her needs. The employee repays the loan through installment or cutback in salary.
The above purposes are also supported by Antonio (2008, 187) as how the Qardhul Hasan might be applied in particularly, the banking industry.
Since the Qardhul Hasan is not a profit oriented product, the fund for this product might be obtained from one of more of following resources: (a) bank capital, and (b) doubtful funds which are received and controlled by [Islamic] bank. These include, for example, the [unavoidable] interest earned from some correspondent conventional banks and funds resulted from the penalty imposed to the customers.
The pool of money from above various sources is then used by the bank in a special and perhaps the only provided by Islamic bank. It is because Islamic bank can only finance their customer commercially on the basis of partnership contract (such as mudarabah or musharakah), or trading contracts like murabahah, bai as-salam, bai al-istitisna, and so forth.
Since the Qardhul Hasan is operated not on the basis of profit-oriented purposes, no margin will be expected from it. It is purely a non-profit loan which is aimed at helping those are in need. It is also understood if this loan used to be made only for short term, hoping that it can be circled among those in need.
10
The lending mechanism for Qardhul Hasan, as surveyed by Adnan and Furywardana (2006) in BNI Syariah Yogyakarta were simpler than any other financing program. However, some basic lending principles, such as character, capacity, collateral, purpose or payment were also leniently considered.
Previous research
Unlike many other products and services the Islamic Banks used to offer (e.g. Murabaha, Mudaraba, Musharaka, Bai as-salam, Bai al-istisna and so forth) there are so limited resources related to Qardhul Hasan. Many discussions in regard to Qardhul Hasan are generally found in the textbooks (Harun & Shanmugam, 1997; Karim, 2008; Antonio , 2000, etc), instead of published scientific journals. The searching has been tried, among others is by using the Google facility. It is surprising that we found there is only study was published by Adnan and Furywardana (2006). This research was about the evaluation of non-performing-loan (NPL), the case study in Bank Negara Indonesia (BNI) Syariah, Yogyakarta branch.
Among the findings of this study is that, the BNI Syariah in general, and the Yogyakarta branch in particular has applied the Qardhul Hasan or benevolent loan. It is reported that the bank has allocated IDR 175,077,500, IDR247,317,000 and IDR249,817,000 iii from 2003 to 2005 respectively. Unfortunately, the yearly increase of the fund loaned on the basis of Qardhul Hasan was also followed by the increase of its non-performing-loan (NPL). The research has reported that the NPL was also increasing from 21% in 2003, to 25% in 2004 and 26% in 2005.
Among the important findings of that research is that the bank has not managed the product well, as no specific person or group of employees are assigned to plan and control the operation of the
11
product. It is also worthy to note that the main factor related to the high rate of NPL is the character of the borrowers or customers. It is proven statistically that two variables (character of borrower and NPL) were significantly associated.
Another reference about Qardhul Hasan was found from the IBR Review (2008, pp. 10-13). However, this is only a forum which discusses the Islamic Bank deposits and Qardhul Hasan. Many (among others are Tahir, Shah, Sultan, Othman, Fadel) express their view in the forum, but they talk more about the theoretical aspects and general observations rather than empirical research.
Research Method
Research Instruments In order to study this issue, secondary data was first analysed to get the information on the Islamic banks that offer Qardhul Hasan and then only primary data were collected in this study, which were obtained through a questionnaire survey that aimed at getting the respondents perceptions towards Qardhul Hasan. The survey approach using the questionnaire is believed to be the most appropriate technique in collecting the primary data. It also allows quantitative analysis to be conducted in testing the deductions and it is also potential to generalize the findings (Neuman, 2003). The questionnaire (as per Appendix 1) consists of four sections. The first section was designed to gather information about knowledge and awareness about Qardhul Hasan. The second section was designed to gather information about the bankers perception towards Qardhul Hasan in general. The third section outlines the problems of Qardhul Hasan and the perceived seriousness among respondents. The last section was designed to gather information about the respondents personal and demographic characteristics. 12
Sample According to Sekaran (2000), the most appropriate sample size for research should be larger than 30 and less that 500. Thus, in this study 130 questionnaires were distributed by post were considered as appropriate to get the response rate between the sample sizes as proposed by Sekaran (2000). This study focused only on the bankers in full-fledged Islamic banks in Malaysia. The sample consists of 13 full-fledged Islamic banks in Malaysia (see Appendix 2 for the list of the banks).
Tools of Analysis The data of this study was analysed using the SPSS software, version 12.0 to tabulate the results. This study used the frequency test to present the information on the profiles of the respondents and the bank facilities they used. The frequency of the respondents was based on their demographic details such as gender, age, religion, educational level, occupation and experience. In addition, descriptive test was used to present the perceptions of the respondents towards Qardhul Hasan.
Data Analysis ad Findings This section presents the analysis and findings of the study. The study used various statistical tests utilizing the SPSS version 12.0. Firstly, the section presents results from the secondary data and then presents the response rate of the questionnaire survey. It later describes the profiles of the respondents and the test of normality. Finally, the results on the perceptions towards Qardhul Hasan and the problems were discussed.
13
Review of the Banks Annual Report This section provides evidence on the Islamic banks that offer Qardhul Hasan. The study reviews 13 full-fledged Islamic banks annual report for the years 2006 and 2007. It emerges clearly from this brief review that only three Islamic banks have Qardhul Hasan mentioned in the financial statements. They are Bank Muamalat Malaysia Berhad, Al Rajhi Banking and Investment Corporation (Malaysia) Berhad and Kuwait Finance House (Malaysia) Berhad. The details are as in Table 1. From Table 1, it can be seen only very small amount of financing reported for Qardhul Hasan for the three banks; Bank Muamalat Malaysia Berhad: 0.1%, Al Rajhi Banking & Investment Corporation (Malaysia) Berhad: 0.15% and Kuwait Finance House (Malaysia) Berhad: 0.001%. Therefore, it is worth to analyse in detail the perceptions of the Islamic bankers in Malaysia towards Qardhul Hasan and the problems of Qardhul Hasan.
Amounts reported 2007 RM000 Qardhul Hasan amount 5,652 2007 RM000 Total net financing 5,585,247
1) 2) 3) 4) 5) 6) 7) 8)
Bank Muamalat Malaysia Berhad BIMB Holdings Berhad RHB Islamic Bank Berhad AmIslamic Bank Berhad EONCAP Islamic Bank Berhad Affin Islamic Bank Berhad Hong Leong Islamic Bank Berhad Al Rajhi Banking & Investment
Y N N N N N N Y 14
2,841
1,866,779
Corporation (Malaysia) Berhad 9) Kuwait Finance House (Malaysia) Berhad 10) Maybank Islamic Berhad 11) CIMB Islamic Bank Berhad 12) Asian Finance Bank 13) Bank Rakyat Malaysia
Y N N N N
33
3,162,310
Response rate 130 questionnaires were distributed to 13 full-fledged Islamic banks in Malaysia, in which 10 questionnaires for each bank. Out of 130 distributed questionnaires, 61 were collected; these resulted in a response rate of 46.9 per cent.
Table 2 summarises the demographic information about the respondents. As showed in table 2, 59.3% of the respondents are male and 40.7% are female. Most of the respondents are between the ages groups of 31-41 years old (51.7%). In addition, 95% of the respondents are Muslim and only 5% are non-Muslim and they are well educated, holding at least a bachelor degree or above (76.6% in total). Moreover, majority of them have more than 5 years working experience and in either middle or top management level (83.4% in total). Table 2: Profile of RespondentPercent Gender Age Male Female Below 20 years 20-30 years 31-40 years 41-50 years Above 50 years Muslim Non Muslim 59.3 40.7 23.3 51.7 15 10 95 5
Religion
15
Education Level
Occupation
Secondary school College/diploma/matriculation Bachelor (First Degree) Professional Qualification Postgraduate (Master or PhD) Top management Middle management Lower management Others
11.7 11.7 48.3 10 18.3 13.3 41.7 41.7 3.3 19 29.3 12 39.7
Working Experience
- Less than 1 year - 1-3 years - 3-5 years - More than 5 years
Test of Normality Before conducting parametric test, it is important to test for normality of each variable. The normality of variables was measured using skewness, kurtosis and Kolmogrov-Smirnov. The results of normality test are presented in Table 3 and Table 4.
The analysis of normality indicates that most of the variables are negatively skewed with tendency to the right side of a graph (scores clustered to the high end). On the other hand, the kurtosis value shows a slightly positive value indicating the distribution that is clustered a bit at the centre. Significant Kolmogorov-Smirnov statistic shows violation of normality assumption. A non-significance result (significance value of more than 0.05) indicates normality (Pallant, 2001). From the analysis, the study concluded that the data for all variables are not normally distributed. Therefore, non parametric tests can be used for this study.
16
familiarity help needy enhance scr no return written off paid back on demand not offer current account use Qardhul Hasan charge service fee collateral problem1 problem2 problem3 problem4 problem5
Statistic .719 .742 .718 .771 .857 .849 .852 .898 .805 .882 .837 .841 .866 .923 .862 .425
Shapiro-Wilk df 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30
Sig. .000 .000 .000 .000 .001 .001 .001 .007 .000 .003 .000 .000 .001 .033 .001 .000
17
The study intends to explore the awareness of Islamic bankers in Malaysia towards Qardhul Hasan using the frequency tests. The results as presented in Table 5 show that majority of the respondents are familiar with Qardhul Hasan (52.5%) and they also agreed that Islamic banks should offer Qardhul Hasan (85%). Table 5: Islamic Bankers Perception on Familiarity with Qardhul HasanItems Very Familiar Familiar Not Sure Not Familiar Not Familiar at all Total Frequency (%) 31.1 52.5 4.9 6.6 4.9 100
General Information on Qardhul Hasan The study also aims to elicit Islamic bankers perceptions towards the Qardhul Hasan by using the descriptive tests. The results are demonstrated Table 6 and Table 7.
Table 6 shows that the majority of the respondents (96.7%) agreed with item 1: Qardhul Hasan can help the needy (with high means and relatively low standard deviation of 4.44 and 0.0563 respectively as per Table 7). This indicates a strong agreement amongst the respondents.
In addition, Table 6 also shows that the majority (90.2%) of the respondent agreed with Qardhul Hasan enhances corporate social responsibility. With a mean of 4.39 and high standard deviation of 0.665 as reported in Table 7, it indicates that the respondents viewed Qardhul Hasan enhances corporate social responsibility. Therefore, it is very important for Islamic banks to offer Qardhul Hasan so that the bank is perceived as incorporating corporate social responsibility in its activities. 18
Table 6 also depicts that 80% of the respondents agreed with item 3 that Qardhul Hasan is less popular due to no return to Islamic banks, with a relatively high mean of 4.12 and standard deviation of 0.885 (Table 7). This also indicates a strong agreement amongst the respondents. Table 6: General information on Qardhul Hasan (Frequency)Strongly Disagree a) b) c) d) e) f) g) Qardhul Hasan can help the needy. Qardhul Hasan enhances corporate social responsibility. Qardhul Hasan is less popular due to no return to Islamic banks. It is also a belief that Qardhul Hasan can be written off. Qardhul Hasan must be paid back on demand.. 1.7 10.0 19.7 2.3 Disagree 6.7 16.7 20.0 49.2 16.3 Neutral 3.3 9.8 13.3 25.0 21.7 24.6 25.6 Agree 49.2 41.0 41.7 48.3 45.0 4.9 41.8 Strongly Agree 47.5 49.2 38.3 8.3 3.3 1.6 14.0 Chisquare 0.000 0.000 0.000 0.000 0.000 0.000 0.001
h)
5.0
15.0
66.7
8.3
0.000
i) j)
5.1 1.7
18.6 5.0
23.7 10.0
44.1 66.7
8.5 16.6
0.000 0.000
k)
18.0
49.2
19.7
11.5
1.6
19
Moreover, table 6 demonstrates that 83.3% of the respondents agreed with the item of Qardhul Hasan should be managed separately from other products. Only 6.7% of them disagreed with this item and 10% neutral. With a relatively low mean and relatively high standard deviation of 3.92 and 0.787 respectively as per Table 7, it implies that the importance of the Islamic banks to manage the Qardhul Hasan transactions separately from other products. These findings are supported by the results of the Chi-square test as shown also in Table 6, which revealed that the Chi-square value of each item is significant at 10%.
Additionally, the study further investigates which groups of the stakeholders assigned to be offered Qardhul Hasan. The analysis is depicted in Table 8. An examination of mean values for groups suggests that the most important group to be offered Qardhul Hasan is the needy students and other economically weaker sections of the society (mean of 4.0), followed by Islamic banks staff (mean of 3.92). On the other hand, the least group to offer Qardhul Hasan as perceived by Islamic bankers is non clients of Islamic banks (mean of 2.54).
20
Table 8: Descriptive Statistics N Investment Accountholders All bank's clients Non clients Needy students Islamic banks staff Individuals Institutions 60 61 39 61 61 44 61 Minimum 1 1 1 2 1 1 1 Maximum 5 5 4 5 5 5 5 Mean 3.05 2.80 2.54 4.00 3.92 2.61 2.90 Std. Deviation 1.096 1.077 .913 .796 .988 1.185 1.165
The study also intends to elicit the perception of Islamic bankers towards the main problems in offering Qardhul Hasan. To analyze this objective, the respondents were asked to rank the six assigned problems in terms of seriousness with 1 the most serious and end with 6, the least serious. Table 9 shows the problems as laid out in the questionnaire.
Table 9: Problems of Qardhul Hasan Problems Not able to generate any profit Not able to cover the financing High administrative and transaction costs High risk No support from top management No demand from customers Rank 1 2 3 4 5 6
Based on the findings, majority of the respondents rank not able to generate profit as the main problem of Qardhul Hasan, followed by high risk and not able to cover financing. This indicates weak understanding of the respondents on Qardhul Hasan because Qardhul Hasan 21
should not include any profit elements. No support from top management and no demand from customers were perceived to be the least serious in Islamic banks in offering Qardhul Hasan.
Other information In this section, the respondents were asked which of the listed products will be most likely to use Qardhul Hasan. A variety of responses were received. In general, there were no specific products that can apply the Qardhul Hasan concept but majority of the respondents agreed that Qardhul Hasan can be mainly used for financing (33.3%).
Difference in the perceptions on Qardhul Hasan among Islamic bankers This section provides the analysis whether any differences among Islamic bankers on their perceptions on Qardhul Hasan and the problems as perceived serious by the bankers. Table 10 shows the significance test for all the items. From the table, it can be seen that all the KruskalWallis values are more than 10%, with the exception of items 2 and 3, Qardhul Hasan enhances corporate social responsibility and Qardhul Hasan is less popular due to no return to Islamic banks, where the Kruskal-Wallis values are less than 10%. This indicates that there is no significant difference in the perceptions of the Islamic bankers with regard to their position level.
22
q) r) s) t) u) v).
With regard to the perceptions on the problems of Qardhul Hasan, there are also no significant differences among different level of Islamic bankers, with the exception of problem 4: High risk where the Kruskal-Walis value is less than 10%.
Conclusion This final section summarises the main results and conclusion of the study. This research study deals with the perceptions of Islamic bankers on the issue of Qardhul Hasan in Islamic banks in Malaysia. The study adopted the methodology of questionnaire survey (most of the questions are close-ended to make the respondents answered them easily) to answer the three research questions. Table 11 summarises the research questions and research objectives of the study. The responses from several groups of respondents were analysed using descriptive statistics and tested using non-parametric tests. The survey questionnaire received a high response rate (46.9%); therefore, the conclusions below may be considered to be representative of informed opinion in the bankers in Malaysian Islamic banks. The responses given by the respondents of this survey reflected their perceptions on Qardhul Hasan as well as the problems in Qardhul Hasan. The findings are divided into three sections:
23
Knowledge and awareness about Qardhul Hasan, General Information on Qardhul Hasan, Problems of Qardhul Hasan and Differences in Perceptions among the Islamic bankers. Table 11: Research Questions and Research Objectives
Research Questions
Research Objectives
1. What are the perceptions among bankers in Islamic banks in Malaysia To elicit the perceptions on Qardhul Hasan among bankers in on Qardhul Hasan? Islamic banks in Malaysia 2. What are the problems as perceived by Islamic bankers with regard to Qardhul Hasan? 3. How difference is the perceptions on Qardhul Hasan in Malaysian Islamic banks? To identify the problems faced by Islamic banks with regard to Qardhul Hasan. To determine any differences in perceptions on Qardhul Hasan in Malaysian Islamic Banks.
The empirical findings show that majority of the Islamic bankers in the study are familiar with Qardhul Hasan and agreed that Islamic banks should offer Qardhul Hasan to enhance corporate social responsibility. In addition, Qardhul Hasan is offered to help needy people. The findings also confirmed that the needy people, particularly needy students will be the most important groups for the Islamic banks to offer Qardhul Hasan. This is not a surprising finding as Qardhul Hasan is benevolent loan, meaning that zero-return financing, that will definitely be favoured by needy people due to less installment to be paid (no profit). However, contrary to this finding, Islamic bankers perceived the most serious problem in offering Qardhul Hasan is not able to generate profit. This somehow shows lack of understanding among the Islamic bankers with the definition of Qardhul Hasan itself, which not supposed to earn any profit. High risk is also perceived as a very serious problem.
24
When the perceptions between the top management, middle management and lower management are tested to see any significant differences, it is found that no significant differences among them with the exception of items 2 and 3, Qardhul Hasan enhances corporate social responsibility and Qardhul Hasan is less popular due to no return to Islamic banks, where there are significant differences among the respondents. Similar findings also applied to the problem with the exception of problem high risk where there is significant difference among the three groups. In addition, majority of the respondents agreed that Qardhul Hasan should be applied to financing. As a conclusion, the findings could provide some insights to Islamic banks in order to diversify their products by offering as well Qardhul Hasan to the customers. The study proves that Islamic banks perceived Qardhul Hasan is important to be offered to the customers. However, this can only be allowed after proper policies have been developed so that there will be no recurring problems in the future. The targeted customers also must be clearly defined so that the Qardhul Hasan will fulfill the needs of the society. As Islamic organisations, Islamic banks are accountable to Allah and to the communities in which they operate and have a duty to be transparent in all their activities. Based on these principles, Qardhul Hasan is definitely the product in meeting the expectations of the Islamic community. Implication of Findings The findings confirm some suspicious arisen by the public that many Islamic banks have only a strong profit-motive orientation. They have not appropriate balance to function socially (as opposed to commercially), as it is expected by Islamic tenets generally. Due to this, the Islamic banks top management, in particular need to be warned about this issue. In the long terms, while 25
this motive prolongs, the existence of Islamic banks might be in trouble. They are not going to achieve al-falah, or the maqasid of shariah, as they should be laid as the main intention of establishing of Islamic banks. Since the study also found the misunderstanding of Islamic bank operators on Qardhul Hasan concept, we believe that they need to be taught more the Islamic bank products. The focus should not be given merely to the commercial or profitable ones, but also the products or services which are integrally attached to the existence of Islamic banks such as Qardhul Hasan and Zakat. Policy Implications The research found that the majority of respondents agree that the Qardhul Hasan can help the needy, as well as it enhance corporate social responsibility, perhaps it is now the time where Bank Negara Malaysia enforces the implementation the Qardhul Hasan product to all Islamic banks in the country. Two purposes hopefully might be achieved by this policy: First, to balance the profit-motive orientation with the social responsibility among the Islamic banks, and second, to have a better image in the society that Islamic banks have a good CSR. Theoretical Implications Since this research can be classified as a preliminary study, no theoretical implication can be affected. Except perhaps, we might conclude that (1) Islamic banks in Malaysia in general have a stronger profit-motive (commercial) than social function, and (2) there is a lack of understanding of Malaysian Islamic Banks operators on Qardhul Hasan. Limitations There is no perfect study and the current one is no exception. Therefore, this section will discuss some limitations in the present study, which include: 26
The data were collected mainly from questionnaire. No interview so far was conducted due to time and budget limit. Having deep interview with some selected respondents, perhaps will give more comprehensive picture about the Qardhul Hasan in Islamic banks operators in Malaysia. This is an exploratory study in nature. It is conducted due to so limited research on this topic was held previously. Consequently, the study has also very limited literature review. In turn, no hypotheses can be developed, as well as no such sophisticated statistical examination can be run. Further Research Directions Many more research can be done in the context of Qardhul Hasan in Malaysian Islamic banks. These include, the studies of demand on Qardhul Hasan, the perception of customers or stakeholders on Qardhul Hasan, the [case studies] operation of Qardhul Hasan in the some Islamic banks that have launched the Qardhul Hasan products, the study comparison between Malaysian context and other Muslim countries which have been operating the same industry (Islamic bank), and so forth. Since this topic is so far rarely studied, we believe that ample opportunities in this topic are waiting for researchers.
Notes:i
There are about 8 to 11 times the terms of riba is stated in the Holy Quran (See for example: QS Al-Baqarah 275279; Ar-Rum 39; An-Nisa 160-161 and Ali Imran 130). This indirectly indicates the serious view of Islamic teachings against the practice of riba.ii
See Table 1 below. This amount is about 15-16% of the total Qardhul Hasan funds allocated by the BNI Syariah nationally.
iii
27
References Abdul Rahman, Abdul Rahim (2007). Islamic Microfinance: A Missing Component in Islamic Banking Kyoto Bulletin of Islamic Area Studies, 1-2 (2007), pp. 38-53. Abdul Rahman, Zaharuddin Hj (2006). Management Fees in Qardhul Hasan', NST Business Times, 20th Sept 2006. Adnan, Muhammad Akhyar and Firdaus Puriwardana (2006). Qardhul Hasan, Kasus BNI 46, Indonesia, Jurnal Akuntansi dan Auditing Indonesia (JAAI), Vol. 10, No. 2, pp. 207-229. Antonio, M. Syafii, (2000). Bank Syariah, Suatu Pengenalan Umum, Edisi Khusus, Jakarta: Tazkia Institute. Ayub, Muhammad (2007). Understanding Islamic Finance (West Sussex: John Wiley & Sons, Ltd). Harun, S. and Shanmugam, B. (1997). Islamic Banking System, Concepts and Applications. Selangor, Darul Ehsan: Pelanduk Publications. IBR Review (2008). Discussion Forum, Islamic Bank Deposits and Qardhul Hasan. Vol. 3, No. 6, pp. 10-13. Islamic Banking System: Financing by Concept (2008). Available at < > , Access Date: 5 February 2009. Karim, Adiwarman A., (2005). Islamic Banking, Fiqh and Financial Analysis, 3rd edition, Jakarta: PT Raja Grafindo Persada. Neuman W. L. (2003). Social Research Methods, New York, Allyn. Pallant (2001). SPSS Survival Manual: A step by step guide to data analysis using SPSS, New York Open University Press. Sekaran, Uma (2000). Research Methods for Business, 3rd Edition, John Wiley & Sons, Inc. Canada.
28
29
|
https://www.scribd.com/doc/76580551/The-Perceptions-of-Islamic-Bankers-on-Qardhul-Hasan-in-Malay
|
CC-MAIN-2019-39
|
refinedweb
| 6,618
| 52.49
|
pg
Description
Pg is the Ruby interface to the PostgreSQL RDBMS.
It works with PostgreSQL 9 2.2 or newer
PostgreSQL 9.2.x or later (with headers, -dev packages, etc).
It usually.
If you want to install as a signed gem, the public certs of the gem signers can be found in the `certs` directory of the repository.
Type Casts
Pg can optionally type cast result values and query parameters in Ruby or native C code. This can speed up data transfers to and from the database, because String allocations are reduced and conversions in (slower) Ruby code can be omitted.
Very basic type casting can be enabled by:
conn.type_map_for_results = PG::BasicTypeMapForResults.new conn # ... this works for result value mapping: conn.exec("select 1, now(), '{2,3}'::int[]").values # => [[1, 2014-09-21 20:51:56 +0200, [2, 3]]] conn.type_map_for_queries = PG::BasicTypeMapForQueries.new conn # ... and this for param value mapping: conn.exec_params("SELECT $1::text, $2::text, $3::text", [1, 1.23, [2,3]]).values # => [["1", "1.2300000000000000E+00", "{2,3}"]]
But Pg's type casting is highly customizable. That's why it's divided into 2 layers:
Encoders / Decoders (ext/pg_*coder.c, lib/pg/*coder.rb)
This is the lower layer, containing encoding classes that convert Ruby objects for transmission to the DBMS and decoding classes to convert received data back to Ruby objects. The classes are namespaced according to their format and direction in PG::TextEncoder, PG::TextDecoder, PG::BinaryEncoder and PG::BinaryDecoder.
It is possible to assign a type OID, format code (text or binary) and optionally a name to an encoder or decoder object. It's also possible to build composite types by assigning an element encoder/decoder. PG::Coder objects can be used to set up a PG::TypeMap or alternatively to convert single values to/from their string representation.
PG::TypeMap and derivations (ext/pg_type_map*.c, lib/pg/type_map*.rb)
A TypeMap defines which value will be converted by which encoder/decoder. There are different type map strategies, implemented by several derivations of this class. They can be chosen and configured according to the particular needs for type casting. The default type map is PG::TypeMapAllStrings.
A type map can be assigned per connection or per query respectively per result set. Type maps can also be used for COPY in and out data streaming. See PG::Connection#copy_data . <ged@FaerieMUD.org> and Lars Kanis <lars@greiz-reinsdorf.de>.
Copying
Jeff Davis <ruby-pg@j-davis.com>
Guy Decoux (ts) <decoux@moulon.inra.fr>
Michael Granger <ged@FaerieMUD.org>
Lars Kanis <lars@greiz-reinsdorf.de>
Dave Lee
Eiji Matsumoto <usagi@ruby.club.or.jp>
Yukihiro Matsumoto <matz@ruby-lang.org>
Noboru Saitou <noborus@netlab.jp>
You may redistribute this software under the same terms as Ruby itself; see or the BSDL.
|
https://www.rubydoc.info/gems/pg
|
CC-MAIN-2018-22
|
refinedweb
| 470
| 52.36
|
In this chapter, we'll cover the following recipes:
Building with windows and views
Adding a tabgroup to your app
Creating and formatting labels
Creating textfields for user input
Working with keyboards and keyboard toolbars
Enhancing your app with sliders and switches
Passing custom variables between windows
Creating buttons and capturing click events
Informing your users with dialogs and alerts
Creating charts using Raphael JS
Building an actionbar in Android
The ability to create user-friendly layouts with rich, intuitive controls is an important factor in successful app designs. With mobile apps and their minimal screen real estate, this becomes even more important. Titanium leverages a huge amount quantity of native controls found in both the iOS and Android platforms, allowing a developer to create apps just as rich in functionality as those created by native language developers.
How does this compare to the mobile Web? When it comes to HTML/CSS-only mobile apps, savvy users can definitely tell the difference between them and a platform such as Titanium, which allows you to use platform-specific conventions and access your iOS or Android device's latest and greatest features. An application written in Titanium feels and operates like a native app, because all the UI components are essentially native. This means crisp, responsive UI components utilizing the full capabilities and power of your device.
Most other books at this point would start off by explaining the fundamental principles of Titanium and, maybe, give you a rundown of the architecture and expand on the required syntax.
Yawn...!
We're not going to do that, but if you want to find out more about the differences between Titanium and PhoneGap, check out.
Instead, we'll be jumping straight into the fun stuff: building our user interface and making a real-world app! In this chapter, you'll learn all of this:
How to build an app using windows and views, and understanding the differences between the two
Putting together a UI using all the common components, including TextFields, labels, and switches
Just how similar the Titanium components' properties are to CSS when it comes to formatting your UI
You can pick and choose techniques, concepts, and code from any recipe in this chapter to add to your own applications or, if you prefer, you can follow each recipe from beginning to end to put together a real-world app that calculates loan repayments, which we'll call LoanCalc from here on.
The complete source code for this chapter can be found in the
/Chapter 1/LoanCalc folder.
We're going to start off with the very basic building blocks of all Titanium applications: windows and views. By the end of this recipe, you'll have understood how to implement a window and add views to it, as well as the fundamental differences between the two, which are not as obvious as they may seem at first glance.
If you are intending to follow the entire chapter and build the LoanCalc app, then pay careful attention to the first few steps of this chapter, as you'll need to perform these steps again for every subsequent app in the book.
Note
Note
We are assuming that you have already downloaded and installed Appcelerator Studio, along with XCode and iOS SDK or Google's Android SDK, or both.
To follow along with this recipe, you'll need Titanium installed plus the appropriate SDKs. All the examples generally work on either platform unless specified explicitly at the start of a particular recipe.
The quickest way to get started is by using Appcelerator Studio, a full-fledged Integrated Development Environment (IDE) that you can download from the Appcelerator website.
If you prefer, you can use your favorite IDE, such as TextMate, Sublime Text, Dashcode, Eclipse, and so on. Combined with the Titanium CLI, you can build, test, deploy, and distribute apps from the command line or terminal. However, for the purposes of this book, we're assuming that you'll be using Appcelerator Studio, which you can download from.
To prepare for this recipe, open Appcelerator Studio and log in if you have not already done so. If you need to register a new account, you can do so for free from within the application. Once you are logged in, navigate to File | New | Mobile App Project and select the Classic category on the left (we'll come back to Alloy later on), then select Default Project and click on Next. The details window for creating a new project will appear. Enter LoanCalc, the name of the app, and fill in the rest of the details with your own information, as shown in the following screenshot. We can also uncheck the iPad and Mobile Web options, as we'll be building our application for the iPhone and Android platforms only:
Note
Pay attention to the app identifier, which is written normally in backwards domain notation (for example,
com.packtpub.loancalc). This identifier cannot be changed easily after the project has been created, and you'll need to match it exactly when creating provisioning profiles to distribute your apps later on. Don't panic, however: you can change it.
First, open the
Resources/app.js file in your Appcelerator Studio. If this is a new project, the studio creates a sample app by default, containing a couple of Windows inside of a TabGroup; certainly useful, but we'll cover tabgroups in a later recipe, so we go ahead and remove all of the generated code. Now, let's create a Window object, to which we'll add a view object. This view object will hold all our controls, such as textfields and labels.
In addition to creating our base window and view, we'll also create an imageview component to display our app logo before adding it to our view (you can get the images we have used from the source code for this chapter; be sure to place them in the
Resources folder).
Finally, we'll call the
open() method on the window to launch it:
//create a window that will fill the screen var win1 = Ti.UI.createWindow({ backgroundColor: '#BBB' }); //create the view, this will hold all of our UI controls //note the height of this view is the height of the window //minus 20 points for the status bar and padding var view = Ti.UI.createView({ top: 20, bottom: 10, left: 10, right: 10, backgroundColor: '#fff', borderRadius: 2 }); //now let's add our logo to an imageview and add that to our //view object. By default it'll be centered. var logo = Ti.UI.createImageView({ image: 'logo.png', width: 253, height: 96, top: 10 }); view.add(logo); //add the view to our window win1.add(view); //finally, open the window to launch the app win1.open();
Firstly, it's important to explain the differences between windows and views, as there are a few fundamental differences that may influence your decision on using one compared to the other. Unlike views, windows have some additional abilities, including the
open() and
close() methods.
If you are coming from a desktop development background, you can imagine a Window as the equivalent of a form or screen; if you prefer web analogies, then a window is more like a page, whereas views are more like a
Div.
In addition to these methods, windows have display properties such as full screen and modal; these are not available in views. You'll also notice that while creating a new object, the create keyword is used, such as
Ti.UI.createView() to create a view object. This naming convention is used consistently throughout the Titanium API, and almost all components are instantiated in this way.
Windows and views can be thought of as the building blocks of your Titanium application. All your UI components are added to either a window, or a view (which is the child of a Window). There are a number of formatting options available for both of these objects, the properties and syntax of which will be very familiar to anyone who has used CSS in the past. Note that these aren't exactly like CSS, so the naming conventions will be different.
Font,
Color,
BorderWidth,
BorderRadius,
Width,
Height,
Top, and
Left are all properties that function in exactly the same way as you would expect them to in CSS, and apply to windows and almost all views.
Note
It's important to note that your app requires at least one window to function and that window must be called from within your entry point (the
app.js file).
You may have also noticed that we have sometimes instantiated objects or called methods using
Ti.UI.createXXX, and at other times, we have used
Ti.UI.createXXX.
Ti. This is simply a shorthand namespace designed to save time during coding, and it will execute your code in exactly the same manner as the full Titanium namespace does.
Tabgroups are one of the most commonly used UI elements and form the basis of the layout for many iOS and Android apps in the market today. A tabgroup consists of a sectioned set of tabs, each containing an individual window, which in turn contains a navigation bar and title. On iOS devices, these tabs appear in a horizontal list at the bottom of screen, whereas they appear as upside-down tabs at the top of the screen on Android devices by default, as shown in the following image:
We are going to create two separate windows. One of these will be defined inline, and the other will be loaded from an external
CommonJS JavaScript module.
Before you write any code, create a new JavaScript file called
window2.js and save it in your
Resources directory, the same folder in which your
app.js file currently resides.
Now open the
window2.js file you just created and add the following code:
//create an instance of a window module.exports = (function(){ var win = Ti.UI.createWindow({ backgroundColor: '#BBB', title: 'Settings' }); return win; })();
If you have been following along with the
LoanCalc app so far, then delete the current code in the
app.js file that you created and replace it with the following source. Note that you can refer to the Titanium SDK as Titanium or
Ti; in this book, I'll be using
Ti:
//create tab group var tabGroup = Ti.UI.createTabGroup(); //create the window var win1 = Ti.UI.createWindow({ backgroundColor: '#BBB', title: 'Loan Calculator' }); //create the view, this will hold all of our UI controls var view = Ti.UI.createView({ top: 10, bottom: 10, left: 10, right: 10, backgroundColor: '#fff', borderRadius: 2, layout: 'vertical' }); //now let's add our logo to an imageview and add that to our //view object var logo = Ti.UI.createImageView({ image: 'logo.png', width: 253, height: 96, top: 10 }); view.add(logo); //add the view to our window win1.add(view); //add the first tab and attach our window object (win1) to it var tab1 = Ti.UI.createTab({ icon:'calculator.png', title:'Calculate', window: win1 }); //create the second window for settings tab var win2 = require("window2"); //add the second tab and attach our external window object //(win2 / window2) to it var tab2 = Ti.UI.createTab({ icon:'settings.png', title:'Settings', window: win2 }); //now add the tabs to our tabGroup object tabGroup.addTab(tab1); tabGroup.addTab(tab2); //finally, open the tabgroup to launch the app tabGroup.open();
Logically, it's important to realize that the tabgroup, when used, is the root of the application and it cannot be included via any other UI component. Each tab within the tabgroup is essentially a wrapper for a single window.
Windows should be created and assigned to the
window property. At the time of writing this book, it may be possible to still use the
url property (depending on the SDK you are using), but do not use it as it will be removed in later SDKs. Instead, we'll be creating windows using a
CommonJS pattern, which is considered the proper way of developing modular applications.
The tabs icon is loaded from an image file, generally a PNG file. It's important to note that in both Android and the iPhone, all icons will be rendered in grayscale with alpha transparency—any color information will be discarded when you run the application.
You'll also notice in the
Resources folder of the project that we have two files for each image—for example, one named
settings.png and one named
[email protected]. These represent normal and high-resolution retina images, which some iOS devices support. It's important to note that while specifying image filenames, we never use the
@2x part of the name; iOS will take care of using the relevant image, if it's available. We also specify all positional and size properties (width, height, top, bottom, and so on) in non-retina dimensions.
This is also similar to how we interact with images in Android: we always use the normal filename, so it is
settings.png, despite the fact there may be different versions of the file available for different device densities on Android.
Finally, notice that we're in the view and we're using vertical as a layout. This means that elements will be laid out down the screen one after another. This is useful in avoiding having to specify the top values for all elements, and, if you need to change one position, having to change all the elements. With a vertical layout, as you modify one element's top or height value, all others shift with it.
Apple can be particularly picky when it comes to using icons in your apps; wherever a standard icon has been defined by Apple (such as the gears icon for settings), you should use the same.
A great set of 200 free tab bar icons is available at.
Whether they are for presenting text content on the screen, identifying an input field, or displaying data within a tablerow, labels are one of the cornerstone UI elements that you'll find yourself using all the time with Titanium. Through them, you'll display the majority of your information to the user, so it's important to know how to create and format them properly.
In this recipe, we'll create three different labels, one for each of the input components that we'll be adding to our app later on. Using these examples, we'll explain how to position your label, give it a text value, and format it.
Open up your
app.js file, and put these two variables at the top of your code file, directly under the tabgroup creation declaration. These are going to be the default values for our interest rate and loan length for the app:
//application variables var numberMonths = 36; //loan length var interestRate = 6.0; //interest rate
Let's create labels to identify the input fields that we'll be implementing later on. Type the following source code into your
app.js file. If you are following along with the
LoanCalc sample app, this code should go after your imageview logo, added to the view from the previous recipe:
var amountRow = Ti.UI.createView({ top: 10, left: 0, width: Ti.UI.FILL, height: Ti.UI.SIZE }); //create a label to identify the textfield to the user var labelAmount = Ti.UI.createLabel({ width : Ti.UI.SIZE, height : 30, top : 0, left : 20, font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : 'Loan amount: $' }); amountRow.add(labelAmount); view.add(amountRow); var interestRateRow = Ti.UI.createView({ top: 10, left: 0, width: Ti.UI.SIZE, height: Ti.UI.SIZE }); //create a label to identify the textfield to the user var labelInterestRate = Ti.UI.createLabel({ width : Ti.UI.SIZE, height : 30, top : 0, left : 20, font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : 'Interest Rate: %' }); interestRateRow.add(labelInterestRate); view.add(interestRateRow); var loanLengthRow = Ti.UI.createView({ top: 10, left: 0, width: Ti.UI.FILL, height: Ti.UI.SIZE }); //create a label to identify the textfield to the user var labelLoanLength = Ti.UI.createLabel({ width : 100, height : Ti.UI.SIZE, top : 0, left : 20, font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : 'Loan length (' + numberMonths + ' months):' }); loanLengthRow.add(labelLoanLength); view.add(loanLengthRow);
By now, you should notice a trend in the way in which Titanium instantiates objects and adds them to views/windows, as well as a trend in the way formatting is applied to most basic UI elements using the JavaScript object properties. Margins and padding are added using the absolute positioning values of
top,
left,
bottom, and
right, while font styling is done with the standard font properties, which are
fontSize,
fontFamily, and
fontWeight in the case of our example code.
Here are a couple of important points to note:
The width property of our first two labels is set to
Ti.UI.SIZE, which means that Titanium will automatically calculate the width of the Label depending on the content inside (a string value in this case). This
Ti.UI.SIZEproperty can be used for both the width and height of many other UI elements as well, as you can see in the third
labelthat we created, which has a dynamic height for matching the label's text. When no height or width property is specified, the UI component will expand to fit the exact dimensions of the parent view or window that encloses it.
You'll notice that we're creating views that contain a label each. There's a good reason for this. To avoid using absolute positioning, we're using a vertical layout on the main view, and to ensure that our text fields appear next to our labels, we're creating a row as a view, which is then spaced vertically. Inside the row, we add the label, and in the next recipes, we will have all the text fields next to the labels.
The
textAlignproperty of the labels works the same way as you'd expect it to in HTML. However, you'll notice the alignment of the text only if the width of your label isn't set to
Ti.UI.SIZE, unless that label happens to spread over multiple lines.
TextFields in Titanium are single-line textboxes used to capture user input via the keyboard, and usually form the most common UI element for user input in any application, along with labels and buttons. In this section, we'll show you how to create a Textfield, add it to your application's View, and use it to capture user input. We'll style our textfield component using a constant value for the first time.
Type the following code after the view has been created but before adding that view to your window. If you've been following along from the previous recipe, this code should be entered after your labels have been created:
//creating the textfield for our loan amount input var tfAmount = Ti.UI.createTextField({ width: 140, height: 30, right: 20, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Ti.UI.RETURNKEY_DONE, hintText: '1000.00' }); }); interestRateRow.add(tfInterestRate);
In this example, we created a couple of basic textfield with a rounded border style, and introduced some new property types that don't appear in labels and imageviews, including
hintText. The
hintText property displays a value in the textfield, which disappears when that textfield has focus (for example, when a user taps it to enter some data using their keyboard).
The user input is available in the textfield property called
value; as you must have noted in the preceding recipe, accessing this value is simply a matter of assigning it to a variable (for example,
var myName = txtFirstName.value), or using the
value property directly.
textfield are one of the most common components in any application, and in Titanium there are a couple of points and options to consider whenever you use them.
It's important to note that when you want to retrieve the text that a user has typed in a textfield, you need to reference the
value property and not the text, like many of the other string-based controls!
Try experimenting with other textfield border styles to give your app a different appearance. Other possible values are the following:
Ti.UI.INPUT_BORDERSTYLE_BEZEL Ti.UI.INPUT_BORDERSTYLE_LINE Ti.UI.INPUT_BORDERSTYLE_NONE Ti.UI.INPUT_BORDERSTYLE_ROUNDED
When a textfield or textarea control gains focus in either an iPhone or an Android phone, the default keyboard is what you see spring up on the screen. There will be times, however, when you wish to change this behavior; for example, you may only want to have the user input numeric characters into a textfield when they are providing a numerical amount (such as their age or a monetary value). Additionally, keyboard toolbars can be created to appear above the keyboard itself, which will allow you to provide the user with other options, such as removing the keyboard from the window, or allowing copy and paste operations via a simple button tap.
In the following recipe, we're going to create a toolbar that contains both a system button and another system component called flexiblespace. These will be added at the top of our numeric keyboard, which will appear whenever the TextField for amount or interest rate gains focus. Note that in this example, we have updated the
tfAmount and
tfInterestRate textfield objects to contain the
keyboardType and
returnKeyType properties.
Note that toolbars are iOS-specific, and currently they may not be available for Android in the Titanium SDK.
Open your
app.js file and type the following code. If you have been following along from the previous recipe, this code should replace the previous recipe's code for adding the amount and interest rate textfields:
//flexible space for button bars var flexSpace = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); //done system button var buttonDone = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.DONE, bottom: 0 }); //add the event listener 'click' event to our done button buttonDone.addEventListener('click', function(e){ tfAmount.blur(); tfInterestRate.blur(); interestRate = tfInterestRate.value; }); //creating the textfield for our loan amount input var tfAmount = Ti.UI.createTextField({ width: 140, height: 30, right: 20, borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED, returnKeyType:Ti.UI.RETURNKEY_DONE, hintText: '1000.00', keyboardToolbar: [flexSpace,buttonDone], keyboardType:Ti.UI.KEYBOARD_PHONE_PAD });, keyboardToolbar: [flexSpace,buttonDone], keyboardType:Ti.UI.KEYBOARD_PHONE_PAD }); interestRateRow.add(tfInterestRate);
In this recipe, we created a textfield and added it to our view. You should have noticed by now how many properties are universal among the different UI components: width, height, top, and right are just four properties that are used in our textfield called
tfAmount and were used in previous recipes for other components.
Many touchscreen phones do not have physical keyboards; however, we are using a touchscreen keyboard to gather our input data. Depending on the data you require, you may not need a full keyboard with all the QWERTY keys, and you may want to just display a numeric keyboard, for example, if you were using the telephone dialing features on your iPhone or Android device.
Additionally, you may require the QWERTY keys, but in a specific format. A custom keyboard makes the user input quicker and less frustrating for the user by presenting custom options, such as keyboards for inputting web addresses and e-mails with all the
www and @ symbols in convenient touch locations.
In this example, we're setting
keyboardType to
Ti.UI.KEYBOARD_PHONE_PAD, which means that whenever the user clicks on that field, they see a numeric keypad.
In addition, we are specifying the
keyboardToolbar property to be an array of our Done button as well as the the flexspace button, so we get a toolbar with the Done button. The event listener added to the Done button ensures that we can pick up the click, capture the values, and blur the field, essentially hiding the keypad.
Tip
Downloading the example code
You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.
Try experimenting with other keyboard styles in your Titanium app!
Sliders and switches are two UI components that are simple to implement and can bring that extra level of interactivity into your apps. Switches, as the name suggests, have only two states—on and off—which are represented by boolean values (true and false).
Sliders, on the other hand, take two float values—a minimum value and a maximum value—and allow the user to select any number between and including these two values. In addition to its default styling, the slider API also allows you to use images for both sides of the track and the slider thumb image that runs along it. This allows you to create some truly customized designs.
We are going to add a switch to indicate an on/off state and a slider to hold the loan length, with values ranging from a minimum of 6 months to a maximum of 72 months. Also, we'll add some event handlers to capture the changed value from each component, and in the case of the slider, we will update an existing label with the new slider value. Don't worry if you aren't yet 100 percent sure about how event handlers work, as we'll cover them in further detail in Chapter 6, Getting to Grips With Properties and Events.
If you're following with the LoanCalc app, the next code should replace the code in your
window2.js file. We'll also add a label to identify what the switch component does and a view component to hold it all together:
//create an instance of a window module.exports = (function(){ var win = Ti.UI.createWindow({ backgroundColor: '#BBB', title: 'Settings' }); //create the view, this will hold all of our UI controls var view = Ti.UI.createView({ width: 300, height: 70, left: 10, top: 10, backgroundColor: '#fff', borderRadius: 5 }); //create a label to identify the switch control to the user var labelSwitch = Ti.UI.createLabel({ width: Ti.UI.SIZE, height: 30, top: 20, left: 20, font: {fontSize: 14, fontFamily: 'Helvetica', fontWeight: 'bold'}, text: 'Auto Show Chart?' }); view.add(labelSwitch); //create the switch object var switchChartOption = Ti.UI.createSwitch({ right: 20, top: 20, value: false }); view.add(switchChartOption); win.add(view); return win; })();
Now let's write the slider code; go back to your app.js file and type the following code underneath the
interestRateRow.add(tfInterestRate); line:
//create the slider to change the loan length var lengthSlider = Ti.UI.createSlider({ width: 140, top: 200, right: 20, min: 12, max: 60, value: numberMonths, thumbImage: 'sliderThumb.png', highlightedThumbImage: 'sliderThumbSelected.png' }); lengthSlider.addEventListener('change', function(e){ //output the value to the console for debug console.log(lengthSlider.value); //update our numberMonths variable numberMonths = Math.round(lengthSlider.value); //update label labelLoanLength.text = 'Loan length (' + Math.round(numberMonths) + ' months):'; }); loanLengthRow.add(lengthSlider);
In this recipe, we added two new components to two separate views within two separate windows. The first component—a switch—is fairly straightforward, and apart from the standard layout and positioning properties, it takes one main boolean value to determine its on or off status. It also has only one event,
change, which is executed whenever the switch changes from the on to off position or vice versa.
On the Android platform, the switch can be altered to appear as a toggle button (default) or a checkbox. Additionally, Android users can display a text label using the title property, which can be changed programmatically by using the
titleOff and
titleOn properties.
The slider component is more interesting and has many more properties than a Switch. sliders are useful for instances where we want to allow the user to choose between a range of values; in this case, it is a numeric range of months from 12 to 60. This is a much more effective method of choosing a number from a range than listing all the possible options in a picker, and is much safer than letting a user enter possibly invalid values via a textfield or textarea component.
Pretty much all of the slider can be styled using the default properties available in the Titanium API, including
thumbImage and
highlightedThumbImage, as we did in this recipe. The
highlightedThumbImage property allows you to specify the image that is used when the slider is being selected and used, allowing you to have a default and an active state.
You'll often find a need to pass variables and objects between different screen objects in your apps, such as windows, in your apps. One example is between a master and a child view. If you have a tabular list of data that shows only a small amount of information per row, and you wish to view the full description, you might pass that description data as a variable to the child window.
In this recipe, we're going to apply this very principle to a variable on the settings window (in the second tab of our LoanCalc app), by setting the variable in one window and then passing it back for use in our main window.
Under the declaration for your second window,
win2 in the
app.js file, include the following additional property called
autoShowChart and set it to
false. This is a custom property, that is, a property that is not already defined by the Titanium API. Often, it's handy to include additional properties in your objects if you require certain parameters that the API doesn't provide by default:
//set the initial value of win2's custom property win2.autoShowChart = false;
Now, in the
window2.js file, which holds all the subcomponents for your second window, replace the code that you created earlier to add the switch with the following code. This will update the window's
autoShowChart variable whenever the switch is changed:
//create the switch object var switchChartOption = Ti.UI.createSwitch({ right: 20, top: 20, value: false }); //add the event listener for the switch when it changes switchChartOption.addEventListener('change', function(e){ win.autoShowChart = switchChartOption.value; }); //add the switch to the view view.add(switchChartOption);
How this code works is actually pretty straightforward. When an object is created in Titanium, all the standard properties are accessible in a dictionary object of key-value pairs; all that we're doing here is extending that dictionary object to add a property of our own.
We can do this in two ways. As shown in our recipe's source code, this can be done after the instantiation of the window object, or it can also be done immediately within the instantiation code. In the source code of the second window, we are simply referencing the same object, so all of its properties are already available for us to read from and write to.
In any given app, you'll notice that creating buttons and capturing their click events is one of the most common tasks you do. This recipe will show you how to declare a button control in Titanium and attach a click event to it. Within that click event, we'll perform a task and log it to the info window in Appcelerator Studio.
This recipe will also demonstrate how to implement some of the default styling mechanisms available for you via the API.
Open your
app.js file and type the following code. If you're following along with the LoanCalc app, the following code should go after you created and added the textfield controls:
//calculate the interest for this loan button var buttonCalculateInterest = Ti.UI.createButton({ title: 'Calculate Total Interest', id: 1, top: 10 }); //add the event listener buttonCalculateInterest.addEventListener('click', calculateAndDisplayValue); //add the first button to our view view.add(buttonCalculateInterest); //calculate the interest for this loan button var buttonCalculateRepayments = Ti.UI.createButton({ title: 'Calculate Total Repayment', id: 2, top: 10 }); //add the event listener buttonCalculateRepayments.addEventListener('click', calculateAndDisplayValue); //add the second and final button to our view view.add(buttonCalculateRepayments);
Now that we've created our two buttons and added the event listeners, let's create the
calculateAndDisplayValue() function to do some simple fixed interest mathematics and produce the results, which we'll log to the Appcelerator Studio console:
//add the event handler which will be executed when either of //our calculation buttons are tapped function calculateAndDisplayValue(e) { //log the button id so we can debug which button was tapped console.log('Button id = ' + e.source.id); if (e.source.id == 1) { //Interest (I) = Principal (P) times Rate Per Period //(r) times Number of Periods (n) / 12 var totalInterest = (tfAmount.value * (interestRate / 100) * numberMonths) / 12; //log result to console console.log('Total Interest = ' + totalInterest); } else { //Interest (I) = Principal (P) times Rate Per Period (r) //times Number of Periods (n) / 12 var totalInterest = (tfAmount.value * (interestRate / 100) * numberMonths) / 12; var totalRepayments = Math.round(tfAmount.value) + totalInterest; //log result to console console.log('Total repayments' + totalRepayments); } } //end function
Most controls in Titanium are capable of firing one or more events, such as
focus,
onload, or (as in our recipe)
click. The
click event is undoubtedly the one you'll use more often than any other. In the preceding source code, you will notice that, in order to execute code from this event, we are adding an event listener to our button, which has a signature of click. This signature is a string and forms the first part of our event listener. The second part is the executing function for the event.
It's important to note that other component types can also be used in a similar manner; for example, an imageview can be declared. It can contain a custom button image, and can have a click event attached to it in exactly the same way as a regular button can.
There are a number of dialogs available for you to use in the Titanium API, but for the purposes of this recipe, we'll be concentrating on the two main ones: alert dialog and option dialog. These two simple components perform two similar roles, but with a key difference. The alert dialog is normally used only to show the user a message, while the option dialog asks the user a question and can accept a response in the form of a number of options. Generally, an alert dialog only allows a maximum of two responses from the user, whereas the option dialog can contain many more.
There are also key differences in the layout of these two dialog components, which will become obvious in the following recipe.
First, we'll create an alert dialog that simply notifies the user of an action that can not be completed due to missing information. In our case, that they have not provided a value for the loan amount in
tfAmount TextField. Add the following code to the
calculateAndDisplayValue() function, just under the initial
console.log command:
if (tfAmount.value === '' || tfAmount.value === null) { var errorDialog = Ti.UI.createAlertDialog({ title: 'Error!', message: 'You must provide a loan amount.' }); errorDialog.show(); return; }
Now let's add the option dialog. This is going to display the result from our calculation and then give the user the choice of viewing the results as a pie chart (in a new window), or of canceling and staying on the same screen.
We need to add a couple of lines of code to define the
optionsMessage variable that will be used in the option dialog, so add this code below the line calculating
totalRepayments:
console.log('Total repayments = ' + totalRepayments) : var optionsMessage = "Total repayments on this loan equates to $" + totalRepayments;
Then add the following code just below the line of code defining
totalInterest:
console.log('Total interest = ' + totalInterest) : var optionsMessage = "Total interest on this loan equates to $" + totalInterest;
Finally, at the end of the function, add this code:
//check our win2 autoShowChart boolean value first (coming //from the switch on window2.js) if (win2.autoShowChart == true) { // openChartWindow(); } else { var resultOptionDialog = Ti.UI.createOptionDialog({ title: optionsMessage + '\n\nDo you want to view this in a chart?', options: ['Okay', 'No'], cancel: 1 }); //add the click event listener to the option dialog resultOptionDialog.addEventListener('click', function(e){ console.log('Button index tapped was: ' + e.index); if (e.index == 0) { // openChartWindow(); } }); resultOptionDialog.show(); } //end if
The alert dialog, in particular, is a very simple component that simply presents the user with a message as a modal, and it has only one possible response, which closes the alert. Note that you should be careful not to call an alert dialog more than once while a pending alert is still visible, for example, if you're calling that alert from within a loop.
The option dialog is a much larger modal component that presents a series of buttons with a message at the bottom of the screen. It is generally used to allow the user to pick more than one item from a selection. In our code,
resultOptionDialog presents the user with a choice of two options—Okay and No. One interesting property of this dialog is Cancel, which dismisses the dialog without firing the click event, and also styles the button at the requested index in a manner that differentiates it from the rest of the group of buttons.
Note that we've commented out the
openChartWindow() function because we haven't created it yet. We'll be doing that in the next recipe.
Just like the Window object, both of these dialogs are not added to another View, but are presented by calling the
show() method instead. You should call the
show() method only after the dialog has been properly instantiated and any event listeners have been created.
The following images show the difference between the alert dialog and the option dialog:
Let's finish off our calculations visually by displaying charts and graphs. Titanium lacks a native charting API. However, there are some open source options for implementing charts, such as Google Charts. While the Google solution is free, it requires your apps to be online every time you need to generate a chart. This might be okay for some circumstances, but it is not the best solution for an application that is meant to be usable offline. Plus, Google Charts returns a generated JPG or PNG file at the requested size and in rasterized format, which is not great for zooming in when viewing on an iPhone or iPad.
A better solution is to use the open source and MIT-licensed Raphael library, which (luckily for us) has a charting component! It is not only free but also completely vector-based, which means any charts that you create will look great in any resolution, and can be zoomed in to without any loss of quality.
Note
Note that this recipe may not work on all Android devices. This is because the current version of Raphael isn't supported by non-WebKit mobile browsers. However, it will work as described here for iOS.
Download the main Raphael JS library from. The direct link is.
Download the main Charting library from (the direct link is), and any other charting libraries that you wish to use.
Download the Pie Chart library, which is at.
If you're following along with the LoanCalc example app, then open your project directory and put your downloaded files into a new folder called
charts under the
Resources directory. You can put them into the
root folder if you wish, but bear in mind that you will have to ensure that your references in the following steps are correct.
To use the library, we'll be creating a webview in our app, referencing a variable that holds the HTML code to display a Raphael chart, which we'll call chartHTML. A webview is a UI component that allows you to display web pages or HTML in your application. It does not include any features of a full-fledged browser, such as navigation controls or address bars.
Create a new file called
chartwin.js in the
Resources directory and add the following code to it:
//create an instance of a window module.exports = (function() { var chartWin = Ti.UI.createWindow({ title : 'Loan Pie Chart' }); chartWin.addEventListener("open", function() { //create the chart title using the variables we passed in from //app.js (our first window) var chartTitleInterest = 'Total Interest: $' + chartWin.totalInterest; var chartTitleRepayments = 'Total Repayments: $' + chartWin.totalRepayments; //create the chart using the sample html from the //raphaeljs.com website var chartHTML = '<html><head> <title>RaphaelJS Chart</title><meta name="viewport" content="width=device-width, initial-scale=1.0"/> <script src="charts/raphael-min.js" type="text/javascript" charset="utf-8"></script> <script src="charts/g.raphael-min.js" type="text/javascript" charset="utf-8"></script> <script src="charts/g.pie-min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> window.onload = function () { var r = Raphael("chartDiv"); r.text.</div> </body></html>'; //add a webview to contain our chart var webview = Ti.UI.createWebView({ width : Ti.UI.FILL, height : Ti.UI.FILL, top : 0, html : chartHTML }); chartWin.add(webview); }); return chartWin; })();
Now, back in your
app.js file, create a new function at the end of the file, called
openChartWindow(). This function will be executed when the user chooses Okay from the previous recipe's option dialog. It will create a new window object based on the
chartwin.js file and pass to it the values needed to show the chart:
//we'll call this function if the user opts to view the loan //chart function openChartWindow() { //Interest (I) = Principal (P) times Rate Per Period (r) //times Number of Periods (n) / 12 var totalInterest = (tfAmount.value * (interestRate / 100) * numberMonths) / 12; var totalRepayments = Math.round(tfAmount.value) + totalInterest; var chartWindow = require("chartwin"); chartWindow.numberMonths = numberMonths; chartWindow.interestRate = interestRate; chartWindow.totalInterest = totalInterest; chartWindow.totalRepayments = totalRepayments; chartWindow.principalRepayments = (totalRepayments - totalInterest); tab1.open(chartWindow); }
Finally, remember to uncomment the two
//
openChartWindow() lines that you added in the previous recipe. Otherwise, you won't see anything!
Essentially, what we're doing here is wrapping the Raphael library, something that was originally built for the desktop browser, into a format that can be consumed and displayed using the iOS's WebKit browser. You can find out more about Raphael at and, and learn how it renders charts via its JavaScript library. We'll not be explaining this in detail; rather, we will cover the implementation of the library to work with Titanium.
Our implementation consists of creating a webview component that (in this case) will hold the HTML data that we constructed in the
chartHTML variable. This HTML data contains all of the code that is necessary to render the charts, including the scripts listed in item #2 of the Getting Ready section of this recipe. If you have a chart with static data, you can also reference the HTML from a file using the
url property of the webview object, instead of passing all the HTML as a string.
The chart itself is created using some simple JavaScript embedded in the
r.piechart(150, 180, 130, n1, n2) HTML data string, where
n1 and
n2 are the two values we wish to display as slices in the pie chart. The other values define the center point of the chart from the top and left, respectively, followed by the chart radius.
All of this is wrapped up in a new module file defined by the
chartwin.js file, which accesses the properties passed from the first tab's window in our LoanCalc app. This data is passed using exactly the same mechanism as explained in a previous recipe, Passing custom variables between Windows.
Finally, the chart window is passed back to the
app.js file, within the
openChartWindow() function, and from there, we use
tab1.open() to open a new window within
tab1. This has the effect of sliding the new window, similar to the way in which many iOS apps work (in Android, the new window would open normally).
The following screenshot shows the Raphael JS Library being used to show a pie chart based on our loan data:
In Android 3.0, Google introduced the actionbar, a tab-style interface that sits under the title bar of an application. The actionbar behaves a lot like the tabgroup, which we're used to in iOS, and coincidently it can be created in the same way as we created a TabGroup previously, which makes it very easy to create one! All that we need to do is make some minor visual tweaks in our application to get it working on Android.
You will be running this recipe on Android 4.x, so make sure you're running an emulator or device that runs 4.x or higher. I'd recommend using GenyMotion, available at, to emulate Android. It's fast and way more flexible than, the built-in Android SDK emulators. It's also fully supported in Titanium and in Appcelerator Studio.
The complete source code for this chapter can be found in the
/Chapter 1/LoanCalc folder.
There's not much to do to get the actionbar working, as we've already created a tabgroup for our main interface. We just need to do just a few tweaks to our app views, buttons, and labels.
First, let's make sure that all our labels are rendering correctly. Add the following attribute to any label that you've created:
color: '#000'
Now we need to fix our buttons. Let's add a tweak to them after we've created them (for Android only). Add the following code after your buttons. To do this, we're going to use
.applyProperties, which allows us to make multiple changes to an element at the same time:
if (Ti.Platform.osname.toLowerCase() === 'android') { buttonCalculateRepayments.applyProperties({ color : '#000', height : 45 }); buttonCalculateInterest.applyProperties({ color : '#000', height : 45 }); }
This block checks whether we're running Android and makes some changes to the buttons. Let's add some more code to the block to adjust the
textfield height as well, as follows:
if (Ti.Platform.osname.toLowerCase() === 'android') { buttonCalculateRepayments.applyProperties({ color : '#000', height : 45 }); buttonCalculateInterest.applyProperties({ color : '#000', height : 45 }); tfAmount.applyProperties({ color : '#000', height : 35 }); tfInterestRate.applyProperties({ color : '#000', height : 35 }); }
Finally, we're going to make a tweak to our settings window to make it play nicely on Android devices with different widths. Edit the
window2.js file and remove the width of the
view variable, changing it to the following:
var view = Ti.UI.createView({ height : 70, left : 10, right: 10, top : 10, backgroundColor : '#fff', borderRadius : 5 });
We'll need to update the
labelSwitch variable too, by adding this line:
color: '#000'
Now let's run the app in the Android emulator or on a device, and we should see the following:
We've not done much here to get an
actionbar working. That's because Titanium takes care of the heavy lifting for us. You must have noticed that the only changes we made were visual tweaks to the other elements on the screen; the actionbar just works!
This is a really nice feature of Titanium, wherein you can create one UI element, a tabgroup, and have it behave differently for iOS and Android using the same code.
Having said that, there are some additional tweaks that you can do to your
actionbar using the
Ti.Android.ActionBar API. This gives specific access to properties and events associated with the actionbar. More information can be found at.
So, for example, you can change the properties of
actionBar by accessing it via the current window:
actionBar = win.activity.actionBar; if (actionBar) { actionBar.backgroundImage = "/bg.png"; actionBar.title = "New Title"; }
As you can see, it's really easy to create an actionbar using a tabgroup and alter its properties in Android.
|
https://www.packtpub.com/product/appcelerator-titanium-smartphone-app-development-cookbook-second-edition/9781849697705
|
CC-MAIN-2021-17
|
refinedweb
| 7,972
| 53.41
|
#include "pxr/pxr.h"
#include "pxr/base/tf/api.h"
#include "pxr/base/arch/functionLite.h"
#include <stddef.h>
Go to the source code of this file.
Functions for recording call locations.
Many macros want to record the location in which they are invoked. In fact, this is the most useful feature that function-like macros have over regular functions. This code provides a standard way to collect and pass that contextual information around. There are two parts. First is a small structure which holds the contextual information. Next is a macro which will produce a temporary structure containing the local contextual information. The intended usage is in a macro.
Definition in file callContext.h.
Definition at line 47 of file callContext.h.
|
https://www.sidefx.com/docs/hdk/call_context_8h.html
|
CC-MAIN-2020-16
|
refinedweb
| 123
| 63.56
|
#include <wx/image.h>
This class encapsulates a platform-independent image.
An image can be created from data, or using wxBitmap::ConvertToImage. An image can be loaded from a file in a variety of formats, and is extensible to new formats via image format handlers. Functions are available to set and get image bits, so it can be used for basic image manipulation.
A wxImage cannot (currently) be drawn directly to a wxDC. Instead, a platform-specific wxBitmap object must be created from it using the wxBitmap::wxBitmap(wxImage,int depth) constructor. This bitmap can then be drawn in a device context, using wxDC::DrawBitmap. wxMask object associated to the bitmap object.
Starting from wxWidgets 2.5.0 wxImage wxIMAGE_ALPHA_TRANSPARENT and wxIMAGE_ALPHA_OPAQUE can be used to indicate those values in a more readable form.
While all images have RGB data, not all images have an alpha channel. Before using wxImage::GetAlpha you should check if this image contains an alpha channel with wxImage::HasAlpha. Currently the BMP, PNG, TGA, and TIFF format handlers have full alpha channel support for loading so if you want to use alpha you have to use one of these formats. If you initialize the image alpha channel yourself using wxImage::SetAlpha, you should save it in either PNG, TGA, or TIFF format to avoid losing it as these are the only handlers that currently support saving with alpha.
The following image handlers are available. wxBMPHandler is always installed by default. To use other image formats, install the appropriate handler with wxImage::AddHandler or call wxInitAllImageHandlers().
When saving in PCX format, wxPC, wxPNMHandler will always save as raw RGB.
Saving GIFs requires images of maximum 8 bpp (see wxQuantize), and the alpha channel converted to a mask (see wxImage::ConvertAlphaToMask). Saving an animated GIF requires images of the same size (see wxGIFHandler::SaveAnimation)
Predefined objects/pointers: wxNullImage
Creates an image with the given size and clears it if requested.
Does not create an alpha channel..
Creates an image from XPM data.
wxPerl Note: Not supported by wxPerl.
Creates an image from a file.
Creates an image from a file using MIME-types to specify the type.
Creates an image from a stream.
Creates an image from a stream using MIME-types to specify the type.
Destructor.
See reference-counted object destruction for more info.
Register an image handler.
Typical example of use:
See Available image handlers for a list of the available handlers. You can also use wxInitAllImageHandlers() to add handlers for all the image formats supported by wxWidgets at once.
Blurs the image in both horizontal and vertical directions by the specified pixel blurRadius.
This should not be used when using a single mask colour for transparency.
Blurs the image in the horizontal direction only.
This should not be used when using a single mask colour for transparency.
Blurs the image in the vertical direction only.
This should not be used when using a single mask colour for transparency.
Returns true if at least one of the available image handlers can read the file with the given name.
See wxImageHandler::CanRead for more info.
Returns true if at least one of the available image handlers can read the data in the given stream.
See wxImageHandler::CanRead for more info.
Deletes all image handlers.
This function is called by wxWidgets on exit.
Initialize the image data with zeroes (the default) or with the byte value given as value.
Removes the alpha channel from the image.
This function should only be called if the image has alpha channel data, use HasAlpha() to check for this.
Computes the histogram of the image.
histogram is a reference to wxImageHistogram object. wxImageHistogram is a specialization of wxHashMap "template" and is defined as follows:
If the image has alpha channel, this method converts it to mask.
If the image has an alpha channel, all pixels with alpha value less than threshold are replaced with the mask colour and the alpha channel is removed. Otherwise nothing is done.
The mask colour is chosen automatically using FindFirstUnusedColour() by this function, see the overload below if you this is not appropriate.
If the image has alpha channel, this method converts it to mask using the specified colour as the mask colour.
If the image has an alpha channel, all pixels with alpha value less than threshold are replaced with the mask colour and the alpha channel is removed. Otherwise nothing is done.
Returns disabled (dimmed) version of the image.
Returns a greyscale version of the image.
The returned image uses the luminance component of the original to calculate the greyscale. Defaults to using the standard ITU-T BT.601 when converting to YUV, where every pixel equals (R * weight_r) + (G * weight_g) + (B * weight_b).
Returns a greyscale version of the image.
Returns monochromatic version of the image.
The returned image has white colour where the original has (r,g,b) colour and black colour everywhere else.
Returns an identical copy of this image.
Creates a fresh image.
See wxImage::wxImage(int,int,bool) for more info.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Creates a fresh image.
See wxImage::wxImage(int,int,unsigned char*,bool) for more info.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Creates a fresh image.
See wxImage::wxImage(int,int,unsigned char*,unsigned char*,bool) for more info.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Destroys the image data.
Finds the first colour that is never used in the image.
The search begins at given initial colour and continues by increasing R, G and B components (in this order) by 1 until an unused colour is found or the colour space exhausted.
The parameters r, g, b are pointers to variables to save the colour.
The parameters startR, startG, startB define the initial values of the colour. The returned colour will have RGB values equal to or greater than these.
Finds the handler with the given name.
Finds the handler associated with the given extension and type.
Finds the handler associated with the given image type.
Finds the handler associated with the given MIME type.
Returns pointer to the array storing the alpha values for this image.
This pointer is NULL for the images without the alpha channel. If the image does have it, this pointer may be used to directly manipulate the alpha values which are stored as the RGB ones.
Return alpha value at given pixel location.
Returns the blue intensity at the given coordinate.
Returns the image data as an array.
This is most often used when doing direct image manipulation. The return value points to an array of characters in RGBRGBRGB... format in the top-to-bottom, left-to-right order, that is the first RGB triplet corresponds to the first pixel of the first row, the second one — to the second pixel of the first row and so on until the end of the first row, with second row following after it and so on.
You should not delete the returned pointer nor pass it to SetData().
Returns the currently used default file load flags.
See SetDefaultLoadFlags() for more information about these flags.
Returns the green intensity at the given coordinate.
Returns the static list of image format handlers.
Gets the height of the image in pixels.:
Iterates all registered wxImageHandler objects, and returns a string containing file extension masks suitable for passing to file open/save dialog boxes.
"(*.ext1;*.ext2)|*.ext1;*.ext2". It is usually a good idea to prepend a description before passing the result to the dialog. Example:
Returns the file load flags used for this object.
See SetLoadFlags() for more information about these flags.
Gets the blue value of the mask colour.
Gets the green value of the mask colour.
Gets the red value of the mask colour.
Gets a user-defined string-valued option.
Generic options:
wxIMAGE_OPTION_FILENAME:The name of the file from which the image was loaded.
Options specific to wxGIFHandler:
wxIMAGE_OPTION_GIF_COMMENT:The comment text that is read from or written to the GIF file. In an animated GIF each frame can have its own comment. If there is only a comment in the first frame of a GIF it will not be repeated in other frames.
Gets a user-defined integer-valued option.
The function is case-insensitive to name. If the given option is not present, the function returns 0. Use HasOption() if 0 is a possibly valid value for the option.
Generic options:
wxIMAGE_OPTION_MAX_WIDTHand
wxIMAGE_OPTION_MAX_HEIGHT:If either of these options is specified, the loaded image will be scaled down (preserving its aspect ratio) so that its width is less than the max width given if it is not 0 and its height is less than the max height given if it is not 0. This is typically used for loading thumbnails and the advantage of using these options compared to calling Rescale() after loading is that some handlers (only JPEG one right now) support rescaling the image during loading which is vastly more efficient than loading the entire huge image and rescaling it later (if these options are not supported by the handler, this is still what happens however). These options must be set before calling LoadFile() to have any effect.
wxIMAGE_OPTION_ORIGINAL_WIDTHand
wxIMAGE_OPTION_ORIGINAL_HEIGHT:These options will return the original size of the image if either
wxIMAGE_OPTION_MAX_WIDTHor
wxIMAGE_OPTION_MAX_HEIGHTis specified.
wxIMAGE_OPTION_QUALITY:JPEG quality used when saving. This is an integer in 0..100 range with 0 meaning very poor and 100 excellent (but very badly compressed). This option is currently ignored for the other formats.
wxIMAGE_OPTION_RESOLUTIONUNIT:The value of this option determines whether the resolution of the image is specified in centimetres or inches, see wxImageResolution enum elements.
wxIMAGE_OPTION_RESOLUTION,
wxIMAGE_OPTION_RESOLUTIONXand
wxIMAGE_OPTION_RESOLUTIONY:These options define the resolution of the image in the units corresponding to
wxIMAGE_OPTION_RESOLUTIONUNIToptions value. The first option can be set before saving the image to set both horizontal and vertical resolution to the same value. The X and Y options are set by the image handlers if they support the image resolution (currently BMP, JPEG and TIFF handlers do) and the image provides the resolution information and can be queried after loading the image.
Options specific to wxPNGHandler:
wxIMAGE_OPTION_PNG_FORMAT:Format for saving a PNG file, see wxImagePNGType for the supported values.
wxIMAGE_OPTION_PNG_BITDEPTH:Bit depth for every channel (R/G/B/A).
wxIMAGE_OPTION_PNG_FILTER:Filter for saving a PNG file, see libpng () for possible values (e.g. PNG_FILTER_NONE, PNG_FILTER_SUB, PNG_FILTER_UP, etc).
wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL:Compression level (0..9) for saving a PNG file. An high value creates smaller-but-slower PNG file. Note that unlike other formats (e.g. JPEG) the PNG format is always lossless and thus this compression level doesn't tradeoff the image quality.
wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL:Compression memory usage level (1..9) for saving a PNG file. An high value means the saving process consumes more memory, but may create smaller PNG file.
wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY:Possible values are 0 for default strategy, 1 for filter, and 2 for Huffman-only. You can use OptiPNG () to get a suitable value for your application.
wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE:Internal buffer size (in bytes) for saving a PNG file. Ideally this should be as big as the resulting PNG file. Use this option if your application produces images with small size variation.
Options specific to wxTIFFHandler:
wxIMAGE_OPTION_TIFF_BITSPERSAMPLE:Number of bits per sample (channel). Currently values of 1 and 8 are supported. A value of 1 results in a black and white image. A value of 8 (the default) can mean greyscale or RGB, depending on the value of
wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL.
wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL:Number of samples (channels) per pixel. Currently values of 1 and 3 are supported. A value of 1 results in either a greyscale (by default) or black and white image, depending on the value of
wxIMAGE_OPTION_TIFF_BITSPERSAMPLE. A value of 3 (the default) will result in an RGB image.
wxIMAGE_OPTION_TIFF_COMPRESSION:Compression type. By default it is set to 1 (COMPRESSION_NONE). Typical other values are 5 (COMPRESSION_LZW) and 7 (COMPRESSION_JPEG). See tiff.h for more options.
wxIMAGE_OPTION_TIFF_PHOTOMETRIC:Specifies the photometric interpretation. By default it is set to 2 (PHOTOMETRIC_RGB) for RGB images and 0 (PHOTOMETRIC_MINISWHITE) for greyscale or black and white images. It can also be set to 1 (PHOTOMETRIC_MINISBLACK) to treat the lowest value as black and highest as white. If you want a greyscale image it is also sufficient to only specify
wxIMAGE_OPTION_TIFF_PHOTOMETRICand set it to either PHOTOMETRIC_MINISWHITE or PHOTOMETRIC_MINISBLACK. The other values are taken care of.
Options specific to wxGIFHandler:
wxIMAGE_OPTION_GIF_TRANSPARENCY:How to deal with transparent pixels. By default, the color of transparent pixels is changed to bright pink, so that if the image is accidentally drawn without transparency, it will be obvious. Normally, this would not be noticed, as these pixels will not be rendered. But in some cases it might be useful to load a GIF without making any modifications to its colours. Use
wxIMAGE_OPTION_GIF_TRANSPARENCY_UNCHANGEDto keep the colors correct. Use
wxIMAGE_OPTION_GIF_TRANSPARENCY_HIGHLIGHTto convert transparent pixels to pink (default). This option has been added in wxWidgets 3.1.1.
wxIMAGE_OPTION_TIFF_SAMPLESPERPIXEL,
wxIMAGE_OPTION_TIFF_BITSPERSAMPLE, and
wxIMAGE_OPTION_TIFF_PHOTOMETRIC. While some measures are taken to prevent illegal combinations and/or values, it is still easy to abuse them and come up with invalid results in the form of either corrupted images or crashes.
Get the current mask colour or find a suitable unused colour that could be used as a mask colour.
Returns true if the image currently has a mask.
Returns the red intensity at the given coordinate.
Returns the size of the image in pixels.
Returns a sub image of the current one as long as the rect belongs entirely to the image.
Gets the type of image found by LoadFile() or specified with SaveFile().
Gets the width of the image in pixels.
Returns true if this image has alpha channel, false otherwise.
Returns true if there is a mask active, false otherwise.
Returns true if the given option is present.
The function is case-insensitive to name.
The lists of the currently supported options are in GetOption() and GetOptionInt() function docs.
Converts a color in HSV color space to RGB color space.
Initializes the image alpha channel data.
It is an error to call it if the image already has alpha data. If it doesn't, alpha data will be by default initialized to all pixels being fully opaque. But if the image has a mask colour, all mask pixels will be completely transparent.
Internal use only.
Adds standard image format handlers. It only install wxBMPHandler for the time being, which is used by wxBitmap.
This function is called by wxWidgets on startup, and shouldn't be called by the user.
Adds a handler at the start of the static list of format handlers.
Returns true if image data is present.
Returns true if the given pixel is transparent, i.e. either has the mask colour if this image has a mask or if this image has alpha channel and alpha value of this pixel is strictly less than threshold.
Loads an image from an input stream.
If the file can't be loaded, this function returns false and logs an error using wxLogError(). If the file can be loaded but some problems were detected while doing it, it can also call wxLogWarning() to notify about these problems. If this is undesirable, use SetLoadFlags() to reset
Load_Verbose flag and suppress these warnings.
Loads an image from a file.
If no handler type is provided, the library will try to autodetect the format.
Loads an image from a file.
If no handler type is provided, the library will try to autodetect the format.
Loads an image from an input stream.
Returns a mirrored copy of the image.
The parameter horizontally indicates the orientation.
Assignment operator, using reference counting.
Copy the data of the given image to the specified position in this image.
Finds the handler with the given name, and removes it.
The handler is also deleted.
Replaces the colour specified by r1,g1,b1 by the colour r2,g2,b2.
Changes the size of the image in-place use either the current mask colour if set or find, use, and set a suitable mask colour for any newly exposed areas.
Converts a color in RGB color space to HSV color space.
Rotates the image about the given point, by angle radians.
Passing true to interpolating results in better image quality, but is slower.
If the image has a mask, then the mask colour is used for the uncovered pixels in the rotated image background. Else, black (rgb 0, 0, 0) will be used.
Returns the rotated image, leaving this image intact.
Returns a copy of the image rotated by 180 degrees.
Returns a copy of the image rotated 90 degrees in the direction indicated by clockwise.
Rotates the hue of each pixel in the image by angle, which is a double in the range of -1.0 to +1.0, where -1.0 corresponds to -360 degrees and +1.0 corresponds to +360 degrees.
Saves an image in the given stream.
Saves an image in the named file.
Saves an image in the named file.
Saves an image in the named file.
File type is determined from the extension of the file name. Note that this function may fail if the extension is not recognized! You can use one of the forms above to save images to files with non-standard extensions.
Saves an image in the given stream.
Returns a scaled version of the image.
This is also useful for scaling bitmaps in general as the only other way to scale bitmaps is to blit a wxMemoryDC into another wxMemoryDC.
The parameter quality determines what method to use for resampling the image, see wxImageResizeQuality documentation.
It should be noted that although using
wxIMAGE_QUALITY_HIGH produces much nicer looking results it is a slower method. Downsampling will use the box averaging method which seems to operate very fast. If you are upsampling larger images using this method you will most likely notice that it is a bit slower and in extreme cases it will be quite substantially slower as the bicubic algorithm has to process a lot of data.
It should also be noted that the high quality scaling may not work as expected when using a single mask colour for transparency, as the scaling will blur the image and will therefore remove the mask partially. Using the alpha channel will work.
Example:
This function is similar to SetData() and has similar restrictions.
The pointer passed to it may however be NULL in which case the function will allocate the alpha array internally – this is useful to add alpha channel data to an image which doesn't have any.
If the pointer is not NULL, it must have one byte for each image pixel and be allocated with malloc(). wxImage takes ownership of the pointer and will free it unless static_data parameter is set to true – in this case the caller should do it.
Sets the alpha value for the given pixel.
This function should only be called if the image has alpha channel data, use HasAlpha() to check for this.
Sets the image data without performing checks.
The data given must have the size (width*height*3) or results will be unexpected. Don't use this method if you aren't sure you know what you are doing.
The data must have been allocated with
malloc(), NOT with
operator new.
If static_data is false, after this call the pointer to the data is owned by the wxImage object, that will be responsible for deleting it. Do not pass to this function a pointer obtained through GetData().
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Sets the default value for the flags used for loading image files.
This method changes the global value of the flags used for all the subsequently created wxImage objects by default. It doesn't affect the already existing objects.
By default, the global flags include
Load_Verbose flag value.
Sets the flags used for loading image files by this object.
The flags will affect any future calls to LoadFile() for this object. To change the flags for all image objects, call SetDefaultLoadFlags() before creating any of them.
Currently the only defined flag is
Load_Verbose which determines if the non-fatal (i.e. not preventing the file from being loaded completely) problems should result in the calls to wxLogWarning() function. It is recommended to customize handling of these warnings by e.g. defining a custom log target (see Logging Overview), but if such warnings should be completely suppressed, clearing this flag provides a simple way to do it, for example:
Specifies whether there is a mask or not.
The area of the mask is determined by the current mask colour.
Sets the mask colour for this image (and tells the image to use the mask).
Sets image's mask so that the pixels that have RGB value of mr,mg,mb in mask will be masked in the image.
This is done by first finding an unused colour in the image, setting this colour as the mask colour and then using this colour to draw all pixels in the image who corresponding pixel in mask has given RGB value.
The parameter mask is the mask image to extract mask shape from. It must have the same dimensions as the image.
The parameters mr, mg, mb are the RGB values of the pixels in mask that will be used to create the mask.
Sets a user-defined option.
The function is case-insensitive to name.
For example, when saving as a JPEG file, the option quality is used, which is a number between 0 and 100 (0 is terrible, 100 is very good).
The lists of the currently supported options are in GetOption() and GetOptionInt() function docs.
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Set the color of the pixel at the given x and y coordinate.
Sets the colour of the pixels within the given rectangle.
This routine performs bounds-checks for the coordinate so it can be considered a safe way to manipulate the data.
Set the type of image returned by GetType().
This method is mostly used internally by the library but can also be called from the user code if the image was created from data in the given bitmap format without using LoadFile() (which would set the type correctly automatically).
Notice that the image must be created before this function is called.
Returns a resized version of this image the areas of the larger image not covered by this image are made transparent by filling them with the image mask colour (which will be allocated automatically if it isn't currently set).
Otherwise, the areas will be filled with the colour with the specified RGB components.
|
https://docs.wxwidgets.org/3.1.2/classwx_image.html
|
CC-MAIN-2019-09
|
refinedweb
| 3,858
| 58.28
|
Handwritten Digit Prediction using Convolutional Neural Networks in TensorFlow with Keras and Live Example using TensorFlow.js
Whenever we start learning a new programming language we always start with Hello World Program. Likewise, most AI/ML developers say “Just like programming has Hello World, machine learning has MNIST”.
Like everyone, I wanted to start from there. In fact, I wanted to write my first article/story related ML on MNIST but that didn’t sound exciting because the internet has loads of MNIST articles. I want my article/story different from others so I thought with code why can’t I share a live example also?
Let’s get started. I hope you have TensorFlow, Keras in your system if not please read my previous article. It has instructions about how to install them.
First, Lets import all necessary libraries required..optimizers import Adam
from keras.utils import np_utils
Next, let’s load the MNIST data provided by Keras
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
The datasets(training & test) are 3D arrays. Training dataset shape is (60000, 28, 28) & Testing dataset shape is (10000, 28, 28).
The input shape that CNN expects is a 4D array (batch, height, width, channels). Channels signify whether the image is grayscale or colored. In our case, we are using grayscale images so we give 1 for channels if these are colored images we give 3(RGB). Below code for reshaping our inputs.
# Reshaping to format which CNN expects (batch, height, width, channels)
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2], 1).astype('float32')X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1).astype('float32')
It’s always good to normalize data. Our Datasets will have data in each pixel in between 0–255 so now we scale it to 0–1 using below code.
# normalize inputs from 0-255 to 0-1
X_train/=255
X_test/=255
Our output ranges between 0–9. So, its a multi-class classification problem. All values(output) are equal to us so it’s better to use one-hot encoding. One-hot encoding transforms integer to a binary matrix where the array contains only one ‘1’ and the rest elements are ‘0’.
For example, we are expecting output as 8 means value of output variable 8 so according to one-hot coding its [0,0,0,0,0,0,0,0,1,0]
# one hot encode
number_of_classes = 10
y_train = np_utils.to_categorical(y_train, number_of_classes)
y_test = np_utils.to_categorical(y_test, number_of_classes)
Now let’s build model
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(X_train.shape[1], X_train.shape[2], 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(number_of_classes, activation='softmax'))
Let’s understand above code step by step.
- The first hidden layer is a convolutional layer called a Convolution2D. The layer has 32 filters/output channels, which with the size of 5×5 and an activation function. This is the input layer, expecting images with the structure outlined above (height, width, channels).
- The Second layer is the MaxPooling layer. MaxPooling layer is used to down-sample the input to enable the model to make assumptions about the features so as to reduce over-fitting. It also reduces the number of parameters to learn, reducing the training time.
- One more hidden layer with 32 filters/output channels with the size of 3×3 and an activation function.
- One more MaxPooling layer.
- The next layer is a regularization layer using dropout called Dropout. It is configured to randomly exclude 20% of neurons in the layer in order to reduce overfitting.
- Next layer converts the 2D matrix data to a vector called Flatten. It allows the output to be processed by standard fully connected layers.
- Next layer is a fully connected layer with 128 neurons.
- Next(last) layer is output layer with 10 neurons(number of output classes) and it uses softmax activation function. Each neuron will give the probability of that class. It’s a multi-class classification that’s why softmax activation function if it was a binary classification we use sigmoid activation function.
Let’s compile the model. I used categorical_crossentropy as a loss function because its a multi-class classification problem. I used Adam as Optimizer to make sure our weights optimized properly. I used accuracy as metrics to improve the performance of our neural network.
# Compile model
model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])
It’s time for our model training. The model is going to fit over 10 epochs and updates after every 200 images training. The test data is used as the validation dataset, allowing you to see the skill of the model as it trains.
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)
I want to test my trained model with my own images so I want to store my model on my local hard disk.
# Save the model
model.save('models/mnistCNN.h5')
The test dataset is used to evaluate the model and after evaluation Test loss & Test Accuracy metrics will be printed.
# Final evaluation of the model
metrics = model.evaluate(X_test, y_test, verbose=0)
print("Metrics(Test loss & Test Accuracy): ")
print(metrics)
I got around 99.19% accuracy. You will find this example code with name mnistCNN.py at my GitHub repository.
After completing this I didn’t get satisfaction because it ran on the data provided by Keras. I want to verify my trained model on my own data. So I created a couple of images by myself & stored the images in my data folder and then checked with my model. Results looked decent. Code for this
# Importing the Keras libraries and packages
from keras.models import load_model
model = load_model('models/mnistCNN.h5')from PIL import Image
import numpy as npfor index in range(10):
img = Image.open('data/' + str(index) + '.png').convert("L")
img = img.resize((28,28))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,28,28,1)
# Predicting the Test set results
y_pred = model.predict(im2arr)
print(y_pred)
You will find above code, images & model file at at my GitHub repository. To run above code you need Pillow Package. You need to run below command to get the package.
pip3 install pillow
But still, I am not satisfied so I thought let’s do something more. We all know Google introduced TensorFlow.js. I read that we can use our existing model also. So I thought why not build a small page for this example. From here journey became more excited.
First, we need canvas where the user can draw a number. For this, I wrote an HTML with the help of this article.
Now we want our model to be used at browser level for that we need to convert into the format by which TensorFlow.js can consume. For this task, this article helped me. To convert Keras model to TensorFlow js consumable model we need tensorflowjs_converter. For this we need to install tensorflowjs package.
pip3 install tensorflowjs
I used below command to convert the format
tensorflowjs_converter --input_format keras models/mnistCNN.h5 models/
Now a model file & a couple of supporting files for the model will be created at models folder. With these(model.json, group1-shard1of1, group2-shard1of1, group3-shard1of1, group4-shard1of1) names. These are going to help us to use our Trained DL(Deep Learning) model.
Now I am going to reveal our secret ingredient for this story
I am going to explain 3 important things here rest all are fairly straightforward. It all starts with TensorFlow.js script include. Need to include TensorFlow.js for that add below line to your HTML file.
<script src=""> </script>
Next our init function. 2 lines are important in this init function.
1. I used the async function because I want to make sure model is loaded before using the example. that’s why await used at the time of loading model.
2. Load the model. Use below code for this.
model = await tf.loadModel('model.json');
Next most important one, our Predict function.
function predict() {
const imageData = ctx.getImageData(0, 0, 140, 140);
//convert to tensor
var tfImg = tf.fromPixels(imageData, 1);
//Resize the image
var smalImg = tf.image.resizeBilinear(tfImg, [28, 28]);
smalImg = tf.cast(smalImg, 'float32');
var tensor = smalImg.expandDims(0);
tensor = tensor.div(tf.scalar(255));
const prediction = model.predict(tensor);
const predictedValues = prediction.dataSync();
var isThereAnyPrediction = false;
for (index = 0; index < predictedValues.length; index++) {
if (predictedValues[index] > 0.5) {
isThereAnyPrediction = true;
document.getElementById('rightside').innerHTML = '<br/>Predicted Number: ' + index;
}
}
if (!isThereAnyPrediction) {
document.getElementById('rightside').innerHTML = '<br>Unable to Predict';
}
}
Let’s understand above code step by step.
- First, we are extracting the grayscale image from the canvas.
- Then converting that image to tensor(Array)
- We want 28*28 array(image) so we are resizing the array
- We want data to be in the float32 format so we are type casting data to the float32 format
- We need [1, 28, 28, 1] shape for Model because it expects (batch, height, width, channels)
- We need to normalize the data so we divided data with 255.
- Then trying to predict the number
You will find this code at my another GitHub repository.
You can see its live example here. It’s not perfect but performs decently.
Peace. Happy Coding.
See my original article here.
|
https://medium.com/coinmonks/handwritten-digit-prediction-using-convolutional-neural-networks-in-tensorflow-with-keras-and-live-5ebddf46dc8
|
CC-MAIN-2020-10
|
refinedweb
| 1,589
| 52.15
|
Learn all about the new Angular 2 router and how to set it up in your app.
TL;DR: The new component router in Angular 2 comes with a lot of features and a slightly different approach to setting up routing. In this article we take a look at the router's features by implementing them in a simple Github user explorer application. Follow along here or take a look at the repo to get started with the code.
If you'd like to see our other Angular 2 content, we've also covered pipes, dependency injection, HTTP, and authentication.
Angular 2 comes with a brand new component router that is packed with features. At the Beta 1 release, the documentation on Angular 2's router is in pretty good shape, and there is even an extensive guide on setting it up. There are, howevever, some features and use cases that have yet to be documented.
Those coming from Angular 1.x will likely be familiar with UI Router, a third party routing system contributed by the community. Some aspects of the new component router in Angular 2 will look familiar to those who have used UI Router, but there are definitely some new features and concepts that haven't been seen before. For example, child routes in Angular 2 are designed to work best by requiring separate routing and view components.
In this article we'll get a feel for the new router by implementing it in a simple Github user explorer application. In the app, we'll be able to search for Github accounts based on username, and we'll set up a way to explore further detail about the users. To do this, we'll set up child routes and work with route parameters.
Getting Started with the New Angular 2 Router
It's best to get started with a seed project. If you'd like to use Webpack, the Angular 2 Webpack Starter from AngularClass is an excellent option.
The router in Angular 2 provides both a
HashLocationStrategy and a
PathLocationStrategry, one of which is used when we bootstrap the app. As you might guess,
HashLocationStrategy uses hashes in the URL, which is what we're used to as the default from Angular 1.x. Many prefer not to use hashes, in which case
PathLocationStrategy can be applied.
HashLocationStrategy PathLocationStrategy
// main.ts ... import {LocationStrategy, PathLocationStrategry} from 'angular2/router'; ... bootstrap(App, [ ... provide(LocationStrategy, { useClass: PathLocationStrategy }) ])
Creating the Root Component
Our
app.ts file will serve as the root component for our app and will eventually have some routing configuration that points to other components. For now, let's just set it up so that we can query Github users and have them displayed in a list.
// src/app.ts import {Component} from 'angular2/core'; import {ROUTER_DIRECTIVES, RouteConfig, Router} from 'angular2/router'; import {FORM_PROVIDERS, FORM_DIRECTIVES, Control} from 'angular2/common'; import {Http} from 'angular2/http'; @Component({ selector: 'app', providers: [ FORM_PROVIDERS ], directives: [ ROUTER_DIRECTIVES, FORM_DIRECTIVES ], pipes: [], template: ` <div id="sidebar" class="col-sm-3"> <div class="search"> <input [ngFormControl]="searchTerm" class="form-control" placeholder='Seach for users' /> <button class="btn btn-primary" (click)="getUsers()">Get Users</button> </div> <div class="list-group"> <p class="no-users" *No users found</p> <a class="users list-group-item" * <img class="img-circle" src="{{user.avatar_url}}" /> <strong>{{user.login}}</strong> </a> </div> </div> <div id="main" class="col-sm-9"> <router-outlet></router-outlet> </div> `, styles: [` #main { margin: 10px 0 } #main button { margin-bottom: 5px } .search * { margin: 10px 0; } .no-users { color: red; } .container { width: 100% } img { max-width: 50px; } `] }) export class App { users: Array<Object> = []; searchTerm: Control = new Control(); constructor(public http: Http) {} getUsers() { this.http.get(`{this.searchTerm.value}`) .map(response => response.json()) .subscribe( data => this.users = data, error => console.log(error) ); } }
Now when we enter a search term and click "Get Users", we get a list of 30 users. We won't bother setting up any kind of ordering by relevence or pagination in this example because we want to keep the focus on routing. However, Github's API returns useful information such as a
score which indicates search relevence, so things like ordering can be done easily if you like.
Notice that towards the end of the template, we have a
router-outlet tag. This tag will be replaced by content from our other routes and is the spot where other content is "let out", hence
router-outlet. Let's give it a route to render.
Setting Up the Home Route
Let's start with a
Home route that will just have a simple welcome message. This will go in a file called
Home.ts.
// src/Home.ts import {Component} from 'angular2/core'; @Component({ template: `<h1>Search for a Github user and view their profile</h1>` }) export class Home {}
Now we need to set up our initial routing configuration. This is done with the
@RouteConfig decorator, which takes an array of objects called
RouteDefinitions that describe our app's various routing paths and their respective components. We'll use
@RouteConfig as a decorator on the
App class here to set up the base routing, but we'll also use it in our other components later on. We already imported
RouteConfig, so let's now set it up to just have the
App class definition.
// src/app.ts import {Home} from './Home'; ... @RouteConfig([ { path: '/home', component: Home, name: 'Home' }, { path: '/**', redirectTo: ['Home'] } ]) ...
So far we only have one real route set up, and that is the
/home route. We are also instructing the app to redirect any request to unrecognized routes to the
Home component. Each
RouteDefinition requires a
path, a
name, and either a
component,
loader, or
redirectTo. Here we see the
component and
redirectTo case, and later we'll see how
loader can be used to lazily load components.
Setting Up the User Detail Component and Route
The
router-outlet in the main
App component can only show the
Home route right now, but of course want to show others routes as well. We should put in some routing so that when we click the list item for a user in the returned results, we get a route like
/users/<username>. For that, let's create another component called
Users.
// src/Users.ts import {Component} from 'angular2/core'; import {Http} from 'angular2/http'; import {ROUTER_DIRECTIVES, RouteParams, RouteConfig} from 'angular2/router'; @Component({ template: ` <div class="panel panel-default"> <div class="panel-heading"> <h1></h1> </div> <div class="panel-body"> <router-outlet></router-outlet> <div> </div> `, directives: [ROUTER_DIRECTIVES] }) export class Users { userLogin: Object; constructor(params: RouteParams) { this.userLogin = params.get('userLogin'); } }
This is a simple component that so far just displays the user's login name. The
router-outlet in the template will be the place where the content from our child components will show up, which we'll cover next. You'll notice that we are retrieving the user's login name using
params.get which is a method given by
RouteParams, a class that gives us a map of parameters for the route. To pass this parameter on to the
Users component, we need to send it from the
App component. An easy way to do this is to add it in as an object when we attach a
routerLink to an element.
// src/app.js ... import {Home} from './Home'; import {Users} from './Users'; ... template: ` ... <a class="users list-group-item" * ... ` ... @RouteConfig([ { path: '/home', component: Home, name: 'Home', useAsDefault: true }, { path: '/users/:userLogin/', component: Users, name: 'Users' }, { path: '/**', redirectTo: ['Home'] } ]) ...
We've also set up an additional
RouteDefinition that points to our
Users component and has a path that contains the
userLogin parameter. This parameter is a variable one, indicated by the colon. When we click the list item for a returned user,
userLogin will be set to their login name, and will be displayed as a segment on the URL.
Moving to Child Components
Child routes in Angular 2 work somewhat differently than what we may have become accustomed to in UI Router. In fact, child routes have caused quite a bit of confusion and are considered to be flawed by some. The issue (which some argue is not an issue) seems to stem from how Angular 2's router handles terminal and non-terminal routes. A terminal route is basically one that has a defined end point, whereas a non-terminal route is one that can facilitate further routing. That sounds a bit confusing, so let's see how it looks in practice.
The first thing we need to do is tell the router that our
/users/:userLogin path should be able to handle children. We do that by appending ellipses to the end of the path.
// src/app.ts ... @RouteConfig([ { path: '/home', component: Home, name: 'Home', useAsDefault: true }, { path: '/users/:userLogin/...', component: Users, name: 'Users' }, { path: '/**', redirectTo: ['Home'] } ]) ...
Depending on how we want our app set up, we might like to have a
/detail path that indicates we're looking at a detailed profile area for the user. This can be a child of our
Users route. Let's set up a new component that will fetch and display the user's details. First, we need to set up another
@RouteConfig in
User.ts.
// src/User.ts ... @RouteConfig([ { path: '/detail', component: UserDetail, name: 'UserDetail' } ]) ...
User has now become a routing component instead of stictly a view component because it is facilitating further routing. In fact, this is by design in Angular 2's router, but can be undesirable because it causes the need for additional files. The router's design means that the ideal routing setup should look like this:
Let's now create the
UserDetail view component.
// src/UserDetail.ts import {Component, Injector} from 'angular2/core'; import {Http} from 'angular2/http'; import {ROUTER_DIRECTIVES, Router, RouteParams, RouteConfig} from 'angular2/router'; @Component({ directives: [ROUTER_DIRECTIVES], template: ` <div class="col-sm-3"> <img class="img-circle" src="" /> <p * <i class="glyphicon glyphicon-user"></i> </p> <p * <i class="glyphicon glyphicon-briefcase"></i> </p> <p * <i class="glyphicon glyphicon-globe"></i> </p> </div> <div class="col-sm-9"> </div> `, styles: [` img { width: 100px; margin-bottom: 10px; } `] }) export class UserDetail { params: RouteParams; userLogin: string; userData: Object = {}; constructor(public http: Http, params: RouteParams, injector: Injector, private _router: Router) { // We use injector to get a hold of the parent's params this.params = injector.parent.parent.get(RouteParams); this.userLogin = this.params.get('userLogin'); } ngOnInit() { this.http.get(`{this.userLogin}`) .map(response => response.json()) .subscribe( data => this.userData = data, err => console.log(err) ); } }
You'll notice that the way we're getting the
userLogin param is quite different in this case. We can't get at the params of the parent route by simply using
params.get like we previously did, and instead we need to use the
Injector to reference the
RouteParams of the parent. For nesting that doesn't go too deep this isn't a big deal, but as we'll see later, it can get cumbersome when we nest further. This method of getting the params from the parent is a bit of a workaround, and will hopefully be improved in later releases of the router.
There's a problem with the route configuration above, and we can take this opportunity to demonstrate the non-terminal route error. If we run it and try to select a user, we can see the error in the console.
The issue here is that an explicit instruction for which route should be the terminal one is required. We do this by setting
setAsDefault to
true on the
/details route.
// app/User.ts ... @RouteConfig([ { path: '/detail', component: UserDetail, name: 'UserDetail', useAsDefault: true } ]) ...
Now we can get the user detail.
Another Child Route and OnActivate
As was mentioned above, the new router is designed such that we should be creating distinct routing and view components, but this can get cumbersome for deep routing. We can provide a terminal route directly to a parent if we like. Let's see this by creating a component to list out a user's followers.
// src/UserFollowers.ts import {Component, Injector} from 'angular2/core'; import {Http} from 'angular2/http'; import {RouteParams, OnActivate, ComponentInstruction} from 'angular2/router'; @Component({ template: ` <ul class="list-group"> <h3>Followers</h3> <li class="list-group-item" *</li> </ul> ` }) export class UserFollowers implements OnActivate { userLogin: string; followers: Array<Object> = []; constructor(public http: Http, injector: Injector, params: RouteParams) { // This is one way to get params but is ugly // this.params = injector.parent.parent.parent.parent.get(RouteParams); this.userLogin = params.get('userLogin'); } routerOnActivate(to: ComponentInstruction, from: ComponentInstruction) { return new Promise((resolve) => { this.http.get(`{this.userLogin}/followers`) .map(response => response.json()) .subscribe( data => { this.followers = data; resolve(true); }, error => console.log(error) ); }); } }
This route also gives us the chance to introduce another class from the new router:
OnActivate. If we implement this class for our component, we're able to use the
routerOnActivate method which does two things for us.
- We're able to get information about the current and previous routes by use of their
ComponentInstructions
- We can wait until a promise resolves for the route to be navigated to
In the
UserFollowers component we are seeing how to hold off on completing navigation until we get a result back from the request to Github's API for the user's followers.
Getting the
userLogin from the params in this component can be done like we did last time, but now we're getting to a point where we need to keep calling
parent over and over. Obviously this isn't too scalable. Instead, we can pass the param down from the parent if we use
router.navigate to explicitly go to this route.
// src/User.ts ... template: ` ... <div class="col-sm-9"> <button class="btn btn-primary" (click)="getFollowers()">Load Followers</button> <router-outlet></router-outlet> </div> ... `, ... @RouteConfig([ { path: '/followers', component: UserFollowers, name: 'UserFollowers' } ] ... constructor(public http: Http, params: RouteParams, injector: Injector, private _router: Router) { this.params = injector.parent.parent.get(RouteParams); this.userLogin = this.params.get('userLogin'); } getFollowers() { this._router.navigate(['UserFollowers', { userLogin: this.userLogin }]); } ...
You'll notice that the
userLogin param shows up explicitly as the last segment and is separated from the rest with a semicolon. This is called matrix URI notation and is a bit different than what we're used to.
What Else Can the Router Do?
We've got some basic child routing set up, but there are some other features that we haven't explored yet.
Restricting Routes
The router provides a hook called
@CanActivate that allows us to restrict routes based on a condition. With it we get the same
ComponentInstructions that we saw earlier, which allow us to get information about the
to and
from routes. If the funtion in the hook resolves to false, the router won't allow navigation to that route.
We can apply the decorator directly in our components. A good example is using the
tokenNotExpired function from angular2-jwt to determine if the user is authenticated or not.
... @CanActivate(() => tokenNotExpired()) export class MyComponent { ... }
Passing Data in Routes
Much like UI Router, we can pass an arbitrary data object with routes if we like. This is done in the
@RouteConfig.
... @RouteConfig([ { path: '/myroute', component: MyComponent, name: 'MyRoute', data: { isAdmin: true } } ]) ...
We can then read this data with the
RouteData class in whichever component is being navigated to.
... import {RouteData} from 'angular2/router'; export class MyComponent { isAdmin: boolean; constructor(data: RouteData) { this.isAdmin = data.get('isAdmin'); } }
Lazy Component Loading
As our apps get larger, it might become desireable to hold off on loading components until they are needed. For this, we lazily load components by using an
AsyncRoute in the
@RouteConfig.
... import {RouteConfig, AsyncRoute} from 'angular2/router'; ... @RouteConfig([ new AsyncRoute({path: '/async', loader: () => System.import('app/Async').then(m => m.About), name: 'Async'}) ]) ...
This will now load the route's component only when it is needed, meaning the initial download of our app can be smaller.
Custom Router Outlet
We might like to define our own custom
router-outlet so that we can have better control over its behavior. For this, we can extend
RouterOutlet in our own directive.
import {Directive} from 'angular2/core'; import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router'; @Directive({ selector: 'router-outlet' }) export class MyOwnRouterOutlet extends RouterOutlet { ... activate() { console.log('Hello from the new router outlet!'); } }
For a full example of extending
RouterOutlet, see this repo.
Aside: Easy Authentication with Auth0
You can easily add authentication to your Angular 2 app with Auth0, and with it you can have features like social login, single sign-on and passwordless authentication at the flip of a switch.
Let's go through the simple steps of adding Auth0 to your app.
If you haven't already done so, sign up for your free Auth0 account.
Install angular2-jwt for Authenticated HTTP Requests
npm install angular2-jwt
Add the
Auth0Lock Script
<!-- Auth0 Lock script --> <script src=""></script> <!-- Setting the right viewport --> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
Instantiate Lock and Add Login/Logut Controls
// app.ts ... @Component({ selector: 'app', template: ` <h1>Welcome to Angular2 with Auth0</h1> <button *Login</button> <button *Logout</button> ` }) export class AuthApp { lock = new Auth0Lock('AUTH0_CLIENT_ID', 'AUTH0_DOMAIN'); constructor() { // Add callback for lock `authenticated` event var self = this; this.lock.on("authenticated", authResult => { self.lock.getProfile(authResult.idToken, (error, profile) => { if (error) { // handle error return; } localStorage.setItem('profile', JSON.stringify(profile)); localStorage.setItem('id_token', authResult.idToken); }); }); } login() { this.lock.show(); } logout() { localStorage.removeItem('profile'); localStorage.removeItem('id_token'); } }
Make Authenticated Requests
// app.ts import {AuthHttp} from 'angular2-jwt'; constructor(public authHttp: AuthHttp) {} getSecretThing() { this.authHttp.get('') .subscribe( data => console.log(data.json()), err => console.log(err), () => console.log('Complete') ); ); }
Protect Routes
If the user has an expired token, they shouldn't be allowed to navigate to a protected route. Use the
CanActivate hook for this.
import {tokenNotExpired} from 'angular2-jwt'; ... @CanActivate(() => tokenNotExpired()) export class MyComponent {}
Done!
For full details, including configuration, check out the Auth0 Angular 2 docs or download a seed project for Webpack and SystemJS.
Wrapping Up
The new router in Angular 2 has some powerful features and is, for the most part, fairly intuitive. The main point of confusion for developers right now is the distinction between terminal and non-terminal routes, and the need for separate routing and view components. If issues which point this out as a flaw like this one keep popping up, it's possible that we might see some changes to the router API in the future.
"The main point of confusion for developers right now is the distinction between terminal and non-terminal routes"
|
https://auth0.com/blog/amp/angular-2-series-part-4-component-router-in-depth/
|
CC-MAIN-2019-18
|
refinedweb
| 3,104
| 55.03
|
Setup of a Local Kubernetes and Istio Dev Environment
Setup of a Local Kubernetes and Istio Dev Environment
For developers who prefer to work locally, check out this tutorial on setting up Kubernetes and Istio on your machine.
Join the DZone community and get the full member experience.Join For Free
As a developer, I like to do as much development as possible locally, because it's generally easier and faster to develop and debug code. In order to build cloud-native applications and microservices, it's very convenient to have a local Kubernetes cluster and Istio running locally. This article describes how to install these components and some additional tools like Kiali.
Minikube
In order to run Kubernetes clusters locally, there are different alternatives. One is to use the Kubernetes functionality integrated in Docker Desktop. The alternative that I've chosen is Minikube, which runs a single-node Kubernetes cluster inside a VM on your development machine.
Follow the instructions to install kubectl and Minikube. For a hypervisor, I'm using VirtualBox, which is supported on Mac, Linux, and Windows.
When running Istio and your own applications, you need more memory and CPUs than you get by default. Here are my settings:
$ minikube config set cpus 4 $ minikube config set memory 8192 $ minikube config set disk-size 50g $ minikube addons enable ingress $ minikube start
minikube start can take several minutes when starting for the first time. Be patient.
Sometimes
minikube start doesn't work for me. In that case, I stop my VPN, invoke
minikube delete# , delete the
.minikube directory, restart my machine and start it again.
After this, you can get the Minikube IP address and open the Kubernetes dashboard via these commands:
$ minikube ip $ minikube dashboard
Minikube comes with it's own Docker daemon, so you don't have to use Docker Desktop. You only need the Docker CLI and to point it to Minikube:
$ eval $(minikube docker-env)
To stop the cluster run this command:
$ minikube stop
Istio
To download Istio, run this command:
$ curl -L | sh -
Follow the instructions in the terminal to set the path.
To install Istio, run these commands:
$ cd istio-1.0.6 $ kubectl apply -f install/kubernetes/helm/istio/templates/crds.yaml $ kubectl apply -f install/kubernetes/istio-demo.yaml
Make sure that all pods are running or completed before continuing. This can take several minutes when starting the pods for the first time. Be patient.
$ kubectl get pod -n istio-system
This screenshot shows all Istio pods running or completed (ignore the Kiali one for now).
In the last step, enable automatic sidecar injection:
$ kubectl label namespace default istio-injection=enabled
After the setup of Minikube and Istio you can use the following tools:
Kubernetes Dashboard
$ minikube dashboard
Jaeger Dashboard
$ kubectl port-forward -n istio-system $(kubectl get pod -n istio-system -l app=jaeger -o jsonpath='{.items[0].metadata.name}') 16686:16686
URL to Open Jaeger:
Grafana Dashboard
$ kubectl -n istio-system port-forward $(kubectl -n istio-system get pod -l app=grafana -o jsonpath='{.items[0].metadata.name}') 3000:3000 &
URL to open Grafana:
Prometheus Dashboard
$ kubectl -n istio-system port-forward $(kubectl -n istio-system get pod -l app=prometheus -o jsonpath='{.items[0].metadata.name}') 9090:9090 &
URL to open Prometheus:
Kiali
Run the following command to install Kiali:
$ bash <(curl -L)
Note: For some reason the script didn't work for me. I had to replace one line:
get_downloader github_api_url="" kiali_version_we_want="v0.15.0"
To launch Kiali you need the IP address and NodePort:
$ minikube ip $ kubectl get svc -n istio-system kiali --output 'jsonpath={.spec.ports[*].nodePort}'
URL to open Kiali: https://[minikube-ip]:[kiali-nodeport]/kiali
Sample Application
I'm working on a simple sample application that shows some of the Istio and MicroProfile functionality to build cloud-native applications. I'll blog more about this soon.
For now you can install two sample microservices from this project. Make sure Minikube runs and you have installed all the necessary prerequisites:
$ git clone $ scripts/check-prerequisites.sh $ scripts/deploy-articles-java-jee.sh $ scripts/deploy-web-api-java-jee.sh
The following screenshot shows a BFF (backend for frontend)
web-api microservice invoking another
articleswebservice:
Most of the information in this article I got from Harald Uebele. Thanks Harald. I just added some details that I had to do differently. }}
|
https://dzone.com/articles/setup-of-a-local-kubernetes-and-istio-dev-environm-1?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone
|
CC-MAIN-2019-18
|
refinedweb
| 727
| 52.9
|
Distributing your own plugin package¶
If you are looking to customize glue for your own use, you don’t necessarily
need to create a plugin package - instead you can just use a
config.py file
as described in Configuring Glue via a startup file. However, if you are interested in sharing
your customizations with others, then the best approach is to develop and
distribute a plugin package.
Plugin packages use the same mechanism of registering customizations described
in Customizing your Glue environment as you would if you were using a
config.py file -
the only real difference is the file structure you will need to use. To make
things easier, we provide a template plugin package at to show you how files should be
organized.
Required files¶
To start with, any Python code that is part of the plugin package should be
placed in a directory with the name of the module for the plugin. In our
template, this is the
myplugin directory - for some of the real plugins we
have developed in the past, this is for example
glue_medical or
glue_geospatial. This directory should contain at least one Python file
that contains the customizations that you would otherwise have put in your
config.py file. In the template example, this is the
data_viewer.py file
which contains a custom data viewer.
In addition to this file (or multiple files), you will need an
__init__.py
file, which should contain a
setup function. This function is used to
register any customizations with glue. In this function, you should import any
files containing customizations. If the customizations use a decorator to be
registered (e.g.
@data_factory or
@menubar_plugin), then you are all set.
Otherwise, for registering e.g. custom_viewers, the
setup function should
also do the registration - in the template, this looks like:
def setup(): from .data_viewer import MyViewer from glue.config import qt_client qt_client.add(MyViewer)
Finally, at the root of the package, you will need a
setup.py file similar
to the one in the template (you can copy it over and edit the relevant parts).
One of the important parts is the definition of
entry_points, which is the
part that tells glue that this package is a plugin:
entry_points = """ [glue.plugins] myplugin=myplugin:setup """
The entry in
[glue.plugins] has the form:
plugin_name=module_name:setup_function_name
In general, to avoid confusion, the
plugin_name and
module_name should
both be set to the name of the directory containing the code (
myplugin in
our case).
Once you have this in place, you should be able to install the plugin in ‘develop’ mode (meaning that you can then make changes and have them be updated in the installed version without having to re-install every time) with:
pip install -e .
You can then start up glue with:
glue -v
The startup log then contains information about whether plugins were successfully loaded. You should either see something like:
INFO:glue:Loading plugin myplugin succeeded
Or if you are unlucky:
INFO:glue:Loading plugin myplugin failed (Exception: No module named 'numpyy')
In the latter case, the exception should help you figure out what went wrong. For a more detailed error message, you can also just import your plugin package and run the setup function:
python -c 'from myplugin import setup; setup()'
Optional files¶
The only files that are really required are the directory with the source code
and the
setup.py file - however, you should make sure you also include an
open source license if you are planning to
distribute the package, as well as a README file that describes your package,
its requirements, and how to install and use it.
Consider also adding tests (using e.g. the pytest framework), as well as setting up continuous integration services such as Travis to run the tests any time a change is made. Describing how to do this is beyond the scope of this tutorial, but there are plenty of resources online to help you do this.
Distributing the package¶
Since your package follows the standard layout for packages, you can follow the Packaging Python Projects guide to release your package and upload it to PyPI. The usual release process for glue plugins is as follows:
Start off by editing the changelog (if present) and change the release date from
unreleasedto today’s date, in the
YYYY-MM-DDformat, for example:
0.2 (2019-02-04) ----------------
Edit the
version.pyfile in your package to not include the
.dev0suffix, e.g.:
version = '0.2'
Commit the changes, e.g.:
git add CHANGES.rst */version.py git commit -m "Preparing release v0.2"
Remove any uncommitted files/changes with:
git clean -fxd
Now create the release with:
python setup.py sdist
Provided you don’t have any C extensions in your package, you can also make a so-called ‘wheel’ release:
python setup.py bdist_wheel --universal
Go inside the
distdirectory and use the twine tool to upload the files to PyPI:
cd dist twine upload *.tar.gz *.whl
Optionally tag the release in git with:
git tag -m v0.2 v0.2
Add a new section in the changelog file for the next release:
0.3 (unreleased) ---------------- - No changes yet.
and update the
version.pyfile to point to the next version, with a
.dev0suffix:
version = '0.3.dev0'
Finally, commit the changes and push to GitHub:
git add CHANGES.rst */version.py git commit -m "Back to development: v0.3" git push --tags upstream master
If you are interested in including your package as a conda package in the
glueviz channel, please let us know by opening an issue at.
|
http://docs.glueviz.org/en/latest/customizing_guide/writing_plugin.html
|
CC-MAIN-2021-17
|
refinedweb
| 932
| 63.09
|
Run WSO2 API Manager in OpenShift
Run WSO2 API Manager in OpenShift
Learn how to deploy the WSO2 API manager in OpenShift.
Join the DZone community and get the full member experience.Join For Free
The purpose of this article is to show how easily the WSO2 API Manager can be deployed in OpenShift. For simplicity, I am going to explain the deployment process using Minishift.
The following softwares are expected to be present in your system for executing this example.
- Minishift (v1.3)
- Docker
- WSO2 API Manager (2.6.0) zip
- JDK 1.8 zip
Before we start, let's go through a mini introduction of Minishift and its installation. The installation process of Minishift is quite straightforward. Here is a link to the official documentation.
Installing Minishift
I am using Mac and here is the command for its installation:
$ brew cask install minishift
After that, you need to configure some virtualization environment. Please refer to this official document regarding this.
Once you are done with that, execute the following command to start the Minishift cluster:
$ minishift start
The following things will happen after successful execution of the command:
- The Minishift Virtual Machine (VM) will be created.
- A Docker daemon (engine) will be started inside the VM.
- OpenShift cluster will be running inside the Docker daemon.
Here is the architecture diagram of Minishift taken from the official documentation.
So, it means that you don't need a Docker daemon (Engine) running in your local machine to work with images. Docker client is just enough and we can point the Docker client to the Docker daemon (running in the VM) created by the Minishift.
To verify the Docker daemon (Engine) running in the Minishift VM, execute the following command:
$ minishift docker-env
Here is a sample output:
export DOCKER_TLS_VERIFY="1" export DOCKER_HOST="tcp://192.168.64.2:2376" export DOCKER_CERT_PATH="/Users/anupamgogoi/.minishift/certs" # Run this command to configure your shell: # eval $(minishift docker-env)
To point to the Docker daemon (Engine) running in the Minishift VM just execute the following command,
$ eval $(minishift docker-env)
That's it and you can check the containers, images etc that belong to that Docker daemon (Engine).
To check the Minishift GUI, just execute the following command:
$ minishift console
The default login and password are developer and developer.
Installing OC (OpenShift Client) CLI
It's not necessary to download the OC CLI separately. Once the Minishift VM is up and running, you can have the information of the OC CLI installed in your local machine.
Execute the following command to check the OC CLI:
$ minishift oc-env
Here is the sample output:
export PATH="/Users/anupamgogoi/.minishift/cache/oc/v3.11.0/darwin:$PATH" # Run this command to configure your shell: # eval $(minishift oc-env)
Execute the following command to put the OC CLI in PATH variable:
$ eval $(minishift oc-env)
Now, to verify the installation, run the command:
$ oc version
For more information, please go through the official documentation.
Create Docker Image
In this section, we are going to create a Docker image for WSO2 API Manager. The complete Dockerfile can be found on this GitHub URL. It's a very basic Dockerfile for the sake of simplicity. The focus of the article is not exploring Docker.
Here is a snapshot of the simple Dockerfile.
In the folder structure, under the product directory just copy and paste the JDK and WSO2 API Manager zip (tar) files and unzip them. After that, create the image. For example:
$ docker build -t wso2am-centos .
You can do a:
$ docker image ls
to check the image created. Note that these images are stored in the Docker daemon (Engine) running in the Minishift VM.
Create Project (Namespace) in Minishift
A project (namespace) can be created either by Web Console or OC. Here, I will demonstrate both ways.
By Console
It's quite simple to create a project via the console. To bring in the console, execute the following command.
$ minishift console
This will open the web console in the default browser. Click the button Create Project in the pop-up and that's it.
By OC
Execute the following command to create a project using OC CLI,
$ oc new-project wso2
Once a project is created, we need to deploy apps (Docker image, etc.) to the project. Here, the focus is deploying an app from a Docker image. For more information, please refer to this official document.
Deploy App (Docker Image)
The focus of this article is to deploy an image from Image Stream. An alternative to this is to pull an image from docker registry (Docker Hub, local, or private).
To know more about Image Stream, please read the official documentation.
Here is the complete process to push the docker image to the Minishift docker registry and create an image stream for it.
Create an Image Stream for the Project (Namespace) Created
$ oc create is wso2am -n wso2
Here, wso2am is the name of the image stream and wso2 is the project (namespace).
Tag the Docker Image
This is the expected format for tagging the Docker image.
<<DOCKER_REGISTRY>>/<<PROJECT_NAME>>/<<IMAGE_STREAM>>
To find out the Minishift Docker registry, execute the following command:
$ minishift openshift registry
Here is a sample output:
172.30.1.1:5000
This is the Minishift's internal docker registry host and port.
Now, let's tag our docker image:
$ docker tag wso2am-centos 172.30.1.1:5000/wso2/wso2am
Remember that wso2am-centos was the name of the docker image we generated.
After tagging the Docker image, log in to the Docker registry using the following command:
$ docker login -u developer -p $(oc whoami -t) $(minishift openshift registry)
After logging in successfully, push the image to the Docker daemon:
$ docker push 172.30.1.1:5000/wso2/wso2am
To check the Image Stream, execute the following command:
$ oc project wso2 # Select the project. $ oc get is # List the Image Streams created for the project.
You should see the following output:
NAME DOCKER REPO TAGS UPDATED wso2am 172.30.1.1:5000/wso2/wso2am latest 18 hours ago
At this point, we have done the following things:
- Created a project called wso2.
- Created an Image Stream named wso2am for the project wso2.
- Created a Docker image for WSO2 API Manager and tagged it as 172.30.1.1:5000/wso2/wso2am.
- Pushed the Docker image to the Docker registry.
Now, the next steps will be to pull the image from the Image Stream and create the pod. This is quite straightforward and I am going to use the web console for it. Alternatively, you can use the OC tools for it without any restriction.
Deploy WSO2 API Manager Image
Click the Overview menu of the project and you will be presented this GUI. Then, select the Deploy Image option.
Now, choose the image stream and then click deploy,
Once it's deployed, you can see the following page:
Click the service wso2am (marked in red) under the NETWORKING section and let's create a passthrough route.
After successfully created the Route, you can view it as shown below,
In my case, I will have the following URLs:
Publisher: Store: Admin: Carbon:
Conclusion
In this article, I have explained in a simple fashion how to deploy WSO2 API Manager in Openshift. In the next articles, I will try to add MySQL as a persistent store to the API Manager. Thanks for reading! }}
|
https://dzone.com/articles/run-wso2-api-manager-in-openshift
|
CC-MAIN-2019-13
|
refinedweb
| 1,238
| 63.8
|
This chapter introduces typedef format of C language. This is a simple topic. Type definition (typedef) is a keyword which helps in creating new name of data type. This usually adds to readability of program. We can have short declarations instead of complex jargons. Let us study in detail about typedef.
18.1 C Type definition (typedef)
typedef keyword is used in C programming language to create a different or new name/names for an already existing data type.
These new names are called user-defined data types. Format of typedef is as follows:
typedef datatype newname_1, newname_2;
Explanation: Here,
typedef is the keyword
datatype is an already existing data type
newname_1, newname_2 are the new names created for the existing data type datatype
Let us consider an example to make things crystal clear.
typedef float SALARY, IDENTITY;typedef float SALARY, IDENTITY;
Explanation: Here,
typedef is the keyword
float is one of the basic data types
SALARY, IDENTITY are the new names of data type provided to basic data type float. These are called user-defined data types.
As we are already aware of the fact that after defining, next step is to declare them so let us do it now.
Let us consider the above typedef and learn the usage of typedef. Consider the following declaration:
float basic, gross, monthly;
float employee_id, college_id,student_id;
By the usage of user-defined data types, above declaration can be modified as follows:
typedef float SALARY, IDENTITY;
SALARY basic, gross, monthly;
IDENTITY employee_id, student_id, college_id;
Let us consider sample program to explain things better:
/* Program to demonstrate typedef */
# include <stdio.h> # include <string.h> # include <stdlib.h> # include <conio.h> void main() { clrscr(); struct employee { char name [10]; int employee_id; char department[10]; float salary; }; typedef struct employee EMP; EMP e1, e2; strcpy(e1.name, "DEBASIF"); strcpy(e1.department, "MANAGEMENT"): e1.employee_id=546502; e1.salary=50000; printf("Name of employee is %s\n", e1.name); printf("Employee id is %d\n", e1.employee_id); printf("Employee salary is %d\n", e1.salary); prntf("Employee department is %s\n", e1.department); printf(“\n\n”); strcpy(e2.name, "ASMITA"); strcpy(e2.department, "ACCOUNTS"): e2.employee_id=546503; e2.salary=40000; printf("Name of employee is %s\n", e2.name); printf("Employee id is %d\n", e2.employee_id); printf("Employee salary is %d\n", e2.salary); prntf("Employee department is %s\n", e2.department); getch(); }
Program will looks similar in editor as in following snapshot:
Figure - Program to demonstrate typedef
After compiling program looks similar as in following snapshot:
Figure - Program to demonstrate typedef after compiling
Output of program will look similar as in following snapshot:
Figure - Output of program to demonstrate typedef
We conclude chapter with this and next chapter will introduce typecasting. Thank you.
|
http://www.wideskills.com/c-tutorial/c-typedef
|
CC-MAIN-2019-51
|
refinedweb
| 458
| 50.23
|
talking strip birthday card:
It's even possible to tune rumble strips on a road so that your car turns into a musical instrument as it drives over. Here is a musical road near MT Fuji, Japan:
another musical road - Lancaster, CA:
Enter the email associated with your account and we will send you your username and a temporary password.
Thanks for your great project
I try to play with it, but i got trouble with python like following:
File "sound.py", line 21, in <module>
frameOneChannel[i] = frameInt[4*i+1]*2**8+frameInt[4*i] #separate channels and store one channel in new list
IndexError: list index out of range
python ver 2.5.4
any one had this issue??
Thxxx
The sound-strip idea was used at least as far back as 1955 - I remember an advertising novelty from the Schwinn bicycle company. A ridged red plastic ribbon/strip about 1/8 inch wide was tied to the center of a bicycle-wheel shaped disc (as a resonator). Running your fingernail along the strip clearly played "I like Schwinn bikes." I wonder how this was made - it sure was not computers encoding the speech.
Hello.
Thank you for this instructables.
I am trying to print some words on different objects and find some applications for signaletic projects. So I want to get the wave of my sound, but without the thickness of the strip.
I have followed all your instructions and the .stl is a 15M file for just one word with 483324 triangles written. to big for my CPU.
Is there a way to just have the curve ?
I have tried to change the thickness and different parameters but I still have a big block with more 400.000 triangles, not just the desired curve.
all the best for your different beautifull project and thank you for your works.
M.
change this function:
void drawGrooves(float[] audioData){
int totalSampleNum = audioData.length -1;
float xPosition;
float zPosition;
//draw outer){
lastEdge.add(xPosition,sideWidth+bevel,-zPosition);
} else {
lastEdge.add(xPosition,sideWidth+bevel,zPosition);
}
}
}
int lastSampleIndex = 0;
float finalZPosition = 0;
//draw inner){
currentEdge.add(xPosition,sideWidth+bevel+grooveWidth,-zPosition);
finalZPosition = -zPosition;
} else {
currentEdge.add(xPosition,sideWidth+bevel+grooveWidth,zPosition);
finalZPosition = zPosition;
}
lastSampleIndex = sampleNum;
}
}
connectVertices();
print("total length: ");
print(speed/samplingRate*totalSampleNum);
println(" inches");
}
If you still didn't found way to get the audiosample value with Processing without the help of the Python script it is very fast easy with the Minim library (already there with the IDE) :
import ddf.minim.*;
Minim minim;
AudioSample sample;
float[] audioDataLeft;
float[] audioDataRight;
void setup() {
minim = new Minim(this);
sample = minim.loadSample("yourFilePathHere");
audioDataLeft = sample.getChannel(BufferedAudio.LEFT);
audioDataRight = sample.getChannel(BufferedAudio.RIGHT);
//etc ... etc ...
}
etc ...
You'll get the audio data as array of float value between -1 and 1, if I remember well.
In fact, if you assume a "read" speed of 26 inch/s and a resolution of 300dpi, that translates to 7800 dots/s, or 3900 grooves/s=3.9kHz. I.e. any frequency higher than 3.9kHz would be impossible to print with just 300dpi. (All that is assuming I remember some fragment of my signal processing course and that I managed to not screw up my numbers anywhere. A tall order, I know...)
Actually, if I were to venture a guess I would think that filtering it down further to just a few distinct frequences using a comb filter may yield even better results.
My idea of using a comb filter may or may not be usable, but here's my thought process behind suggesting it anyway.
Since I wouldn't expect the size of the bumps of the printed strip to actually produce much difference in sound amplitude when dragging an edge over it (I would actually expect having sporadic larger bump would cause the edge to jump and skip over grooves, degrading the sound quality), the geometry would probably work better if it was more like how the musical roads works. That is, a waveform that is essentially digital (low or high) and the sound is produced by the distance between the grooves rather than the varying amplitude of a proper waveform.
My thinking was that by trimming it down to fewer frequencies, it would be result in a waveform with fewer "overlapping" grooves, leading to a cleaner separation between the grooves. But as I said, it was mostly a guess which may be way off. It might be enough to just remove all frequencies below some limit that is way lower than the theoretical maximum above.
I think the biggest issue is that I didn't print at 600dpi, I only printed at 300. The difference between 300 and 600 with the 3d printed records was huge
I think your test is good, but if you use a higher pitch the result would be better. Maybe the amplitude of the waves is too large, try to reduce it too.
|
http://www.instructables.com/id/3D-Printed-Sound-Bites/
|
CC-MAIN-2014-42
|
refinedweb
| 825
| 62.48
|
only error i get is when i use set saying it is no a compatible type
only error i get is when i use set saying it is no a compatible type
the output for this gives sherlock 10 null
if i change getPerson() to setPerson() i get an error.
public class Test
{
public static void main(String[] args)
{
Dog dog[]...
Sorry want to create a new person and 2 dogs set that person to be the dogs owner
--- Update ---
i want to test that george owns the dogs
public class Test
{
We have two classes person and dog person object acts as an owner for dog and dog acts as pet for the person i.e a bidierctional association i have done this (see code) i modify the person class so...
thanks will do
never done that im afraid
oh get you now yes every bit of info goes to an array /list i have tried to do that but just wont work i know how to append the file but not a certain part of the file
to be honest youve lost me do u mean like the readfile method
in modules.txt the number registered will have to change and the user.txt file will have to change as well
currently writing a prog to carry out various operations as part of a module registration application. All info is taken from files,one option is to allow a student to deregister from a module do i...
@norm yeah will tidy it up now
@jps thanks very much noted for next time
norm your a legend my friend have got it now
this is new output
Enter the name of the test fileTwoTimesTables.txt
2*1=0?
false
2*2=4?
true
2*3=8?
false
2*5=10?
am i passing the file?
The value should be the number of questions that have been asked/contained in the file but how do i pass that
no because the number of questions in the file is 11 so 6 should give a grade of c i think
scorei is holding the same value as max ie both are taking say 6 if the person get 6 right
max is printing whatever the bestscore is
i am passing the bestscore ie say 8 to calgrades() and it is i think using this to work out the grades
ok have this program that reads in questions and answers from a txt file . then it reads the stusents answers and other info from a txt file and calculates their score. the problem i have is that...
the modules are stored in
String[] moduleName = {"PSP1", "PSP2", "Computer Architecture","Computer Hardware"};
for jack black if he selects list my modules all i want display is PSP1
so i use the find() method agin but just amend it to suit
i want to return the vale in one array depending on user ie
if the user is jack black i want to list his modules through the menu
NORM you are a genius have it fixed i basically over complicated the whole thing select was storing the value i entered but because i had added selects it needed the value again to carry out the...
back again i happy with prog now except for one thing below is the code for one of the menus that is displayed
public static void menuAdmin(String[] moduleName)
{
int selects;
int...
will do but must hit the hay its 1.15am here , i have figured out how to get array contents to display through menu.
thank you for your help ill be at it again tomorrow (wreck ur head again)lol
i tried this
if(userType=1)
but no good
|
http://www.javaprogrammingforums.com/search.php?s=3bd1edb0d414090e652349c57c31db0f&searchid=203313
|
CC-MAIN-2016-30
|
refinedweb
| 622
| 62.95
|
Solution for
Programming Exercise 6.8
THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to the following exercise from this on-line Java textbook.:
Discussion
The main applet class for this exercise is identical to the applet class for the HighLowGUI game, except that it uses a BlackjackCavas instead of a HighLowCanvas. So, the real work of this program is writing the BlackjackCanvasBlack() method checks the state when it draws the applet. If the game is over, the card is face up. This is nice example of state-machine thinking.
Note that writing the paint() method required some calculation. The cards are 80 pixels wide and 100 pixels tall. Horizontally, there is a gap of 10 pixels between cards, and there are gaps of 10 pixels between the cards and the left and right edges. (The total width needed for the applet, 466, allows for five 80-pixel cards, six 10-pixel gaps, and two 3-pixel borders along the edges: 5*80 + 6*10 + 2*3 = 466.)() method. Allowing 100 pixels for the second row of cards and 30 pixels for the message at the bottom of the board, we need a height of 290 pixels for the canvas. I set the overall height of the applet to 346 to allow 6 pixels for a border and 50 pixels for the panel that contains the buttons. (This might be too much, but the sizes of buttons can vary from one platform to another, and I want to be safe.)
In this GUI version of Blackjack, things happen when the user clicks the "Hit", "Stand", and "New Game" buttons. The applet, so gameIsProgress has to be false, and the only action that the user can take at that point is to click the "New Game" button again. (Note that the doNewGame() routine is also called by the constructor of the BlackjackCanvas class. This sets up the first game, when the applet has.
The Solution
/*.*; public class BlackjackGUI extends Applet { hit = new Button( "Hit!" ); hit.addActionListener(board); hit.setBackground(Color.lightGray); buttonPanel.add(hit); Button stand = new Button( "Stand!" ); stand.addActionListener(board); stand.setBackground(Color.lightGray); buttonPanel.add(lower); Button newGame = new Button( "New Game" ); newGame.addActionListener(board); newGame.setBackground(Color.lightGray); buttonPanel.add(newGame); } // end init() public Insets getInsets() { // Specify how much space to leave between the edges of // the applet and the components it contains. The background // color shows through in this border. return new Insets(3,3,3,3); } } // end class HighLowGUI class BlackjackCanvas extends Canvas implements ActionListener { // A class that displays the card game and does all the work // of keeping track of the state and responding to user events.. BlackjackCanvas() { // Constructor. Creates fonts and starts the first game. setBackground( new Color(0,120,0) ); smallFont = new Font("SansSerif", Font.PLAIN, 12); bigFont = new Font("Serif", Font.BOLD, 14); doNewGame(); } public void actionPerformed(ActionEvent evt) { // Respond when the user clicks on a button by calling // the appropriate procedure. Note that the canvas is // registered as a listener in the BlackjackGUI class. String command = evt.getActionCommand(); if (command.equals("Hit!")) doHit(); else if (command.equals("Stand!")) doStand(); else if (command.equals("New Game")) doNewGame(); } void doHit() { //(); } void doStand() { // This method is called when the user clicks the "Stand!" button. // Check whether a game is actually in progress. If it is, // the game ends. The dealer takes cards until either the // dealer has 5 cards or more than 16 points. Then the // winner of the game is determined.(); } void doNewGame() { // Called by the constructor, and called by actionPerformed() if // the use clicks the "New Game" button. Start a new game. // Deal two cards to each player. The game might end right then // if one of the players had blackjack. Otherwise, gameInProgress // is set to true and the game(); public void paint(Graphics g) { // The paint method shows the message at the bottom of the // canvas, and it draws all of the dealt cards spread out // across the canvas. g.setFont(bigFont); g.setColor(Color.green); g.drawString(message, 10, getSize().height -(); void drawCard(Graphics g, Card card, int x, int y) { // Draws a card as a 80 by 100 rectangle with // upper left corner at (x,y). The card is drawn // in the graphics context g. If card is null, then // a face-down card is drawn. (The cards are // rather primitive.) class BlackjackCanvas
[ Exercises | Chapter Index | Main Index ]
|
http://math.hws.edu/eck/cs124/javanotes3/c6/ex-6-8-answer.html
|
crawl-002
|
refinedweb
| 728
| 65.83
|
Fix tested and works! Comment from PR duplicated here.
I tested this fix by editing the 3.7.3 IDLE code by hand, and editing this test program as code.py on a CIRCUITPY drive on Windows 10:
import time
i = 0
while True:
print(i)
i += 1
print("""\
12367890
""")
time.sleep(1)
I typically test write flushing by editing a short program like this, and duplicating the print lines so that the size of the program grows by >512 bytes. This forces a rewrite of the FAT12 information because the program has increased in size by one or more filesystem blocks. Then I shrink it back down again. If file flushing doesn't happen immediately, the program will often throw a syntax error (because it's missing some blocks), or CircuitPython will get an I/O error, which is what happened before I patched IDLE.
So this looks good!
|
https://bugs.python.org/msg342274
|
CC-MAIN-2020-50
|
refinedweb
| 150
| 74.08
|
[
]
Bogdan Drozdowski commented on NET-333:
---------------------------------------
Why not an enum? The reason I had was simple: although enums provide type safety (which is
very good), I believe enums can't be subclassed nor they can derive from other classes, so
if we have "enum IMAPCommand", we can't have a class, say "public class IMAPSCommand extends
IMAPCommand" or "public enum IMAPSCommand extends IMAPCommand". This means that additional
commands must either be inserted into the base class, say IMAPCommand (now what if you're
using just the binary release?), or inserted into the class that uses them (like I did in
the AuthenticatingSMTPClient or ExtendedPOP3Client), or have their own class, completely unrelated
to the base class. The first is possible only if you have the source and either build it yourself
or wait for your patch to be applied, because it's impossible to subclass the base class currently.
The second and third solutions, on the other hand, spread the set of commands among many classes.
That's why I did it this way. With this in mind, the "final" keyword on the IMAPReply class
declaration is an error, I copied too much from other classes. If these classes aren't made
enum/final, users can subclass them without the source code and inherit all the commands/replies
automatically, so they can, for example, subclass *Client classes and have them use or produce
their own subclasses of *Command and *Reply.
I'm not currently subscribed to the mailing list, I'll browse the archives to check the volume
and perhaps I'll join you. Yes, some code is plainly copied between the classes, but the details
vary. Every clas has a __getReply() but, for example, the line continuation algorithm varies.
This could be made abstract, but what if we want just a SocketClient? We couldn't instantiate
it now. Currently (in the classes I'm interested in: IMAP, POP3, SMTP, FTP) I can see that
add/removeProtocolCommandListener could be immediately pushed up either to SocketClient or
to something new between the SocketClient class and the protocol classes (not the *Client
classes).
Did you verify that POP3SClient and SMTPSClient work for you? I used them and they worked
fine for me, but the IMAPSClient shows that they shouldn't (because they don't replace _reader
and _writer from the SSLSocket) and I'm puzzled.
> would you provide a class used for imap protocol?
> -------------------------------------------------
>
> Key: NET-333
> URL:
> Project: Commons Net
> Issue Type: Improvement
> Reporter: iceviewer
> Attachments: IMAP.zip
>
>
> would you provide a class used for imap protocol?
--
This message is automatically generated by JIRA.
For more information on JIRA, see:
|
http://mail-archives.apache.org/mod_mbox/commons-issues/201103.mbox/%3C1510896918.3683.1300799945797.JavaMail.tomcat@hel.zones.apache.org%3E
|
CC-MAIN-2016-07
|
refinedweb
| 438
| 60.65
|
Java supports variables of three different lifetimes:
A member variable of a class is created when an instance is created, and it is destroyed when the object is destroyed. All member variables that are not explicitly assigned a value during declaration are automatically assigned an initial value. The initialization value for member variables depends on the member variable's type.
The following table lists the initialization values for member variables:
In the following example, the variable x is set to 20 when the variable is declared.
public class Main{ int x = 20; }
The following example shows the default value if you don't set them.
class MyClass {// w w w . ja v a2s. co m int i; boolean b; float f; double d; String s; public MyClass() { System.out.println("i=" + i); System.out.println("b=" + b); System.out.println("f=" + f); System.out.println("d=" + d); System.out.println("s=" + s); } } public class Main { public static void main(String[] argv) { new MyClass(); } }
The output:
An automatic variable of a method is created on entry to the method and exists only during execution of the method. Automatic variable is accessible only during the execution of that method. (An exception to this rule is inner classes).
Automatic variable(method local variables) are not initialized by the system. Automatic variable must be explicitly initialized before being used. For example, this method will not compile:
public class Main{ public int wrong() { int i; return i+5; } }
The output when compiling the code above:
There is only one copy of a class variable,
and it exists regardless of the number of instances of the class.
Static variables are initialized at class load time;
here
y would be set to 30 when the
Main class is loaded.
public class Main{ static int y = 30; }
this refers to the current object.
this can be used inside any method to refer to the current object.
The following code shows how to use
this keyword.
// A use of this. Rectangle(double w, double h) { this.width = w; // this is used here this.height = h; }
Use
this to reference the hidden instance variables.
Member variables and method parameters may have the same name. Under this situation we can use this to reference the member variables.
Rectangle(double width, double height) { this.width = width; this.height = height; }
The following example shows how to use this to reference instance variable.
class Person{// w ww. java 2 s . c o m private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Main{ public static void main(String[] args) { Person person = new Person("Java"); System.out.println(person.getName()); person.setName("new name"); System.out.println(person.getName()); } }
The code above generates the following result.
|
http://www.java2s.com/Tutorials/Java/Java_Language/5050__Java_class_variable.htm
|
CC-MAIN-2017-43
|
refinedweb
| 467
| 60.11
|
In this post, we will see Java interview questions for 5 to 6 years experience.
When you have 5 years of experience as java developer, you need to have good understanding of collections, multithreading concepts.
If you are looking for below queries then this post will help you as well.
- Java interview questions for 4 years experience
- Java interview questions for 6 years experience
- Java interview questions for 7 years experience
Here are some questions which are most asked for 5 years experience java programmers. You might find some of the questions very easy but believe me most developers failed to answer these questions.
1. Guess the output of below program.
package org.arpit.java2blog; class A { void m1() { System.out.println("In m1 A"); } } class B extends A { void m1() { System.out.println("In m1 B"); } void m2() { System.out.println("In m2 B"); } } public class Test { public static void main(String[] args) { A a=new B(); a.m2(); } }
What will be the output?
A. In m2 B
B. Compile time error
C. Runtime error
B. Compile time error
There will be compile time error.Even though we are assigning B's object to A's reference we can call only methods which are in A from A's reference.
2. Guess the output of below program.
package org.arpit.java2blog; class A { void m1() throws ArrayIndexOutOfBoundsException { System.out.println("In m1 A"); } } class B extends A { void m1() throws IndexOutOfBoundsException { System.out.println("In m1 B"); } } public class Test { public static void main(String[] args) { A a=new B(); a.m1(); } }
What will be the output?
A. In m1 B
B. Compile time error
C. Runtime error
A. In m1 B
This will work fine as ArrayIndexOutOfBoundsException and IndexOutOfBoundsException are Runtime exceptions and there is no rule for runtime exceptions while method overriding.
3. Guess the output of below program.
package org.arpit.java2blog; import java.io.IOException; class A { void m1() throws IOException { System.out.println("In m1 A"); } } class B extends A { void m1() throws Exception { System.out.println("In m1 B"); } } public class Test { public static void main(String[] args) { A a=new B(); try { a.m1(); } catch (IOException e) { e.printStackTrace(); } } }
What will be the output?
A. In m1 B
B. Compile time error
C. Runtime error
B. Compile time error
As IOException and Exception are checked exception, so you can not broaden the scope of Exception while method overriding.
4. What will happen in case of below program?
class A { synchronized void m1() { System.out.println("In m1 A"); } does not require lock to access m2 method./div>
5. What will happen in case of below program?
class A { synchronized?
No, T2 will not be able to access m2 as it requires lock to access m2 method which is already taken by T1 thread.
6. What will happen in case of below program?
class A { synchronized static requires object level lock to access m2 method and T1 thread has taken class level lock.You can read more about Object level lock vs Class level lock.
7. Guess the output of below program.
package org.arpit.java2blog; import java.util.HashSet; public class Customer { String name; int age; Customer(String name,int age) { this.name=name; this.age=age; } public static void main(String[] args) { Customer c1= new Customer("John",20); Customer c2= new Customer("John",20); HashSet<Customer> customerSet=new HashSet<>(); customerSet.add(c1); customerSet.add(c2); System.out.println(customerSet.size()); } // getters and setters }
Output will be 2 as we did not implement hashcode and equals method in Customer class.
8. Guess the output of below program.
package org.arpit.java2blog; public class Employee { String name; int age; public Employee(String name,int age) { this.name=name; this.age=age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Main class
package org.arpit.java2blog; import java.util.HashMap; import java.util.Map; public class HashMapMain { public static void main(String[] args) { Employee emp1=new Employee("Martin",27); Map<Employee,String> hm=new HashMap<Employee,String>(); hm.put(emp1, "Verified"); emp1.setName("John"); System.out.println(hm.get(emp1)); } }
[showhide type="question8" more_text="Show Answer" less_text="Hide Answers"]
Output will be null.
We have implemented Employee's hashcode and equals method using name and age attributes, so when you put emp1 as key in hashmap, it will use hashcode and equals method and will be put in HashMap.
After putting emp1 in HashMop, we have changed name of the employee, so when you will try to retrieve element from HashMap using hm.get(emp1), you won't be able to get object which we have put earlier and it will return null.
[/showhide]
9. How to decide young generation and old generation size for your application?
It depends on nature of application.
If you have lots of temporary objects then there will be lot of minor gc. You can provide arguments XX:NewRatio=1 to distribute 50% to young generation and 50% to old.
By default, NewRatio=2 hence young Generation is 1/3 of total heap.
Similarly, If you have too many long-lived objects, then you might need to increase size of tenure space by putting high value of NewRatio.
10. What is garbage collection in java?
Garbage collection is the process of identifying used and unused objects on java heap and removing unused object from the heap.
A live object means object is still being referred to some part of program. Unused object means object is not being referred by any part of program and is eligible for garbage collection.
Programmer does not have to do manual garbage collection like C or C++. Java takes care of
11. What are types of garbage collectors in java?
You can see detailed answer over here.
12. What is difference between Collection.synchronizedMap(map) and ConcurrentHashMap?
When you make map thread safe by using Collection.synchronizedMap(map), it locks whole map object, but ConcurrentHashMap does not lock the whole map, it just locks part of it(Segment).
You can read more about ConcurrentHashMap over here.
13. What will happen when you run below code
package org.arpit.java2blog; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; public class IterateMapMain { public static void main(String args[]) { // HashMap with Country as key and capital as value HashMap<String,String> map=new HashMap<String,String>(); map.put("India","Delhi"); map.put("Japan","Tokyo"); map.put("France","Paris"); map.put("Russia","Moscow"); // Iterating java iterator System.out.println("Iterating java Iterator"); Iterator<String> countryKeySetIterator=map.keySet().iterator(); while(countryKeySetIterator.hasNext()){ String countryKey=countryKeySetIterator.next(); map.put("Nepal", "KathMandu"); System.out.println(countryKey); } System.out.println("-----------------------------"); } }
You will get below output
Iterating java IteratorException in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1489)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1512)
at org.arpit.java2blog.IterateMapMain.main(IterateMapMain.java:24)
Japan
Whenever you try to change count of hashmap while iterating, it will throw java.util.ConcurrentModificationException because we call iterator.next,it checks for modCount and initial count, if it does not match it will throw ConcurrentModificationException.
14. Write a program to print odd even numbers using threads in sequence?
Here is the program to print odd and even numbers using threads in sequence.
15. Which design pattern you have used in your project?
You can name few design patterns such as Singleton, Observer etc. which you might have used in your project.
16. What is double level locking in singleton design pattern?
Double level locking in single design pattern is used to make it thread-safe.
public static Singleton getInstance() { if (_instance == null) { // Single Checked synchronized (Singleton.class) { if (_instance == null)// Double checked { _instance = new Singleton(); } } } return _instance; }
Let's say two threads(T1 and T2) checked for null and both reached at synchronized (Singleton.class) . T1 gets the lock and create instance of Singleton and return.Now T2 enters in synchronized block, as we have checked for null again,it will not create object again.
17. Write a program to implement producer-consumer problem using BlockingQueue?
You can find detailed answer over here
18. Have you worked on Java 8? Can you share major changes in Java 8?
If you have worked on Java 8, you can share major changes such Stream, lambada expression, defaults method in interface etc.
19. Have you worked on Serialization? Can you tell difference between Serializable and Externalizable?
You can find detailed answer over here
20. How will you detect memory leak in your application?
There is no simple answer to this question. You can take thread dump via JVisualVM and do the analysis in eclipse memory analyzer tool.
That's all about Java interview questions for 5 to 6 years experience.
- Spring interview questions
- Spring boot interview questions
- Hibernate interview questions
- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
- Could not reserve enough space for object heap in java
Discussion
Thank you for this wonderful compilation. I'm enjoying reading which I know and working out which I'm not familiar. In that series, No 9, I'm struggling to understand what the question itself.. Can you add few more Laymen term to understand that question in better way please? Is it about ageing of the application ? What concept do I need to learn to understand ? Thanks for sharing your valuable time.
Thank you for the kind words :)
To understand question 9, you must go through this link
java2blog.com/garbage-collection-j....
Sure, thanks
I managed to answer 17 out of 20, and I haven't even started working yet. Should I skip the junior dev role ? xD
That's awesome :)
Indeed, you should xD
Good explanation!!!....Can you post more interview questions and program as well
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/arpitmandliya/java-interview-questions-for-4-to-7-years-experience-17k9
|
CC-MAIN-2020-45
|
refinedweb
| 1,739
| 60.51
|
The best way to give an insight into something new is by answering some obvious questions and we are going to do the same. So, let's get into this and know what really an algorithm is?
What is an algorithm?
An algorithm is a technique to solve a well-defined problem. It can also be defined as a set of precise steps to solve a problem.
Suppose, we have to make an analysis of the stock market and we have data for one month. Our analysis needs us to find the day on which a maximum profit could be made. Let's assume that the investment will be done at the start of the day and it will be sold at the end. Of course, this isn't entirely a practical problem, at least with the assumptions we have made but it will make you understand what basically an algorithm is.
So, we have a problem with the data for one month and this is the input to our problem. Our problem also has some constraints about when a stock can be purchased and when it will be sold. And the expected output is the maximum profit.
To solve this problem, we would first calculate the difference between the prices of the stocks at the end of the day and at the start of the day. Then we will calculate the maximum among these differences and that would be our output.
So, we have basically developed a method to solve a specific problem and our method takes an input (data of one month) and gives us an output (the day of maximum profit) and this is an algorithm.
So, you are now clear with the idea of what is an algorithm. So, let's answer one more question.
Is algorithm related only to the Computer Science and do I really need to know how to code to learn it?
No, algorithms are not only related to Computer Science but in our world, it is the computer which handles and processes a very large amount of data. Even talking for non-Computer Science domains, algorithms are just well-defined steps to solve a problem and developing an algorithm is the work of a brain, so no coding is required here. We develop algorithms to calculate the position of a robotic arm or to calculate the trajectory of fluid and these are not purely Computer Science domains. And these algorithms are pretty much successful in getting the result if the size of the problem is small.
So, why algorithms are studied as a part of Computer Science?
Most of our real-world problem doesn't operate on tens or hundreds of data but on a much larger number like thousands and millions. So, implementing those steps on a dataset which is much larger is not a task of any human and we need to develop code to implement those steps in a computer. Even a computer is going to take a significant amount of time (like days, weeks or even more) if the algorithm we have developed is not good and then we need to optimize our algorithm. So, designing an efficient algorithm is very important for many practical problems.
Do I really need to take a course on algorithm?
Suppose, you are having lunch at your favorite restaurant and you liked the food very much and you want to cook it yourself but you have never cooked anything before. Even though you have never cooked anything but still you know how food is cooked, but is this knowledge is enough to cook the food you ate at the restaurant? Possibly, no. But what if you have a strong piece of knowledge in cooking and know how to make a food with a specific taste, texture, etc., can you create the recipe that matches to the food you had tasted? Probably, yes.
The point is if you have a prior knowledge of solving problems (cooking food in this example), then you can tackle a more difficult problem on your own (in this case, cooking the food served at the restaurant). And any course on Algorithms makes you face some problems first so that you are ready to solve further much more difficult problem on your own or to make an algorithm to solve a problem which is entirely new.
We can develop algorithms but is it necessary to optimize it with today's computer speed?
Now, this is a real question, at least if you are a beginner, you think it is. Also, time is not the only thing we are concerned about, we also optimize our algorithm to take less space (memory), programmer's effort, etc. in many cases. The one line answer for these questions would be - we are not provided with a computer with unlimited speed and space, therefore, we need to optimize our approach to solve a problem using a computer.
Even with the high-end computers available in the market, a badly written algorithm can take a significant amount of time like days or weeks or even more. However, an optimized algorithm can finish the same job in minutes or seconds with a much slower computer.
I don't believe you, can you give me an example?
Just try running this code to print the first 10,000 prime numbers.
- C
- Python
- Java
#include <stdio.h> int is_prime(int x) { int i; int prime = 1; for(i=2; i<x; i++) { if ((x%i) == 0) prime = 0; } return prime; } int main() { int count = 0; int number = 2; while (count<10000) { if (is_prime(number)) { printf("%d\n",number); count++; } number++; } return 0; }
So, this course only teaches me some algorithms and expects me to memorize them?
Of course, this course has many examples to explain the concepts behind the different algorithms but this doesn't only end there. Through the entire course, we have focused on the concepts, how a particular algorithm works, and the thought process of coming with the algorithm. At the end of this course, you would have enough understanding so that you will be able to come up with a new method to solve a new problem.
Now, you know about the algorithms and are ready to learn how to know which algorithm is good or how to measure optimization of an algorithm. So, let's move to the next chapter.
|
https://www.codesdope.com/course/algorithms-introduction/
|
CC-MAIN-2021-25
|
refinedweb
| 1,068
| 67.28
|
Advanced VR Interactions in Unity Tutorial
Create advanced interactions and mechanics in your Unity VR app, including working with tooltips, joints, snapping and haptic feedback!
Version
- C# 7.2, Unity 2018.2
This is an abridged version of a chapter from our new book: Unity AR & VR by Tutorials. Enjoy!
If you’ve already worked with VRTK a bit, and you feel that you’ve mastered the basics of implementing gameplay in virtual reality using VRTK, you’re ready to dive into some more exciting ways to interact with your virtual worlds.
In this tutorial, you’ll learn how to:
- Create tooltips for objects and controllers.
- Fix objects to your controllers.
- Use joints to accurately pick up objects.
- Snap objects into place.
- Use haptic feedback.
It’s time for some VR action!
Getting Started
First, download the materials for this chapter using the Download Materials button at the top or bottom of this page.
Before diving straight into the deep end, take a moment to get familiar with the project.
Project Overview
In Unity, open the starter project for this tutorial and look at the Project window. As you can see, this project comes pre-loaded with many assets:
Here’s an overview of what’s inside:
- OculusPlatform, OVR & OvrAvatar: The APIs for the Oculus Rift.
- Plugins: Code libraries for the Oculus Rift.
- Resources: Contains the settings file for Oculus Avatar.
- Standard Assets: Unity’s standard character controllers and physics materials.
- SteamVR: The SteamVR plugin, along with its scripts and prefabs.
- VRTK: The Virtual Reality Toolkit plugin.
To get things started, open the Chapter 8 – Advanced Interactions scene from the Razeware\Scenes folder, and review the scene in the editor.
The scene comes with a few things already set up:
Here’s the breakdown:
- AdvancedFullChapter8: Contains all of the basic static meshes for the scene.
- BasicLight & ExtraLights: Various lights for the scene. ExtraLights is disabled by default.
- RW Props: Contains the statues in the scene and is the parent GameObject for the interactables.
- Chapter8 BGM: A simple GameObject with an Audio Source attached that plays classical music in the background. If that’s not your style, feel free to replace the music with some funky beats!
Now that you know this project inside and out, it’s time to get cracking.
Creating the VRTK Setup
By now, you may know how to prepare everything for VRTK, but to make it easier on yourself, you’re going to create a template setup which you can reuse.
SDK Manager
Create a new GameObject, name it [VRTK_SDK_MANAGER], and reset its Transform component. This will serve as the parent for the different SDK setups.
Add a VRTK_SDK Manager component to the newly created GameObject, and check any of the SDK_OCULUS_AVATAR checkboxes; the other one will get checked automatically.
Add another empty GameObject as a child of [VRTK_SDK_MANAGER], name it [VRTK_SDK_SETUPS], and reset its Transform.
Now create the following GameObjects, reset their Transform, and parent them to [VRTK_SDK_SETUPS]:
- SteamVR
- Oculus
- Simulator
When you’re done, the hierarchy in the SDK Manager will look like this:
To create parented instances, drag the [CameraRig] and [SteamVR] prefabs from the SteamVR\Prefabs folder onto the SteamVR GameObject.
Drag the OVRCameraRig prefab from the OVR\Prefabs folder onto Oculus to parent the prefab. Do the same for the LocalAvatar prefab from the OvrAvatar\Content\Prefabs folder.
Select OVRCameraRig and change the value of Tracking Origin Type to Floor Level. This helps position the camera correctly.
Now drag the VRSimulatorCameraRig prefab from the VRTK\Prefabs folder onto the Simulator GameObject.
Select the three SDK GameObjects you’ve just added, and add a VRTK_SDK Setup component to all of them. Select them all separately and assign the appropriate value to Quick Select for each one:
- SteamVR: SteamVR
- Oculus: Oculus (Rift)
- Simulator: Simulator
Now that you’ve added all of the SDK setups, let the SDK Manager auto populate its setup list by selecting [VRTK_SDK_MANAGER] and clicking on the Auto Populate button at the bottom.
That’s it for the SDK Manager. You’re ready to move on to the play area and controller aliases.
Play Area and Controller Aliases
As a child of [VRTK_SDK_MANAGER], create an empty GameObject. Reset its Transform and name it [VRTK_SETUP]. Create the following empty GameObjects and add them as children of [VRTK_SETUP]:
- Play Area
- Left Controller
- Right Controller
When you’re done, the resulting hierarchy will look like this:
Add a VRTK_Adaptive Quality component to Play Area, set its Msaa Level to 2, and set Scale Render Viewport between 0.5 & 2.5.
This adjusts the render resolution depending on the performance; it can both upscale and downscale, so you’ll always use the optimal resolution.
Now add a VRTK_Height Adjust Teleport component to the Play Area. This serves as the base teleport method for all scenes unless specified otherwise. You can leave the variables at their defaults.
Add the following components to both Left Controller and Right Controller:
- VRTK_Controller Events
- VRTK_Interact Touch
- VRTK_Interact Grab
Leave all of these components at their default values.
Add a VRTK_Pointer and a VRTK_StraightPointerRenderer component to Left Controller. This will add a straight pointer to your left controller which you can use to teleport.
Finally, click the selection button next to VRTK_Pointer’s Pointer Renderer slot, and select Left Controller.
Select VRTK_SDK_MANAGER, and hook up the controller aliases by dragging Left Controller and Right Controller to their respective slots.
Now that the SDK Manager is ready, create a new folder under Razeware named Prefabs. To turn the manager into a prefab, drag [VRTK_SDK_MANAGER] to the newly created Razeware\Prefabs folder.
Test if everything works correctly by taking a look around the scene with your preferred headset. If you find any issues, backtrack through this section and compare the steps with what you have.
The work you’ve done will prove to be a considerable time saver later on, but now it’s time to move on.
In the next section, you’ll learn how to add tooltips to GameObjects.
Object Tooltips
Tooltips are like small 3D signs you can use to label objects.
For this tutorial, you’ll be adding a name label to the armored horse, named “Knight”, in the middle of the museum. You may remember him from Unity Games by Tutorials!
To make a tooltip, you need two GameObjects: a root GameObject that will act as the target and the actual ObjectTooltip that’s provided by VRTK.
Start off by creating a container for tooltips; this helps to keep the scene nice and tidy.
Create a new GameObject, name it Object Tooltips, and reset its Transform component.
Now create the target for the knight by adding a new, empty GameObject as a child of Object Tooltips. Name it KnightTip and change its Position to (X:0, Y:1.8, Z:0).
Drag an ObjectTooltip prefab from the VRTK \ Prefabs folder onto KnightTip to make it a child.
Change the Position of ObjectTooltip to (X:1.35, Y:1.3, Z:-0.5), and change the following properties of its VRTK_Object Tooltip component:
- Display Text: Knight
- Font Size: 200
- Container Size: (X:600, Y:250)
- Line Width: 0.01
- Font Color: Pure White (R:255, G:255, B:255)
- Container Color: Pure Black (R:0, G:0, B:0)
- Always Face Headset: Checked
Here’s what your settings should look like when done:
All of these, except the last one, change the visuals of the tooltip.
Always Face Headset causes the tooltip to look at the player’s headset at all times so they will never be looking at the text sideways or from the back. The reason why Draw Line From & Draw Line To isn’t being set is because you’re using a parent GameObject, and the tooltip knows to draw the line from that position to itself.
All of these changes alter the look from this tiny tooltip for ants:
To this hulking, beefy powerhouse of a tooltip:
Well at least it’s easy to see, right?
To test if it’s working correctly, play the scene and look at the knight from different angles; the tooltip should always be visible!
That’s it for object tooltips, be sure to experiment with different styles in your projects.
Next up, the controller, which can also have tooltips!
Controller Tooltips
When you start playing a new game, learning the controls can get confusing, especially with VR — a developing platform that doesn’t yet have a lot of standard controls schemes like PCs and consoles.
In this section, you’ll create a set of tooltips like this one:
Creating these is ridiculously simple, all you need to do is drag a ControllerTooltips prefab from the VRTK\Prefabs folder onto Left Controller.
This adds a bunch of pre-configured tooltips — like you added in the previous section — and the VRTK_Controller Tooltips component acts as a manager for these.
Look at the Button Text Settings on the newly added ControllerTooltips. These correspond to all possible buttons on the HTC Vive and Oculus Rift. The names don’t necessarily match that of the controller, however, here’s an overview of the HTC Vive controller and an Oculus Touch controller:
- Trigger: Hair Trigger on Vive, Trigger on Rift
- Grip: Grip on Vive, Grip on Rift
- Touchpad: Touchpad on Vive, Analog Stick on Rift
- Button One: N/A on Vive, Bottom Button on Rift
- Button Two: Menu Button on Vive, Top Button on Rift
- Start Menu: N/A on Vive, Start Button on Rift
Notice the last three differ between the Vive and the Rift. In this case, you’ll be targeting the HTC Vive setup as an example. If you’re using an Oculus Rift, switch around the Button Two and Start Menu Text.
Change the Button Text Settings to the following:
- Trigger Text: Teleport Pointer
- Grip Text: Grab
- Touchpad Text: Shoot
- Button One Text: (empty)
- Button Two Text: Menu
- Start Menu Text: (empty)
The Object Tooltips are hidden for all empty text fields. That means, if you only want to label just one or two inputs, that’s not a problem!
Now that tooltips are done, save the scene so you don’t lose any work. Then, run the scene, look at your controller, and you’ll see the tooltips spread all around it.
Adding tooltips was fun, right?
In the next sections, you’ll explore how to add some specific functionality to pick up objects.
Fixing Objects to your Hands
In some cases, you might want an object to be fixed to a controller. Or you might want to replace an object with another one after you grab it. Think guns, swords and boxing gloves, for example. You can even automatically grab a GameObject or cloned prefab right at the start of the scene.
For now, though, you’ll start off with creating a basic example: a tank figurine that attaches to your controller permanently once you grab it. This is what happens when you spill a bottle of glue on your tank!
Simple Fixing
Create a new empty GameObject, name it TankFigure, and set its Position to (X:8, Y:1.115, Z:3.5). Then, drag Tank from the Razeware\Models folder and drop it onto TankFigure, making Tank a child of TankFigure.
Change the newly added model’s Scale to (X:0.21, Y:0.21, Z:0.21), and drag TankFigure onto RW Props to parent it.
When you’re done, the new hierarchy will look like this:
Create a new folder inside the Razeware\Prefabs folder and name it Grab. Drag the TankFigure onto the new folder to turn it into a prefab.
You’ll now have a little tank sitting on the table.
This is cool, but you need a way to interact with it.
The easiest and fastest way to add the components you’ll need for this interaction is to use VRTK’s interactable setup wizard.
With TankFigure still selected, open the setup by selecting Window ▸ VRTK ▸ Setup Interactable Object in the top menu.
Leave everything at their default values and press the Setup selected object(s) button at the bottom.
Close the setup window and remove the VRTK_Interact Haptics component from TankFigure.
Under the Grab Options in the VRTK_Interactable Object, set Valid Drop to No Drop; this setting makes it so the player can’t drop the tank after grabbing it.
Before testing if it all works, add a Box Collider component to TankFigure, set its Center to (X:0, Y:0.06, Z:0) and its Size to (X:0.3, Y:0.23, Z:0.3).
This surrounds the small tank. To test it out, dive into VR and try to pick up the sticky tank.
No matter how hard to try, this tank won’t come off! If you don’t want your players to drop something important, or if you want to attach silly stuff to their controllers, this works out nicely.
Next, you’re going to add a pistol that replaces the controller.
Custom Fixing
Add a new empty GameObject to the scene as a parent of RW Props, and name it Pistol. Change its Position to (X:8, Y:1.15, Z:4.5), and drag the Pistol model from the Razeware \ Models folder onto Pistol to create a child.
At the moment, the pistol is a tad too big and not positioned correctly. To fix this, change its Position to (X:0, Y:0, Z:0), its Rotation to (X:-90, Y:90, Z:-90), and its Scale to (X:23, Y:23, Z:23).
There, all better:
Select the Pistol parent and open the VRTK setup wizard (Window ▸ VRTK ▸ Setup Interactable Object). Leave everything at their default values and hit the Setup selected object(s) button.
Close the window and remove the VRTK_Interact Haptics component from Pistol.
Add a Box Collider and set its Center and Size to (X:0, Y:-0.018, Z:0.065) and (X:0.11, Y:0.24, Z:0.37) respectively.
Change Valid Drop on the VRTK_Interactable Object component to No Drop. Right now, it behaves exactly like the tank. To hide the controller when the pistol is grabbed, add a VRTK_Interact Controller Appearance component to the Pistol, and enable the Hide Controller On Grab checkbox.
Test out the scene and see if the controller disappears when you grab the pistol. Well, the controller disappears, but you’re stuck with a gun that’s at an awkward angle:
The reason for this is because GameObjects are attached to your controller at the angle you started grabbing them. To fix this, you’ll need to add a snap handle so the position and rotation of the pistol are always the same relative to the controller.
To create the snap handle, create a new empty GameObject as a child of the parent Pistol GameObject and name it SnapHandle.
Set its Position to (X:0, Y:0.015, Z:0.015) and its Rotation to (X:75, Y:0, Z:0); this will orient the handle like this:
Notice how the handle is rotated 75 degrees on the x-axis? This is important to remember if you want to position snap handles correctly for objects with a grip like guns, swords and other objects.
Here’s how the snap handle will affect how the controller grabs the pistol:
Now drag the SnapHandle to the Right and Left Snap Handle slots in Pistol’s VRTK_Child Of Controller Grab Attach component.
Make the Pistol into a prefab by dragging it into the Razeware\Prefabs\Grab folder, then play the scene again.
The pistol is now aligned to your hand in a more natural position and will follow your hand rotation. The controller itself is also hidden.
This what the developers of Job Simulator have dubbed Tomato presence:
Before moving on to the next section, there’s one more related mechanic you need to work out: automatically grabbing a GameObject.
Auto Grabbing
To automatically grab an object at the start of the scene, you could write a script, but as it turns out, VRTK has a handy component you can add to a controller alias called VRTK_Object Auto Grab. This can automatically grab any interactable objects from the scene or an instantiated prefab.
Select the Right Controller under [VRTK_SDK_MANAGER] \ [VRTK_SETUP], and add a VRTK_Object Auto Grab component to it.
Then, drag the Pistol to the Object To Grab field.
That’s it! Try the scene again, and the pistol will automagically replace your right controller.
Hand Attachments with Joints
There are other methods of attaching objects to controllers besides just parenting them.
If you played around in the scene a bit, you might have noticed you can move the objects right through other objects as soon as you’re holding them. It’s almost as if you’re holding a ghost object. Spooky!
This is because the rigidbody gets set to kinematic if you’re using the VRTK_Child Of Controller Grab Attach component.
For the next object, you’ll use a fixed joint to attach the object to the controller, giving it some realistic behavior.
Create a new empty GameObject as a child of RW Props. Name it VikingDoll, and set its Position and Rotation to (X:8, Y:1.04, Z:5.5) and (X:0, Y:-90, Z:0) respectively.
Drag the Viking model from the Razeware\Models folder onto VikingDoll in the Hierarchy to parent an instance of the model, and set its Scale to (X:0.16, Y:0.16, Z:0.16).
Now, to add a basic VRTK setup.
Select VikingDoll and open the VRTK setup wizard (Window ▸ VRTK ▸ Setup Interactable Object).
Leave everything at their default values except for Grab Attach Mechanic; set this to Fixed Joint and hit the Setup selected object(s) button.
Close the window and remove the VRTK_Interact Haptics component and enable Precision Grab on the VRTK_Fixed Joint Grab Attach component.
Add a Box Collider to the VikingDoll, and set the Center to (X:0, Y:0.2, Z:0.02) and the Size to (X:0.2, Y:0.4, Z:0.18).
That’s all you have to change to get fixed joint attaching working!
The precision grab allows you to grab the object at the particular point where the controller is colliding with the object.
Try the scene again and grab the viking doll. If you attempt to move the doll through the table, you’ll “lose grip”, and you’ll drop the doll.
The joint breaks because the force between the controller and the doll is too great. The controller can move around freely, but the doll can’t enter solid objects, so it’s as if you pull a string from both ends until it snaps.
The force needed to snap this imaginary string is set by the Break Force field on the VRTK_Fixed Joint Grab Attach component.
If you don’t want to break the link between the controller and the object at all, but still want to avoid objects going through each other, there’s also the Track Object grab attach mechanic.
This attachment method applies the velocity of the controller to the grabbed object. It’s less accurate than the methods previously discussed, but it may help you in certain scenarios.
Object Snapping
You can create a lot of different behaviors by snapping objects together. Snapping objects together means that you can insert one object into another object. For example, a USB stick in a USB port, a wheel on a car, and so on.
In this section, you’ll create a battery and a battery holder, which provides the museum with some extra juice to power an extra set of lights.
First, create the battery:
Add a new empty GameObject to the scene, name it Battery, and set its Position and Rotation to (X:8, Y:1.08, Z:8) and (X:0, Y:-120, Z:0) respectively.
Drag the Battery model from the Razeware\Models folder onto the GameObject you just created, so it has some visuals.
The Battery model is composed of two parts: the battery and the battery holder:
Separate BatteryHolder by dragging it between Object Tooltips and Battery in the Hierarchy. You’ll be asked to break the prefab instance. When prompted, select OK.
To make things less confusing moving on, rename it to BatteryHolderModel, and reset its Position to (X:0, Y:0, Z:0) so it’s out of the way. To add basic functionality to the battery, select the Battery parent GameObject and open the Interactable Object wizard.
Set the Touch Highlight Color to a solid yellow (R:255, G:255, B:0), uncheck Add Haptics, and click the Setup selected object(s) button.
Add a Capsule Collider component to the Battery. Set its Radius to 0.08, its Height to 0.4, and enable Is Trigger. Also, set the Direction to X-Axis.
Finally, drag the parent Battery GameObject to the Razeware\Prefabs\Grab folder to turn it into a prefab.
You can now pick up the battery and throw it around, but there’s still nowhere to plug it in. This is where the BatteryHolder comes into play!
Create a new empty GameObject, name it BatteryHolder, and set its Position to (X:0, Y:1.35, Z:9.2).
Drag BatteryHolderModel onto BatteryHolder to parent it, and set its Position and Rotation to (X:0, Y:0, Z:0) and (X:-90, Y:180, Z:0) respectively. The result will look like this:
To allow objects to accept other objects to snap onto them, you need a Snap Drop Zone — this component filters out the objects that can be attached to it and handles the movement, rotation and scale transition.
Add a VRTK_Snap Drop Zone component to the BatteryHolder. Assign the Battery prefab to the Highlight Object Prefab field, and set Snap Duration to 0.2. Set the Highlight Color to a bright green color (X:40, Y:255, Z:0).
You’ll now see a pink transparent copy of the battery inside the holder:
Right now, most of the snap drop zone settings are ready, except it won’t accept any objects as-is. To add valid objects, you need to add a Policy List; this is a handy way of filtering based on several requirements. It can filter by tag, script or layer, and can even accept or reject everything if you wish.
Add a VRTK_Policy List component to the BatteryHolder, set its Operation to Include, and fill in Battery in Element 0 of the list.
Now all of the objects with the Battery tag are allowed to snap into this object. Assign the Battery tag to the Battery by selecting the Battery GameObject and choosing Battery from the Tag dropdown. Click the Apply button afterward, so the prefab gets saved too.
Select BatteryHolder and drag the VRTK_Policy List component onto the VRTK_Snap Drop Zone component’s Valid Object List Policy field to set up the reference to the policy list that should be used for objects allowed to be snapped into place on the battery holder.
The drop zone needs a collider and a rigidbody so it can detect when an object enters in range. Select BatteryHolder and add a Rigidbody and a Capsule Collider component. Disable the gravity on the rigidbody and make it kinematic: you don’t want it falling on the floor.
Set the Radius on the collider to 0.1, set Height to 0.5, and change the Direction to X-Axis.
There’s one final part missing to complete the BatteryHolder: you need a way of making stuff happen when the battery is put inside the batter holder. For this, you’ll need another component: a Snap Drop Zone Unity Events. This lets you visually link the events.
Add a VRTK_Snap Drop Zone_Unity Events component to BatteryHolder, and add a new event to both On Object Snapped To Drop Zone and On Object Unsnapped From Drop Zone. Drag ExtraLights to both Object slots and select GameObject ▸ SetActive. For the snap event, check the box so it’ll become active.
Create a new folder in the Razeware\Prefabs folder named DropZone. Drag the BatteryHolder to the newly created folder to turn BatteryHolder into a prefab.
Everything is ready for snapping now. Run the scene and try to pick up the battery; teleport to the battery holder and snap the battery into place.
If everything works correctly, you’ll see an extra set of lights switch on.
Haptic Feedback
There are a few ways to add haptic feedback (or vibration) to interactions, such as adding a component that handles the haptics.
Add a new empty GameObject to the Hierarchy, name it BombToy, and parent it to RW Props. Set its Position to (X:8, Y:1.11, Z:6.5), and drag the Bomb model from the Razeware\Models folder onto the newly made GameObject to give it some visuals.
Reset the Bomb Position to (X:0, Y:0, Z:0); and to size it down a bit, set its scale to (X:18.5, Y:18.5, Z:18.5). You’ll now have a bomb sitting on the table:
Don’t worry; it’s safe!
Select BombToy and open the VRTK setup wizard (via Window ▸ VRTK); leave everything at their default values and click the Setup selected object(s) button.
Add a Sphere Collider component to the BombToy with a Radius of 0.105 to prevent it from dropping through the floor.
The component you’re interested in is VRTK_Interact Haptics. Until now, you’ve removed this as it wasn’t needed for the other objects.
To get it to work, you’ll need to tweak its variables.
Set Strength On Touch to 0.2, Duration On Touch to 0.1 and Interval On Touch to 0.1 as well in the Haptics On Touch section.
This gives a light and short vibration when you touch the bomb with your controller.
To make it vibrate when you grab it, change the following:
Set Strength On Grab to 0.4, Duration On Grab to 0.2 and Interval On Grab to 0.05 as well in the Haptics On Grab section. This causes the controller to vibrate a bit more violently, letting you know you’ve successfully grabbed the object.
Drag the BombToy to the Razeware\Prefabs\Grab folder to turn it into a prefab. Test if the bomb works as intended by running the scene then touching and grabbing the bomb.
You can also create more interesting effects by creating your own scripts to handle the haptics. To demonstrate, you’ll add a pulse-effect to the battery while you hold it.
Create a new C# script in the Razeware\Scripts folder, name it PulseOnHold, and open it in your code editor.
Remove the
Start() and
Update() methods, and add the following line below the other
using statements:
using VRTK;
Now replace this line:
public class PulseOnHold : MonoBehaviour {
With this one:
public class PulseOnHold : VRTK_InteractableObject {
This causes the script to derive from InteractableObject, which includes some essential functionality.
Now, add the following variables below the class declaration:
public float pulseInterval = 2f; // 1 public float pulseDuration = .2f; // 2 private VRTK_ControllerReference controllerReference; // 3 private IEnumerator pulseRoutine; // 4
Here’s what they’re used for:
- The time between every pulse.
- The amount of time the pulse lasts.
- A reference to the controller that receives the vibration.
- A cached coroutine for correctly starting and stopping the haptic feedback.
Add the following coroutine to do the vibrating:
IEnumerator DoPulsing() { while (gameObject.activeSelf) { VRTK_ControllerHaptics.TriggerHapticPulse(controllerReference, 0.5f, pulseDuration, 0.01f); yield return new WaitForSeconds(pulseInterval); } }
This keeps vibrating the controller at the specified interval until the GameObject gets deactivated or the coroutine is stopped.
Next, add the following methods:
private void OnEnable() // 1 { base.OnEnable(); pulseRoutine = DoPulsing(); } public override void Grabbed(VRTK_InteractGrab grabbingObject) // 2 { base.Grabbed(grabbingObject); controllerReference = VRTK_ControllerReference.GetControllerReference(grabbingObject.controllerEvents.gameObject); StartCoroutine(pulseRoutine); } public override void Ungrabbed(VRTK_InteractGrab grabbingObject) // 3 { base.Ungrabbed(grabbingObject); controllerReference = null; StopCoroutine(pulseRoutine); }
Here’s the breakdown:
- Call the base class
OnEnable()method and cache a reference to the
DoPulsing()coroutine.
- This method gets called when a controller grabs the GameObject to which this script is attached. The
grabbingObjectis stored as the controller, and the pulse routine is started.
- This method gets called when a controller releases the GameObject to which this script is attached. The controller is cleared, and the pulse routine is stopped.
Save the script and return to the Unity editor.
Add the Pulse On Hold component to the Battery, and remove the VRTK_Interactable Object component. Your custom component replaces its functionality.
Next, you’ll take a look at the Pulse On Hold component.
Change the Touch Highlight Color to Pure Yellow (R:255, G:255, B:0) and check Is Grabbable.
Don’t forget to update the base battery prefab by clicking Apply on the Battery GameObject in the Hierarchy.
That’s it! Run the scene and grab the battery. You should feel a pulse as long as you’ve got the battery in your hand. Can you feel the force flow with all that energy?
Where to Go From Here?
You can download the final project from this tutorial using the “Download Materials” button at the top or bottom of this page.
Well done! You now know how to add exciting mechanics to your own VR games.
If you had trouble following along, or you want to compare your project to the sample one, you can find the final project included with this tutorial’s resources files.
Here’s a quick recap of what you did. In this tutorial, you learned how to:
- Create tooltips for objects and controllers.
- Fix objects to your controllers.
- Use joints to accurately pick up objects.
- Snap objects into place.
- Use haptic feedback.
If you have any questions or comments, please leave them below!
|
https://www.raywenderlich.com/2163461-advanced-vr-interactions-in-unity-tutorial
|
CC-MAIN-2020-16
|
refinedweb
| 4,988
| 63.59
|
Having had some time to digest all the news from MIX08 I am working on converting a Silverlight 1.1 project to Silverlight 2.0. One of the major changes is to move from ASMX services to WCF services. Now, that cross-domain access is possible and with WCF inherently being more complex there are a lot of failure points.
So, having spend probably a total of 8 hours on updating the structure of the new project and deploying it to a production environment I thought I'd share this with you so you don't have to spend that much time. Since most of the time spent had to do with deployment and WCF configurations I will focus on that.
The 3 main challenges I needed to figure out were...
By default, WCF requires you to have your IIS virtual directly configured to be accessible anonymously. However, if you do some kind of domain related stuff you need your IIS virtual directly to be configured to be Windows Authentication. Here is the code to update your web.config file of the WCF web application.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="MyBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DesignDBServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="DesignDBServiceBehavior" name="DesignDBService">
<endpoint
address=""
binding="basicHttpBinding"
contract="IDesignDBService"
bindingConfiguration="MyBinding">
</endpoint>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
I mainly just needed to get this working because I tried to debug my local SL project having referenced and external cross-domain WCF service. In order to get this working you need to put a "clienataccesspolicy.xml" in the root of your IIS server. This is usually at C:\inetpub\wwwroot. If the file is there and granted the file allows your local domain of your SL project access, Silverlight will automatically acknowledge the file and give access. So, there is nothing you need to do within Silverlight. HOWEVER, MAKE SURE TO RESTART IIS. THE FILE IS NOT RECOGNIZED RIGHT AWAY.
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from>
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
This involves two steps
1. Change to the web.config file of the WCF web application.
2. Adding of a class property of the service class, not the service interface.
using System; using System.ServiceModel; using System.Configuration; using System.Web; using System.Web.Configuration; using System.ServiceModel.Configuration; using System.Text; using System.Security.Principal; using System.ServiceModel.Activation; using System.Collections.Generic;
using System.Linq;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class DesignDBService : IDesignDBService {
Silverlight 2.0 and WCF 今後きっと参考にするだろう情報なのでメモ。 WCFをきちんとやらないとな。。。
Thank you for this - I'll be checking this out soon and hoping that it solves my error as well!
Dear Tolga,
I am still getting this security error trying to call my WCF web service from my silverlight 2 application. Here is the error.
I made the change you said was required for WCF to use windows authentication, but I still get the same error. I have also setup a ICrossDomainPolicyResponder but that didn't work either. Can you help me please?
{System.ServiceModel.CommunicationException: An error occurred while trying to make a request to URI
'localhost/.../main'. This could be due to a cross domain configuration error.
Please see the inner exception for more details. ---> System.Security.SecurityException: Security error.
at MS.Internal.InternalWebRequest.Send()
Hi
I made a simple wcf service hosted in iis. I am trying to call it in silverlight 2 application. I added crossdomain.xml, clientaccesspolicy.xml in the root of service folder.
The service is accessed anonymously i and also followed the third step.
Still i get an exception of type 'System.ServiceModel.ProtocolException'.
Additional information: The remote server returned an unexpected response: (404) Not Found.
can you tell what i am missing ?
Solved it.
Silverlight app was not getting clientaccesspolicy.xml
followed the post here
timheuer.com/.../silverlight-cannot-access-web-service.aspx
Thanks.
How can I pass some information between client and server for all calls. Well, I may be asking a wrong question. I read many online articles about WCF security and Sliverlight. They sound like they are all talking about how to authenticate a client. In my case, it's ok to allow anonymous access to all end points. But if a record can be returned or an operation should be performed is determined in code, by the user name and password provided in a context object, which was input at the first time a user signed in and attached automatically (through a static member in the framework, I guess) to each call to the service.
Could you point me out the solution in Silverlight 2?
In my application, it is ok to allow anonymous access to all end points. But the logic determining if a certain operation can be preformed is in code, by user information provided in a context object. Could you point me out the solution to pass user information automatically for each service call?
Hello everyone:
I apologize for not getting back to you guys earlier. I feel you pain, since it has been mine for days as well. All I can tell you is that what I posed works.
for some of you it seems like the issues are within WCF.
I recommend isolating the issue...
1. Create a regular web app and try to consume the WCF services you created.
2. Create a silverlight project WITH an web application. Build the same WCF service within the Silverlight host web site and run it. Cross domain erros should not appear here, since the Silverlight project and the hosting web project are part of the same solution.
3. Try to consuem the first WCF you created. It needs to be hosted in IIS with the crossdomain.xml file in the root. In my case...wwwroot.
Good luck
--tolga
We have to put the crossdomainpolicy.xml file in the folder C:/Inetpub/wwwroot and host the WCF Web application in IIS by going to properties window of WCF Web Application project, select the Web tab and select the option "Use IIS Web Server". This has to be done in case our WCF service is hosted on a remote machine other than the client app machine....It worked for me...
|
http://weblogs.asp.net/tolgakoseoglu/archive/2008/03/18/silverlight-2-0-and-wcf.aspx
|
crawl-002
|
refinedweb
| 1,067
| 51.04
|
The distinct() method in the IntStream class in Java returns a stream consisting of the distinct elements of this stream.
The syntax is as follows
IntStream distinct()
Let’s say we have the following elements in the stream. Some of them are repeated
IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80);
To get the distinct elements, use the IntStream distinct() method.
The following is an example to implement IntStream distinct() method in Java
import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.of(10, 20, 30, 20, 10, 50, 80, 90, 100, 80); System.out.println("Displaying the distinct elements:"); intStream.distinct().forEach(System.out::println); } }
Displaying the distinct elements: 10 20 30 50 80 90 100
|
https://www.tutorialspoint.com/intstream-distinct-method-in-java
|
CC-MAIN-2021-43
|
refinedweb
| 131
| 67.04
|
#include <reporter.h>
#include <reporter.h>
List of all members.
Definition at line 159 of file reporter.h.
C'tor.
Definition at line 631 of file reporter.cc.
References clear().
Here is the call graph for this function:
D'tor.
Definition at line 637 of file reporter.cc.
Add a path report for this job.
Definition at line 649 of file reporter.cc.
References m_reports, and TRY_nomem.
Referenced by job_archiver::mf_process_report().
Clear all values.
Definition at line 642 of file reporter.cc.
References m_id, and m_reports.
Referenced by job_archiver::clear(), and single_job_report().
Return the descriptive id for this job report.
Definition at line 667 of file reporter.cc.
References m_id.
Set a descriptive ID for this job report.
Definition at line 661 of file reporter.cc.
References m_id, and TRY_nomem.
Referenced by job_archiver::start().
Return a const vector of all path reports.
Definition at line 655 of file reporter.cc.
References m_reports.
If all path reports say that rsync was successful, then return true, else return false.
Definition at line 674 of file reporter.cc.
[private]
Definition at line 177 of file reporter.h.
Referenced by clear(), and id().
Definition at line 176 of file reporter.h.
Referenced by add_report(), clear(), reports(), and status().
|
http://rvm.sourceforge.net/doxygen/1.0/html/classsingle__job__report.html
|
CC-MAIN-2017-39
|
refinedweb
| 204
| 64.78
|
In this article by Magnus Vilhelm Persson, author of the book Mastering Python Data Analysis, we will see that with data comprising of several separated distributions, how do we find and characterize them? In this article, we will look at some ways to identify clusters in data. Groups of points with similar characteristics form clusters. There are many different algorithms and methods to achieve this, with good and bad points. We want to detect multiple separate distributions in the data; for each point, we determine the degree of association (or similarity) with another point or cluster. The degree of association needs to be high if they belong in a cluster together or low if they do not. This can, of course, just as previously, be a one-dimensional problem or a multidimensional problem. One of the inherent difficulties of cluster finding is determining how many clusters there are in the data. Various approaches to define this exist—some where the user needs to input the number of clusters and then the algorithm finds which points belong to which cluster, and some where the starting assumption is that every point is a cluster and then two nearby clusters are combined iteratively on trial basis to see if they belong together.
In this article, we will cover the following topics:
- A short introduction to cluster finding, reminding you of the general problem and an algorithm to solve it
- Analysis of a dataset in the context of cluster finding, the Cholera outbreak in central London 1854
- By Simple zeroth order analysis, calculating the centroid of the whole dataset
- By finding the closest water pump for each recorded Cholera-related death
Applying the K-means nearest neighbor algorithm for cluster finding to the data and identifying two separate distributions
(For more resources related to this topic, see here.)
The algorithms and methods covered here are focused on those available in SciPy.
Start a new Notebook, and put in the default imports. Perhaps you want to change to interactive Notebook plotting to try it out a bit more. For this article, we are adding the following specific imports. The ones related to clustering are from SciPy, while later on we will need some packages to transform astronomical coordinates. These packages are all preinstalled in the Anaconda Python 3 distribution and have been tested there:
import scipy.cluster.hierarchy as hac import scipy.cluster.vq as vq
Introduction to cluster finding
There are many different algorithms for cluster identification. Many of them try to solve a specific problem in the best way. Therefore, the specific algorithm that you want to use might depend on the problem you are trying to solve and also on what algorithms are available in the specific package that you are using.
Some of the first clustering algorithms consisted of simply finding the centroid positions that minimize the distances to all the points in each cluster. The points in each cluster are closer to that centroid than other cluster centroids. As might be obvious at this point, the hardest part with this is figuring out how many clusters there are. If we can determine this, it is fairly straightforward to try various ways of moving the cluster centroid around, calculate the distance to each point, and then figure out where the cluster centroids are. There are also obvious situations where this might not be the best solution, for example, if you have two very elongated clusters next to each other.
Commonly, the distance is the Euclidean distance:
Here, p is a vector with all the points' positions,that is,{p1,p2,...,pN–1,pN} in cluster Ck, that is P E Ck , the distances are calculated from the cluster centroid,Ui . We have to find the cluster centroids that minimize the sum of the absolute distances to the points:
In this first example, we shall first work with fixed cluster centroids.
Starting out simple – John Snow on Cholera
In 1854, there was an outbreak of cholera in North-western London, in the neighborhood around Broad Street. The leading theories at the time claimed that cholera spread, just like it was believed that the plague spread: through foul, bad air. John Snow, a physician at the time, hypothesized that cholera spread through drinking water. During the outbreak, John tracked the deaths and drew them on a map of the area. Through his analysis, he concluded that most of the cases were centered on the Broad Street water pump. Rumors say that he then removed the handle of the water pump, thus stopping an epidemic. Today, we know that cholera is usually transmitted through contaminated food or water, thus confirming John's hypothesis. We will do a short but instructive reanalysis of John Snow's data.
The data comes from the public data archives of The National Center for Geographic Information and Analysis ( and). A cleaned up map and copy of the data files along with an example of Geospatial information analysis of the data can also be found at wealth of information about physician and scientist John Snow's life and works can be found at.
To start the analysis, we read the data into a Pandas DataFrame; the data is already formatted in CSV-files readable by Pandas:
deaths = pd.read_csv('data/cholera_deaths.txt') pumps = pd.read_csv('data/cholera_pumps.txt')
Each file contains two columns, one for X coordinates and one for Y coordinates. Let's check what it looks like:
deaths.head()
pumps.head()
With this information, we can now plot all the pumps and deaths to visualize the data:
plt.figure(figsize=(4,3.5)) plt.plot(deaths['X'], deaths['Y'], marker='o', lw=0, mew=1, mec='0.9', ms=6) plt.plot(pumps['X'],pumps['Y'], marker='s', lw=0, mew=1, mec='0.9', color='k', ms=6) plt.axis('equal') plt.xlim((4.0,22.0)); plt.xlabel('X-coordinate') plt.ylabel('Y-coordinate') plt.title('John Snow\'s Cholera')
It is fairly easy to see that the pump in the middle is important. As a first data exploration, we will simply calculate the mean centroid of the distribution and plot that in the figure as an ellipse. We will calculate the mean and standard deviation along the x and y axis as the centroid position:
fig = plt.figure(figsize=(4,3.5)) ax = fig.add_subplot(111) plt.plot(deaths['X'], deaths['Y'], marker='o', lw=0, mew=1, mec='0.9', ms=6) plt.plot(pumps['X'],pumps['Y'], marker='s', lw=0, mew=1, mec='0.9', color='k', ms=6) from matplotlib.patches import Ellipse ellipse = Ellipse(xy=(deaths['X'].mean(), deaths['Y'].mean()), width=deaths['X'].std(), height=deaths['Y'].std(), zorder=32, fc='None', ec='IndianRed', lw=2) ax.add_artist(ellipse) plt.plot(deaths['X'].mean(), deaths['Y'].mean(), '.', ms=10, mec='IndianRed', zorder=32) for i in pumps.index: plt.annotate(s='{0}'.format(i), xy=(pumps[['X','Y']].loc[i]), xytext=(-15,6), textcoords='offset points') plt.axis('equal') plt.xlim((4.0,22.5)) plt.xlabel('X-coordinate') plt.ylabel('Y-coordinate') plt.title('John Snow\'s Cholera')
Here, we also plotted the pump index, which we can get from DataFrame with the pumps.index method. The next step in the analysis is to see which pump is the closest to each point. We do this by calculating the distance from all pumps to all points. Then we want to figure out which pump is the closest for each point.
We save the closest pump to each point in a separate column of the deaths' DataFrame. With this dataset, the for-loop runs fairly quickly. However, the DataFrame subtract method chained with sum() and idxmin() methods takes a few seconds. I strongly encourage you to play around with various ways to speed this up. We also use the .apply() method of DataFrame to square and square root the values. The simple brute force first attempt of this took over a minute to run. The built-in functions and methods help a lot:
deaths_tmp = deaths[['X','Y']].as_matrix() idx_arr = np.array([], dtype='int') for i in range(len(deaths)): idx_arr = np.append(idx_arr, (pumps.subtract(deaths_tmp[i])).apply(lambda x:x**2).sum(axis=1).apply(lambda x:x**0.5).idxmin()) deaths['C'] = idx_arr
Quickly check whether everything seems fine by printing out the top rows of the table:
deaths.head()
Now we want to visualize what we have. With colors, we can show which water pump we associate each death with. To do this, we use a colormap, in this case, the jet colormap. By calling the colormap with a value between 0 and 1, it returns a color; thus we give it the pump indexes and then divide it with the total number of pumps, 12 in our case:
fig = plt.figure(figsize=(4,3.5)) ax = fig.add_subplot(111) np.unique(deaths['C'].values) plt.scatter(deaths['X'].as_matrix(), deaths['Y'].as_matrix(), color=plt.cm.jet(deaths['C']/12.), marker='o', lw=0.5, edgecolors='0.5', s=20) plt.plot(pumps['X'],pumps['Y'], marker='s', lw=0, mew=1, mec='0.9', color='0.3', ms=6) for i in pumps.index: plt.annotate(s='{0}'.format(i), xy=(pumps[['X','Y']].loc[i]), xytext=(-15,6), textcoords='offset points', ha='right') ellipse = Ellipse(xy=(deaths['X'].mean(), deaths['Y'].mean()), width=deaths['X'].std(), height=deaths['Y'].std(), zorder=32, fc='None', ec='IndianRed', lw=2) ax.add_artist(ellipse) plt.axis('equal') plt.xlim((4.0,22.5)) plt.xlabel('X-coordinate') plt.ylabel('Y-coordinate') plt.title('John Snow\'s Cholera')
The majority of deaths are dominated by the proximity of the pump in the center. This pump is located on Broad Street.
Now, remember that we have used fixed positions for the cluster centroids. In this case, we are basically working on the assumption that the water pumps are related to the cholera cases. Furthermore, the Euclidean distance is not really the real-life distance. People go along roads to get water and the road there is not necessarily straight. Thus, one would have to map out the streets and calculate the distance to each pump from that. Even so, already at this level, it is clear that there is something with the center pump related to the cholera cases. How would you account for the different distance? To calculate the distance, you would do what is called cost-analysis (c.f. when you hit directions on your sat-nav to go to a place). There are many different ways of doing cost analysis, and it also relates to the problem of finding the correct way through a maze.
In addition to these things, we do not have any data in the time domain, that is, the cholera would possibly spread to other pumps with time and thus the outbreak might have started at the Broad Street pump and spread to other nearby pumps. Without time data, it is difficult to figure out what happened.
This is the general approach to cluster finding. The coordinates might be attributes instead, length and weight of dogs for example, and the location of the cluster centroid something that we would iteratively move around until we find the best position.
K-means clustering
The K-means algorithm is also referred to as vector quantization. What the algorithm does is find the cluster (centroid) positions that minimize the distances to all points in the cluster. This is done iteratively; the problem with the algorithm is that it can be a bit greedy, meaning that it will find the nearest minima quickly. This is generally solved with some kind of basin-hopping approach where the nearest minima found is randomly perturbed and the algorithm restarted. Due to this fact, the algorithm is dependent on good initial guesses as input.
Suicide rate versus GDP versus absolute lattitude
We will analyze the data of suicide rates versus GDP versus absolute lattitude or Degrees From Equator (DFE) for clusters. Our hypothesis from the visual inspection was that there were at least two distinct clusters, one with higher suicide rate, GDP, and absolute lattitude and one with lower. Here, the Hierarchical Data Format (HDF) file is now read in as a DataFrame. This time, we want to discard all the rows where one or more column entries are NaN or empty. Thus, we use the appropriate DataFrame method for this:
TABLE_FILE = 'data/data_ch4.h5' d2 = pd.read_hdf(TABLE_FILE) d2 = d2.dropna()
Next, while the DataFrame is a very handy format, which we will utilize later on, the input to the cluster algorithms in SciPy do not handle Pandas data types natively. Thus, we transfer the data to a NumPy array:
rates = d2[['DFE','GDP_CD','Both']].as_matrix().astype('float')
Next, to recap, we visualise the data by one histogram of the GDP and one scatter plot for all the data. We do this to aid us in the initial guesses of the cluster centroid positions:
plt.subplots(12, figsize=(8,3.5)) plt.subplot(121) plt.hist(rates.T[1], bins=20,color='SteelBlue') plt.xticks(rotation=45, ha='right') plt.yscale('log') plt.xlabel('GDP') plt.ylabel('Counts') plt.subplot(122) plt.scatter(rates.T[0], rates.T[2], s=2e5*rates.T[1]/rates.T[1].max(), color='SteelBlue', edgecolors='0.3'); plt.xlabel('Absolute Latitude (Degrees, \'DFE\')') plt.ylabel('Suicide Rate (per 100\')') plt.subplots_adjust(wspace=0.25);
The scatter plots shows the GDP as size. The function to run the clustering k-means takes a special kind of normalized input. The data arrays (columns) have to be normalized by the standard deviation of the array. Although this is straightforward, there is a function included in the module called whiten. It will scale the data with the standard deviation:
w = vq.whiten(rates)
To show what it does to the data, we plot the same plots as we did previously, but with the output from the whiten function:
plt.subplots(12, figsize=(8,3.5)) plt.subplot(121) plt.hist(w[:,1], bins=20, color='SteelBlue') plt.yscale('log') plt.subplot(122) plt.scatter(w.T[0], w.T[2], s=2e5*w.T[1]/w.T[1].max(), color='SteelBlue', edgecolors='0.3') plt.xticks(rotation=45, ha='right');
As you can see, all the data is scaled from the previous figure. However, as mentioned, the scaling is just the standard deviation. So let's calculate the scaling and save it to the sc variable:
sc = rates.std(axis=0)
Now we are ready to estimate the initial guesses for the cluster centroids. Reading off the first plot of the data, we guess the centroids to be at 20 DFE, 200,000 GDP, and 10 suicides and the second at 45 DFE, 100,000 GDP, and 15 suicides. We put this in an array and scale it with our scale parameter to the same scale as the output from the whiten function. This is then sent to the kmeans2 function of SciPy:
init_guess = np.array([[20,20E3,10],[45,100E3,15]]) init_guess /= sc z2_cb, z2_lbl = vq.kmeans2(w, init_guess, minit='matrix', iter=500)
There is another function, kmeans (without the 2), which is a less complex version and does not stop iterating when it reaches a local minima. It stops when the changes between two iterations go below some level. Thus, the standard K-means algorithm is represented in SciPy by the kmeans2 function. The function outputs the centroids' scaled positions (here z2_cb) and a lookup table (z2_lbl) telling us which row belongs to which centroid. To get the centroid positions in units we understand, we simply multiply with our scaling value:
z2_cb_sc = z2_cb * sc
At this point, we can plot the results. The following section is rather long and contains many different parts so we will go through them section by section. However, the code should be run in one cell of the Notebook:
# K-means clustering figure START plt.figure(figsize=(6,4)) plt.scatter(z2_cb_sc[0,0], z2_cb_sc[0,2], s=5e2*z2_cb_sc[0,1]/rates.T[1].max(), marker='+', color='k', edgecolors='k', lw=2, zorder=10, alpha=0.7); plt.scatter(z2_cb_sc[1,0], z2_cb_sc[1,2], s=5e2*z2_cb_sc[1,1]/rates.T[1].max(), marker='+', color='k', edgecolors='k', lw=3, zorder=10, alpha=0.7);
The first steps are quite simple—we set up the figure size and plot the points of the cluster centroids. We hypothesized about two clusters; thus, we plot them with two different calls to plt.scatter. Here, z2_cb_sc[1,0] gets the second cluster x-coordinate (DFE); then switching 0 for 1 gives us the y coordinate (rate). We set the size of the marker s-parameter to scale with the value of the third data axis, the GDP. We also do this further down for the data, just as in previous plots, so that it is easier to compare and differentiate the clusters. The zorder keyword gives the order in depth of the elements that are plotted; a high zorder will put them on top of everything else and a negative zorder will send them to the back.
s0 = abs(z2_lbl==0).astype('bool') s1 = abs(z2_lbl==1).astype('bool') pattern1 = 5*'x' pattern2 = 4*'/' plt.scatter(w.T[0][s0]*sc[0], w.T[2][s0]*sc[2], s=5e2*rates.T[1][s0]/rates.T[1].max(), lw=1, hatch=pattern1, edgecolors='0.3', color=plt.cm.Blues_r( rates.T[1][s0]/rates.T[1].max())); plt.scatter(rates.T[0][s1], rates.T[2][s1], s=5e2*rates.T[1][s1]/rates.T[1].max(), lw=1, hatch=pattern2, edgecolors='0.4', marker='s', color=plt.cm.Reds_r( rates.T[1][s1]/rates.T[1].max()+0.4))
In this section, we plot the points of the clusters. First, we get the selection (Boolean) arrays. They are simply found by setting all indexes that refer to cluster 0 to True and all else to False; this gives us the Boolean array for cluster 0 (the first cluster). The second Boolean array is matched for the second cluster (cluster 1). Next, we define the hatch pattern for the scatter plot markers, which we later give as input to the plotting function. The multiplier for the hatch pattern gives the density of the pattern. The scatter plots for the points are created in a similar fashion as the centroids, except that the markers are a bit more complex. They are both color-coded, like in the previous example with Cholera deaths, but in a gradient instead of the exact same colors for all points. The gradient is defined by the GDP, which also defines the size of the points. The x and y data sent to the plot is different between the clusters, but they access the same data in the end because we multiply with our scaling factor.
p1 = plt.scatter([],[], hatch='None', s=20E3*5e2/rates.T[1].max(), color='k', edgecolors='None',) p2 = plt.scatter([],[], hatch='None', s=40E3*5e2/rates.T[1].max(), color='k', edgecolors='None',) p3 = plt.scatter([],[], hatch='None', s=60E3*5e2/rates.T[1].max(), color='k', edgecolors='None',) p4 = plt.scatter([],[], hatch='None', s=80E3*5e2/rates.T[1].max(), color='k', edgecolors='None',) labels = ["20\'", "40\'", "60\'", ">80\'"] plt.legend([p1, p2, p3, p4], labels, ncol=1, frameon=True, #fontsize=12, handlelength=1, loc=1, borderpad=0.75,labelspacing=0.75, handletextpad=0.75, title='GDP', scatterpoints=1.5) plt.ylim((-4,40)) plt.xlim((-4,80)) plt.title('K-means clustering') plt.xlabel('Absolute Lattitude (Degrees, \'DFE\')') plt.ylabel('Suicide Rate (per 100 000)');
The last tweak to the plot is made by creating a custom legend. We want to show different sizes of the points and what GDP they correspond to. As there is a continuous gradient from low to high, we cannot use the plotted points. Thus we create our own, but leave the x and y input coordinates as empty lists. This will not show anything in the plot but we can use them to register in the legend. The various tweaks to the legend function controls different aspects of the legend layout. I encourage you to experiment with it to see what happens:
As for the final analysis, two different clusters are identified. Just as our previous hypothesis, there is a cluster with a clear linear trend with relatively higher GDP, which is also located at higher absolute latitude. Although the identification is rather weak, it is clear that the two groups are separated. Countries with low GDP are clustered closer to the equator. What happens when you add more clusters? Try to add a cluster for the low DFE, high rate countries, visualize it, and think about what this could mean for the conclusion(s).
Summary
In this article, we identified clusters using methods such as finding the centroid positions and K-means clustering.
For more information about Python Data Analysis, refer to the following books by Packt Publishing:
- Python Data Analysis (-...)
Getting Started with Python Data Analysis (...)
Resources for Article:
Further resources on this subject:
- Python Data Science Up and Running [article]
- Basics of Jupyter Notebook and Python [article]
- Scientific Computing APIs for Python [article]
|
https://www.packtpub.com/books/content/clustering-methods
|
CC-MAIN-2017-13
|
refinedweb
| 3,560
| 56.25
|
SimpleTimer Library for Arduino Author: Marcello Romani Contact: mromani@ottotecnica.com License: GNU LGPL 2.1+
This is (yet another) simple library to launch timed actions.
It's based on millis(), thus it has 1 ms resolution.
It uses polling, so no guarantee can be made about the exact time when a callback is fired. For example, if you setup the library so that it calls a function every 2ms, but this function requires 5ms to complete, then you'll have an invocation every 5ms.
For applications where non-strict timing is enough, not using interrupts avoids potential problems with global variables shared between the interrupt service routine and the main program, and doesn't consune a hardware timer.
Go to the Get the code section and hit the "get the code" link at the bottom of each code block.
#include <SimpleTimer.h> // the timer object SimpleTimer timer; // a function to be executed periodically void repeatMe() { Serial.print("Uptime (s): "); Serial.println(millis() / 1000); } void setup() { Serial.begin(9600); timer.setInterval(1000, repeatMe); } void loop() { timer.run(); }
The base goal is to be able to execute a particular piece of code every n milliseconds, without using interrupts.
The algorithm looks like this:
lastMillis = 0 forever do: if (millis() - lastMillis > n) call the particular piece of code lastMillis = millis() end end
Other libraries with similar or broader goals can be found in the here
The constructor. You usually need only one SimpleTimer object in a sketch.
SimpleTimer timer;
Call function f every d milliseconds. The callback function must be declared as
void f().
void repeatMe() { // do something } timerId = timer.setInterval(1000, repeatMe);
Call function f once after d milliseconds. The callback function must be declared as
void f().
After f has been called, the interval is deleted, therefore the value timerId is no longer valid.
void callMeLater() { // do something } timerId = timer.setTimeout(1000, callMeLater);
Call function f every d milliseconds for n times. The callback function must be declared as
void f().
After f has been called the specified number of times, the interval is deleted, therefore the value timerId is no longer valid.
void repeatMeFiveTimes() { // do something } timerId = timer.setTimer(1000, repeatMeFiveTimes, 5);
Returns true if the specified timer is enabled
if(timer.isEnabled(timerId) { // do domething }
Enables the specified timer.
timer.enable(timerId);
Disables the specified timer.
timer.disable(timerId);
Enables the specified timer if it's currently disabled, and vice-versa.
timer.toggle(timerId);
Causes the specified timer to start counting from "now", i.e. the instant when restartTimer is called. The timer callback is not fired. A use case for this function is for example the implementation of a watchdog timer (pseudocode follows).
void wdCallback() { alert user or perform action to restore program state (e.g. reset the microprocessor) } wd_timer_id; void setup() { wd_timer_id = timer.setInterval(10000, wdCallback); } void loop() { timer.run(); big complex critical code timer.restartTimer(wd_timer_id); }
Free the specified timerId slot. You should need to call this only if you have interval slots that you don't need anymore. The other timer types are automatically deleted once the specified number of repetitions have been executed.
Return the number of used slots in a timer object.
n = timer.getNumTimers();
Last Modified: February 09, 2013, at 10:38 PM
By: terryking228\\
|
http://playground.arduino.cc/Code/SimpleTimer
|
CC-MAIN-2013-20
|
refinedweb
| 544
| 59.7
|
C++ is general-purpose object-oriented programming (OOP) language developed by Bjarne Stroustrup.
Originally, C++ was called “C with classes,” as it had all the properties of the C language with the addition of user-defined data types called “classes.” It was renamed C++ in 1983.
C++ is considered an intermediate-level language, as it includes both high and low-level language features.
Some key benefits of C++ are outlined below:
Using pointers, C++ allows self-memory management, that enhances the execution speed of a program. But it is necessary to explicitly free up the reserved space later on.
Object-oriented support
C++ can be coded in C style or object-oriented style. In certain scenarios, it can be coded either way - making C++ a good example of a hybrid language.
High performance
Since
C++ allows to manipulate the processor on a lower level, it is quite faster than advanced level languages like Python or C#.
Other essential concepts of C++ include:
The following example shows how to print “Hello World” in C++.
#include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; }
View all Courses
|
https://www.educative.io/edpresso/what-is-cpp
|
CC-MAIN-2021-39
|
refinedweb
| 188
| 54.83
|
Here is code.
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print tag.get('href', None)
I was able to accomplish your homework in the following way (please take the time to learn this):
import urllib from bs4 import BeautifulSoup # This function will get the Nth link object from the given url. # To be safe you should make sure the nth link exists (I did not) def getNthLink(url, n): html = urllib.urlopen(url).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('a') return tags[n-1] url = "" # This iterates 4 times, each time grabbing the 3rd link object # For convenience it prints the url each time. for i in xrange(4): tag = getNthLink(url,3) url = tag.get('href') print url # Finally after 4 times we grab the content from the last tag print tag.contents[0]
|
https://codedump.io/share/XfblVHKB2kpu/1/retrieve-links-from-web-page-using-python-and-beautifulsoup-than-select-3-link-and-run-it-4-times
|
CC-MAIN-2018-09
|
refinedweb
| 159
| 73.17
|
KRB5.CONF(5) MidnightBSD File Formats Manual KRB5.CONF(5)
NAME
krb5.conf — configuration file for Kerberos 5
SYNOPSIS
#include <krb5.h>
DESCRIPTION:
sections:
section:
section_name:
bindings:
binding:
name:.
etypes
valid encryption types are: des-cbc-crc, des-cbc-md4, des-cbc-md5, to be used for Kerberos applications. You can specify defaults per application, realm, or a combination of these. The preference order is:
1.
application realm option
2.
application option
3.
realm option
4.
option
The supported options are: your ‘‘local realm’’. The default is the result of krb5_get_host_realm(local hostname).
clockskew = time
Maximum time differential (in seconds) allowed when comparing times. Default is 300 seconds (five minutes). ‘‘FILE:/etc proxiable. This option is ... realm may be the token ‘dns_locate’, in which case the actual realm will be determined using DNS (independently of the setting of the ‘dns_lookup_realm’ option).
[realms]
REALM = {
kdc = [service/]host[:port]
Specifies a list of kdcs for this realm. If the optional port is absent, the default value for the ‘‘kerberos/udp’’ ‘‘kerberos/tcp’’, and ‘‘http/tcp’’ port (depending on service) will be used. The kdcs will be used in the order that they are specified.
The optional service specifies over what medium the kdc should be contacted. Possible services are ‘‘udp’’, ‘‘tcp’’, and ‘‘http’’. Http can also be written as ‘‘http://’’. Default service is ‘‘udp’’ and ‘‘tcp’’.
admin_server = host[:port]
Specifies the admin server for this realm, where all the modifications to the database are performed.
kpasswd_server = host[:port]
Points to the server where all the performed addresses-less tickets.
allow-anonymous = BOOL
If the kdc is allowed to hand out anonymous tickets.
encode_as_rep_as_tgs_rep = BOOL
Encode as-rep as tgs-rep tobe compatible with mistakes:
[
v4
The Kerberos 4 salt des:pw-salt:
use_v4_salt = BOOL
When true, this is the same as
default_keys = des3:pw-salt v4
and is only left for backwards compatibility.
ENVIRONMENT
KRB5_CONFIG points to the configuration file to read.
FILES
/etc/krb5.conf
configuration file for Kerberos 5.
EXAMPLES
[libdefaults]
[domain_realm]
[realms]
[logging]
DIAGNOSTICS
Since krb5.conf is read and parsed by the krb5 library, there is not a lot of opportunities for programs to report parsing)
HEIMDAL March 9, 2004 HEIMDAL
|
http://www.midnightbsd.org/documentation/man/krb5.conf.5.html
|
CC-MAIN-2014-35
|
refinedweb
| 363
| 52.15
|
NAME
khttp_parse,
khttp_parsex — parse a CGI
instance for kcgi
LIBRARY
library “libkcgi”
SYNOPSIS
#include
<sys/types.h>
#include <stdarg.h>
#include <stdint.h>
#include <kcgi.h>
enum kcgi_err
khttp_parse(struct kreq *req,
const struct kvalid *keys, size_t
keysz, const char *const *pages,
size_t pagesz, size_t
defpage);
enum kcgi_err
khttp_parsex(struct kreq *req,
const struct kmimemap *suffixes, const
char *const *mimes, size_t mimesz,
const struct kvalid *keys, size_t
keysz, const char *const *pages,
size_t pagesz, size_t defmime,
size_t defpage, void *arg,
void (*argfree)(void *arg), unsigned
int debugging, const struct kopts *opts);
extern const char *const
kmimetypes[KMIME__MAX];
extern const char *const khttps[KHTTP__MAX];
extern const char *const kschemes[KSCHEME__MAX];
extern const char *const kmethods[KMETHOD__MAX];
extern const struct kmimemap ksuffixmap[];
extern const char *const ksuffixes[KMIME__MAX];
DESCRIPTION
The
khttp_parse()
and
khttp_parsex() functions parse and validate
input and the HTTP environment (compression, paths, MIME types, and so on).
They are the central functions in the kcgi(3) library,
parsing and validating key-value form (query string, message body, cookie)
data and opaque message bodies.
They must be matched by khttp_free(3) if and
only if the return value is
KCGI_OK. Otherwise,
resources are internally freed.
The collective arguments are as follows:
- arg
- A pointer to private application data. It is not touched unless argfree is provided.
- argfree
- Function invoked with arg by the child process starting to parse untrusted network data. This makes sure that no unnecessary data is leaked into the child.
- debugging
- This bit-field enables debugging of the underlying parse and/or write routines. It may have
KREQ_DEBUG_WRITEfor writes and
KREQ_DEBUG_READ_BODYfor the pre-parsed body. Debugging messages to kutil_info(3) consist of the process ID followed by "-tx" or "-rx" for writing or reading, a colon and space, then the logged data. A newline will flush the existing line, as well reaching 80 characters. If flushed at 80 characters and not a newline, an ellipsis will follow the line. The total logged bytes will be emitted at the end of all reads or writes.
- defmime
- If no MIME type is specified (that is, there's no suffix to the page request), use this index in the mimes array.
- defpage
- If no page was specified (e.g., the default landing page), this is provided as the requested page index.
- keys
- An optional array of input and validation fields or
NULL.
- keysz
- The number of elements in keys.
- mimesz
- The number of elements in mimes. Also the MIME index used if no MIME type was matched. This differs from defmime, which is used if there is no MIME suffix at all.
- mimes
- An array of MIME types (e.g., “text/html”), mapped into a MIME index during MIME body parsing. This relates both to pages and input fields with a body type. Any array should include at least
text/plain, as this is the default content type for MIME documents.
- opts
- Tunable options regarding socket buffer sizes and so on. If set to
NULL, meaningful defaults are used.
- pages
- An array of recognised pathnames. When pathnames are parsed, they're matched to indices in this array.
- pagesz
- The number of pages in pages. Also used if the requested page was not in pages.
- req
- This structure is cleared and filled with input fields and HTTP context parsed from the CGI environment. It is the main structure carried around in a kcgi(3) application.
- suffixes
- Define the MIME type (suffix) mapping.
The first form,
khttp_parse(),
is for applications using the system-recognised MIME types. This should work
well enough for most applications. It is equivalent to invoking the second
form,
khttp_parsex(), as follows:
khttp_parsex(req, ksuffixmap, kmimetypes, KMIME__MAX, keys, keysz, pages, pagesz, KMIME_TEXT_HTML, defpage, NULL, NULL, 0, NULL);
Types
A struct kreq object is filled in by
khttp_parse() and
khttp_parsex(). It consists of the following
fields:
- void *arg
- Private application data. This is set during
khttp_parse().
- enum kauth auth
- Type of “managed” HTTP authorisation performed by the web server according to the
AUTH_TYPEheader variable, if any. This is
KAUTH_DIGESTfor the
AUTH_TYPE"digest",
KAUTH_BASICfor "basic",
KAUTH_UNKNOWNfor other values of
AUTH_TYPE, or
KAUTH_NONEif
AUTH_TYPEis not set. See the rawauth field for raw authorisation requests.
- struct kpair **cookiemap
- An array of keysz singly linked lists of elements of the cookies array. If cookie->key is equal to one of the entries of keys and cookie->state is
KPAIR_VALIDor
KPAIR_UNCHECKED, the cookie is added to the list cookiemap[cookie->keypos]. Empty lists are
NULL. If a list contains more than one cookie, cookie->next points to the next cookie. For the last cookie in a list, cookie->next is NULL.
- struct kpair **cookienmap
- Similar to cookiemap, except that it contains the cookies where cookie->state is
KPAIR_INVALID.
- struct kpair *cookies
- Key-value pairs read from request cookies found in the
HTTP_COOKIEheader variable, or
NULLif cookiesz is 0. See fields for key-value pairs from the request query string or message body.
- size_t cookiesz
- The size of the cookies array.
- struct kpair **fieldmap
- Similar to cookiemap, except that the lists contain elements of the fields array.
- struct kpair **fieldnmap
- Similar to fieldmap, except that it contains the fields where field->state is
KPAIR_INVALID.
- struct kpair *fields
- Key-value pairs read from the
QUERY_STRINGheader variable and from the message body, or
NULLif
fieldszis 0. See cookies for key-value pairs from request cookies.
- size_t fieldsz
- The number of elements in the fields array.
- char *fullpath
- The full requested path as contained in the
PATH_INFOheader variable. For example, requesting "", where "app.cgi" is the CGI program, this value would be /dir/file.html. It is not guaranteed to start with a slash and it may be an empty string.
- char *host
- The host name received in the
HTTP_HOSTheader variable. When using name-based virtual hosting, this is typically the virtual host name specified by the client in the HTTP request, and it should not be confused with the canonical DNS name of the host running the web server. For example, a request to "" would have a host of "bsd.lv". If
HTTP_HOSTis not defined, host is set to "localhost".
- struct kdata *kdata
- Internal data. Should not be touched.
- const struct kvalid *keys
- Value passed to
khttp_parse().
- size_t keysz
- Value passed to
khttp_parse().
- enum kmethod method
- The
KMETHOD_ACL,
KMETHOD_CONNECT,
KMETHOD_COPY,
KMETHOD_DELETE,
KMETHOD_GET,
KMETHOD_HEAD,
KMETHOD_LOCK,
KMETHOD_MKCALENDAR,
KMETHOD_MKCOL,
KMETHOD_MOVE,
KMETHOD_OPTIONS,
KMETHOD_POST,
KMETHOD_PROPFIND,
KMETHOD_PROPPATCH,
KMETHOD_PUT,
KMETHOD_REPORT,
KMETHOD_TRACE, or
KMETHOD_UNLOCKsubmission method obtained from the
REQUEST_METHODheader variable. If an unknown method was requested,
KMETHOD__MAXis used. If no method was specified, the default is
KMETHOD_GET.
Applications will usually accept only
KMETHOD_GETand
KMETHOD_POST, so be sure to emit a
KHTTP_405status for undesired methods.
- size_t mime
- The MIME type of the requested file as determined by its suffix matched to the mimemap map passed to
khttp_parsex() or the default kmimemap if using
khttp_parse(). This defaults to the mimesz value passed to
khttp_parsex() or the default
KMIME__MAXif using
khttp_parse() when no suffix is specified or when the suffix is specified but not known.
- size_t page
- The page index found by looking up pagename in the pages array. If pagename is not found in pages, pagesz is used; if pagename is empty, defpage is used.
- char *pagename
- The first component of fullpath or an empty string if there is none. It is compared to the elements of the pages array to determine which page it corresponds to. For example, for a fullpath of "/dir/file.html" this component corresponds to dir. For "/file.html", it's file.
- char *path
- The middle part of fullpath, after stripping pagename/ at the beginning and .suffix at the end, or an empty string if there is none. For example, if the fullpath is bar/baz.html, this component is baz.
- char *pname
- The script name received in the
SCRIPT_NAMEheader variable. For example, for a request to a CGI program /var/www/cgi-bin/app.cgi mapped by the web server from "", this would be app.cgi. This may not reflect a file system entity and it may be an empty string.
- uint16_t port
- The server's receiving TCP port according to the
SERVER_PORTheader variable, or 80 if that is not defined or an invalid number.
- struct khttpauth rawauth
- The raw authorization request according to the
HTTP_AUTHORIZATIONheader variable passed by the web server. Some web servers, for example Apache, do not set
HTTP_AUTHORIZATIONby default.
- char *remote
- The string form of the client's IPv4 or IPv6 address taken from the
REMOTE_ADDRheader variable, or "127.0.0.1" if that is not defined. The address format of the string is not checked.
- struct khead *reqmap[
KREQU__MAX]
- Mapping of enum krequ enumeration values to reqs parsed from the input stream.
- struct khead *reqs
- List of all HTTP request headers, known via enum krequ and not known, parsed from the input stream, or
NULLif reqsz is 0.
- size_t reqsz
- Number of request headers in reqs.
- enum kscheme scheme
- The access scheme according to the
HTTPSheader variable, either
KSCHEME_HTTPSif
HTTPSis set and equal to the string "on" or
KSCHEME_HTTPotherwise.
- char *suffix
- The suffix part of the last component of fullpath or an empty string if there is none. For example, if the fullpath is /bar/baz.html, this component is html. See the mime field for the MIME type parsed from the suffix.
The application may optionally define
keys provided to
khttp_parse()
and
khttp_parsex() as an array of
struct kvalid. This structure is central to the
validation of input data. It consists of the following fields:
- const char *name
- The field name, i.e., how it appears in the HTML form input name. This cannot be
NULL. If the field name is an empty string and the HTTP message consists of an opaque body (and not key-value pairs), then that field will be used to validate the HTTP message body. This is useful for
KMETHOD_PUTstyle requests.
- int (*)(struct kpair *) valid
- A validation function returning non-zero if parsing and validation succeed or 0 otherwise. If it is
NULL, then no validation is performed, the data is considered as valid, and it is bucketed into cookiemap or fieldmap as such.
User-defined valid functions usually set the type and parsed fields in the key-value pair. When working with binary data or with a key that can take different data types, it is acceptable for a validation function to set the type to
KPAIR__MAXand for the application to ignore the parsed field and to work directly with val and valsz.
The validation function is allowed to allocate new memory for val: if the val pointer changes during validation, the memory pointed to after validation will be freed with free(3) after the data is passed out of the sandbox.
These functions are invoked from within a system-specific sandbox that may not allow some system calls, for example opening files or sockets. In other words, validation functions should only do pure computation.
The struct kpair
structure presents the user with fields parsed from input and (possibly)
matched to the keys variable passed to
khttp_parse()
and
khttp_parsex(). It is also passed to the
validation function to be filled in. In this case, the MIME-related fields
are already filled in and may be examined to determine the method of
validation. This is useful when validating opaque message bodies.
- char *ctype
- The value's MIME content type (e.g.,
image/jpeg), or an empty string if not defined.
- size_t ctypepos
- If ctype is not
NULL, it is looked up in the mimes parameter passed to
khttp_parsex() or ksuffixmap if using
khttp_parse(). If found, it is set to the appropriate index. Otherwise, it's mimesz.
- char *file
- The value's MIME source filename or an empty string if not defined.
- char *key
- The NUL-terminated key (input) name. If the HTTP message body is opaque (e.g.,
KMETHOD_PUT), then an empty-string key is cooked up. The key may contain an arbitrary sequence of non-NUL bytes, even non-ASCII bytes, control characters, and shell metacharacters.
- size_t keypos
- If found in the keys array passed to
khttp_parse(), the index of the matching key. Otherwise keysz.
- struct kpair *next
- In a cookie or field map, next points to the next parsed key-value pair with the same key name. This occurs most often in HTML checkbox forms, where many fields may have the same name.
- union parsed parsed
- The parsed, validated value. These may be integer in i, for a 64-bit signed integer; a string s, for a NUL-termianted character string; or a double d, for a double-precision floating-point number. This is intentionally basic because the resulting data must be reliably passed from the parsing context back into the web application.
- enum kpairstate state
- The validation state:
KPAIR_VALIDif the pair was successfully validated by a validation function,
KPAIR_INVALIDif a validation function was invoked but failed, or
KPAIR_UNCHECKEDif no validation function is defined for this key.
- enum kpairtype type
- If parsed, the type of data in parsed, otherwise
KFIELD__MAX.
- char *val
- The (input) value, which may contain an arbitrary sequence of bytes, even NUL bytes, non-ASCII bytes, control characters, and shell metacharacters. The byte following the end of the array, val[valsz], is always guaranteed to be NUL. The validation function may modify the contents. For example, for integer numbers and e-mail adresses, trailing whitespace may be replaced with NUL bytes.
- size_t valsz
- The length of the val buffer in bytes. It is not a string length.
- char *xcode
- The value's MIME content transfer encoding (e.g.,
base64), or an empty string if not defined.
The struct khttpauth structure holds authorisation data if passed by the server. The specific fields are as follows.
- enum kauth type
- If no data was passed by the server, the type value is
KAUTH_NONE. Otherwise it's
KAUTH_BASICor
KAUTH_DIGEST, with
KAUTH_UNKNOWNif the authorisation type was not recognised.
- int authorised
- For
KAUTH_BASICor
KAUTH_DIGESTauthorisation, this field indicates whether all required values were specified.
- char *digest
- An MD5 digest of
REQUEST_METHOD,
SCRIPT_NAME,
PATH_INFO, header variables and the request body. It is not a NUL-terminated string, but an array of exactly
MD5_DIGEST_LENGTHbytes. Only filled in when
HTTP_AUTHORIZATIONis "digest" and authorised is non-zero. Otherwise, it remains
NULL. Used in khttpdigest_validatehash(3).
- d
- An anonymous union containing parsed fields per type: struct khttpbasic basic for
KAUTH_BASICor struct khttpdigest digest for
KAUTH_DIGEST.
If the field for an HTTP authorisation request is
KAUTH_BASIC, it will consist of the following for
its parsed entities in its struct khttpbasic
structure:
- response
- The hashed and encoded response string.
If the field for an HTTP authorisation request is
KAUTH_DIGEST, it will consist of the following in
its struct khttpdigest structure:
- alg
- The encoding algorithm, parsed from the possible
MD5or
MD5-Sessvalues.
- qop
- The quality of protection algorithm, which may be unspecified,
Author
Auth-Init.
- user
- The user coordinating the request.
- uri
- The URI for which the request is designated. (This must match the request URI).
- realm
- The request realm.
- nonce
- The server-generated nonce value.
- cnonce
- The (optional) client-generated nonce value.
- response
- The hashed and encoded response string, which entangled fields depending on algorithm and quality of protection.
- count
- The (optional) cnonce counter.
- opaque
- The (optional) opaque string requested by the server.
The struct kopts structure consists of tunables for network performance. You probably don't want to use these unless you really know what you're doing!
- sndbufsz
- The size of the output buffer. The output buffer is a heap-allocated region into which writes (via khttp_write(3) and khttp_head(3)) are buffered instead of being flushed directly to the wire. The buffer is flushed when it is full, when the HTTP headers are flushed, and when khttp_free(3) is invoked. If the buffer size is zero, writes are flushed immediately to the wire. If the buffer size is less than zero, it is filled with a meaningful default.
Lastly, the struct khead structure holds parsed HTTP headers.
- key
- Holds the HTTP header name. This is not the CGI header name (e.g.,
HTTP_COOKIE), but the reconstituted HTTP name (e.g.,
Coookie).
- val
- The opaque header value, which may be an empty string.
Variables
A number of variables are defined
<kcgi.h> to simplify
invocations of the
khttp_parse()
family. Applications are strongly suggested to use these variables (and
associated enumerations) in
khttp_parse() instead of
overriding them with hand-rolled sets in
khttp_parsex().
- kmimetypes
- Indexed list of common MIME types, for example, “text/html” and “application/json”. Corresponds to enum kmime enum khttp.
- khttps
- Indexed list of HTTP status code and identifier, for example, “200 OK”. Corresponds to enum khttp.
- kschemes
- Indexed list of URL schemes, for example, “https” or “ftp”. Corresponds to enum kscheme.
- kmethods
- Indexed list of HTTP methods, for example, “GET” and “POST”. Corresponds to enum kmethod.
- ksuffixmap
- Map of MIME types defined in enum kmime to possible suffixes. This array is terminated with a MIME type of
KMIME__MAXand name
NULL.
- ksuffixes
- Indexed list of canonical suffixes for MIME types corresponding to enum kmime. This may be a
NULLpointer for types that have no canonical suffix, for example. “application/octet-stream”.
RETURN VALUES
khttp_parse() and
khttp_parsex() return an error code:
KCGI_OK
- Success (not an error).
KCGI_ENOMEM
- Memory failure. This can occur in many places: spawning a child, allocating memory, creating sockets, etc.
KCGI_ENFILE
- Could not allocate file descriptors.
KCGI_EAGAIN
- Could not spawn a child.
KCGI_FORM
- Malformed data between parent and child whilst parsing an HTTP request. (Internal system error.)
KCGI_SYSTEM
- Opaque operating system error.
On failure, the calling application should terminate as soon as possible. Applications should not try to write an HTTP 505 error or similar, but allow the web server to handle the empty CGI response on its own.
SEE ALSO
AUTHORS
The
khttp_parse() and
khttp_parsex() functions were written by
Kristaps Dzonsons
<kristaps@bsd.lv>.
|
https://kristaps.bsd.lv/kcgi/khttp_parse.3.html
|
CC-MAIN-2021-21
|
refinedweb
| 2,950
| 66.44
|
A torque than the other stepper motors like NEMA 14, NEMA17.
In this tutorial, we are going to control NEMA17 stepper motor using Arduino Uno and A4988 stepper driver module. Nema17 stepper motor has higher torque and higher operating voltage than 28-BYJ48. Here a potentiometer will also be attached to control the direction of stepper motor.
Component Required
- Arduino UNO
- NEMA17 Stepper Motor
- A4988 Stepper Driver Module
- 47 µf Capacitor
- Potentiometer
NEMA17 Stepper Motor.
As you can see that this motor has a Unipolar six-wire arrangement. These wire are connected in two split windings. Black, Yellow, Green wires are part of first winding where Black is center tap, and Yellow and Green are coil end while Red, White, and Blue is part of a second winding, in which White is center tap and Red and Blue are coil end wires. Normally center tap wires left disconnected.
Steps Per Revolution for NEMA17
Steps Per Revolution for a particular stepper motor is calculated using the step angle of that stepper motor. So in the case, NEMA 17 step angle is 1.8 deg.
Steps per Revolution = 360/ step angle 360/1.8 = 200 Steps Per Revolution
Specifications of NEMA17
- Rated Voltage: 12V DC
- Step Angle: 1.8 deg.
- No. of Phases: 4
- Motor Length: 1.54 inches
- 4-wire, 8-inch lead
- 200 steps per revolution, 1.8 degrees
- Operating Temperature: -10 to 40 °C
- Unipolar Holding Torque: 22.2 oz-in
Also check various stepper motor related projects here, which not only incudes basic interfacing with various microcontrollers but also have robotics projects which involves stepper motor.
A4988 Stepper Driver Module
A stepper driver module controls the working of a stepper motor. Stepper drivers send the current to stepper motor through various phases.
The A4988 Nema 17 stepper driver is a microstepping driver module that is used to control bipolar stepper motors. This driver module has a built-in translator that means that we can control the stepper motor using very few pins from our controller.
Using this Nema 17 motor driver module, we can control stepper motor by using only two pins, i.e., STEP and DIRECTION. STEP pin is used to control the steps while DIRECTION pin is used to control the direction of the motor. A4988 driver module provides five different step resolutions: full-step, haft-step, quarter-step, eight-step, and sixteenth-step. You can select the different step resolutions using the resolution selector pins ((MS1, MS2, and MS3). The truth table for these pins is given below:
Specifications of A4988)
Circuit Diagram
Circuit diagram to control Nema.
Code Explanation
Complete code with working video. As we calculated,(1000);
Now in the main loop, we will read the potentiometer value from A0 pin. In this loop, there are two functions one is potVal, and the other is Pval. If the current value, i.e., potVal is higher than the previous value, i.e., Pval Nema17 stepper motor using the potentiometer. The complete working of the project is shown in the video below. If you have any doubts regarding this project, post them in the comment section below.
#include <Stepper.h>
#define STEPS 200
// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver
Stepper stepper(STEPS, 2, 3); // Pin 2 connected to DIRECTION & Pin 3 connected to STEP Pin of Driver
#define motorInterfaceType 1
int Pval = 0;
int potVal = 0;
void setup() {
// Set the maximum speed in steps per second:
stepper.setSpeed(1000);
}
void loop() {
potVal = map(analogRead(A0),0,1024,0,500);
if (potVal>Pval)
stepper.step(10);
if (potVal<Pval)
stepper.step(-10);
Pval = potVal;
}
|
https://circuitdigest.com/microcontroller-projects/controlling-nema-17-stepper-motor-with-arduino-and-a4988-stepper-driver-module
|
CC-MAIN-2020-05
|
refinedweb
| 612
| 56.86
|
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
A very (very) basic scheme interpreter. Originally adapted from Peter Norvig's tutorial, have used the BiwaScheme Interpreter found at repl.it as my reference implementation.
lis.py> (define fact (lambda (n) (if (<= n 1) 1 (* n (fact (- n 1)))))) lis.py> (fact 2) 2 lis.py> (fact 8) 40320 lis.py> (define a 4) lis.py> (* a (+ a (* a a))) 80 lis.py>
Example Usage
Currently there are two ways to interact with pyscheme.
Command Line
The first is via the command line interpreter "lis.py":
pyscheme$ python lis.py lis.py>
An extremely sophisticated Ctr-D or Ctr-C exit mechanism has been implemented ;-)
File evaluation
For evaluating lisp files just pass the filename as an argument:
pyscheme$ python lis.py lisp/cond.s "pass"
Testing
The tests document the features I've implemented and can be run with:
pyscheme$ python -m test.test_lib
Wish List
- Add unit tests that execute a more complex lisp program.
- Implement verbosity command line flag
- Fix my parser to deal with "multi part strings"
- Implement "let"
- Implement the define-syntax
- Proper tear down for each test that resets the namespace and flushes stdout and stdin.
- ...get the interpreter through the PyPy translator.
Versions
During development I've been using Python2.7 and PyPy 1.9.
|
https://bitbucket.org/hardbyte/pyscheme
|
CC-MAIN-2017-26
|
refinedweb
| 236
| 69.07
|
Apache OpenOffice (AOO) Bugzilla – Issue 103295
Date conversion Error while pasting dates in MM/DD/YYYY format
Last modified: 2013-01-29 21:50:02 UTC
While pasting dates in the DD/MM/YYYY format into a new calc spreadsheet, the
dates in the first 12 rows get automatically converted to MM/DD/YY, but the from
13th row onwards, neither the dates convert automatically nor do they convert
even on applying specific formatting on them:
Sample Inputs dates:
01/06/2009
02/06/2009
03/06/2009
04/06/2009
05/06/2009
06/06/2009
07/06/2009
08/06/2009
09/06/2009
10/06/2009
11/06/2009
12/06/2009
13/06/2009
14/06/2009
15/06/2009
16/06/2009
Erroneous Output:
01/06/09
02/06/09
03/06/09
04/06/09
05/06/09
06/06/09
07/06/09
08/06/09
09/06/09
10/06/09
11/06/09
12/06/09
13/06/2009
14/06/2009
15/06/2009
16/06/2009
I can not confirm this, wether on Win XP nor on Linux
Have you formated the cells A13 to A16 ?
set Prio to P3, see
set to invalid
if the intention of closing the issue is to show off that it was 'resolved' in a
record time, then I have no problem with that. But then do not expect that
OpenOffice will ever be treated a good quality product, and users like me will
be discouraged to further report (and help) issues !!
I already mentioned, that I even tried to apply formatting of different kind and
there wasn't any effect of that on the row no. 13 and below.
I can confirm the effect, but it may not be a defect. It is caused on my system
by the English(US)language or locale setting. Anything greater than 12 in the
month slot is not recognized as a date. Therefore that data with a month
greater than 12 is pasted as text. If one changes the locale to English(UK)
(DD/MM/YY), the pasted data is correctly recognized as a date.
TomW
OOO310m11 & OOO2.4.1 on Vista SP2
I would still consider it a defect, since OOO is incorrectly assuming it to be a
month in first place, than a date.
If the locale is set to EN(US), it shouldn't be that one has to paste the dates
always in MM/DD/YYYY format.
Secondly, even if OOO assumes that the date is in MM/DD/YYYY format, it should
at least allow the formatting to be change when someone manually attempts to
change it. Even that isn't happening here.
Third, if locale was to control that you put the date always in one particular
format, then how has MS Excel or Sun's Soffice got it right ? This problem
doesn't occur in soffice or MS Excel.
I just created a Excel workbook that shows the same handling of the date,
whether copy/paste or typed in.
Will attached Excel file.
TomW
000310m11 on Vista SP2 and Excel 2003 on XP SP2.
Created attachment 63364 [details]
Excel 2003 sheet with Date Example
I only testet it, with the german localisation.
It may be a duplicate to issue 103213.
If it is, please send me a message
For me it's not a defect. As far as I know, the formatting of the cell does not
decide whether a string that seems to be a date must be interpreted as a date.
@viren297 : in which case do you encounter this problem ? When you copy/paste
from the web ?
I think you have a workaround : paste your text to a plain text document in a
text editor, copy the result and paste it in your speadsheet. Now Calc open an
import dialog which allows you to choose the date format of your data.
I tested this procedure under Ubuntu with gedit as text editor.
@tomwb: I have tested it in Excel 2007, and this problem does surface. If you
require I can attach the sheet. And it doesn't occur in Soffice either.
@wope: I am not sure if issue 103213 and this, are one and the same.
@jbfaure: I have tried all, i.e. writing into spreadsheet, copying from a text
editor, and pasting in html format etc. etc. All show the same results.
As far as using a workaround is concerned, well, people need a work around, when
there is an issue / defect / problem with the usual functioning of the
application, which again confirms that this indeed is a defect.
Also, as I said earlier, leave alone auto-formatting not sensing the date format
correctly, its also about manual formatting not working either !!
Do you still prefer not to consider it a defect ? If so, please go ahead and
mark it as "Not A Defect" and feel happy about it. But, I must say that, focus
is more here on "closing" the issue than "resolving" it, and this way products
don't improve.
thanks.
Viren
|
https://bz.apache.org/ooo/show_bug.cgi?id=103295
|
CC-MAIN-2021-21
|
refinedweb
| 849
| 69.82
|
Release Notes¶
NumPy 1.12.0 Release Notes¶
This release supports Python 2.7 and 3.4 - 3.5.
Future Changes¶
- In 1.13 NAT will always compare False except for NAT != NAT, which will be True. In short, NAT will behave like NaN.
Relaxed stride checking is the default¶
This will have some impact on code that assumed that F_CONTIGUOUS and C_CONTIGUOUS were mutually exclusive and could be set to determine the default order for arrays that are now both.
np.percentile ‘midpoint’ interpolation method fixed for exact indices¶.
FutureWarning to changed behavior¶
- np.full now returns an array of the fill-value’s dtype if no dtype is given, instead of defaulting to float.
New Features¶
Writeable keyword argument for as_strided¶
np.lib.stride_tricks.as_strided now has a writeable keyword argument. It can be set to False when no write operation to the returned array is expected to avoid accidental unpredictable writes.
Generalized flip¶
flipud and fliplr reverse the elements of an array along axis=0 and axis=1 respectively. The newly added flip function reverses the elements of an array along any given axis.functions nancumsum and nancumprod have been added to compute cumsum and cumprod by ignoring nans.
Improvements.
np.roll can now roll multiple axes at the same time¶
The shift and axis arguments to roll are now broadcast against each other, and each specified axis is shifted accordingly.
The __complex__ method has been implemented on the ndarray object¶
Calling complex() on a size 1 array will now cast to a python complex.aped. Version 1.12 returns ordinary numpy arrays from these operations.
Also, reduction of a memmap (e.g. .sum(axis=None) now returns a numpy scalar instead of a 0d memmap. for reordering array axes.
Build System Changes¶
- Numpy now uses setuptools for its builds instead of plain distutils. This fixes usage of install_requires='numpy' in the setup.py files function exposed in numpy.testing will be removed. That function is left over from early Numpy and was implemented using the Python random module. The random number generators from numpy.random should be used instead.
- The ndarray.view method will an empty array in the result always had dimension (0,) no matter the dimensions of the array being split. This has been changed so that the dimensions will be preserved. A FutureWarning for now that can check exactly whether two arrays have memory overlap is added. np.may_share_memory also now has an option to spend more effort to reduce false positives.
SkipTest and KnownFailureException exception classes are exposed in the numpy.testing namespace. Raise them in a test function to mark the test to be skipped or mark it as a known failure, respectively.
f2py.compile has a new extension keyword parameter that allows the fortran extension to be specified for generated temp files. For instance, the files can be specifies to be *.f90. The verbose argument is also activated, it was previously ignored.
A dtype parameter has been added to np.random.randint Random may be a long instead of long long even if the specified dtype is long long because the two may have the same precision. The resulting type depends on which C type numpy uses for the given precision. The byteorder specification is also ignored, the generated arrays are always in native byte order.
A new np.moveaxis function allows for moving one or more array axes to a new position by explicitly providing source and destination axes. This function should be easier to use than the current rollaxis function as well as providing more functionality.
The deg parameter of the various numpy.polynomial fits has been extended to accept a list of the degrees of the terms to be included in the fit, the coefficients of all other terms being constrained to zero. The change is backward compatible, passing a scalar deg will consistancy, and missing removed from np.genfromtxt.
- Keyword old_behavior removed from np.correlate.
Future Changes¶
- In array comparisons like arr1 == arr2, many corner cases involving strings or structured dtypes that used to return scalars now issue FutureWarning or DeprecationWarning, and in the future will be change to either perform elementwise comparisons or raise an error.
- In np.lib.split an empty array in the result always had dimension (0,) no matter the dimensions of the array being split. In Numpy 1.11 that behavior will be changed so that the dimensions will be preserved. A FutureWarning for.
|
http://docs.scipy.org/doc/numpy-dev/release.html
|
CC-MAIN-2016-30
|
refinedweb
| 743
| 58.48
|
WHAT’S IN THIS TOPIC ?
Scripting is the Swiss Army knife of SSIS. As shown in Creating an End-to-End Package Topic, many different SSIS features are available out-of-the-box. If you need to do something that you just can’t find anywhere else, you will find additional functionality in three features: the Script Task, the Script Component, and expressions. Expressions, covered in Using Variables, Parameters, and Expressions Topic, are small scripts that set properties. The other two scripting concepts provide access into a scripting development environment using Microsoft Visual Studio Tools for Applications (VSTA) that enables SSIS developers to script logic into packages using Microsoft Visual Basic 2012 or Microsoft Visual C# 2012 .NET code.
In this Topic ,.
Introduction
If you think of scripting as something that compiles at runtime and contains unstructured or unmanaged coding languages, then scripting in SSIS does not conform to your idea of scripting. Conversely, if you think of scripting as using small bits of code in specialized places to execute specific tasks, then SSIS scripting won’t be an alien concept. It is helpful to understand why scripting is separated according to functional usage. In this Topic , you will examine the differences and look into the scripting IDE environment, walking through the mechanics of applying programmatic logic into these components — including how to add your own classes and compiled assemblies.
ETL developers have had creative ways of handling logic in their packages. Specifically, digging into what developers were doing, the functional activities can be divided into the following categories:
Retrieving and setting the value of variables and package properties is so prevalent an activity that the SSIS team creates a completely separate feature that enabled this to be less of a programmatic task. Using the Expression Builder, you can easily alter package components by setting component properties to an expression or a variable that represents an expression.
NOTE Refer to Using Variables, Parameters, and Expressions Topic for detailed information about how to use expressions, parameters, and variables.
To modify properties that connect to, manipulate, or define data, you can use the Data Flow Task to visually represent this activity. However, to achieve functionality not provided out of the box, you still need scripting, so the Script Component was added. The primary role of the Script Component is to extend the Data Flow capabilities and allow programmatic data manipulation within the context of the Data Flow. However, it can do more, as you’ll learn later in this Topic.
To continue to enable the numerous miscellaneous tasks that are needed in ETL development, use the Script Task, which can be used only in the Control Flow design surface. In this task, you can perform various manipulations within the managed code framework of .NET.
The Script Task and Script Component use the Visual Studio Tools for Applications (VSTA) environment. VSTA is essentially a scaled-down version of Visual Studio that can be added to an application that allows coding extensions using managed code and .NET languages. Even though SSIS packages are built inside of Visual Studio, when you are in the context of a Script Task or Script Component, you are actually coding in the VSTA environment that is, in fact, a mini-project within the package. The VSTA IDE provides IntelliSense, full edit-and-continue capabilities, and the ability to code in either Visual Basic or C#. You can even access some of the .NET assemblies and use web references for advanced scripting.
NOTE To gain the most from this scripting Topic , you need a basic understanding of programming in either C# or Visual Basic. If you don’t already have it, you can obtain this knowledge from either Beginning Visual C# 2012 Programming by Karli Watson and colleagues (Wrox; ISBN: 978-1-118-31441-8) or Beginning Visual Basic 2012 by Bryan Newsome (Wrox; ISBN: 978-1-118-31181-3).
Getting Started In SSIS Scripting
The Script Task and Script Component have greatly increased your possibilities when it comes to script-based ETL development in SSIS. However, it is important to know when to use which component and what things can be done in each.
The following matrix explains when to use each component:
To get a good look at the scripting model, the next example walks through a simple “Hello World” coding project in SSIS. Although this is not a typical example of ETL programming, it serves as a good introduction to the scripting paradigm in SSIS, followed by the specific applications of the Script Task and Script Component.
Selecting the Scripting Language
SSIS allows the developer to choose between two different scripting languages: C# or Visual Basic (VB). To see where you can make this choice, drop a Script Task onto the Control Flow design surface. Right-click the Script Task and click Edit from the context menu. The first thing you’ll notice is the availability of two scripting languages: Microsoft Visual C# 2012 and Microsoft Visual Basic 2012 in the ScriptLanguage property of the task. below screen shot shows these options in the Script Task Editor.
After clicking the Edit Script button, you’ll be locked into the script language that you chose and you won’t be able to change it without deleting and recreating the Script Task or Script Component. This is because each Script item contains its own internal Visual Studio project in VB or C#. You can create separate Script items whereby each one uses a different language within a package. However, using Script items in both languages within the same package is not recommended, as it makes maintenance of the package more complex. Anyone maintaining the package would have to be competent in both languages.
Using the VSTA Scripting IDE
Clicking the Edit Script button on the editor allows you to add programmatic code to a Script Task or Script Component. Although the Script Task and Script Component editors look different, they both provide an Edit Script button to access the development IDE for scripting, as shown in below screen shot
Once you are in the IDE, notice that it looks and feels just like Visual Studio. below screen shot shows an example of how this IDE looks after opening the Script Task for the VB scripting language.
The code window on the left side of the IDE contains the code for the item selected in the Solution Explorer on the top-right window. The Solution Explorer shows the structure for the project that is being used within the Scripting Task. A complete .NET project is created for each Script Task or Component and is temporarily written to a project file on the local drive where it can be altered in the Visual Studio IDE. This persistence of the project is the reason why once you pick a scripting language, and generate code in the project, you are locked into that language for that Scripting item. Notice in above the screenshot that a project has been created with the namespace of ST_a8363e166ca246a3bedda7. However, you can’t open this project directly, nor need you worry about the project during deployment. These project files are extracted from stored package metadata. With the project created and opened, it is ready for coding.
Example: Hello World
In the IDE, the Script Task contains only a class named ScriptMain. In the entry-point function, Main(), you’ll put the code that you want executed. Part of that code can make calls to additional functions or classes. However, if you want to change the name of the entry-point function for some reason, type the new name in the property called EntryPoint on the Script page of the editor. (Alternatively, you could change the name of the entry point at runtime using an expression.)
In the VSTA co-generated class ScriptMain, you’ll also see a set of assembly references already added to your project, and namespaces set up in the class. Depending upon whether you chose VB or C# as your scripting language, you’ll see either.
These assemblies are needed to provide base functionality as a jump-start to your coding. The remainder of the class includes VSTA co-generated methods for startup and shutdown operations, and finally the entry-point Main() function, shown here in both languages.
Note that the Script Task must return a result to notify the runtime of whether the script completed successfully or not. The result is passed using the Dts.TaskResult property. By your setting the result to ScriptResults.Success, the script informs the package that the task completed successfully.
NOTE The Script Component does not have to do this, since it runs in the context of a Data Flow with many rows. Other differences pertaining to each component are discussed separately later in the topic.
Frequently Asked SSIS Interview Questions & Answers
To get a message box to pop up with the phrase “Hello World!” you need access to a class called MessageBox in a namespace called System.Windows.Forms. This namespace can be called directly by its complete name, or it can be added after the Microsoft.SqlServer.Dts.Runtime namespace to shorten the coding required in the class. Both of these methods are shown in the following code.
to insert the MessageBox code into the Main() function.
Get in the habit now of building the project after adding this code. The Build option is directly on the menu when you are coding. Previous versions of SSIS gave you the opportunity to run in precompile or compiled modes. SSIS now will automatically compile your code prior to executing the package at runtime. Compiling gives you an opportunity to find any errors before the package finds them. Once the build is successful, close the IDE and the editor, and right-click and execute the Script Task. A pop-up message box should appear with the words “Hello World!” (see below the screen shot).
Adding Code and Classes
Using modal message boxes is obviously not the type of typical coding desired in production SSIS package development. Message boxes are synchronous and block until a click event is received, so they can stop a production job dead in its tracks. However, this is a basic debugging technique to demonstrate the capabilities in the scripting environments before getting into some of the details of passing values in and out using variables. You also don’t want to always put the main blocks of code in the Main() function. With just a little more work, you can get some code reuse from previously written code using some cut-and-paste development techniques. At the very least, code can be structured in a less procedural way. As an example, consider the common task of generating a unique filename for a file you want to archive.
Typically, the filename might be generated by appending a prefix and an extension to a variable like a guid. These functions can be added within the ScriptMain class bodies to look like this
Instead of all the code residing in the Main() function, structured programming techniques can separate and organize SSIS scripting. In this example, the GetFileName function builds the filename and then returns the value, which is shown in a message box, as shown in below screen shot.
Of course, copying and pasting the same code into multiple Script Tasks is pretty inefficient and produces solutions that are difficult to maintain. If you have preexisting compiled code, shouldn’t you be able to reuse this code without finding the original source for the copy-and-paste operation? What a great question! You can, with some caveats.
Using Managed Assemblies
Reusing code, no matter what language it was written in, increases the maintainability and supportability of an application. While you can only write SSIS scripts using Visual Basic and C#, SSIS provides the capability to reuse code by reusing assemblies that are part of the .NET Framework or any assembly created using a .NET-compliant language, including C#, J#, and even Delphi, but there are some important qualifications:
If you think about this it makes sense, but within SSIS, it might seem confusing at first. On the one hand, a subproject is created for the Script Task, but it is deployed as part of the metadata of the package; there is no separate physical DLL file for the assembly. In this case, you don’t have to worry about deployment of individual script projects. However, when you use an external assembly, it is not part of the package metadata, and here you do have to worry about deployment of the assembly. Where then do you deploy the assembly you want to use? Because SSIS packages are typically deployed within SQL Server, the most universal place to find the assembly would be in the GAC.
If you are using any of the standard .NET assemblies, they are already loaded and stored in the GAC and the .NET Framework folders. As long as you are using the same framework for your development and production locations, using standard .NET assemblies requires no additional work in your environment. To use a standard .NET assembly in your script, you must reference it. To add a reference in a scripting project, open the VSTA environment for editing your script code — not the SSIS package itself. Right- click the project name in the Solution Explorer or go to the Project menu and select the Add Reference option. The new Reference Manager dialog will appear, as in below screen shot.
Select the assemblies from the list that you wish to reference and click the OK button to add the references to your project. Now you can use any objects located in the referenced assemblies either by directly referencing the full assembly or by adding the namespaces to your ScriptMain classes for shorter references, similar to the Windows Forms assembly used in the Hello World example. References can be removed from the project References screen. Find this screen by double-clicking the My Project node of the Solution Explorer. Select the References menu to see all references included in your project. To remove a reference, select the name and click the Delete key.
Example: Using Custom .NET Assemblies
Although using standard .NET assemblies is interesting, being able to use your own compiled .NET assemblies really extends the capabilities of your SSIS development. Using code already developed and compiled means not having to copy-and-paste code into each Script Task, enabling you to reuse code already developed and tested. To examine how this works, in this section you’ll create an external custom .NET library that can validate a postal code and learn how to integrate this simple validator into a Script Task. (To do this, you need the standard class library project templates that are part of Visual Studio. If you installed only SQL Server Data Tools, these templates are not installed by default.) You can also download the precompiled versions of these classes.
To start, open a standard class library project in the language of your choice, and create a standard utility class in the project that looks something like his
Because you are creating projects for both languages, the projects (and assemblies) are named SSISUtilityLib_VB and SSISUtilityLib_Csharp. Notice the use of static or shared methods. This isn’t required, but it’s useful because you are simulating the development of what could later be a utility library loaded with many stateless data validation functions. A static or shared method allows the utility functions to be called without instantiating the class for each evaluation.
Now sign the assembly by right-clicking the project to access the Properties menu option. In the Signing tab, note the option to “Sign the assembly,” as shown in below screen shot. Click New on the dropdown and name the assembly to have a strong name key added to it.
In this example, the VB version of the SSISUtilityLib project is being signed. Now you can compile the assembly by clicking the Build option in the Visual Studio menu. The in-process DLL will be built with a strong name, enabling it to be registered in the GAC.
On the target development machine, open a command-line prompt window to register your assembly with a command similar to this:
NOTE Note that you may have to run the command line as administrator or have the User Access Control feature turned off to register the assembly.
If you are running on a development machine, you also need to copy the assembly into the appropriate .NET Framework directory so that you can use the assembly in the Visual Studio IDE. Using the Microsoft .NET Framework Configuration tool, select Manage the Assembly Cache. Then select Add an Assembly to the Assembly Cache to copy an assembly file into the global cache.
NOTE For a detailed step-by-step guide to the deployment, see the SSIS Developer’s Guide on Custom Objects located at.
To use the compiled assembly in an SSIS package, open a new SSIS package and add a new Script Task to the Control Flow surface. Select the scripting language you wish and click Edit Script. You’ll need to right-click the Solution Explorer node for references and find the reference for SSISUtilityLib_VB.dll or SSISUtilityLib_CSharp.dll depending on which one you built. If you have registered the assembly in the GAC, you can find it in the .NET tab. If you are in a development environment, you can simply browse to the .dll to select it.
Add the namespace into the ScriptMain class. Then add these namespaces to the ScriptMain class:
Note that the SSIS C# Script Task in the sample packages you’ll see if you download the Topic materials from use both the C# and the VB versions of the utility library. However, this is not required. The compiled .NET class libraries may be intermixed within the SSIS Script Task or Components regardless of the scripting language you choose.
Now you just need to code a call to the utility function in the Main() function like this Compile the Script Task and execute it. The result should be a message box displaying a string to validate the postal code 12345-1111. The postal code format is validated by the DataUtility function IsValidUSPostalCode. There was no need to copy the function in the script project. The logic of validating the format of a U.S. postal code is stored in the shared DataUtility functionand can easily be used in both Script Tasks and Components with minimal coding and maximum consistency. The only downside to this is that there is now an external dependency in the SSIS package upon this assembly. If the assembly changes version numbers, you’ll need to open and recompile all the script projects for each SSIS package using this. Otherwise, you could get an error if you aren’t following backward compatibility guidelines to ensure that existing interfaces are not broken. If you have a set of well-tested business functions that rarely change, using external assemblies may be a good idea for your SSIS
|
https://mindmajix.com/ssis/scripting-in-ssis
|
CC-MAIN-2022-40
|
refinedweb
| 3,189
| 61.46
|
The short answer is 80 bytes.
Here’s the longer answer:
In Python, you can determine the size of any object
x by using the function
sys.getsizeof(x).
The complex number consists of two parts: the real and the imaginary part.
On my notebook, a complex number is represented by 32 bytes:
import sys a = complex(1, 1) print(sys.getsizeof(a)) # 32 b = complex(9**150, 9**150) print(sys.getsizeof(b)) # 32
Note that the
sys.getsizeof() method only returns the number of bytes the object is directly accountable for. It does not return the size of the objects to which a container object points in memory. Hence, the method is not suitable to calculate the size of container types.
As it turns out, a complex number is a container type: it contains two floats (the real and the imaginary part). Each float has 24 bytes:
b = complex(8**10, 9**150) print(sys.getsizeof(b)) # 32 print(sys.getsizeof(b.imag)) # 24 print(sys.getsizeof(b.real)) # 24
Therefore, I would argue that a complex number needs 32 bytes for the complex number object itself and 2*24 bytes for the real and imaginary parts (float type). In total, a complex number needs 80 bytes in memory.
|
https://blog.finxter.com/how-many-bytes-does-a-complex-number-have-in-python/
|
CC-MAIN-2020-34
|
refinedweb
| 211
| 67.65
|
Knockout.js is a Java Script library used for creating MVVM model. Using this model, you can segregate the user interface html from the rest of the code. This will be useful if your user interface changes often.
Twitter Bootstrap is a popular user interface framework. I’ve several other articles about using Bootstrap with ASP.NET. But, in this article, I’ve combined Knockout and Bootstrap with ASP.NET MVC with Razor view engine, to create a website with MVVM architecture.
This will be a simple sample website with a single table with two views. This step by step sample creation will be helpful, especially for the beginners who are trying to create their first application with Knockout, Bootstrap and MVC.
For convenience, I’ve split this article into two parts.
Part 1: In part 1 of this article, you will create solution with database and create the controller and the views using entity framework. Then you will implement bootstrap user interface framework.
Part 2: In part 2, you will implement the MVVM using Knockout.JS.
Let’s start our sample with Knockout.js and Bootstrap with ASP.NET MVC.
Tools and Technologies Used:
- Visual Studio Express 2012 for Web.
- SQL Server Compact 4.0 Local Database.
- ASP.NET MVC 4.
- Razor View Engine.
- Entity Framework 5.
- Knockout.js v2.2.0.
- JQuery v1.9.1.
- Bootstrap UI Framework v2.3.2 from NuGet.
- Bootstrap fluid layout from here.
Sample Source Code:
The sample source code generated from this article is available in GitHub.
Creating the Project and the Solution:
- Launch Visual Studio Express 2012 for Web or any edition of Visual Studio 2012.
- Go to File menu and select New Project…
- Create a new ASP.NET MVC 4 Web Application project.
- Select Basic project template.
- Once the project and the solution are created, check the scripts folder under the project. You will see jQuery and Knockout js files already available. As we have selected basic template, several NuGet packages needed for a basic website is already added to the solution.
- Go to Solution Explorer –> right-click the solution and select Manage NuGet Packages.
- In the Manage NuGet Packages screen, select Online from the left panel, Then NuGet official Package source underneath and search for Bootstrap.
- From the search result list in the center panel, select Bootstrap (version 2.3.2 or higher).
- Click the Install button to install Bootstrap.
- Now the solution is ready to start the coding.
Creating local Database and the Table:
- In the solution explorer, right-click the folder App_Data and add an SQL Server Compact 4.0 Local Database.
- Enter the name of the database in the pop-up screen.
- Right click the newly created database and select Open to open the Database Explorer.
- In the database explorer right-click the Tables folder and select Create Table.
- In the New Table window, enter the table name and add the columns. Add the constraints needed. For this example, I’ve created a table called MTB_Articles. There are 4 columns. The primary key column id is an identity column. The remaining columns are nvarchar.
- Add the database connection details to the web.config file.
<add name="MyTecBitsDBContext" connectionString="Data Source=|DataDirectory|\MyTecBitsDB.sdf" providerName="System.Data.SqlServerCe.4.0"/>
Creating a Model:
- In the solution explorer, right-click the Models folder; select Add and then New item….
- In the Add New Item screen select Class.
- Enter the Name of the class as MTB_Article.cs. Then click Add.
- In the newly created model file, replace the existing code with the below code.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace MyTecBits_Knockout_Bootstrap_MVC_Sample.Models { public class MTB_Article { public int id { get; set; } public string Title { get; set; } public string Excerpts { get; set; } public string Content { get; set; } } public class MyTecBitsDBContext : DbContext { public DbSet<mtb_article> MyTecBitsDB { get; set; } } }
- Rebuild the solution.
Creating a Controller and the Views:
Now, we’ll create a controller for the model and the related view files using entity framework.
- In the solution explorer, right-click the Controllers folder.
- Select Add and then Controller….
- In the Add Controller scree, change the name of the controller to MTB_ArticlesController.
- In the Scaffolding options, select the template MVC controller with empty read/write actions and views, using Entity Framework.
- Select the model class MTB_Article.
- Select the data context class MyTecBitsDBContext.
- Leave the views as Razor.
- Click Add. This will create a controller MTB_ArticlesController.cs and the five views (Create, Delete, Details, Edit and Index) for the model.
- In the solution explorer, right click the project and select Properties.
- In the properties screen, go to Web section and select Specific page.
- In the Specific page field enter the view folder name MTB_Articles. This will load the Index.cshtml view under the folder MTB_Articles.
- Rebuild and load the solution. You will see the simple index view loaded. Now the project is ready to implement Bootstrap and Knockout.js.
Adding Bootstrap to the Layout:
- From the solution explorer open the file BundleConfig.cs under the folder App_Start.
- BundleConfig.cs file add bootstrap style sheet file to the bundle list.
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css", "~/Content/bootstrap-responsive.min.css", "~/Content/bootstrap.min.css"));
- Add the bootstrap java script file to the bundle list.
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js"));
- The modified BundleConfig.cs file looks like this.
- In the solution explorer, expand the Views folder and then the Shared folder. Open the layout file _Layout.cshtml.
- Replace the content of the file with the below.
<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>@ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="My <span class=" />Tec Bits - Articles"> <meta name="author" content="My <span class=" />Tec Bits"> <!-- Style Sheet Section --> @Styles.Render("~/Content/css") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <button type="button" class="btn btn-navbar" data- <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="#">My Tec Bits</a> <div class="nav-collapse collapse"> <p class="navbar-text pull-right"> Logged in as <a href="#" class="navbar-link">Username</a> </p> <ul class="nav"> <li class="active"><a href="@Url.Action("", "MTB_Articles")">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> <!--<span class="hiddenSpellError" pre=""-->ul> </div> <!--/.nav-collapse --> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Articles</li> <li><a href="@Url.Action("", "MTB_Articles")">Home</a></li> <li><a href="@Url.Action("Create", "MTB_Articles")">Add</a></li> <li class="nav-header">Categories</li> <li><a href="#">Category 1</a></li> <li><a href="#">Category 2</a></li> <li><a href="#">Category 3</a></li> </ul> </div> <!--/.well --> </div> <!--/span--> <div class="span9"> <div class="row-fluid"><br /> @RenderBody() </div> </div> <!--/span--> </div> <!--/row--> <hr> <footer> <p>© MyTecBits.com 2013</p> </footer> </div><!--/.fluid-container--> <!-- <span class="hiddenSpellError" pre="">javascript</span> Section --> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
- Expand the Content folder in the solution explorer. Open the style sheet file style.css. Add the below code.
body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } @media (max-width: 980px) { /* Enable use of floated navbar text */ .navbar-text.pull-right { float: none; padding-left: 5px; padding-right: 5px; } }
- Rebuild the project and run. You can see the webpage looks like this.
Now the solution is ready to implement Knockout.JS. We will work on the Knockout.js in Part 2.
Go to Part 2 (Implementing KnockoutJS) >>
This is an article that I would really like to get working. Any chance of updating it to VS2013? Too much seems to have changed in the newer release.
Yeah it totally breaks up in VS 2013. Request the author to update this blog. Than ks in advance!!.
Good article for beginners, yet to start with second part.
I was playing with bundling since my bootstrap files were not loading properly, my problem was I was adding min files in bundling and not normal debug version of file. and bundling bydefault only includes normal files in debug mode and in release mode it searches for min version and if exists includes that in page
Thanks to khellang
Thank you,
Sandesh Daddi
Twinkle,
It worked for my with ie8. I would be nice if you could bring back the edit, details and delete features that got deleted in part2. I am having some difficulties to get them to work
It us a nice and helpful example nevertheless.
Dear Twinkle,
I have tried to follow all the steps in your article but i am unable to get the desired result.
In your source code on the following link
I have identified a few difference .
your code has a Scripts/ViewModel/IndexVM.js file
but there is no such file in my code.
Also my Views/MTB_Articles/ index.cshtml is very different to the one in your source code.
If you would like I can post the both files.
I hope you ‘ll help me to figure out what’s going wrong and what i am doing wrong.
Thanks in advance
Zia
Hello Zia Ul Hassan,
This article has 2 parts. The IndexVM.js file and the additional changes in index.cshtml are done in the Part-2 of this article. Please refer () for part-2.
Really wonderful article. Everything has been perfectly put together. It looks like we will get such UI only with browser higher than IE8. Can you explain what changes are required to get this look and feel with IE8
Hello Nirmit,
I haven’t got a chance to test this ui in IE version 8 or lower. According to Knockout JS documentation () it will support IE 6 and higher.
According to Bootstrap documentation (), version 1.1 of bootstrap was tested with IE7+. The Bootstrap documents for Version 2.3 and higher doesn’t say anything about browser support. I tried to load the this sample in IE 10 and changed the browser and document compatibility mode to IE 7 and IE8. In IE 8 and lower, the rounded edges were missing. So I believe Bootstrap 2.3 or higher will support IE9 or higher.
If I find any workaround to get the similar rounded edge buttons in IE8 or lower using bootstrap, I’ll update this article.
|
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-1
|
CC-MAIN-2014-49
|
refinedweb
| 1,782
| 61.12
|
I have a hybrid app built using phonegap. After updating to xcode 8
the tele prompt to call the selected phone number stopped working. We no longer get the popup box to call or cancel the selected phone number. This happens only for the app. We get the pop up when we select the phone number in the the browser.
Please share your config.xml (minus secret/identifying information), and your Content Security Policy meta tag if you have one in your index.html file. Also share any code you're using to trigger the telephone # prompt.
Thanks for replying.
In our hybrid app, we are launching our website in the IFrame.
Phone no is listed in the xml file as
<PhoneNumbers><PhoneNumber><Rank>1</Rank><Country>Main</Country><Phone>+1 214 333 4000</Phone></PhoneNumber><PhoneNumbers>
I tried removing + and space from the phone number. This did not fix the issue.
Our content security policy is as follows
<meta http-
Config.xml :
<content src="index.html" />
<gap:plugin
<gap:plugin
<gap:splash
<gap:plugin
<access origin="*" />
<allow-intent
<allow-intent
<allow-intent
<allow-intent
<allow-intent
<allow-intent
<allow-navigation
<allow-intent
<allow-navigation
Thanks
You've not shared the code you use to trigger the prompt; I assume you're just using an anchor though? <a href="tel:..."/>
Your comment that you're embedding your website in an iframe is concerning; you should strive to keep as much of your code local to the device for many reasons (security, user experience, and Apple will almost certainly reject this kind of app if you're targeting the app store).
My suggestion: try using a "tel:" link outside of the iframe and see if that works.
Also -- you're using "gap:" tags -- are you using PhoneGap Build rather than the PhoneGap/Cordova CLIs? Either way, drop the "gap:" namespace and use the more modern syntax(If using PGB: Plugins | PhoneGap Docs ). Oh, and update that really old status bar plugin.
|
https://forums.adobe.com/thread/2266660
|
CC-MAIN-2018-17
|
refinedweb
| 330
| 56.76
|
In previous articles we used requests and BeautifulSoup to scrape the data. Scraping data this way is slow (Using selenium is even slower).
Sometimes we need data quickly. But if we try to speed up the process of scraping data using multi-threading or any other technique, we will start getting http status 429 i.e. too may requests. We might get banned from the site as well.
Purpose of this article is to scrape lots of data quickly without getting banned and we will do this by using docker cluster of celery and RabbitMQ along with Tor.
For this to achieve we will follow below steps:
Let's start.
Dockerfile used to build the worker image is using python:3 docker image.
Directory structure of code:
. --- celery_main | --- celery.py | --- __init__.py | --- task_receiver.py | --- task_submitter.py --- docker-compose.yml --- dockerfile --- README.md --- requirements.txt 1 directory, 8 files
Run the below command to start the docker cluster:
sudo docker-compose up
This will run one container for each worker and RabbitMQ. Once you see something like
worker_1 | [2018-03-01 10:46:30,013: INFO/MainProcess] celery@5af881b83b97 ready.
Now you can submit the tasks. But before going any further lets try to understand the code while it is simple and small.
from celery import Celery app = Celery( 'celery_main', broker='amqp://myuser:mypassword@rabbit:5672', backend='rpc://', include=['celery_main.task_receiver'] )).
The third argument is backend. A backend in Celery is used for storing the task results.
task_submitter.py:
from .task_receiver import do_work if __name__ == '__main__': for i in range(10): result = do_work.delay(i) print('task submitted' + str(i))
This code will submit the tasks to workers. We need to call
do_work method with delay so that it can be executed in async manner.
Flow returns immediately without waiting for result. If you try to print the result without waiting, it will print
None.
task_receiver.py:
from celery_main.celery import app import time import random @app.task(bind=True,default_retry_delay=10) def do_work(self, item): print('Task received ' + str(item)) # sleep for random seconds to simulate a really long task time.sleep(random.randint(1, 3)) result = item + item return result
We can easily create a task from any callable by using the
task() decorator. This is what we are doing here.
bind=True means the first argument to the task will always be the task instance (self). Bound tasks are needed for retries, for accessing information about the current task request.
sudo docker-compose up.
We will not be running containers in detached mode (-d ) as we need to see the output. By default it will create one worker.
In another terminal go inside the worker container using command
sudo docker exec -it [container-name] bash. It will start the bash session in working directory defined by
WORKDIR in dockerfile.
Run the task submitter by using command
python -m celery_main.task_submitter. Task submitter will submit the tasks to workers and exit without waiting for results.
You can see the output (info, debug and warnings) in previous terminal. Find out how much seconds cluster took to complete 10 tasks.
Now stop all containers, remove them and restart them. But this time keep the worker count to 10. Use command
sudo docker-compose up --scale worker=10.
Repeat the process and find the time taken to complete the tasks. Repeat above step by changing the worker count and concurrency value in dockerfile to find the best value for your machine where it took least time.
Increasing concurrency value beyond a limit will no longer improve the performance as workers will keep switching the context instead of doing actual job. Similarly increasing the worker count beyond a limit will make your machine go unresponsive. Keep a tab on CPU and memory consumed by running top command in another terminal.
All the twitter handles are in
handles.txt file placed in root directory of code.
Update the
task_submitter.py file to read the handles and submit them to to the task receiver.
Task Receiver will get the response from twitter and parse the response to extract the tweets available on first page. For simplicity we are not going to the second page.
Code to extract the tweets is as below:
@app.task(bind=True,default_retry_delay=10) def do_work(self, handle): print('handle received ' + handle) url = "" + handle session = requests.Session() response = session.get(url, timeout=5) print("-- STATUS " + str(response.status_code) + " -- " + url) if response.status_code == 200: parse_tweets(response, handle) def parse_tweets(response, handle): soup = BeautifulSoup(response.text, 'lxml') tweets_list = list() tweets = soup.find_all("li", {"data-item-type": "tweet"}) for tweet in tweets: tweets_list.append(get_tweet_text(tweet)) print(str(len(tweets_list)) + " tweets found.") # save to DB or flat files. def get_tweet_text(tweet): try: tweet_text_box = tweet.find("p", {"class": "TweetTextSize TweetTextSize--normal js-tweet-text tweet-text"}) images_in_tweet_tag = tweet_text_box.find_all("a", {"class": "twitter-timeline-link u-hidden"}) tweet_text = tweet_text_box.text for image_in_tweet_tag in images_in_tweet_tag: tweet_text = tweet_text.replace(image_in_tweet_tag.text, '') return tweet_text except Exception as e: return None
Now if you run this code, it will start throwing too many requests i.e. HTTP status 429 error after few hits. To avoid this we need to use tor network to send the requests from different IPs and we will also use different user agent in each request.
git clone
- Build the image and use the same name in docker-compose file.
rproxy: hostname: rproxy image: anuragrana/rotating-proxy environment: - tors=25 ports: - "5566:5566" - "4444:4444"
- You may skip above steps as docker image with tag used in docker-compose is already present in docker hub.
- Create a file
proxy.py and write the below code in it.
import requests import user_agents import random def get_session(): session = requests.session() session.proxies = {'http': 'rproxy:5566', 'https': 'rproxy:5566'} session.headers = get_headers() return session def get_headers(): headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-language": "en-GB,en-US;q=0.9,en;q=0.8", "User-Agent": random.choice(user_agents.useragents) } return headers
- Create a new file
user_agents.py. This will contain the list of user agents and we will use one of these, selected randomly, in each request.
If you will run the container now, IP will be changed after every few requests and user agent will be changed on each hit, resulting in almost zero 429 status responses.
|
https://pythoncircle.com/post/518/scraping-10000-tweets-in-60-seconds-using-celery-rabbitmq-and-docker-cluster-with-rotating-proxy/
|
CC-MAIN-2021-39
|
refinedweb
| 1,064
| 51.65
|
This is the eleventh
- Graph Databases
- Object-Oriented Databases (This article)
- an Object-Oriented database system. I’ll briefly explain the concepts and then move on to the methods you can use to use and manage the one I’ve chosen.
Concepts and Rationale
As far as database management systems go, the trinity of technologies has been Flat Files, the Relational Database Management System, and an offering that many new data technologists may not be familiar with: Object-Oriented Database systems.
The concepts behind an Object-Oriented Database (OOD) are similar to the concepts for Object-Oriented Programming (OOP). This article isn’t intended to make you an OOP expert, but a quick overview of those concepts will help frame the discussion for OOD systems. I’ll be a little loose with the terminology here, so if you’re a purist writing Machine-Level or C++ code, you may want to look away for a few moments. If you’re interested in a more complete, longer, and far more technically accurate discussion of Object Oriented Programming, there’s a decent explanation here:
When you write software code, you’re really creating a higher-level description of what you want a machine to do. In the early days of computing the programmer sent specific instructions for moving a datum (such as a 1 or a 0) to a particular memory location, perform some math function on it, copy it, delete it, re-arrange it or some other function. Later in the code the datum might be operated on again, or read from memory and displayed to some output. It was similar to what you would do with a hand-held calculator.
Working with a list of instructions (a program) in this way is cumbersome and prone to error. Humans don’t read instructions this way, and the input of keyboards, mice, other programs, machines and a myriad of other sources along with an equally complex method of outputs made understanding, and changing a program almost impossible.
So the first levels of abstraction in programming began. Programmers wrote programs in the lower-level languages into “higher” level ones that were more human-language friendly. As time passed, higher and higher levels of abstraction made programming easier, at the cost of making the programs larger, and a higher memory and CPU use.
In the 1950’s and 1960’s, the first mention of “Object Oriented” programming came into being, and this term really meant a high level of code re-use. Later, Object Oriented Programming came to mean creating a “model” of something you want to work with (the Object).
The Object has Properties (information about the object) and Methods (things the Object can do). You can use an Object to create another Object, and you can encapsulate the information in the Object – meaning that changes to the copy you make to the copy doesn’t affect the first one.
Another advantage is that you can make a “child” Object that inherits all of the Properties and Methods of the parent Object, and extends it with new information or actions. It’s this last feature that makes Object Oriented technology particularly interesting to the data professional.
Later, OOP added Events, which are notifications on an Objects state or activities that can be watched to trigger even more Events, Methods or Properties. Object Oriented Programming now encompasses dozens of concepts, but for this article, I’ll stick with encapsulation, Properties, and Methods.
Let’s take a look at an analogy to help explain OOP – which of course will sacrifice some fidelity for understanding these concepts.
Assume that you have an Object called “Pizza”. A Pizza, at its very simplest, contains some sort of crust made from dough, and a sauce – for this example, all Pizza objects have tomato-based sauce. All Pizza objects also have cheese. In this case, since programming is abstract and Pizzas are real, we’ll call a recipe a Pizza object. All of the components of the recipe are Properties of the pizza Object.
Now let’s assume that you have a customer that would like a Pizza, but with onions. On an order slip you write down that you want a “Pizza with Onions” object. The cook takes the original Pizza recipe, and creates another one – but adds an additional Property to it: Onions. The customer gets a Pizza object, but with Onions. The next customer might get a Pizza object with Onions, and also with Jalapeños. And so it goes on.
…they are simply an engine …’
Now assume that the original Pizza recipe changes to add more salt. That information doesn’t have to be transmitted to all of the new recipes – the information is encapsulated inside the original Pizza recipe, and all of the new child objects can simply inherit more salt. (And yes, the child Object can change something it inherited from the parent Object by simply over-riding the Property For instance, if the recipe calls for less salt, not more, the child object can override the Salt property.)
A pizza can’t do a lot, of course – but stretching the analogy a bit we could say that it gets cooked, transported and eaten. Those might be thought of as Methods for the pizza object. We could take the original pizza recipe, extend the ingredients, cook, transfer and eat a pizza.
This simple example has some holes in it, but we’ll stick with it for now. Let’s take what we’ve talked about in the OOP world and apply that to OOD systems.
Object-Oriented Databases (OOD) have some salient characteristics, but the most specific is that OOD systems are very tightly integrated into the user-level OOP code – in some cases, so integrated that they are simply an engine that ships with the code itself. The developer references the engine at the top of their code, and then can proceed to instantiate OOD objects directly into the code. This means there isn’t as much separation as you might see with a C# program, for instance, and a SQL Server database. In that case, the code calls up data, and the database handles retrieving and persisting the data down to a physical store. In the case of an OOD, that separation doesn’t exist.
You’ll find that various OOD systems either lend themselves well to a specific language, such as Delphi and Smalltalk, or have a separate query language that most any program can use. And if the data is fairly small, in some cases there is no OOD at all – the OOP language simply works with objects as normal and persists them down to data on storage within the code – there’s no OOD at all.
Rationale and Examples
If the developer works with objects natively, and the code can write data down to the hard drive, why have an OOD at all? Why not just leave that in the code?
Well, this gets back to why we have databases to begin with: you have to deal with multiple people using the same data at the same time, and you have to have a reliable structure to find and use data. An OOD system does just that – using various mechanisms to handling locking, schemas, data protection and other data requirements. It’s this multi-use requirement that makes a good case for using an Object-Oriented Database system.
And working within a single database environment allows the developer to focus more on what the code does at the logic-layer rather than handling all of the vagaries of dealing with the data management. In addition, some systems allow a type of “journaling” feature, which gives you the ability to track changes in the data through time. This is very advantageous in a Computer Aided Design (CAD) and other systems.
So the key to choosing an OOD over an RDBMS or a NoSQL engine (or perhaps in addition to those) is that it is very developer-centric. It works with objects the way a developer might directly in their code, so there is a good connection between the concepts the developer uses and how the database works.
Database theorists debate the relative merits of OODs and RDBMS
However…
Most developers have learned and adapted well to working with an RDBMS or a NoSQL engine. Because of that, and the strength and variety of capabilities in the RDBMS engines, there are far fewer Object-Oriented Database systems in wide use today. Most of the original OOD vendors have either gone out of business, merged with other companies, or changed owners. In the end, there are only a few to choose from, and even fewer that run on a given platform.
My research led me to choose db40 – db4Objects from Versant. I used the evaluation version for my lab system. This product seems to be in high production use and have good support – as I’ve mentioned before in this series, if I intend to spend time learning a product, I want to make sure it’s something I’ll be able to use in production if needed.
Installation
I started at the main page of the db40Objects at:
At the top is the “Download Now” button, and this is what I chose. This installs the local developer edition – which is what I’ll focus on in this article. You can use db4Objects in a shared mode, but I’m not covering that process in this lab – my focus is learning the language and platform in this system.
After selecting the button, I was brought to a screen where I selected the underlying product that I wanted to install. Here is where the power of this platform lies – it meets the developer at the platform they work with.
Since my Java-fu isn’t very good, I selected the .NET 4.0 release.
It’s a quick download, and then the installer starts.
Clicking next brings up the panel to select the features to install.
I picked “Custom” so that I could set the install path to the “S:” drive I have on my Windows Azure Virtual Machine, although your installation choices might be different.
After I set the path the installation continues the process.
And at the last screen there is a fantastic option – the installer opens a tutorial! I think this is brilliant, and I’m surprised that every product doesn’t follow this model.
At this point I can start using the product, and there’s a simple step-by-step process of working with it.
I’ll leave you to walk through that tutorial, since it would be redundant to cover it here. It covers working with the native query language, which is really just working directly with the objects using the Application Programming Interface (API) for data objects.
What I wanted to focus on in my test is working in a development environment, specifically using Language-Integrated Query (LINQ) to create and query data in a familiar way.
Example
I start by opening Visual Studio (I have the full product on my Lab system, you can get the free version here if you want to follow along) and creating a new Project:
I’ll create a simple console application to test the process – I’ll try to create a couple of Pizza objects from my earlier explanation.
Once I created the Project and Solution, the first thing I did (following the instructions from the tutorial provided) was to add two references (right-click the project name and select Add…References) in the paths shown in the screen below. I’m adding two key references: one for the Db4objects, which gets me access to the engine, and the other for LINQ, which allows me to use LINQ for queries in addition to the native query methods in the dB4Objects API.
From there I added a couple of statements to use those references, and then added some code to create the database, instantiate some objects as data, and query that data with LINQ. The code is shown in more detail in the next section.
Before we take a closer look at that code, a couple of notes are in order. First, this code isn’t very comprehensive – it isn’t meant to be a full demo of the product. Second, you can perform this process without using dB4Objects as the persistence layer. In fact, you don’t need a database engine at all to replicate the demo here – but that’s the point.
Whenever I test and explore a product, I start with something I know well, and then add in the unknown. In this case, I know how to create and query data objects in .NET and LINQ – and in this simple example I’ll add in the dB4Objects as the persistence layer.
So let’s take a look at that code, block by block. I won’t dive into every statement, but I’ll show the general things that make it dB4Objects-specific.
In this section, I’m simply adding in the standard components for a console application, and I include LINQ as well.
In lines 6 and 7 I’m setting up “using” statements for the references I created to dB4Objects earlier.
Lines 8-10 start a simple namespace for the program, and set up the outer container.
After the main program insertion point starts in line 12, line 14 deletes any database files I had from the previous program run. Of course, you wouldn’t do that in production! For testing, I can comment this line to continue with the previous run or delete it as I have here.
And in line 15 I create a new container for the data, of the dB4Objects type. I use the Factory API call to create a new database called Linq.db40.
In lines 17-18 I create two new Pizza objects, with two attributes each. The main Class will be defined below, but at the moment I simply create two new objects from the Pizza Class. I’ll make one with a thin “Crust” and a regular “Sauce”, and the other with a think “Crust” and light “Sauce”. Once again, I have a lot of leeway on what a Pizza Class (from which I can create more Objects). Line 19 reads the values from the database.
In lines 20-24 I’m simply waiting for a key to be pressed to continue the program – perhaps here the program could do more from the data input side and so on.
Lines 25-34 I’m using the data that returns into the object in a LINQ query. Then I iterate through that list with a foreach action to line 1a. where I write the data to the screen.
And down in lines 35-40 I define the Class for Pizza. This is fairly simplistic, of course, and has only two Properties, both publicly accessible and writable. The Class would be far more complex, with non-settable “base” Properties, Methods for baking and delivering and so on.
It’s a short program – could be even shorter if the formatting were different, but it definitely shows the integration with the data persistence layer for the developer.
As a side note, there is an Object Browser you can use with dB4Objects without diving into code. In my experiments so far, it seems to be much easier to evaluate the product in either Java or .NET.
In the next installment, I’ll cover Distributed File Databases that I’ll work with in the laboratory.
|
https://www.red-gate.com/simple-talk/cloud/data-science/data-science-laboratory-system-object-oriented-databases/
|
CC-MAIN-2019-35
|
refinedweb
| 2,602
| 58.92
|
AbouttheAuthor
IshaKapoorisaSharePointMVPandfounder&authorofafamous
SharePointwebsiteLearningSharePoint.com.Shehasmorethan6
yearsofexperienceinSharePointandhaveimplementedmultiple
SharePointprojectsforvariousFortune500CompaniesacrossNorth
America.ShecurrentlyworksasaSharePointConsultantthroughher
companyAkruraTechnologies.
YoucanconnectwithIshaonLinkedInoremailherat
admin@learningSharepoint.com
Thisdocumentisprovidedasis.Informationandviewsexpressedinthisdocument,includingURLandother
Internetwebsitereferences,maychangewithoutnotice.Youbeartheriskofusingit.
SharePoint, MOSS, SharePoint 2010, SharePoint 2013 and Microsoft are trademarks of the
Microsoft Corporation.
Contents
ContentManagement
3. Download - WithDownloadacopyenduserscandownloadacopyofthis
documenttotheirlocal.Clickonthelittlestackiconinpreviewpaneofa
documenttogotodownloadacopyOption.
4. Embed Code - With Embed Information users can get the embed code for a
document and then paste it in a Script editor or Content Editor webpart to embed
this documents in a SharePoint page. Click on the little stack icon in preview pane
of a document to go to the Embed Code option. See the post How to Embed a Word
document in your Site Page for details.
5. Print to PDF - Print to pdf solves two purposes converting your Word doc to PDF
and letting you Print the PDF right from the document library. Click on the little
stack icon in preview pane of a document to go to the Print to PDF option. For
details see Word to PDF Conversion in SharePoint 2013 (via Print to PDF)
6. Share & Follow Feature - These are the part of SharePoints new Social integration
piece. You can Share a document with Users, Groups or everyone in the company.
You can also Follow the document yourself by click the Follow button in Preview
pane. When you follow the document you would see it under Documents in your
News feed (towards right).
For more Info on above Document library features see SharePoint 2013 document libraries Drag
Drop, Download, Preview, Print, Share and more..
8. Edit Managed Metadata - In the new DataSheet View users can now edit values
for Managed Metadata Columns (when in edit items mode). In the Metadata
dropdown select the metadata term and then click on the small orange button that
appears. You will be able to set, add or remove terms then.
9. Find a File - A new Search box Find a file has been added to each Document
Library which can help users find files form within a Library. This is an Instant
real-time search.
10. PDF Support - SharePoint 2013 now offers Out of box PDF Support.PDF icon is
now natively supported and when a PDF is Opened SharePoint will try to open
PDF file in the Adobe Reader and prompt user to either checkout & open or open
the file in PDF directly.
11. Digital Asset Content Types - In SharePoint 2013 MS has introduced a new set of
content types called Digital Asset Content Types for better use of Audio, Video
and Images as Web Content. These content types can be added to any library and
be used as a one of the items\files. For more Info on Digital Asset Content Types
see SharePoint 2013 The new Digital Asset Content Types (Audio, Video,
Image and more..)
12. TimeLine & Project Summary WebParts - TimeLine & Project Summary are two
new WebParts in which are added by default to the Project Site
Template.TimeLine as shown in any Tasks list represents the Tasks and Subtasks
with dates as a timeline. . For more Info on Timeline and Project Summary see
The New TimeLine and Project Summary WebPart in SharePoint 2013
13. Asserts library - The Improved Asserts Library lets users upload Digital Asset
Content Types and provides various Out-of-Box views like Thumbnails and
Out-of-Box pages like Video Page to View these Content types in an Interactive
way. For more Info on Asserts Library see How to add a Video to SharePoint 2013 site
14. Video Page & Thumbnail - When a user uploads a Video in Asserts Library a
default videoplayerpage.aspx gets created to view video and its metadata. This
Page also includes options to Upload or Capture the Thumbnail and add other
metadata for the Video. For more Info on Video Page & Thumbnail see How to add
a Video to SharePoint 2013 site
15. People in Video - As a part of a Video Content type a new Column People in
videos has been introduced where you can specify people you company who are a
part of the Video to be included as Video Metadata. The column is available when
you edit the properties of your Video that you uploaded in Site Asserts library. For
more Info on People in Video see Search Videos with the new People in videos column
in SharePoint 2013
16. Reindex List and Reindex document library - There is a new Option Reindex List
and Reindex document library that allows users to force the Content of list and
library to be re-indexed.In clear words the Reindex option marks the whole list
or library to be picked up by a Continuous crawl, regardless of whether the items
have actually changed. For more Info on Reindex option see The New Reindex List
and Reindex document library option in SharePoint 2013
17. Cut & Paste from Word - Content Editors can now Copy & Paste directly from a
Word Document into any text field like Blog Post Body or Announcement
description field. For Info see SharePoint 2013 Now you can Cut and Paste from Word
18. Most Popular Items - Most Popular Items is new feature in document library that
lets user see the Popularity and Visits of a document in a document library. For
Info see SharePoint 2013 - Most Popular Items in Document Library
19. Image renditions - Image renditions let you display different sized versions of an
image on different pages. When you create an image rendition, you specify the
width and height for all images that use that image rendition.
20. Geolocation Field Type - SharePoint 2013 Introduces a new field type named
Geolocation that can show Bing maps instead of location entered in list item. In a
Column of type Geolocation, you can enter location Info as a pair of latitude and
longitude coordinates in decimal degrees or retrieve the coordinates of the users
current location from the browser.
21. Ratings (Star and Likes) - In SharePoint 2013 apart from Star ratings on List Items,
users you can now turn-on Like rating for any list item by simply setting as switch
in the Rating Settings. For Info see SharePoint 2013 List Item Rating (Stars, Likes)
22. Focus on Content - In the new UI of SharePoint 2013, there is a new button in the
top Suite bar called Focus on Content which lets you highlight the Content area
by hiding the quick Launch or Left Nav on the page. For more Info on Focus on
Content see Hide Quick Launch\Left Nav using Focus on Content
23. Script Editor Webpart - The new webpart Script Editor Webpart represented as
Embed code in Ribbon under Insert tab, lets you add HTML\Javascript\Jquery in
your SharePoint Site Page. For more Info on Script Editor see SharePoint 2013
Where to add JavaScript\Jquery in your SharePoint site
24. Tiles Structure - SharePoint 2013 Introduces a new Title Structure added to default
home page of a Team Site. These tiles represent important tasks to perform on the
Site. This Tile webpart can be very useful to promote important links on your
Intranets Home page. You can create a Custom Set of titles using a new list
template called Promoted Links. For more Info on Tiles see SharePoint 2013 Add
Custom Tiles to SharePoint site Page
25. Document Library SYNC (Work with Documents Offline) - With the Introduction of
new SYNC button, users can now have any Document Library SYNCed to their
Local Including the SkyDrive PRO Library. For
more Info on SYNC see How to work with Documents Offline in SharePoint 2013
26. IFrames - SharePoint 2013 added an Out-of-Box Support for IFrames. Admins can
now embed dynamic content from other sites, such as videos or maps to any
SharePoint site by using IFrames in an HTML field. Admins would need to add the
Domain for the external site in HTML Field Security first. For more Info on
IFrames see How to use IFrames in SharePoint 2013
27. Related Items - A new Site Column Related Items has been Introduced which
lets users add a reference to another Item or a document in any List\Library as a
related entity to this Current Item. For more Info on Related Items see SharePoint
2013 The New Related Items Site Column
28. Page Not Found Error Page - By default, each Publishing site now Contains a
default Error\404 page PageNotFoundError.aspx page to handle all 404
requests in the site. This page can be customized by users to add a Custom text on
the page. For more Info on 404 Error Page see HTTP 404 (Page Not Found) Error Pages
in SharePoint 2013
29. Status Bar - The Location of Status Bar in SharePoint 2013 has changed. Similar to
SharePoint 2010 the class SP.UI.Status in SharePoint 2013 provides the following
methods to work with Status bar. For more Info on Status Bar Set Value for Status
Bar in SharePoint 2013
Social
30. Social Capabilities - In SharePoint 2013 Microsoft has introduced new Social
Capabilities to let users Collaborate Socially in the Company. MY Sites have been
Improved Incredibly to Integrate Social Capabilities. Apart from My Sites new
Community Sites, Newsfeed, Follow people and Follow Sites has been introduced.
31. Community Sites - SharePoint 2013 has introduced a new site template
Community Site that provides advanced Discussion list features such as
Community Tools (Tools for managing the site, like you were presented in blog
posts), Reputation model (you can assign badges to users and give points for the
activities, Social (Like & Rely) and more. For more Info on Community Sites see
SharePoint 2013 Social Networking Capabilities Complete Tutorial
32. My Sites and NewsFeed - My Sites has been enhanced with a NewsFeed WebPart,
a New Task list, a New My Documents Library and an entire section for Follow.
The home page of your My site displays feed that contains updates from User and
people they follow. For more Info on My Sites and News Feed see SharePoint 2013
Social Networking Capabilities Complete Tutorial
33. Site Feeds - As a part of SharePoint 2013s social Capabilities Uses can Follow and
UnFollow sites to track updates for the sites that they follow. For more Info on Site
Feed see What are Site Feeds and how to Follow & Unfollow Sites in SharePoint 2013
34. Suite Links (DeltaSuiteLinks) - The new top blue bar with links NewsFeed,
SkyDrive, Sites is called DeltaSuiteLinks.These links are useful to navigate to
Skydrive Pro, My Sites, NewsFeed and Administration center. For more Info on
DeltaSuiteLinks see SharePoint 2013 Hide NewsFeed, SkyDrive, Sites (DeltaSuiteLinks)
35. Sharing - Sharing is a feature that let Users Share a Site\Library\Item\File with
people in their Company. Sharing is similar to sending an Invitation to join a site
as in SharePoint Online 2013.Users can simply Share a Site using various Out-of-
Box options available. For more Info on Sharing see All you need to know about
Sharing in SharePoint 2013
36. Access Request Management - SharePoint 2013 has a new "Access requests and
Invitations" Feature to help Admins and End Users Manage Access requests in
SharePoint 2013. For more Info on Access Request Management see SharePoint
2013 the new Access Requests and Invitations Feature
SiteAdministration
37. Settings Wheel -Site Action is now replaced with the new (settings) wheel. A
few actions like add an App, add a Page & Design Manager were added whereas
options like Create Site were remove from this menu.
38. Signin as different user Missing - In SharePoint 2013 Signin as different user
option has been removed from the User Welcome menu. There is no alternative
provided yet.
39. Create Site or Subsite Link - Create Site link which was used to Create Subsites
is now moved to the Site Contents (earlier known as View all Site content) page.
The link is called new site. For more Info on How to Create Subsite see How to
Create a SubSite in SharePoint 2013
40. Apps for SharePoint - All the List and Libraries are now Apps. Simply click on
Site Content and select Add an App to Create a List or a Library. For more Info on
How to Create List & Libraries see How to Create a Custom List in SharePoint 2013
41. Project Sites - SharePoint 2013 has new Project Sites Template that provides Out-
of-box webparts and pages that facilitate Project Managers and Teams work
efficiently. For more Info on Project Sites see The New Project Sites in SharePoint
2013
42. Create WebPart Page and Wiki Page - To Create a WebPart Page or Wiki Page you
need to navigate to Site Pages and New document ribbon button. For more Info on
How to Create WebPart Page see SharePoint 2013 How to create a WebPart Page?
43. Edit Links (Quick Launch) - The new Quick Launch can now be edited from Edit
Links option which is available in the quick launch itself. Edit Links puts the
quick launch in Edit mode. Users can Create, Delete, Re-order, drag and drop links
in the quick launch in Edit mode.For more Info on Edit Links see SharePoint 2013
Add\Edit Links in Quick Launch or Left Navigation
44. Global Links (Top Navigation) - Global Navigation has also gone through a
Change. Similar to Quick Launch you can edit global navigation with Edit Links
provided next to the Global navigation links.
45. New Task List - In SharePoint 2013 Task list is significantly improved. Task list
now has a Task Timeline (like on MS project), Days left for due date, Creating
subtask option, Task quick edit mode and lot more attractive features. For more
Info on Task List see How to Create a Task list in SharePoint 2013
46. New Discussion list - Discussion Board got a huge makeover in SharePoint 2013.
There were new changes in the UI and some new Views introduced to View
Discussions from a Management point of view. For more Info on Discussion list
see Create Discussion Board in SharePoint 2013 Complete Tutorial
47. Site Policies in SharePoint 2013 -A Site policy specifies the conditions under
which to close or delete a site automatically. There are the four options Do not
close or delete the site automatically, Delete the site automatically, Close the site
automatically and delete the site automatically and Run a workflow to close the
site, and delete the site automatically.
48. New Themes - SharePoint 2013 introduces a set of new Themes which can switch
the look and feel of your site in minutes. For more Info on Themes see Change the
Look and Feel of your Public Website with Themes in SharePoint 2013 Online
49. Composed Look - Composed Looks is a new Library that Contains Font Schema of
Theme and its other Components.
50. New Master Pages - New Master Pages has been introduced. App.master,
belltown.master, mwsdefaultv15.master, overlay.master and v15.master.Master
Pages can be Created and Switched using various ways in SharePoint 2013. For
more Info on Master Page see SharePoint 2013 How to change the Master page of your
SharePoint site
51. Design Manager - Design Manager is a feature in SharePoint 2013 that makes it
easier to create a fully customized, pixel-perfect design using HTML with tools
like Front end, Dreamweaver etc. Design Manager is a publishing feature that is
available in publishing sites in both SharePoint Server 2013 and Office 365. You
can also use Design Manager to brand the public-facing website in Office 365 as
well. For more Info on Design Manager see Overview of Design Manager in SharePoint
2013
52. Snippet Gallery - Snippet Gallery is a feature that lets you add SharePoint
Components to your HTML or Master Page Design file. Users can select a
component, configure its properties and copy the HTML snippet that's generated.
The Snippet Gallery also gives you a high-fidelity preview of that component, both
in the server-side preview and in your HTML editor of choice. After you add
SharePoint components to your HTML files, you can use CSS to fully brand them.
53. Device Channels - With device channels in SharePoint 2013, you can render a
single publishing site in multiple ways by using different designs that target
different devices. These device channels can each be given a different master page
and thus CSS file to give users a more optimal viewing experience. Device
Channels are optimized for search engine optimization (SEO). You can use them to
transform the look and feel of existing pages to support mobile scenarios. For more
Info see Plan device channels in SharePoint Server 2013
54..
55. Product Site Template - Product Site template is a part of new set of templates
introduced in SharePoint 2013. Out of the box this site template already comes
with the cross site collection publishing feature enabled.
57. Catalogs - Catalogs contain the content that is reused across site collections. Any
List or Library can be shared as a catalog if the Cross-Site Collection Publishing
feature is activated for the site collection. For more Info on Catalogs see Share a
library or list as a catalog
58. Managed Metadata Site Columns - In SharePoint 2013 now you can add Managed
Metadata type Site columns from with the site Collection. In addition to Metadata
type Field type all the Site columns that contain values will automatically become
managed properties when they are crawled.
59. Managed Navigation - SharePoint 2013 now offers Custom Navigation of sites via
the Managed Metadata Term Store. In the Term Store Management Tool, use the
left pane to navigate to the Term Set you want to use for the navigation. Then in
the Term Set, Create Terms to reflect your desired navigation. Use the Navigation
tab at the top to manage Navigation and Term-Driven Pages. For more Info on
Managed Navigation see Managed navigation in SharePoint 2013
61. Category pages - Category pages are page layouts that are used for displaying
structured content such as catalog data. You can use category pages when you
want to aggregate content that meets certain criteria or parameters. Category pages
are closely tied to managed navigation. This is because you can associate a
category page with a specific term within the term set that is used for managed
navigation. For more Info on Category pages see Plan publishing sites for cross-site
publishing in SharePoint Server 2013
62. Site Collection SEO - In addition to the SEO settings in Publishing Pages and Term
Sets (for Managed Navigation) In SharePoint 2013 you can also set SEO at Site
Collection level. At Site Collection level you can set Meta Tags and XML Sitemap
unlike in SharePoint 2010. In SharePoint 2010 though you can add Meta Tags in
your Mater Page using the Delegate control or a Webpart of a Custom Control. For
more Info on Site Collection SEO see SharePoint 2013 Site Collection SEO
63. App Catalog Site Collection - The App Catalog site is a special Site collection
scoped for a particular web application to contain all apps that you want to make
available for a web application. For more Info on App Catalog Site see SharePoint
2013 All about App Catalog
64. New Information Rights Management (IRM) Settings - With the Introduction of
new Office 2013 there have been new additions to Information Rights
Management (IRM) in SharePoint 2013. New UI settings has been added to
document libraries where Admins can now set access rights, including rights to
print, run scripts to enable screen readers, or enable writing on a copy of the
document. For more Info on Information Rights Management see SharePoint 2013
New Features in Information Rights Management (IRM)
FarmAdministration
65. Improved SPSite Cmdlet - In SharePoint 2013 SPSite Powershell Cmdlet has
improved to make Site Collection Operations easier.For example a new parameter
'HostHeaderWebApplication' is added to set a Host-name for a Site Collections
and a new cmdlet Copy-SPSite cmdlet is added to make a copy of a site collection
from one Source content database. For more Info on SPSite Cmdlet see SPSite Site
Collection Operations in SharePoint 2013
67. Shredded Storage - Shredded Storage is a new Feature that allows Documents and
Changes to the Documents to be stored as Shredded BLOBS. Unlike SharePoint
2010, it helps to lower down the amount of storage required for saving files by
saving only the Changes and not the entire Versions of the Files in database. For
more Info on Shredded Storage see SharePoint 2013 Shredded Storage How it Works
69. Dual License - SharePoint 2013 introduces the concept of Dual License. Now
Admins can assign a set of Users access to Enterprise CAL features while other
users (with Standard CAL) will have restricted access to the additional Enterprise
CAL features. The License Enforcement is gracefully handled by SharePoint when
in case a Standard CAL user tries to access a feature that is only available to
Enterprise CAL Users. For more Info on Dual License see Introducing the Dual
License Model in SharePoint 2013
70. Request Management - SharePoint Server 2013 introduces a new capability called
Request Management that helps SharePoint farm manage incoming requests by
evaluating logic rules against them in order to determine which action to take, and
which machine or machines in the farm (if any) should handle the requests. For
more Info on Request Management see Request Management in SharePoint Server 2013
Format (.pdf) for archival purposes, distribution to clients who do not have
Microsoft PowerPoint installed, or to protect the presentation from editing. For
more Info on PowerPoint Automation Services see Introduction to PowerPoint
Automation Services in SharePoint Server 2013
Search
73. New Search architecture - In SharePoint 2013 the best of two Search Engines
SharePoint Search and FAST Search Server for SharePoint was combined to
make one Search Engine that would provide greater redundancy and for better
scalability. For more Info on Search architecture see Search 2013 Architecture
74. Continuous Crawl - A new Crawl Option "Continuous crawls" has been introduced
in in search's Crawl Schedule category to help keep the search index and search
results as fresh as possible. Continuous crawls run every 15 minutes by default.
When running, the crawler gets changes from SharePoint sites and pushes them to
the content processing component. The document will then get processed by the
content processing component on the fly. No index has to be merged and the Item
appears in the search results right after they have been crawled. For more info on
Continuous crawls see Manage continuous crawls in SharePoint Server 2013
75. Query Rules - Manage Search Keywords has been removed in SharePoint 2013 and
a New Option of Query Rules has been Introduced. With Query Rules admins
can set rules to show blocks of results relevant to users query. Query Rules is
available in Site Settings page under the Search heading. For more info see Query
Rules see What happened to Best Bets? Introducing Query Rules
76. Result Sources - Result Sources are actually the combination of Federated Search
and Search Scopes. In SharePoint 2013 you can create a new Result Source and
specify the Protocol (to search Local SharePoint or Remote SharePoint farm
etc.) and can specify the Query Transformation. With Result Sources You can
create complex Search queries to restrict results to a subset of content. For more
info on Result Sources see SharePoint 2013 The New Result Sources for Search Results
77.). For
more Info on Display templates see SharePoint 2013 The new Display templates for
styling your Content
78. Result Types - Result Type rules determine what type of result youre looking at,
and what hover panel should be shown based on those rules. You can find Result
types in site collection Site Settings under Search. SharePoint administrators can
create a new display template in HTML and then add it to the Result types. This
display template will be invoked based on a set of rules. For more info on Result
Types see SharePoint 2013 The Concept of Result Types in Search
79. Spelling Correction Feature - Spelling Correction Feature is a new feature that is
hosted in the Termstore. With this feature if a user enters a word in a search query
that appears to be misspelled, the search results page displays query spelling
corrections (under a "Did you mean?" text). You can add terms to the Query
Spelling Exclusions and the Query Spelling Inclusions list to influence how query
spelling corrections are applied or not. It takes up to 10 minutes for any changes to
the Query Spelling Exclusions or the Query Spelling Inclusions list to take effect.
For more Info on Spelling Correction see Manage query spelling correction in SharePoint
Server 2013
80. Query suggestions - Query suggestions, also referred to as search suggestions, are
suggested phrases that users have already searched for. Query suggestions appear
in a list below the Search Box as a user types a query. By default, the search
system automatically creates suggestions for a query when users have clicked the
results for that query at least six times. This can be one result, or any combination
of results for that query. A query suggestion appears only if it contains at least one
of the words that are typed. For more Info on Query suggestions see Manage query
suggestions in SharePoint Server 2013
81. Authoritative Pages - In SharePoint 2013 admins can specify Pages\URLs that
should be ranked higher or lower in Search results. Authoritative and Non-
authoritative pages are added with the options to specify if it is "Most
authoritative, Second-level authoritative, Third-level authoritative or demoted.
For more Info on Authoritative Pages see SharePoint 2013 Search Authoritative and Non-
authoritative Urls
82. Name Suggestions - With the new "Name Suggestions" feature of People search
Microsoft has introduced a simple, easy, and intuitive way to find people by their
names. "Word wheelingtyping a character(s) and seeing all the names starting
with that character(s), is available on all names in the profile database, and
therefore also in the People index. The feature supports exact name matches and
also supports "fuzzy" matches. With fuzzy name matches, the spelling is similar
but not exact because of phonetic misspellings or typing errors. For more Info on
Name Suggestions see SharePoint 2013 - The new "Name Suggestions" Feature
83. Managed Properties (Sort and Refine) - Search Schema in SharePoint 2013 has
introduced new attributes sort and refine that you can apply to managed properties.
84.. For more Info on Content
Search Web Part see SharePoint 2013 Content Search Web Part (CSWP) VS Content
Query Web Part (CQWP)
85. Refiners and Faceted Navigation - You can add refiners to a page to help users
quickly browse to specific content. Refiners are based on managed properties from
the search index. To use managed properties as refiners, the managed properties
must be enabled as refiners. Faceted navigation is the process of browsing for
content by filtering on refiners that are tied to category pages. Faceted navigation
allows you to specify different refiners for category pages, even when the
underlying page displaying the categories is the same. For more Info on Refiners
and Faceted Navigation see Configure refiners and faceted navigation in SharePoint Server
2013
86. Search Relevance and Ranking models - SharePoint Server 2013 provides new
ranking models that determines recall (which items are displayed in the search
results) and rank (the order in which search results are displayed). The search
system determines the relevance of search results by how content is connected,
how often an item appears in search results, and which search results people click.
The search system also determines which items users most commonly click in
SharePoint.
88. Usage Analytics - SharePoint 2013 has a new component called Usage Analytics
to present you with informative Site Usage Analytics or Statistics. Usage Analytics
is an improved version of Web Analytics which is now discarded in SharePoint
2013. Analytics Processing Component runs the analytics jobs to produce Usage
analytics that analyzes user actions, or usage events, such as clicks or viewed
items, on the SharePoint site. For more Info on Usage Analytics see The New Usage
Analytics in SharePoint 2013
89. Popularity Trends & Most Popular Items Reports - The Analytics Processing
Component in SharePoint 2013 Search generates and stores statistical information,
such as usage event counts, from different analyses in Analytics reporting
database. SharePoint Server uses the information in this database to create
Popularity Trends & Most Popular Items Reports Excel reports for the search
administrators. For more Info on Usage Reports see The New Usage Analytics in
SharePoint 2013
90. Search Verticals & Search Results Pages - Search Verticals are Categories that are
displayed Under the Search box such as Content, People, Conversations, Videos
and other Custom Result Scopes. You can add a new Search vertical using Query
Rules and Result Sources. SharePoint 2013 Creates Search Result Pages for default
Search Verticals. For more Info see SharePoint 2013 Search Verticals and Search Result
Pages
Development
91. Apps for SharePoint -. For more Info see
What is an app for SharePoint in SharePoint 2013?
92. New Client Web Part - A new WebPart called Client WebPart has been
introduced in Visual Studio 2012. The main purpose of this WebPart is to specify a
path to an .aspx page which it then load in an IFRAME. This webpart is essentially
used to display SharePoint-hosted Apps as an App WebPart or a WebPart. For
more Info see How to: Build a SharePoint-hosted Client Web Part in SharePoint 2013
93. New CSOM and REST based APIs -. For more Info see Programming using
the SharePoint 2013 REST service
94. Social APIs -With the Introduction of new Social capabilities a new namespace
Microsoft.Office.Server.Social has been added to interact with social
components like Feeds, Follow People, Follow Content and more. For more Info
see Programmatically Follow Documents in SharePoint 2013
95. New Visual WebPart -Visual WebPart template has been enhanced in Visual
Studio 2012. The new Visual web part is not mapped to Control Templates
folder to store the ascx files. Both User Control and WebPart classes are merged to
create one template. This Visual WebPart template can be used to create both
Sandbox and Farm solutions.
96. New TilesViewWebPart - To support the Tile Structure a new abstract class
TilesViewWebPart has been added to the object model. To create a new Tile
WebPart add a SharePoint webpart and Inherit the WebPart from
TilesViewWebpart and implement the abstract class. For more Info see SharePoint
2013: Create a Metro Live Tile Programmatically
97. New Event Receivers -In SharePoint 2013 Microsoft has introduced a new Event
Receiver class SPSecurityEventReceiver to handle events for SharePoint
Groups, Users, Roles and Permission Inheritance. For more Info see SharePoint 2013
New Event Receiver for Groups,Users,Roles,Inheritance
98. Callout popup framework -In SharePoint 2013 Microsoft has used Notification or
Preview Callout Popups on various pages, Lists and Libraries. These Hover Over
popups can be fully Customized using the new Callout popup framework. For
more Info see The new Hover Over\Preview\Callout Popups in SharePoint 2013
99. New Delegate Controls - In SharePoint 2013 three new Delegate Controls has been
added.These are PromotedActions, SuiteBarBrandingDelegate and
SuiteLinksDelegate. These Controls can be used to add and remove links from
Delta suite bar.
100. JS Link - In SharePoint 2013 a new property "JSLink" has been added to SPField
class that allows users to Control the Rendering (presentation and validation) of
any Custom or Out-of-box SPField. This property is available for Out-of-box
Listview\Dataview webparts where you simply set the property without modifying
the webpart in SharePoint designer. For more Info seeUsingJsLinktoaddJavascriptto
Listview\Dataviewwebpart
101. Mobility -.
|
https://pt.scribd.com/document/352551515/101-New-Features-in-SharePoint-Consultant
|
CC-MAIN-2019-35
|
refinedweb
| 5,231
| 61.16
|
I hate error testing and I have an order for with 12 inputs and each input needs testing for allowed and non allowed input - say 5 different tests on each input
I normaly do this manualy by inputting all the options but soon get lost with what I have and have not tried. Is there a simpler better way to do this?
I don't know if you would benefited from some automated form testing with Selenium IDE, but I have been using this for testing different test cases and longer forms in several projects.
I'm working on something similar (not in PHP) and have to validate all kinds of input on a rather large web-facing form.I went the TDD route which involves writing failing tests, then writing the necessary code to make the tests pass.
An example: say you want to ensure that the user doesn't leave the email address blank, you would write something like this:
def test_should_require_email
@applicant.email = ""
assert !@applicant.save
end
When you run the test it will obviously fail.Then you can write something like:
validates_presence_of :email
run the test again and it will pass.
You can then repeat this for the next desired specification, for example that an email address is valid:
def test_email_should_be_valid
@applicant.email = "pullo@yahoo.com"
assert @applicant.save
@applicant.email = "pullo_at_yahoo_dot_com")
assert !@applicant.save
end
This will fail.Add the following code and it will pass:
validates_format_of :email, :with => /\\A([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})\\Z/i
So, what I might be tempted to do in your situation is to set up some unit tests on your form's validation logic and test the form programatically.
I'm not sure about the best way to do this in PHP, but here are a couple of helpful links:
I know this might seem a bit unwieldy at first, but once you get the hang of it, it really pays dividends.
Thank you very much for the information and it has made me think:In this case I could create some different forms that all submit to the validation code with the input variables set using value. It will be a lot quicker than filling in the form and the values can be tweeked slightly on each form by for example adding a number where it is not allowed etc.
Also since writing this I have found filter_var() which means I do not need regular expressions - I need to have a look around and see if there are any problems using it. Although I am not 100% sure about it, as validate email still lets through all these characters !#$%&'*+-/=?^_`{|}~@.[].
I will have to check out the other options you have both posted for future use.
Hey Rubble,
That's an interesting approach.With the form I am working on, I wanted to do some manual testing, too, so I wrote a user script.This script reads a bunch of values from a JS object literal, then inserts them in the form in the correct places.I'm sure it could be easily tweaked to do what you are proposing above.Let me know if you're interested in this approach and I'll give you some more info.
@Pullo ; My first thought on how to populate the table was to use php and array in some fashion but I thought it take longer to develop that than to do the error testing the manual way!
Yes I would be interested in your method although I have no experience in JS.
Well, I wrote a tutorial on how to do this using TamperMonkey and Chrome.Have a read of that and let me know how you get on.If you have any questions or comments I am more than happy to help out.
Pullo
I have a couple of errors and for some reason the last } was a ] or something after pasting your code.
On the $('Body') lineWarning: '$' Was used before it was definedError expected ';' and instead saw '$'
3 Other similar errors on different lines
I presume this is preventing the code running as I do not get a Populate button.
Oh dear.I presume you are using latest Chrome and latest TamperMonkey.
Could you post the full userscript and (if it's not too much bother) the HTML of the form you want to autofill?
I have got rid of the errors now although I may have done it wrong and this is my code:
// ==UserScript==// @name Auto-fill Order form// @version 0.1// @description Autofills fields in my massive form // @match*// @require ==/UserScript==/*global $, jQuery*/$('body').prepend('<input type="button" value="Populate" id="populate">');$("#populate").on("click", function(){ console.log("I was clicked"); });var values = { Forename: "Fred", Surname: "Blogs", Email: "freddyboy@gmail.com", Message: "Your tutorial is simply the best!"};
$('body').prepend('<input id="populate" type="button" value="Populate"/>');
$("#populate").on("click", function(){ Object.keys(values).forEach(function(key){ $("#" + key).val(values[key]); } }
I was only trying to match a few fields to start with and see how it went.
Yes the latest version of Chrome and TamperMonkey.
I have PM'd you some further details.
That's cool. I got your PM.When you say, you've got rid of the errors, does that mean you've got it working?
I'm just playing around with the code now.
You had some errors in your JS.Change your entire user script to this:
// ==UserScript==
// @name Auto-fill Order form
// @version 0.1
// @description Autofills fields in my massive form
// @match*
// @require
// ==/UserScript==
var values = {
Forname: "Fred",
surname: "Blogs",
};
$('body').prepend('<input type="button" value="Populate" id="populate">');
$("#populate").on("click", function(){
Object.keys(values).forEach(function(key){
$("#" + key).val(values[key]);
});
});
Don't forget to adapt the path, but leave "order.php" off the end.
Thank you Pullo and it is working now; I just need to add the other fields.
Excellent
|
http://community.sitepoint.com/t/best-way-to-error-test-a-form/34355
|
CC-MAIN-2014-41
|
refinedweb
| 990
| 63.7
|
QSqlRelationalTableModel and complex queries
How about QAbstractListModel instead of QAbstractItemModel?
Because I have a list (a QTableView), I suppose this is the one I should use.
My header:
#ifndef PGSSQLMODEL_H #define PGSSQLMODEL_H #include <QAbstractListModel> #include <QStringList> class PGsSqlModel : public QAbstractListModel { Q_OBJECT public: explicit PGsSqlModel(QObject *parent = 0); PGsSql; signals: public slots: }; #endif // PGSSQLMODEL_H
My Source:
#include "pgssqlmodel.h" PGsSqlModel::PGsSqlModel(QObject *parent) : QAbstractListModel(parent) { stringList << "bbb" << "aaa"; } int PGsSqlModel::rowCount(const QModelIndex &parent) const { return stringList.count(); } QVariant PGsSqlModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= stringList.size()) return QVariant(); if (role == Qt::DisplayRole) return stringList.at(index.row()); else return QVariant(); } QVariant PGsSqlModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) return QString("Column %1").arg(section); else return QString("Row %1").arg(section); }
I use set model for a QTableView, but I get a table with two empty rows.
I should get two rows containing:
bbb
aaa
What ust I do?
And how can I access the database?
Hi,
How are you setting that model ?
Hi SGaist.
It's ok now, I'm getting the expected result. I was just hiding a column (forgotten code) without noticing it (ok, very silly of me :)).
I use this to set the model(if this is what you mean):
PGsSqlModel *manufacturers_tbl_model = new PGsSqlModel; ui.manufacturers_tbl->setModel(manufacturers_tbl_model);
How can I access the database from within the class?
Through
QSqlQuery
I ended up using QAbstractTableModel, I think this is the one I need.
Now, let 's say I make a function getDataFromDB, and result set is stored in a QStringList (?? I don't know, I 'm asking, maybe you can suggest me what to use).
Then in ::data function, how shall I use this variable to return the data to the "user"? (I mean the QTableView that will use the data to display them)
I'd suggest a
QHash<quint64,QVariant>where the key has the most significant 32 bits as the row index and the least significant 32 as the column
I 've made this function: (I call it of course, like this: model->setQuery("SELECT id, name FROM parts"))
void TableModel::setQuery(const QSqlQuery &qry) { query = qry; }
I suppose this is not enough for the model to get the data from db and then be available (I mean the data from db) to the model? (a QAbstractTableModel)
Must I do something more?
And this is the data function:
QVariant TableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= query.size()) return QVariant(); if (role == Qt::DisplayRole) { query.seek(index.row()); return query.value(index.column()); } else { return QVariant(); } }
Where I get an error:
...\tablemodel.cpp:74: error: C2662: 'QSqlQuery::seek' : cannot convert 'this' pointer from 'const QSqlQuery' to 'QSqlQuery &'
Conversion loses qualifiers
It's at the line 'query.seek(index.row());'.
How did you declared your
querymember variable ?
private:
QSqlQuery query;
I read from this:
"get rid of the const with const_cast"
What does this mean?
"get rid of the const with const_cast"
NOOOOOOOOOOOOOOOOOOO!!!!
mutable QSqlQuery query;solves your compilation issue but I don't think your logic is going anywhere.
Just a second here. let's take a step back: what do you want to achieve?
- does the model need to be editable and changes be reflected in the database?
- will you have more than 1 column?
I want my QTableView to display data from two tables.
This in SQL means my model should have the ability to:
- make LEFT JOINS on the second table
- Concatenate two fields.
For these things, QSqlQueryModel works fine.
But I also need to add and remove records, which QSqlQueryModel cannot do.
So, my conclusion is I should subclass QSqlQueryModel (this is what I'm doing right now, but I have problems...) and add custom functionality for adding and removing rows.
What do you think?
Personally I would not subclass anything, I'd use a QStandardItemModel fill it with a QSqlQuery and react to QStandardItemModel::rowsInserted and QStandardItemModel::rowsRemoved signals to trigger the update in the db via another QSqlQuery
The problem is I don't have the slightest idea how to do all this.
Is there some example I could look at?
EDIT: QStandardItemModel has no setQuery function.
How shall I "fill it with a QSqlQuery"?
You mean wit QStandardItemModel::setItem?
@Panoss said in QSqlRelationalTableModel and complex queries:
How shall I "fill it with a QSqlQuery"
manually, outside the model
model->removeRows(0, model->rowCount()); model->removeColumns(0, model->columnCount()); QSqlQuery testQuery; testQuery.prepare("select * from MyTable"); if (testQuery.exec()) { for (bool firstRun = true; testQuery.next();) { const QSqlRecord currRecord = testQuery.record(); if (firstRun) { firstRun = false; model->insertColumns(0, currRecord.count()); for (int i = 0; i < currRecord.count(); ++i) model->setHeaderData(i, Qt::Horizontal, currRecord.fieldName(i)); } const int newRow = model->rowCount(); model->insertRow(newRow); for (int i = 0; i < currRecord.count(); ++i) model->setData(model->index(newRow, i), currRecord.value(i)); } }
Works, the model->removeRow works, it removes a row from the model ,but how do I remove this row from the db too? Something like this?
QSqlQuery query; query.prepare("DELETE FROM MyTable WHERE id=1"); if (query.exec()) { etc. etc.
You'll likely have to make a more precise delete query but otherwise, yes.
What do you mean by "more precise"? I thought "WHERE id=1" makes it absolutely precise (the value "1" was chosen for the shake of the example).
Sorry, that was badly written, I meant that you would have to ensure that you are passing the correct parameter(s) to the delete query to ensure you are deleting the same row in the database.
Ah, ok, guys, VRonin, SGaist, thank you very much.
be careful here as if you naively connect the database delete to
rowsRemovedthe first two lines:
(
model->removeRows(0, model->rowCount()); model->removeColumns(0, model->columnCount());)
will delete your entire database and you cannot just use a
QSignalBlockeron the model either or the view won't update
|
https://forum.qt.io/topic/76135/qsqlrelationaltablemodel-and-complex-queries/27
|
CC-MAIN-2018-43
|
refinedweb
| 1,008
| 58.38
|
Web scraping made easy by NickJS
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
How to scrape HackerNews with NickJS, the next gen scraping library
Hello and welcome to this very first NickJS tutorial!
Headless Web browsers are amazingly powerful but yet complicated to use. NickJS is the easiest wrapper on Headless Chrome and PhantomJS. It gives you access to all the features you need with less than 15 methods.
Let's take a look at a simple use case.
If you want to scrape a web page, you'll always need to repeat the same three steps.
- Do actions that will get you closer to the data. There are only four possible choices: open a page, fill a form, simulate user input (mouse/keyboard event) and trigger a DOM event.
- Wait for the actions to have an effect. There are only two possible things we can do: wait for specific DOM elements to appear or disappear.
- Extract data from the page. Running a few lines of jQuery directly inside the DOM works every time.
The scraping "Hello World" is a scraper for Hacker News. To do so, we'll apply the same three steps seen below.
- Accessing the web page using its URL
- Waiting for the data to be loaded
- Get the data using jQuery
This example will take us less than 5 minutes. You only need to be familiar with JavaScript ES2016+.
0- The NickJS context
All we need is an instance of NickJS and to create a new tab. The promise pattern will automatically handle all the potential errors.
// To be sure that all the code will be ES2016+ import 'babel-polyfill' // Import the library import Nick from "nickjs" // Instantiate the web browser const nick = new Nick() // Create a new tab to browse the web nick.newTab(async (tab) => { // // Now we have our tab available we'll be able to load URLs // }) .then(() => { // When everything is sucessfully done we exit with the usual code '0' nick.exit(0) }) .catch((err) => { // When there is an error we quit with code '1' or whatever number that makes sens. console.log(err) nick.exit(1) })
1- Accessing news.ycombinator.com
We first need to load the web page using:
nick.newTab(async (tab) => { // We'll load the URL using open await tab.open("news.ycombinator.com") // Careful! Here, we're not sure the page is fully loaded! })
2- Waiting for the wanted data to appear
To be sure the DOM element – containing the data we need – is loaded, we'll ask our Web browser to wait until it's added.
nick.newTab(async (tab) => { await tab.open("news.ycombinator.com") await tab.waitUntilVisible("#hnmain") // // The element we need, matching "#hnmain", is loaded. // })
3- Inject client side libraries:
The Web page is not ready to be scraped yet. We'll use jQuery to manipulate the DOM and extract an array of data. Hacker News doesn't provide this library; no worries, we'll insert it ourselves using the
inject() method.
nick.newTab(async (tab) => { await tab.open("news.ycombinator.com") await tab.waitUntilVisible("#hnmain") // Inject also works with a CDN's URL. await tab.inject("") // jQuery is accessible in the web page context. So $("*") doesn't work here! For more informations take a look to the next section. })
4- Returning the data:
Now, the best part! The scraping of the title and URL of each article and return an Array of Objects. The
evaluate() method allows us to execute a function in the web page context. All the client-side libraries are available. There are two contexts:
- The web browser (Nick).
- The web page itself, accessible using the
evaluate()method. Check out the example.
nick.newTab(async (tab) => { await tab.open("news.ycombinator.com") await tab.waitUntilVisible("#hnmain") await tab.inject("") // The content of data will be copied to the hackerNewsLinks const variable. const hackerNewsLinks = await tab.evaluate((arg, callback) => { // Here we're in the page context. It's like being in the web browser's inspector tool const data = [] $(".athing").each((index, element) => { data.push({ title: $(element).find(".storylink").text(), url: $(element).find(".storylink").attr("href") }) }) // The callback() function must be called when the scraping algorithm is done. callback(null, data) // \o/ }) })
5- Print the result:
We are all set. We'll
console.log() our result.
Here is a complete recap'.
import 'babel-polyfill' import Nick from "nickjs" const nick = new Nick() nick.newTab(async (tab) => { await tab.open("news.ycombinator.com") await tab.waitUntilVisible("#hnmain") await tab.inject("") const hackerNewsLinks = await tab.evaluate((arg, callback) => { const data = [] $(".athing").each((index, element) => { data.push({ title: $(element).find(".storylink").text(), url: $(element).find(".storylink").attr("href") }) }) callback(null, data) }) console.log(JSON.stringify(hackerNewsLinks, null, 2)) }) .then(() => { nick.exit(0) }) .catch((err) => { console.log(err) nick.exit(1) })
Here we are. We successfully scraped Hacker News in less than two minutes using only 5 methods. You can now try it by yourself and create more (careful, on Tech.io the script is limited to 30 seconds of execution)
Run NickJS
Do you want to know more?
- You can clone the repo on.
- The full documentation is available here.
- Any questions? Feel free to ask on <NickJS.org>.
|
https://tech.io/playgrounds/857/web-scraping-made-easy-by-nickjs
|
CC-MAIN-2018-17
|
refinedweb
| 879
| 70.19
|
- Type:
Improvement
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 0.10.0
-
- Component/s: Perl - Compiler, Perl - Library
- Labels:
- Environment:
Perl
Currently our perl package module files contain multiple packages. We should break each package out to an individual file (or at least make sure everything is in the Thrift namespace) and properly version it. Package versioning was introduced in Perl 5.10 so:
1. Update the minimum required perl to 5.10. This is based on indicating that perl version object was added to perl in 5.10.
2. For each package use the perl MODULE VERSION perlmod syntax, where VERSION is v0.11.0. This is based on.
3. Each module not under the Thrift namespace must be moved there (TApplicationException, TMessageType, TType). This will be a breaking change, but necessary for proper packaging of the library.:
Thrift 0.010000 J/JK/JKING/thrift/Thrift-0.10.0.tar.gz Thrift::BinaryProtocol 0.009000 G/GS/GSLIN/Thrift-0.9.0.tar.gz
There are some anomalies, for example packages defined in Thrift.pm come out at the top level namespace like:
So technically if you do 'install TApplicationException' I would expect you might get thrift. This is wrong and should be fixed. TApplicationException needs to be inside Thrift, not at the top level.
Also we should pull in relevant changes from the patch in
THRIFT-4059 around improving packaging.
Also we should actually use TProtocolException and TTransportException instead of just TException everywhere.
- supercedes
THRIFT-4059 Bump the version dependency to 5.8.1 + update some meta data
- Closed
- links to
-
|
https://issues.apache.org/jira/browse/THRIFT-4069
|
CC-MAIN-2021-31
|
refinedweb
| 265
| 59.7
|
men with money image by PaulPaladin from Fotolia.com
A standard small business loan isn't the only way to get funding to start your new company. You can also seek out investors for your business. Investors give you start up money to help you get up and running, including funds to purchase equipment, pay initial overhead costs and buy advertising space to get the word out about your business. In exchange the investor may ask for percentage ownership or repayment with a return (interest) on the investment within a certain time.
Create a detailed business plan backed with research for your company before you start to seek investors. Most investors want to see your concept written in detail before seriously considering an investment in your business. Provide financial projections and clear, step-by-step information on how you plan to use the funds if issued. Ask a business consultant to review it and make recommendations before finalizing the plan for presentation to an investor.
Compile a listing of venture capital firms who tend to invest in businesses like yours (See Resources). For instance, some venture capitalists prefer to invest in solid new online ventures, and others invest in restaurants. Learn everything you can about the venture capitalists on your list, including the minimum and maximum investments they commonly issue and the application process. Hire a lawyer or business consultant to contact the venture capitalists on your list on your behalf with your business proposal.
Related Reading: How to Get Investors for Your Start Up Business
Try to attract angel investors by posting a business profile on an angel's network (See Resources). An angel investor is someone, sometimes just a wealthy individual, that provides funding to struggling or new businesses. Sometimes the motivation is financial gain, while in other cases the other party just wants to help out the community in some way. If an interested party comes across your profile, he'll contact you to learn more about your idea and possibly agree to help you with funding.
Tap family members and friends to invest in your small business—you can consider them angel investors as well. Sit down with them in a professional setting and present your business plan just as you would with a stranger when you ask for financial assistance. Ask your friends, family and colleagues if they can refer you to small investment clubs in your area also. Use all of your personal contacts to your advantage when seeking out investors.
Solicit silent partners for your small business as another alternative. This can be anyone from a close friend to a business colleague in your industry. The silent partners holds a stake in your business and makes an investment toward operations but does not make business decisions. The offer of a stake in your business could make the other party more willing to help you out with financing.
Things Needed
- Business plan
References (3)
Resources (2)
Photo Credits
- men with money image by PaulPaladin from Fotolia.com
|
http://smallbusiness.chron.com/investors-business-312.html
|
CC-MAIN-2014-49
|
refinedweb
| 503
| 52.19
|
Asif Jan wrote ..
>
> Hello, I am using mod_python 3.1.4, and doing psp development. The
> pages work fine without any probelms. However, when I change the psp
> page on disk the changes are not reflected on the version that is
> served to client. I am not caching pages at the browser side.
>
> However restarting the apache server results in correct page being
> served. Is there a way to tell psp handler not to cache the pages?
Although pages are cached, both the in memory cache and the DBM
caching mechanisms have code in them that should mean that if the
file is changed on disk, it will reload them. Ie., from file cache:
def get(self, filename, mtime):
try:
hits, c_mtime, code = self.cache[filename]
if mtime != c_mtime:
del self.cache[filename]
return None
else:
self.cache[filename] = (hits+1, mtime, code)
return code
except KeyError:
return None
and from DBM cache:
def dbm_cache_get(srv, dbmfile, filename, mtime):
dbm_type = dbm_cache_type(dbmfile)
_apache._global_lock(srv, "pspcache")
try:
dbm = dbm_type.open(dbmfile, 'c')
try:
entry = dbm[filename]
t, val = entry.split(" ", 1)
if long(t) == mtime:
return str2code(val)
except KeyError:
return None
finally:
try: dbm.close()
except: pass
_apache._global_unlock(srv, "pspcache")
Are you sure you aren't connecting to the server via a proxy with caching
enabled or some other caching system like Squid?
When you make the request after changing the file, do you actually see
a request logged in the Apache log file at that time to indicate that the
request is actually getting through to Apache?
Graham
|
https://modpython.org/pipermail/mod_python/2005-May/017988.html
|
CC-MAIN-2022-21
|
refinedweb
| 261
| 67.86
|
'wil. :)\user1
just as before. (this way runs with wscript instead of cscript but it still works.)
Here is what I added:
'/========================)
'Process)
'/=== 'move\cimv2" -filter "Name='user1' AND LocalAccount=True"
$new_user = get-wmiobject -class "Win32_UserAccount" -namespace "root\cimv2" -filter "Name='user1' AND Domain='CONTOSO'"
$profile = get-wmiobject -class "Win32_UserProfile" -namespace "root\cimv2" -filter "SID='$($original_user.SID)'"
$profile.ChangeOwner($new_user.SID, [uint32]0)
[/code]
Which could be even shorter:
$original_user = get-wmiobject "Win32_UserAccount WHERE Name='user1' AND LocalAccount=True"
$new_user = get-wmiobject "Win32_UserAccount WHERE Name='user1' AND Domain='CONTOSO'"
$profile = get-wmiobject "Win32_UserProfile WHERE SID='$($original_user.SID)'"
$profile.ChangeOwner($new_user.SID, 0)
Hey perennialmind,
Thats great coding.
I am sorry to hear that you had issues with the VBScript.
thank's a lot, i will try your script Rob, but if it's doesn't works with my park, this powerShell Scritp works ? (I just change in row 2 "Domain='Tralala'"
$original_user = get-wmiobject "Win32_UserAccount WHERE Name='user1' AND Domain='Tralala'"
Trademarks |
Privacy Statement
|
http://blogs.technet.com/askds/archive/2008/09/09/vista-s-moveuser-exe-replacement.aspx
|
crawl-002
|
refinedweb
| 164
| 54.93
|
How to Punctuate Your Java Code
In English, punctuation is vital. Punctuation is also important in a Java program. The use of curly braces, semicolons, parentheses, double quotation marks, and periods tells Java how to read the code and makes the code easier for humans to understand.
This list lays out a few of Java’s punctuation rules:
Enclose a class body in a pair of curly braces.
In this listing, the MyFirstJavaClass body is enclosed in curly braces.
package org.allyourcode.myfirstproject; public class MyFirstJavaClass { /** * @param args */ public static void main(String[] args) { javax.swing.JOptionPane.showMessageDialog (null, "Hello"); } }
The placement of a curly brace (at the end of a line, at the start of a line, or on a line of its own) is unimportant. The only important aspect of placement is consistency. The consistent placement of curly braces throughout the code makes the code easier for you to understand. And when you understand your own code, you write far better code.
When you compose a program, Eclipse can automatically rearrange the code so that the placement of curly braces (and other program elements) is consistent. To make it happen, click the mouse anywhere inside the editor and choose Source→Format.
Enclose a method body in a pair of curly braces.
In the listing, the main method’s body is enclosed in curly braces.
A Java statement ends with a semicolon.
For example, in the listing, the call to the showMessageDialog method ends with a semicolon.
A declaration ends with a semicolon.
Again in the listing, the first line of code (containing the package declaration) ends with a semicolon.
In spite of the previous two rules, don’t place a semicolon immediately after a closing curly brace (}).
The listing ends with two closing curly braces, and neither of these braces is followed by a semicolon.
Use parentheses to enclose a method’s parameters, and use commas to separate the parameters.
In the listing (where else?) the call to the showMessageDialog method has two parameters: null and "Hello". The declaration of the main method has only one parameter: args.
Use double quotation marks () to denote strings of characters.
In the listing, the "Hello" parameter tells the showMessageDialog method to display the characters Hello on the face of the dialog box.
Use dots to separate the parts of a qualified name.
In the Java API, the javax.swing package contains the JOptionPane class, which in turn contains the showMessageDialog method. So javax.swing.JOptionPane.showMessageDialog is the method’s fully qualified name.
Use dots within a package name.
The dots in a package name are a bit misleading. A package name hints at uses for the code inside the package. But a package name doesn’t classify packages into subpackages and sub-subpackages.
For example, the Java API has the packages javax.swing, javax.security.auth, javax.security.auth.login, and many others. The word javax alone means nothing, and the javax.security.auth.login package isn’t inside the javax.security.auth package.
The most blatant consequence of a package name’s dots is to determine a file’s location on the hard drive. For example, because of its package name, the code in the listing must be in a folder named myfirstproject, which must be in a folder named allyourcode, which in turn must be in a folder named org, as shown in this figure.
|
http://www.dummies.com/how-to/content/how-to-punctuate-your-java-code.html
|
CC-MAIN-2014-42
|
refinedweb
| 567
| 66.33
|
Data Parallelism with Multiple CPU/GPUs?
Run MXNet on Multiple CPU/GPUs with Data Parallelism
MXNet supports training with multiple CPUs and GPUs, which may be located on different physical machines.
Data Parallelism vs Model Parallelism
Workload Partitioning
python
import mxnet as mx
module = mx.module.Module(context=[mx.gpu(0), mx.gpu(2)], ...)
while if the program accepts a
--gpus flag (as seen in
example/image-classification),
then we can try
bash
python train_mnist.py --gpus 0,2 ...
Advanced Usage Machines
KVStore also supports a number of options for running on multiple machines.
dist_syncbehaves similarly to
localbut exhibits one major difference. With
dist_sync,
batch-sizenow means the batch size used on each machine. So if there are n machines and we use batch size b, then
dist_syncbehaves like
localwith batch size n*b.
dist_device_syncis similar to
dist_sync. The difference between them is that
dist_device_syncaggregates gradients and updates weight on GPUs while
dist_syncdoes so on CPU memory.
dist_asyncperforms asynchronous updates. The weight is updated whenever gradients are received from any machine. The update is atomic, i.e., no two updates happen on the same weight at the same time. However, the order is not guaranteed.
How to Launch a Job
To use distributed training, we need to compile with
USE_DIST_KVSTORE=1(see MXNet installation guide for more options).
Launching a distributed job is a bit different from running on a single
machine. MXNet provides
tools/launch.py to
start a job by using
ssh,
mpi,
sge, or
yarn.
An easy way to set up a cluster of EC2 instances for distributed deep learning is using an AWS CloudFormation template. If you do not have a cluster, you can check the repository before you continue.
Assume we are at the directory
mxnet/example/image-classification
and want to train LeNet to classify MNIST images, as demonstrated here:
train_mnist.py.
On a single machine, we can run:
python train_mnist.py --network lenet
Now, say we are given two ssh-able machines and MXNet is installed on both machines.
We want to train LeNet on these two machines.
First, we save the IPs (or hostname) of these two machines in file
hosts, e.g.
$ cat hosts 172.30.0.172 172.30.0.171
Next, if the mxnet folder is accessible from both machines, e.g. on a network filesystem, then we can run:
python ../../tools/launch.py -n 2 --launcher ssh -H hosts python train_mnist.py --network lenet --kv-store dist_sync
Note that here we
- use
launch.pyto submit the job.
- provide launcher,
sshif all machines are ssh-able,
mpiif
mpirunis available,
sgefor Sun Grid Engine, and
yarnfor Apache Yarn.
-nnumber of worker nodes to run on
-Hthe host file which is required by
sshand
mpi
--kv-storeuse either
dist_syncor
dist_async
Synchronize Directory
Now consider if the mxnet folder is not accessible.
We can first copy the
MXNet library to this folder by
bash
cp -r ../../python/mxnet .
cp -r ../../lib/libmxnet.so mxnet
then ask
launch.py to synchronize the current directory to all machines'
/tmp/mxnet directory with
--sync-dst-dir
python ../../tools/launch.py -n 2 -H hosts --sync-dst-dir /tmp/mxnet \ python train_mnist.py --network lenet --kv-store dist_sync
Use a Particular Network Interface
MXNet often chooses the first available network interface.
But for machines that have multiple interfaces,
we can specify which network interface to use for data
communication by the environment variable
DMLC_INTERFACE.
For example, to use the interface
eth0, we can
export DMLC_INTERFACE=eth0; python ../../tools/launch.py ...
Debug Connection
Set
PS_VERBOSE=1 to see the debug logging, e.g
export PS_VERBOSE=1; python ../../tools/launch.py ...
|
http://mxnet.incubator.apache.org/versions/1.8.0/api/faq/multi_device
|
CC-MAIN-2021-17
|
refinedweb
| 603
| 58.99
|
Hi,
I am trying to externalize a class and am having problems getting my class to work. On the flash timeline, I have this function call:
CreateText(lessonTitle, "Headline_1", textWidth, textX, textY - 5, 0xFCAF17, 54, 1, true, 0);
Which calls out to an external class:
package { import flash.display.*; import flash.text.*; public class CreateTextBlock extends MovieClip { public function CreateTextBlock() { // init }); } } }
My function call does not recognize CreateText(), but recognizes CreateTextBlock, however, if rename my CreateText function to ChangeTextBlock, I continually receive the error message:
1137: Incorrect number of arguments. Expected no more than 1.
Can anyone help me refactor this to a working class?, or point out my flaw?, hopefully it's platently obvious.
Thanks so much,
Chipleh
Do you create an instance of the CreateTextBlock class? If so, you should be targeting that instance to call upon its CreateText method.
Well, I found the answer to most of my question; I wasn't instantiating the class correctly. The solution was:
import CreateTextBlock;
var TextCreator:CreateTextBlock = new CreateTextBlock();
TextCreator.CreateText(lessonTitle, "Headline_1", textWidth, textX, textY - 5, 0xFCAF17, 54, 1, true, 0);
heyas Ned,
Thanks for the reply. Yes indeed, that's what I was missing. I posted my sample code, is there a better way to go about doing this?
Also, I'm trying to return the value of textName to the stage, so Flash can destroy the text object when the stage is finished with it. Right now, I'm using getChildByName to destroy the text object, i.e.:
var headLineText:DisplayObject = MovieClip(root).getChildByName("Headline_1");
if(headLineText != null)
{
MovieClip(root).removeChild(headLineText);
}
Before, all the code was happening internally, now that I've externalized the class that creates the text object, the stage seemingly doesn't understand the name of the text object, since it is not being removed anymore. Am I not adding the name to the display list properly? Any suggestions?
~Chipleh
Unfortunately I am anything but adept in class matters.
If you used:
addChild(TextCreator);
to add the object, and that is the object you want to remove, then using:
removeChild(TextCreator);
should be all you need to do, and just after that assign it to be null to remove all traces of it and make it available for GC:
TextCreator = null;
Thanks Ned, much appreciation as always.
~Chipleh
You're welcome
North America
Europe, Middle East and Africa
Asia Pacific
South America
|
http://forums.adobe.com/message/4549997?tstart=0
|
CC-MAIN-2013-20
|
refinedweb
| 399
| 54.22
|
1. Simple SpreadSheet collaboration We've added a simple collabortation mode to the SpreadSheet, so one SpreadSheet can import data from cells of other SpreadSheets. Much more advanced collabortation is in the works. 2. Big speed-up in VisAD line graphics under Java2D This applies for most single width (the default) lines, including contour lines. 3. Linux port of Java 2, pre-release-v1 It didn't work (AWT) on our Linux systems, but this was consistent with the warning in its README file about trouble with a libstdc++ library so we'll try again on the next release. Still no update of the AIX port of Java 2. 4. Java 2 Solaris Production Release First, note that you'll need to install Java3D 1.1.1 to avoid some thread bugs that occur if you run Java3D 1.1 with the Java 2 Solaris Production Release. The Java 2 Solaris Production Release is very fast. In fact, for simple computations about as fast as C. I ran a simple speed comparison between 'identical' C and Java programs. Here's the Java code: public class test2 { static final int size = 1000000; static final int mult = 10; static final int iterations = 10; public static void main(String args[]) { int i, j, k; float[] array1 = new float[size]; float[] array2 = new float[size]; for (i=0; i<size; i++) { array1[i] = i; array2[i] = 2.0f; } for (j=0; j<iterations; j++) { for (k=0; k<mult; k++) { for (i=0; i<size; i++) { array1[i] = array2[i] * array1[i] + 1.0f; } } System.out.println("interation " + j); } } } And here's the 'identical' C code: #define size 1000000 #define mult 10 #define iterations 10 #include <stdio.h> #include <math.h> #include <string.h> main() { int i, j, k; float array1[size]; float array2[size]; for (i=0; i<size; i++) { array1[i] = i; array2[i] = 2.0; } for (j=0; j<iterations; j++) { for (k=0; k<mult; k++) { for (i=0; i<size; i++) { array1[i] = array2[i] * array1[i] + 1.0; } } printf("interation %d\n", j); } } Here are the timings, on my Ultra 10: 9 seconds - C code compiled with optimization 12 seconds - Java code running under Solaris Production Release 15 seconds - C code compiled without optimization This is consistent with what we're seeing for the computationally intensive parts of VisAD. Now we know that Java can be as fast as C and Java3D can be as fast as OpenGL. Once this reality is ported to lots of platforms, there is no reason not to do visualization in pure Java using VisAD. Way to go, Sun. Cheers, Bill ---------------------------------------------------------- Bill Hibbard, SSEC, 1225 W. Dayton St., Madison, WI 53706 whibbard@xxxxxxxxxxxxx 608-263-4427 fax: 608-263-6738
visadlist information:
visadlist
visadarchives:
|
https://www.unidata.ucar.edu/mailing_lists/archives/visad/1999/msg00069.html
|
CC-MAIN-2019-26
|
refinedweb
| 461
| 62.98
|
cTieoct rit «tt«t
'hilanthropies Report: 'A Long Way to Go' OMAHA - The 1»7S Omaha JewUh Phflantrtopiea Campafgn "Is making good I pragNM," according to General Chairman Eh : M. Zalkln, but there's still a lot left to do The report followed a meeting Monday, ' night. May 19. at the Jewish Community Center in which the various F^llanthropes division dialimen and other officials reviewed and , dtioNMit the campaign to date. ~ Tbe ins Campaign goal Is $3,450,000. ZaUdn ' Mid the drive "Is making good progress ap' proaching the haifway mark." Those in attendance with Zalldn Included .Harlan Noddle, president of the Jewish Federation of Omaha; Morley Zipursky, im; nMdIate past president of the Federation; ^ Buddy Goldstein, chairman o( the Philanthropies of Standing Committee; Racky -Newman and David Prlediand, Keynoters Division co-chairmen; Stanley Slosburg, ; Pacesetters; Leo Meyerson, Initial Gifts; Sam 'Ftted, Telethon and Jack Safersteln, Senior ,EMcuUve«. "Each of the chairmen reported they were ' warmly received by those they called upon and
that In most of the commltntents, the response has been generous," said Zalkln. "However, we do have a long way to go to meet our goal and raise the necessary funds with which to operate." The many services provided by the Federation's agencies to the Jewish community of Omaha are dependent upon the Philanthropies campaign he noted, naming (he Community Center, Jewish Family Service, Dr. PhUlp Sher Home (or the Aged, the Jewish Press, Camp Ester K, Newman and the Federation Library, among the agencies. "And we cannot forget the funds raised illso go to rescuing as many fellow Jews a« is possible," he added, citing the cause of Soviet Jewery. "We strongly urge those who have not yet made a commitment to keep in mind that every dollar they commit goes to alleviate sometxidy's suffering and also goes to make somebody's life a little more meanin^lful, whether It be a life at the Dr. Sher Home, in Omaha or In some home for the aged In Israel," the chairman said.
Ghorbalinterview Believed: Diplomat NEW YOBK (JTA) - A senior Israeli dlplonaat told " the Jewish Telegraphic Agency thai he haa no dout>ts ; that Mbraf Ghort>al, Egypt's
published in Buenos Aires. Aba Gefen, a former Consul in Argentina and presently the director ol cultural affairs at tlw Israel Foreign Ministry In JeniKalPnn
. States, did advocate tbe extermination of all traces of r Judaism in the MIdsasI in ait I Interview puMlihad aarlier ^this year in Marphar, a rlghtwing periodical
tjld
caslon of Mohammed's birthday, views basically simlllar to thai which Ghorbal Expressed In Marchar.
Pool Opening Sunday OMAHA - Gary Jafltch, center, Community Center aquatics director, goes over some points with David Northam, a Ufeguard supervisor, as Oiuck McCoUum, Center maintenance man, works on special vacuum machinery hi tbe Center's new outdoor •wimmlng pool, which officially opens Sunday, May IS, at 10:30 a.m. The pool, located at tbe south end of the Center, bu a snack bar con-
that
"Ghorbal was only echoing the view of hlsbo««. President AnwBrSidaf*'"*'*^ ' According to Gefen, Sadat declared last year in Al Hassln nuMque in Cairo, on the oc-
SERVING DES MOINES, Here are some Interesting questions about your contribution to Omaha Jewish Philanthropies. How many can you correctly answer? The answers will appear elsewhere In this issue of The Jewish Press.
ti7,<i0O, mflio, mjnot 2. What does one year's vocational-academic training In an CRT School in Morocco cost for a needy Jewish student - $1,100, taOO, 13907 . 3. What does your year's subscription to Tbe Jewish Press cost - $1,17.90, nO?
?Sher Home Open House Is Scheduled for June 1 Elderly) members, as well as residents, will act as hosts and hostesses and assist with all arrangements, according to Mrs. Sol Parsow and Mrs. Jack B. Cohen, LOVE cochairmen. The purpose of the Open House Is to better acquaint the community with the Dr, Sher Home and the important services It provides.
Center Stage Auditions Set i OMAHA - Auditions (or [ Center Stage's production of f "Sweet Charity" directed by ^Norman F'Ubert will be held r Sunday. June 1, at 2 p.m and
Monday, June 2, at 7:30 p.m at the Jewish Community Center The musical will run July 24. 28,27,31 and Aug. 2 and 3
COUNCIL BLUFFS, UNCOLN, OMAHA
Omaha, Nab., Fri., May 23,197B
Vol. UV No. 30
Terrorist Incidents Investigated
i. Haw much does It cost for one Jewish family from the Soviet Unton to Immigrate and be absort>ed Into Israeli society (Including all services Involved in the process) —
OMAHA - Invitations have , been tent to the Jewish comnnunlties of Omaha, ' Lincoln and Council Bluffs to [ attend the fourth annual Open • House from 2 to 4 p.m. Sun. day, June U at the Dr. Philip ; Sher Home for the Aged. [ Home residents, directed by ' Mary Wine and Ida Potash, ^ will bake all refreshments \ler\ea. LOVE (League Of' tering Volunteers lor the
cession stand which Includes bathroom facilities and vending machines. The big poA, designed to aecomodste about SOO persons, has room for sunbathers and a wading pool tor toti. Hours of operatkm tUa weekend will be 10:30 a.m.-t p.m. on Sunday, noon to • p.m. on Monday. The hidoor pocd also will operate tbrougb the summer months. (JP Photo)
Damaged Menorah OMAHA - A menorah daoiaged by the May ( tornado standt CB the denk In Rabbi SUtaey Brooks' study at TUnple Israel. RabU Brooks •aid that "people have been absolutely marvelous" In their offers of help to the damaged synagogue and laM calls have come in from all over the country n well a* from Omaha. Among tiM aid pledged was 15,000 from Dundee Preabyterlan Church, tbe rabbi said. The Temple office this week moveil its temporary headquarters from the Jewish Community Oenter on South isand Street to the Ovariaad WoK office building, •n« Pacific St., Suite 2U, Omaha Mioe (5564536). All religloui services will continue at the Community Canter. (JP Photo)
JERUSALEM (JTA) - The explosion of a booby-trapped picnic basket that injured 20 persons on a crowded public l)each on the sliores of the Dead Sea was one o( several terrorist Incidents on the West Bank and In Israel under investigation by police at the close of the long Shavuol weekend. Four of the people Injured on the beach were still hospitalized this morning. The other injured, rushed to two Jerusalem hospitals, have been discharged. The explosion occurred at about 2 p.m. local time at Ein Feshcha, one o( several public tieaches on the Dead Sea where both Jews and Arabs congragete on holidays. Farts lasa Awad, a, was killed by a hand grenade while be was tarring the roof of a school building near Acre on Haifa Bay. Police said that Awad, a school employe, was carrying tbe grenade when it exploded. Its pin, found near the body, Identified the grenade of Dutch make. Recently, explosive charges
detonated under Arab-owned trucks In Ramallah, 15 miles north of Jerusalem and In the neighboring village of Alblrah. One person was slightly injured. Police believe that all of the weekends Incidents were the work of local terrorists. Terrorist induration from outside Is believed to have been prevented by the heavy security measures taken In all border areas last week to forestall assaults on civilians during May 15, the 27th anniversary of Israel's Independence and the Shavuot holiday that (ollowed. A number o( Arabs were detained (or questioning after the beach expolsion but most of them were released. According to eye-witnesses, an explosive concealed In a picnic hamper the fragments of which were found scattered over a wide area of the beach. The exloslve created panic among the hundreds of bathers from all parts of tbe country who came to Eln Fashca yesterday because II Is still too chilly to bathe In
other areas. Jews and Arabs frequent the Dead Sea beaches In almost equal numbers and no dlsturt>ances have ever been reported between them. AN EXPLOSIVE CHARGE WAS DISCOVERED NEAR the Rockefeller Museum bi Bast Jerusalem this morning and was dismantled by polica without caushig bijurles or fifffrmgg
Israeli security forces, meanwhile, uncovered a terrorist cell In the process of organization inside Israel and arrested suspectd members from Nazareth and nearby Yafia village. One of "the suspects was identified as Mahmoud Gazzalin, ^2, deputy chairman of the Yafia town council, who Is reported to have had a number of detonators In his possession. The gang is believedd to have been preparing (or acts of sabotage on May IS when they were apprehended. Gazzalin was electd to the coiincil on a non-partisan ticket associated with Rakah one o( Israel's two Communist parties.
Mw 23.1976
TtM JinMh Pr—
•atM
Omahans in Business t!ooperatlon and a rationaJ approach to problem-solving were cited last Friday by Nathan and Ernest Nogg as the keys to the brothers' having been In business together 50 years. The two, chairman of the board and president, respectively, of Nogg Paper Co., Inc.. were honored by their employees at a special party at the office. 323 South 10th Street Some 275 well wishers — present and former employees, supplier salesmen and dealers — attended "Cooperation between brothers." said Nate. "We were taught by our parents to have love lor each other and to live a life as'brothers. Ernie and 1 have been in business SO years and there has never — emphasis on 'never' — been one word" of argument. Said Ernie, "We have rationalized. We've had disagreements where we've been able to sit down and rationalize and come to an understanding without having to have unnecessary arguments." "There was love and respect and consideration for the other fellow" in theii- parents' home, added Ernie His wife said another factor was that the husbands were the ones who ran the business the wives stayed out of that and Nate's wife cited the family closeness, indtiding that between she and her sister-in-law, both named Ruth. "We respect each other, we love each other, we love each other's children." she said. •It's been a delight" to work (or the Noggs, said 32-year veteran salesman Harry G. Mendelson. and Jack Donald, national account sales manager of Crown-Zellerbach who came from San Francisco
Nate, left, and Erale, aeoaad firam left, greet guetto at tlMlr SOtb annlvenary cdebratloo. The controlling interest of S. for the party, praised the brothers as "very fair" and Riekes and Sons, Inc. has been sold to the Alco Standard honest. Nogg Paper Co . established Corporation of Valley Forge. June 1,1925, deals in industrial Pa paper products and custodial Alco. a diversified supplies out of both Omaha maniftacturing, mining and and Grand Island. distributing company, anNate's sons. Alvin and nounced the purchase of Donald, are vice president and Riekes common shares secretary, respectively, and representing 58 per cent of the Ernie's son Alan is treasurer. outstanding shares. Nate has been president of Officials said there would be Beth El Synagogue and Ernie no change in management of is a past presideni of the Riekes. which distributes Jewish Federation and a glassware, containers and former general chairman of materials handling equipPhilanthropies. In which Nate ment. also has been active. Nate, was longtime chairman of the Dr. Philip Sher Home for the Center's Teacher Ageffind first chairman of itt building committee, while Seated President Eniie was chairman of the OMAHA - Jessie Camp Esther K. Newman Rasmussen, directing teacher building committee. at the Jewish Community Center's Pre-School, has been Paul M. Goldstein, elected president of the president of Capitol Rent-A- Nebraska Association for the Car of Omaha, is a recently Education of Young Children, elected director of the Car and regional unit of the national Truck Renting and Leasing organization. Association. Mrs. Rasmussen, a 1967 University of Nebraska graduate, has taught in preschools in Lincoln. Omaha and Indianapolis.
Omaha Organizations
MTUBOAT, MAT M I'noi •VHti Cha|>i*r>, Omaha Marina. a.M p.m. •UNO*Y.MAT IS Coroor Woman o( Hodat tali, 2 p jn. JCC FamilyMoccobao, l2:Mpjn.
Mamoftai Day OMor AduHt. XC.IO am. 1Un»AT,MAT>7 Mtrochi Rofular moMIng, 12:30 p.m. Ptonaar Woman ftogulor moatinQ. S p.m. Fodaratlon aoord Moollng. KC. 7:30 p.m. tMaiNMAV.MAVM Vnal I'r f •••adbraakan, Hroslda Rottauronl, 2noofl
munoAr.MArat •'noi I'rltti CombiMkar Eloctlon mootlnt. • pjn. AduH Educollon Moollnt. tCC. 7:30 p.m.
-5 Houn Nlofi#sy*rrNMy
t I
10AJIII.-t« PM. %mtmdmy
I
WorU News Briefs Economic Unroat
CALEMMR OF JEWISH EVENTS
'
it • #«tt
MbTOtlANK
n»4m%d MNHaryAva.. "11«a ••nil That Car**"
mondmy^UmY TA.M.tatrJW. urimy $AM.nU
*»«>»i||i iw>i«iiaiiii.ir>—te
PIONEER WOHEN Program plans for the coming year will be discussed at the Pioneer Women meeting Tuesday, May 27, 8 p.m. at the home of Mr. Alan (Gloria) Goodman, 1836 Holling Dr. Final plans will be made for the Donor affair. For information call Gloria (333-3351) or Pearl Rosenberg (556-9939) WZRACHI WOMEN Ida Potash, Molly Franklin and Dorothy Rubeinstein were installed as coiiresldent*' of the Kalah Franklin Chapter of Mizrachi Women during the joint ceremonies with the MIzarchI Junkir League. 6:30 p.m: Wednesday, May 21, at Beth Israel Synagogue Mrs. Samuel G. Bellows of Chicago, sister-in-law of author Saul . BeUtnva. wi
ArcMiisltop Speaiu
NEW YORK - Roman Catholics should strive to understand and respect the religious tleniflcane of the link betwten the Jewish people and the land of Israel," the President of the American Catholic hierarchy declared today. Archbishop Joseph L. Bemardin, President of the National Confemce of Catholic Bishops, and Archbishop of Cincinnati, was the guest of honor and principal speaker at a dinner and reception at the national headquarters of the American Jewish Committee, attended by nearly 100 national Jewish and Christian leaders. Addressing the question of the struggle in the ° Middle East. Archbishop Bemardin stated: "The right of Israel to exist aa a sovereign state with secure boundaries is clear and needs to further explanation." He added, however, that "the Palestinian Resist Boycott Arabs must have a voice in the negotiations," NEW YORK The American Jewish Com explalnng thai "a basic human right of any mittee welcomed the action of two of this group is that no settlement In a mailer which country's most prestigious corporations affects them so directly and Intlmelely may be reaffirming their delermlnaton to resist the Imposed on them." Arab boycott and to reject any Arab pressures to discriminate against Jews or members of NATOintarastod any other minority group. fn a statement by its President, Elmer L. COPENHAGEN (ZINS) - Moscow radio Winter, the AJC noted that Internationa was heard here as reporting that NATO Is inBusiness Machines Corp. and the Bank of terested in Haifa as a possible Mediterranean America had made their position clear on this port to serve the naval forces of the Western issue in recent public statements, explicitly Alliance. declaring their unwillingness to engage in any According lo the radio transmission. NATO discriminatory practices. Is said lo be encountering great difficulties In coming lo an agrecmenl with Greece for the use of iU faclllites as a base for NATO forees, Right to Know and this explains the interest' in Haifa port. NEW YORK - The Securities and Exchange According lo Moscow radio, if Israel agrees to Commission should require SEC-reglstere cooperate with NATO, it will create a new companies to disclose the extent of titeir factor conributing to Middle East tensions. comjiliante with Afab boycott demands, the^ American Jewish Congress urged today. In a statement submitted to the SEC. Rabbi Arthur Hertzberg, president of the Congresss, IMiHtaryDuty said investors had a right to know not only JERUSALEM (ZINS) - Since the Vom about a company's financial affairs but also whether it was "polluting the physical en- Kippur War Ihousans of reserve officers have vtronenl, affording equal opportunity for volunteered for active duty with the Israel emplyment and promotion to women and Army, according to a statement made by radical and ethnic minorities, lending (3oi6iiel Bartel to a youth gathemg. Included assistance to the maintenance of a govern- amongst the voluntary enlistees, he aald, are mental system of segregation In South Africa pilots, parachute troops, and peclalists an technicians in various motorized diviskHis. or complying with the Arab boycott." The American Jewish Congress statement Confiscated. was submitted to a hearing on whether the SEC should mandate disdoiure of Information on environmental and other "socially significant matters." WASHINGTON (ZINS) - Israel has been grossly negligent, according to polllteal observers, in falling to call attention to the fact Poaco Coioquium that Arab countries have conflsaled Jewish NEW YORK - An unprecedented meeting of roperty to the tune of about 7 billion dollars representatives from the world's major (atth over te yean. According to the expert, this is s groups will Uke place May 26-30 In Bellagio, political blunder of nujor proportions: The Italy, to develop and recommend guidelines losses were borne by those Jews who could ao and aqtkm programs for religious groups to longer live in Arab lands and who left for IsriMl assist In dealing with the international food or other countries. crisis. The first Inlerreliglous Peace Olloqulum will focus on "The Energy-Food Crisis: A Tuminfi Polntr Challenge to Pease, A Call to Faith," and will bring together leading Catholic, ProteslanI, WASHINGTON (ZINS) - Soviet Foreign Jewish, Eastern Orthodox, Islamic, Buddhist, Minister Andrei Gromyko's public statement and Hindu autrhorltles from all parts of the that his government is ready to guarantee world. Israel's securtly made a deep Impression In The Colloquium was proposed by the local political circles. Especially noteworthy Is Synagogue Council of America, the umbrella the fact that Gromyko received his Instructions agency representing the national religious to make his declaration at a festive recepton bodies of Orthodox, Conervative and Reform (or two prmlnent Arab dlgnltarls • the Forein Judaism lii consultatons with religious agencis Ministers of Egypt and Syria. Most comsuch as the World Council of Churches, the mentators saw this as a positive development Vaican, and representatives of Ortental and while sounding a note of cation to be on guard aganst politk:al trikery. Middle Eastern faiths. TEL AVIV - One who was not surprised by the recent economic unrest in Egypt, la Professor Rliyahu iKanovsky, of Bar-Ilan University, who for «ne time now has pointed out the serious shortcomings of the Egyptian economy. Professor Kanovsky, who specializes in the economies of ttie Middle East, claims, in fact, that the shortcomings are so basic and coninuingthat even the great Influx of financial aid from the oil rich countries now pouring into Egypt will not improve her situation apprecialy. This applies to Syria as well, says the Bar-llan Professor, though to a lesser extent. The basic causes, hv says, are: poor human resouces, a faulty and inflated bureaucracy and a lack of skilled personnel, especially at the managerial level.
Confiacatod
Answers to Philanthropies Quiz: 1. Immigration and absorption costs (or one family total $53,M0. 2. One year's OI^T vocational training costs $350. 3. A subscription to The Jewish Press costs (7.50.
Cancelled OMAHA - The May 27 meeting of the Dr. Philip Sher Home board has been cancelled, according lo Ben Laub, Home director.
M«Y23,
^aimors
to Have 2 Rotes in Upcoming Conceit
OMAHA - What will the big Cantorial Concert, scheduled for June 8 at the Jewish Community Center, afford the Itatenerr^_. . -. an opportunity to hear the cantors In their traditional roles as well as those of concert performers," explained Cantor Chalm Najman of Beth El Synagogue, one of the six who will perform. The program will offer lighter musical selections
such as Yiddish, Israeli and English showtunes in addition to the "main course" — cantorial music, he said. It is scheduled for 8 p.m. in the Center Theater. In addition to Cantor Najman, the outstanding list includes Beth El Cantor Emeritus Aaron Edgar and his son, Cantor Raphael Edgar of Temple Beth ZIon in Buffalo, N.Y.; Cantor L«o Fettman of Beth Israel Synagogue In Omaha; Cantor Plnchas Spiro of
Tifereth Israel Synagogue In Conservative Movement. Des Moines and Cantor Leon Najman, but has among Its Llssek of Congregation B'nai members many cantors from AmoonainSt. Louis. Traditional and Reform CantorUl concert* have Synagogue. been given by the various It has scholarship funds to Omaha oongregatlans through . help young men training for the years. This one, qxMsored the cantorate and funds for by the Jewish Cultural CouDcU various musical, publications, ol Omaha, Is believed unique including newly combecause It is not being spon- missioned musical works and sored by a particular new editions of cantorial synagogue. It features cantors classics. Cantors Llssek and Raphael from the Orthodox, Conservative and Reform Edgar graduated , from the movements of Judaism. Jewish Theological The idea for the concert was Seminary's Cantorial Institute proposed by Omaha's cantors, while Cantor Najman is a in conjunction with their graduate of the Cantorial colleagues in the Midwest Training Institute of Yeshiva region, to Mark Zalkin and University in New York. Ruth Katzman of the Jewish Cantor Spiro received his Cultural Council. They formal training in Israel and brought the idea before the America and is an honorary regular meeting and Mrs. fellow of the Cantors Stan (Jean) Lipsey was Assembly. named chairman of the The Assembly, which program subcommittee. "The recently celebrated its 28th idea has been met with en- birthday, "had done much to thusiasm," said Cantor raise the standards of the cantorate and the professional Najman. The concert is being esteem of the cantor in the presented as a benefit for the eyes of the congregants," said Cantors' Assembly, an Cantor Najman. organization of cantors afTickets for tiie concert, filiated with the United which are tax-deductible, are Synagogues of America. The available at the Center or by Assembly, an arm of the mall.
Fsderation Sponsors Teacher Training at 'J'
'Ahead of 1974' OMAHA-rrank CkiklMrg. rigM, Cfrclialnnan with Paul Ooben of the Young Executive* Dlvtslan of the UTS Omaha Jewlifa PMIanthroples <—nyign repotls that "our dhrialaa at this polttt Is alWMl of last year" In pMfas "willcfa Aoirs the commltment of the younsar people of our community to the need* of tbdr fellow Jews. We bave aa enHwrititlc bond) of worten, young gentlemen who are cnwimllteil andthat'i good, because tU* li the group that is UM key to future Phllantbnple*' swoeaaes-ttey are our fuliire Mg^vers and workers." Goidbetg added the workers are "trying to get increaaes rather than Jurt gat a pledge — an Increaae In cnwimltment to Israel and to Omaha'* Jewish conmiunity. CoCbainnaa Cohen said be anticipated wrapping up work In about two weeks. Shown with GoklMrg are Eli M. ZaUdn. center, PUlantliraple* General chalnnan. and Oerald FlamtMNan of Plalnlleld, N J., division
OMAHA - Dr. Saul Wachs of ISraiideis University, soon to liecome head of Grantz College, will conduct a Teacher Tralnbig Institute at the Jewish Community Center. The Institute will run from Monday, June 2, to Friday, June 6,9:30 a.m.-3 p.m. Announcement of the Institute has been sent to area synagogues and departments of education including Omaha, Des Moines, Sioux City, la. and Lincoln.
Dr. Wachs' program last year was so successful that the Department of Jewish Education of the Jewish Federation asked him to return this year, Steve Riekes, chairman of the Department of Jewish Education said. Religious scliool teachers and others who simply wish to be more informed about Judaism will find the Institute most valuable, Riekes added. Baby sitting service will be available. For further Information, call the Federation office, 334-8200.
197B
Th» J»wwh Pren
^mtm.
Prayer Stand Cover OMAHA — Abraham Blnlamow displays the cover tor the prayer stand which was contributed to the Dr. Sber Home by his son, Ralph.
JCC Day Camp Stiil Has Space OMAHA - Camp Funshlne, the Jewish Community Center's pre-schoel day camp, has a few openings left in both the three-and five-day programs. Camp sessions begin June 23, July 7 and July 21. Children must be 3 years old by June 1 in order to attend the threeday-a-week session. Those children 5 years of age or entering kindergarten in the fall may attend the five-day a week program. Each two-week session costs ^1 for the three-day and $35 for the five-day program. Transportation may be requested. The camp day is 9:30 a.m. until hboh.^ti^ies and outdoor
cooking are part of the program. Applications are available at the JCC.
Maintenance Help OMAHA - The Jewish Community Center is twnefiting from the United Way of the Midlands Comprehensive Manpower Program, according to Chuck McCollum, JCC maintenance engineer. The Center has added one man to Its general maintenance crew for a six-month program which Is funded through the United Way. McCullum said that he hear(^ of the program and expressed interest.
Can't fit anotter thine in yovr closet? IIEMEMBERHADASSAHI vim n**d clothing on hongari, oddi ond •nd» ol glottwor*. bf l<o-broc., dlth«, poti and pom. working opplioncot! W« connot offord 0 pickup truck. Thonk you (or bringing conlributiont to our itor* — iff doductlbl*. VoluntMri noododi Coll BMt Krotno: S56-1133or Sorah loihlniky: 5S3-330I
HADASS/IH "BARGAM BOX" 29 ]8 FARNAM Jusf West of "King's" OPEN SUNDAY THRU FRIDAY 11t00-4t00
0 loemlit {fill ike Canto/te't^gscmbftj
A GALA CANTORIAL CONCERT ,
Sunrffltj.^Hc 8. 1975 8:00q>.uM. ^cu/lsfi Cowrminiiij Centen ^kata
I I I I I I I I I I
S C3 O CO
If
IfiakUnq CAHTOI AARON EDGAI, ^m>ia CANTOR RAPHAU EDGAR, ^fi^Uafo CANTOR LEO FEnMAN, Omka
aWTOR LEON LISSEK, S( ^nui-! UNTOR CHAIM NAJMAN, Omoh CANTOR PINCHAS SPIRO, ^«« Moi^n
o
i 9'(cfcet9 one amikhUs ai'^etk £(S()iiagogu&.^etliv9sitae(Si{nagoque. 'tJtnplk v9sAae( and (lie ^ewisk Coninuiii(ti| CeiiteA.
4-
i-i S -fi "« _s
fm±.
Mw 23.1976
Jhij0»Mt\Pnm
What They're Saying
C>tll*^lll«tll
ill i«r«ic4
Another Side of The News HAIFA - My readers complain that the news from Israel has not made very pleasant reading In recent months. Has it ever occurred to you that most news (lashes sent overseas are chosen on the basis o( their sensationalism? Terrorism, danger of war. threats, upheavals — all appeal to the editor and, i( the truth must lie told, to tlie reading public as well. A publistier in California wtw tried to issue a newspaper accentuating only the happy and positive side of events quickly went broke. It was not what people bought newspapers for. Nevertheless, I have combed through the recent news here and offer you a special edition of Alpert's Happy Tidings, to prove that there is a bright side to things
engineers and technicians from the Soviet Union. Among the latter are to be found a large percentage of women with technical skills. The Israel Students Association informed the Knesset that it refused with thanks the additional subsidy A numlier of kibbutzim, offered by the autlwrities to prcvkNisiy distinguished for provide students with cut their secular approach to rates on domestic tranJewish life, have requested sportation. The Ministry of assistance from the Ministry Education has other, more of Religion in constructing important use for such money, synagogues (or the kU)t>utz tlie students said. membership. Botti Iraq and Jordan have In the last two years been oUsriug hl^ aalailes Juvenile delinquency has sunk and other Iwliifwniwla to to its lowest level since such Arab operta In aylcidture statistics were first begun in and water rawuroee In the Israel in 1962. Weal Bank, to come to tMr Seventy per cent of the new oountrtea. Both lamk wWi to employees absort>ed in the benefit from the qMclal Israel railway system of late training which Israel haa are new immigrants to the isr the Wett Barii country, most of them Kama! Khair, 38, has been sworn in as a judge in the Haifa magistrates court, the first Druze to hold a judicial post in this city. It may be only peanuts to servative Judaism and the United Synagogue of America. you, but Israel had a bumper He made It clear he was peanut crop this year, and referring to some of the most took In over six million dollars commercially successful. from exports akme.far ahead Jawtali wrttcrs "Midi a* Saul of last year. Bellow, Beraard Malamud, The European Professional and ol ooune, PUUp Rod), Basketball League recently who bavc drnnomtralad the ended Its first season. In first ieaat auttMolietty o( AmericaB place were the Israel Sabras, JawlA Uie. Noae of ttaeae have ahead of Belgium, Switwritten meaningfully or zerland, Spain and Germany. poaitlveiy about the Amerlcao New immigrants arriving at Jew. Ben Gurion airport used to be The author was highly required to fill in and sign 17 critical of the Jewish writers different forms. The paper wtM "treat Jews and the work has now been reduced to Jewish family in shabby 6 forms only. What could be faslUon" and who, he said, better news than that? "seem to delight in viUifyIng Solel Boneb Overaeaa, 'the Jewish Mother' wlw has wblch executes major sacrificed so gallantly •Bglneering projecti In throughout this century to rarlouB eoutMm aiwaid the keep her family together, and world, oodMl laat year with a has contributed such a net pram of ILJO,«M,«» and glorious chapter to American Inliflf tallaflrilftnlniiiwi Jewish life." Internationally renowned Angoff asserted that social dermatologists have science studies In the area of the American Jewish com- proclaimed that the Dead Sea munity are virtually non- area provides a combinatkMi existent and are badly needed. of factors which are ideal for He said that "we know more treatment of the skin disease about the Jews of Palestine In known as Psoriaais. So you see, there Is pleasant Biblical times than we really know about the Jews of New and positive news from Israel as well. York today." 31= U U as well. For example: A SaudU-ArabUn Alp was stranded on a coral reef la the Gulf «( aim. In watm unlcr IvMl cooM. IWMi Navy vMMis hauM It off the reef iaMy, and the Alp on it> way UD-
V£. SENATOR CHARUES McC. liATMIAS, JR4IARYLAND - It "would be foolhardy, reckless and to no avail" for any nation to attempt to "drive a wedge between the United States and Israel. . .the United States must furnish the aid and equipment to Israel which she needs in order to Insure peace In that troubled regiaa. Peace can never be achieved by forcing Israel to negotiate from weakness or fear." FORMER SENATOR J. WILLIAM rULBRIGHT TO 8ENATB FOREIGN RELATIONS OOMMTmS-'As long as Israel was created by the (United Nations) Security Council, what would be more approporiate than for the Security OHmclI to
Omahans in The News Samuel M. Greenberg, South Omaha Ixislnessnan and former Ak-Sar-Ben king is recuperating from head surgery which was performed at the University of Minnesota hospital in Minneapolis. The
The Jewish Press PnUishad weekly on Fridoy by Jewish Federation of Omaha. Stanford Lipsay Paul Alpanon Pros ConwninM Co-Oiairman
Richard B.
PMTI
Editor jMtthMortwrg AuittOTi
^
Suzanne R. Sombsrg DobiJoAbroms Second Ctof < PtHtag* Paid
a) Omoho Htbr. and ol additional mailing olficM Annual SubKriplion |7.S0 Advortlting Rotot on Appllcailon
l>» ImMk tnmhmit '*m"M»*-
l-^SSL
:v:
/^*V.«5, CHOP stiev
IvJWus House
surgery was to relieve pressure on a nerve. Greenberg's brother Henry said. He expected to be back In Omaha by this week. Ma. Lucille F. Zellnaky will
This remarfcabis growth has bven accomplished by outstanding service and price... working directly with our regional institutions, municipalities and individuals. First Mid America is one of the larger distributors of New Issue Government Related Securities in the United States. We are also one of the few regional firms in the U.S. which positions U.S. Government and Government Agency Bonds. Our purchasing power reduces our cost and yours Our Government Bond Department is anxious to serve you. Call or write any of our offices with more than 100 experienced account executives who can serve your needs. In Omaha: 100 Continental Building. Omaha, NE 68102. Phone: 402-341-1500. Please use the attached coupon if you wish to receive a pamphlet describing the various government agency securities, some of which are axempt from state and local taxes. FIRST MID AMERICA INC. OOVERNMENT BONO DEFT. 100 Centinontal BulMIng, Omaha. NEeSI 02 Please send me the intormetlon mentioned above:
ACONESS CITY STATE
ONMeaATOUaMMT
locAWMfesMicamM
BUSINESS PHONE
Piny Room up 101SD AlioOntontoGo'
RESIDENCE PHONE
:3c
m^ Thoughtful moves for your money
Firsr Mid America
' Aleittbtr New York Stock Bji^tgnge, Inc., ma I oltter Principal Slock end'Comf^dily Etchtngts Stock* • Canimo<tlti«t • Corporal* and Munleipal Bond* • Qovcrninanl Agtnclas ' ^P****"* * Muluil Fund* • Invastmant Banking
. . . ,„_ «. a Otnih* • Lincoln • Columbut • Orirxl ItltnO • Haiiingm FmST UID AMERICA CUSTOUERS Plfte I . ^,„^,(.. c«)„ R,pK(, . DM MCOM • K Oodg. . give oliice where your eeeouni It eenlced | sioui Ciiy • KWMM City • Chictgo • Si Jo—^
•aurti'Hiii
asTMi coocTAii couwat . voua PAvOMTi aavaRAoaa
tti. • IT
attend the National Association at Social Workers Delegate Assembly In Washington. D.C., May 30June 3. She is a member of the national nominating committee of the organization.
InSyears First Mid America^ dollar volume sales of GOVERNMENT AGENCYBONDS lias increased from *60Millionto HALFAHLUON per year!
Popular Authors Assailed During Jewish Family Meeting MT. FREEDOM, N'J. - A noted author ascribed many of the problems besetting today's Jewish family to the works of Jewish fiction writers "who are either ignorant of Jewish life, filled with shame or even selfhatred, or write out of sheer malice." Author Charles Angoff, professor of literature at Falrleigh Dickinson University, made these remarks as Jewish social scientists, educators and religious leaders — men and women — dealt here recently with Uie problems Jewish families today face. The group attempted to come up with some answers "towards strengthening the family as a major factor in ensuring the continuity of Jewish values." Angoff spoke at a plenary of the National Con> on the Jewish Family sponsored jointly by (he Women's League for <3on-
guarantee Its security." J08IE WAINMAN BURSON, OF MEMPHIS, TENN., AMERICAN MOTHBR OF THE YEAR FOR l«n - "My husband and 1 both feel that we have a responsibility to family, community, ttie Jewish people and our country. A good mother, I believe, must work with her family and for her family to create the kind of world where our children have I future." RBSOUmOW ADOPTBD BY AMERICA JEWISH 0OMHimB-"full and fair emptoyment for all is an essential ingredient of a democratic society. . .a democratic government can have no more urgsoL-goal than to assure to all of lis citizens tiie opportunity (or gainful and dlgnKted work."
«•«
»«
' *«-
'^aa'aMi as *•!«••«• aiai as •
J
M«v23.1976
The United States: An Arab Accomplice?
Edttor't Note: The following Icrtlcle ii a wmmary of tlie •J«r polnU from "Tbe United SUtM A Israel - TUt b) the Middle East?", an analydf of tbe subtly >. changing U.S. role In the East ilnce October 11173, written by Theodore [Draper for the April '75 Issue it Commentary. It U I that Interested ^leaders obtain a copy of thU Informative document as no pr«cls can fully enumerate all ofttaefacUpraieoted.
Summary By Rose Hoffman A "dramatic change" tn U.S. policy in Ihe Middle East took place during the Yom Klppur War In October of 1»73 The full story behind the events of that time were not Immediately known, but gradually emerged. When the truth was eventually pieced together through statements made by former Prime Minister Golda Meir. David Elazar, the Israeli Chief of Staff, and tbe most revealing comments by former Defense Minister, Mosbe Dayan, Ihe 'American ultimatum" was discovered. The Israelis, after 10 days of heavy resistance, had managed to send a small force of troops across the Suez Canal. From this crucial breakthrough, Ihe Israelis proceeded to complete the
encirclement of the Egyptian Army III Corps — an estimated 20.O0(HO,O0O men The Egyptians were close to surrender and, had not the diplomatic shuffling of the big powers prevented the full realization of that "victory", said Moshe Dayan, Israel would have achieved considerable gains in bargaining power and in altering the Egyptian attitude under the Sadat regime On Ihe diplomatic front, the Soviet Union, sensing the critical nature of the Egyptian position, called for an immediate cease-fire. U.S. Secretary of State Henry Kissinger was summoned to Moscow. The result was a^ hasty cease-fire resolution rammed through the U.N. Security Council. During Klailnger's mitslaa in MoMow, President Nixon was occupied with preiilng "domestic" matters and gave Kissinger tbe "power of attorney". lUs is tbe power wliich, in submiarioii to Soviet demands, forced Israel — under threat of conflict with the U.S. should she not comply — to permit a relief oonvoy.to read! tlie trapped Egyptians, thus denying Israel Uie (niits of victory and at tbe same time letting tbe first oftkdal precedent for a new U.S. policy in dealing with tbe Arab-Iaraell coofUct.
When you begin to look llko this.. . it's time to send your clothes to the
COUWH THMFT SHOP Your nwrciwndiM will provid* foy% and •ducollonal molcrloli tor dilldran In IVMI through our Shlp-o-IOM progrom.
Coll 341-3249 for drop-off locotions or pickup, or bring your merchondise to 623 So. 24th St. ALL CONTRIBUTIONS ARE TAX DCDUCTABLE
This change in practice was a goal the Nixon administration had been trying to achieye for years — namely the "even-handedness" which allowed Henry Kissinger to appear as a "savior of both sides." The underlying motivations are now obvious. Kissinger's actions were evidence that American Interests went "deeper" than the immediate hostilities of October. 1973 The Kissinger-Breshnev deal represented a direct intervention by the major powers with the Soviets imposing on the Americans and the Americans under Henry Kissinger pressuring Israel. To provide a clearer understanding of the implications of this shift in American policy, Theodore Draper traces the history of previous American foreign policy in the Near East. He notes the changes that differentiate the Nasser administration from Sadat's rule and Ihe subtle and yet powerful influence the present leadership has had on the Mideast situation. Whereas Nasser worried about U.S. Intervention and counted on the USSR, to neutralize American Involvement, Sadat, taking a new approach, merely asked the U.S. to be "neutral" (Newsweek 1971). How harmless that sounded then In 1973, the twmhination of tbe October War, the Arab oil embargo, and the U.S.U.S.S.R. detente made America's "evenhandedness" policy applicable. The " Imposed setUenMnt" of tbe Yom Klppur War was exactly what Sadat wanted. America was right where Sadat needed ber — in tbe middle. Tbe United SUies oould make Israel do what no one eiae could, so Sadat's regucat that the U.S. remain "neutral" was highly beneficial to tbe Arab position. U.S. intervention In October
'73 saved Sadat from disaster and coat Israel a decisive victory. In February of 1975, Sadat demanded that Israel relinquish occupied territory and then, perhaps, a peace agreement could be reached. When questioned recently as to the "specifics" of such an agreement, Sadat answered that the final solution must wait for Geneva. No doubt, surmises Draper, the Jerusalem question and the PLO—ruled State would be problems a peace conference would be unable to solve. With twth sides giving up in exasperation, everything would be as It was before except that Israel, without the occupied territories, would have absolutely no bargaining power. Accepting the Arab terms for "peace" now would mean sacrificing all that has been gained lor nothing in return. Because of the Arabs' seemingly irreconcilable hardline, the U.S. approach, that of "playing both sides of the coin," has led to a revival of the "guarantee" concept. When Senator William Fulbrlght and several others called for a multilateral guarantee by the U.N. and a bilateral promise between the United States and Israel In 1970, bis proposals never got off the ground. Then, suddenly, following the war in October of 1973, Secretary Kissinger began to talk seriously of guarantees. "Guarantees," Kissinger said, "should compensate Israel for what she cannot get from Ihe Arabs and protect Israel from a serious state of insecurity." If, as Sadat says, he has nothing to give, Israel's support must come from American guarantees, Kissinger advocated, guarantees based on SovietAmerican rapport, guarantees that must be effective and automatic - an impossibility
72nd and Dodge
^EQQW
Jm>J
belligerence, and negotiations between the parties concerned. American guarantees, vehemently opposed by Israel, shift the responsibility away from the Arabs where It rightly belongs. By putting the United SUtea In the "middle". Secretary Kissinger has "dangerously disturbed" the delicate balance which has in the past governed our relations In tbe Middle East. . In summation. Draper concludes that some things have governed Israel's existence from the outset. Only Israel can defend herself. "There can be no peace by proxy." Arabs and Israelis must deal with each other. "Peace is not a piece of paper. Peace in the Middle East will become effective." Draper says, "only when It concerns ways of making a start at living together socially, economically, and intellectually."
Abortion-Mother's Right NEW YORK - That Judaism makes a distinction between a mother's right to abortion andlhe maintenance of the life of a viable fetus was the consensus of rabbinical and Thedlcal speakers at the recent Conservative Conference on at)ortion and fetal research at the Jewish Theological Seminary. Sponsored jointly by the Committee on Bio-Medical Ethics of the Rabbinical Assembly and the Jewish Theological Seminary, there was general agreement that the mother had the right to abortion, but it was generally felt that the fetus outside of the womb had a right to life if viable. There was thus considerable doubt that Dr. Kenneth C. Ediln of Boston was morally right in not taking steps to insure the life of the fetus he removed by abortion. Speakers Included Rabbi David Feidman of New York, author of "Birth Control and Jewish Law"; Dr. Harold M. Nitowsky, professor of pediatrics and genetics at the Albert Einstein College of Medicine and director of its Rose F. Kennedy Genetics Center Counseling Clinic; and Professor Seymour Siegel of the Jewish Theological Seminary, chairman of the Committee on Jewish Law and Standards of the Rabbinical Assembly. Rabbi Feidman Introduced a novel distinction, that between the right to life and tbe right to be bom. The right to
life be called "at>solute, while tlie right to be bom Is relative to the life of the mother. The fetus not yet Iwm, though It is sacred and Inviolate, Is still potential rather than actual human life; as such under special conditions its right to be bom can t>e secondary to the mother's existing rights." On the other hand. Rabbi Feidman pointed out "this very principle means that once the fetus is alive, outside the womb, its claim to life is absolute and the physician, such as may have been the case with Dr. Ekllin in Boston, would have to preserve that life." Rabbi Siegel said that ''Research and experimentation on fetuses ought to be limited to procedures which present no harm or which have as their aim the enhancement of the life-systems of the subjects." It was Rabbi Siegel's view that though Jewish law sanctioned abortion under certain circumstances, "this did not mean that a live fetus can be treated as if it were a mere piece of tissue. Because the fetus is endowed with potential life, it has a right to our bias for life", he said. "This did not mean that all experiments on fetuses are morally prohibited," Rabbi. Siegel continued. "If the experiment is meant to enhance the life of the mother; if It does not have any discernible harm on the fetus, then It could certainly be carried out."
travel f aire
KOSHER FOOD SEQION Mor* Varlstyl Mor* of your Fovorlto Pomous Nam* Brandsl
Ei]aEa[9y
for the U.S., Draper believes, 'since the stationing of U.S. troops In the Middle East clearly smacks of Vietnam. A U.S. guarantee would be just another "illusory band-aid." "No power can substltue lor Israeli power," says Draper. "The U.S. cannot Impose iU terms, whatever they are, equally on Israelis and Arabs. An Imposed settlement Is, In practice, a settlement Imposed on Israel. It implies that the Arabs will give as much or as little as they want to give, that the United States will in some manner pay off for them, and Israel will gel whatever the U.S. and Arabs together choose to give." An "imposed agreement" such as the one in October of 1973 represents a "tilt of policy." According to previous U.N. resolutions 242 and 338, any Israeli withdrawals are to be accompanied by "insubstantial" or "minor" boundary changes, non-
j by land, sea, or air
Q>ine See our Newly EXPANDED
72nd and Dodgo
Th«J«wi»hPfew
gets you there..
stock up forth* Mamorlal Ooy
«»o«kond ohoodl
You'll olio Wnd Kothor foodg In cur Doll. Polry, Cold A^ootg. Fr—lor Soctlons.
397-6900
Orvel Milder Nadine Hale Travel Faire Travel Agency - all tbe services you'd expect from a travel agency — and a few you wouldn't.
8729 ShMmck RoMi ICountrywIa \nhge)
hm9
Th« Jaiwlih
M«v23,1976
PI—
«y ii£&^og ue Omaha BathEl
OHMIUI
T«mpl« Israel
Omaha Bathlsraal
SERVICES: SERVICES: Friday: Frtday: Traditional Evening SerSabbatb Eve Services in the SERVICES: vices iKabbalat Shabbat) 7 Sanctuary at 8: U p.m. Friday: 7:30p.m, Rabbi Myer S Kripke will p.m. Rabbi Sidney H. Brooks and Late evening family serRabbi BaiT>' L. Weinstein will deliver the aertnon. Caiitor Chaim Najman will conduct vices will be conducted by conduct the services. ttie musical service. Rabbi Isaac Nadoff and Cantor Leo Fettman and the Saturday: B'NAIMITZVAH Morning Service 10 a.m. Hidiael Jay Greedberg. son Beth Israel Choir at 8:15 of Mr. and Mm. Avnim MinchaMaarlv 8:30p.m. Satunlay: Greenbefg, will become Bar Sunday: 9 a.m. ' Morning Service: 8:45 a.m. Mitzvah U a.m. Saturday. Weekdays: conducted k>y Rabbi Nadoff Services at 7 a.m. andTp.m. May 24. and Cantor Fettman and the Michael Budwig, son of B'NOT MITZVAH Beth Israel Choir. Susan and Ranald M. Budwlf, Usa and Helanie Kahn The Talmud class will be will become Bar Mitvah 11 daughters of Mr. and Mrs. conducted by Rabbi Nadoff at a.m. Saturday, May 31 Roland Kahn, will become 8p.m. followed at 8:30p.m. by B'not Mlt2vah Friday, May 23 MIocha, Sholas Sudoc and SISTERHOOD If there are any questions and Saturday, May 24. Maariv. concerning Sisterhood, call BAR MITZVAH Sunday: Mrs. Avrum Greenberg, 334Alan Karp, son of Mr. and Minyan 9 a.m. fallowed by SS84. Mrs. Harold Karp, will breakfast and Rabbi's class in become Bar Mitzvah Friday, Mistina. May .30 and Saturday, May 31. Daily: Omaha GRADUATION Services at 7 a.m. and 8:30 Kighth-grade students wiH p.m. B'nai Jacob graduate from Talmud Torah Adas Yashuron on Sunday. May 25 at 10:43 B'NOT MITZVAH Carai Ana Alperton, a.m. A reception will (allow. SDIVICES: Graduates are: Rot>er1 Chap- daughter of Mr. and Mr*. Paul Saturday: nun, JHIrey Clayman. Marsha AlperMm, will become Bat Morning service 8:45 a.m. Cooper. Jonathan Duitch, Sally Mitzvah Friday, May 23, at Sunday: Feidman, JodI Frldman. Barbara 8:15 p.m. Morning Service: 8a.m Fraldenraich. Randy Freund. Services conducted by Amy G«ndlrr. JoHph Goodman. Marti Lynne Rosenblatt, Rabbi Abraham Eisenstein. Rachel Gninkin. U%» Kahn. daughter of Mr. and Mr*. Michelle Katman. Juklin Kohll. Sidney Rosenblatt, will Robert Lull. David Noodell. David become Bat Mitzvah Friday, Ripa. L,atii1e Schirarlz. Andrew May 30, at 8:15 pm. Omaha Watserman Dr. ShartkNna AWARDS ASSEMBLY Ttie religimis school will SERVICES: hold its Awards Assembly Saturday: HYNUt mCHAtOS Sunday. June 1, 9:15 a.m. in 9 a.m. Men ol the comwould like to thank all the sanctuary Awards will be munity are Invited to the hit relatives and Hands presented for Salibath Service Home to make a minyan. (or thair contributions, attendance, classroom at(lowars ortd cords durtendance and scholastic ing his racant ijlnass. achievement.' Certificates of CouncHBIuffffs Promotion will be given to B'nai Israel students entering Talmud I offar my sincara Torah in Septemljer. thanks to oil thosa who SERVICES: rennamberad ma during Saturday: 9a.m. Leon Wintroub, president of my recent illness in so Sunday: 9a.m. Beth Israel Synagogue, Mrs. many meaningful ways. Both services will be conHarold Franklin, president of ALANWOLFSON ducted by Mr. Sam Sacks. Beth Israel Sisterhood and Dr. Arthur Fishkin, chairman. Board of Education, will present the awards. >•»»••,»« lOMv.Bit
PERSONAI^
Sabbath Candle Lighting FriAiy, May 7». 905 p jn. Friday, May M. St31 pjn. Benediction for Kindling Sabbath Lights:
r
Borukh Atoh Adonoy Eloheinu Artelekh Hootom, Asher Kideshonu Bettiitzvotav Vetzivonu Lehodlik NerShelShobbot. (Blessed art Thou, 0 Lord, Our God, King of the Universe, Who sonctifies us by His Commandments and has commanded us to kindle the Sabbath lights.)
This Service Presented as a Courtesy by
<P
(MIAHA aanHOS AMD LOAN ASSOCMnOM on-CM «f lath * Ham*/ 34t-7SPO
arm 1 WM> OMa* noad atrrtoo
*T3t » ]4in SI
rai4M0
Singing, Israeli folk dancing and a play will be presented. tMondMouraan RoaonMott invll* thalr r*laftv«ft and fri«nd«
fo worihip witli thmn a(lh«So<MilTvi* of Ihair dougMM-
MARTI Mdw. May 30. • M S p jn. ••m l«ra»l SynopogMa
MargI* ami Paul Alporaon
Das Moines BathEIJacob SERVICES: FMday: 7:30 p.m. throughout the summer (oneservteel. Saturday: Morning serv ice 9 a. m. Learning service 11 a. m. Rabbi's Class Sp.m Mlncha, Sholas Sudos 6 p.m. Sunday:9a.m 12-1 p.m. - TalmudCiass.
SERVICES: Friday: Evening Services p.m. An Oneg Shabbal will follow services.
DasMoinss ChHdran of Israel
Chalm Najman and Lao Fettman will participate. A reception will follow in the Synagogue Social Hall. The following tludenia will receive their dlplomaa from Dr. Martin P. Wolf, chairman o( Uie board o( diiectora of the high school: Paula Bcmstlen. Vldil Cohen. Justin Cooper, Mark Hockenberg. Scoll Kirshenbaum. Robin Martin. Rob Pred. Marcy Roaenblum. Mk-hael Konentilum. Polly Rownfiekl. Mark Schulman, Stcplianie Shapiro. L,arry SIrcl. Molly Tully, llelene Wasaarman, Susan Wintroub, Steven Wise, Diane ZlpurxJcy.
"What happens when a community suddenly undergoes a great public calamity? What happened, for example, in Omaha wlien a destructive tornado tore a wide path of desolation through the most thickly settled residence sectkMts of the city?
property lose eatinuted dose to |S,000,000, It does not take long to realtxetlie mapilhidw of the eataatraphe, and the need of berate measures of rdlef. . . . devastation by toma^, as was visited up our iUy. is indeed a terrible misfortune, but darkest clouds have sliver linings. As it has been well experienced, instead of a calamity stricken community the experience occasioned by the disaster develops a new spirit of higher citizenship. In ttie social reaction from dire necessity people discover in themselves latent energy and recuperative powers, and a faculty for material helpfulness and cooperation." Ttie foregoing consists excerpts from an article entitled "Repairing a Tornado's Havoc." written in 1913 by Victor Roiewater, editor of the Omaha Bee and published in the Amertcan Review of Reviews. On March 26, 1913, Easter Sunday, Just at dusk, a killer tornado swept through Omaha. The Jewish commimity, concentrated in the area around 24th and Lake Streets, was particularly hard hit. Many homes and places of business were destroyed and ttiere were a numtier of deaths. Jews organized their own tornado relief committee to help storm victims with funds, food, shelter, and clothing.
SERVICES: It is all over in a few seconds Regular minyan services Monday and Thursday 6:45 — then when a survey is had of the resplts amazement is a.m. unbounded and the scene Saturday: Morning Shabbal: Service 9 Indescribable. Huge trees are found torn and sfdlntered like am at Iowa Jewish Home. underbrush; houses Sunday: 9 a.m. Special Vahrzeit service, ' demolished, lifted from their footings, tilted wrong end up, everyone is welcome. Mrs. Biber, lecivtary, 277- clapped together as by a vise, ground to kindling wood or 8601 strewn about in heaps of brick and mortar. Here a telegraph Das Moines pole will be decapitated as 'With a knife, and there the THarath Israel next one pulled up clean from SERVICES: Its socket. Friday: But If these are the physical 8 p.m. Rabbi Barry D. effects of siKh a destructive Cytron will conduct the servisitation, what is the social vice. " reaction? How does a comSaturday: munity respond to the call of Shabbat School 9:15 am the stricken? Morning Services 9:30 a.m. Here is a gIganUc acar or During service Viskor will rather a great open wound, be recited, tram two to six blocks wide Mlncha 6 p. m and teur and a half miles hng Sunday: 8:30a.m. acroaa the lair face of a Mg Dally: 7a.m. city, with 140 persooa deador dying. 3S0 seriously teiand, •SO buildings completely Lincoln wracked, l.lSO mora TIfereth Israel damaged, but sUU repairable, SERVICES: S,SOO people homeiaas, and a Friday: 8p.m. Services conducted by Rabbi Mark BIsman. Saturday: 9 a.m. Jr. Congregation 10 a.m. swdity' 5014WHII1I TlfUlinClub,9a.m.
SHUKERT'S KOSHER MEATS
Uncobi B'nai Jsehurun SERVICES: Friday: 8p.m Rabbi Robert Kaiser wiU conduct the service.
PERSONALS
CAROt
Th« fomily of iWOUM KILMRO riSTBJ. ocknowladgas with appreciation your kind expressions of sympathy and h«lp.
Fr<dS|r,May23.l:l}p,m. loth laraal tynogogv* SlndondChorlM W»lii»tWHowlw»«b»i<<iiii<ad
OMAHA - The entire community has been Invited to attend the first graduation ceremonies of the Omaha High School of Jewish Studies scheduled for 8 p.m. Sunday, June 1, at Beth larael Synagogue. The high school is a Joint program sponsored by Beth El and Beth Israel Synagoguas It is open to all Jewish high school students in the iinnmunlty, grades nine through 12. Rabbis Myer S Kripke and Isaac Nadoff and Cantors
DasMoinss Tampla B'nai Jashurun
InvHe nttlr
fafnilyandfriofids to shara In the piaasura of tlwBatMltivati o>tlMlrdaugt>l«r
City's Jewish Higli School Sdieduies 1st Graduation
Brisket Corned Beef Leon Ground Beef
59«^4«S
^^^3^ .,u.79*
Pfckled Tongue
u.M"
Turiiey Solflmi
^^V^
W* <»M be cl«8«4 MM^, MWMIW Diy OW MWDAT HOURS ME 9 AJI.-2 PJM.
w
May 23,1976
U ^ I
By Helen Newnun Officers for the coming year were installed at the Monday, May 19, meeting of the Older
r
Adult aub.
[ ^, r t
'i I
'" ». r
Mrs. Mary Fellman honored the group by oKlctatIng at the Installation. Mrs. Fellman introduced the new officers and appointees and explained each of their duties. Officers are: Min Cutler. president: Ida Potash, vice president; Helen Newman, publicity vice president; Annetta Brown, recording secretary; Fanny Manvitz, financial secretary; Sam Poska, treasurer; Blanclie Kalman, dues secretary and Fay Sekar, corresponding secretary. Others are Van Ferrand, birthday chairman; Rose Raznick, historian; Harry Weissman, bingo caller and Sam Laahiniky, handyman in charge of table arrangement and microphone.
[ Senior Citizen Scene ] Board members are Dora Arbitmen, Ethel Bleiweiss, Ann Ellis. Mollye Franklin, Hershel Freedman, Dr. Arthur Friedman. Lottie Garber. Sylvia Goldberg, Irving Janger, Sarah Kahn, Bemice Kalman. Mary Katz, Max Katz, Sarah Langer, Helen Papier, Rose Poska. Yetta Saylan. Bessie Silverman, Anne Stone. Lillian Warren, Monie Zaikin, Sigmund Hessel and Ethel Miller. Outgoing President Betty Weissman was presented with a beautiful charm bracelet for her outstanding services to the group. An annual report by Betty outlining the numerous activities throughout the year was read by Mollie Delman. Min Cutler, as new president, gave an acceptance speech. The belated Mothers Day
Arnold Stern Is Elected Beth El's Board President
•'
OMAHA - Arnold J. Stem was elected president of the Beth El Synagogue Board of Trustees at the meeting Tuesday in the synagogue. Stem succeeds Hubert I. (Hub)Rosenblum. Other officers elected were Sheldon Rips, Jerry Gordman and Barton (Bucky) Greenberg, vice presidents; Merle Potash, treasurer; Jean Duilch, secretary. Jean Duitch, wife of Jack; Greenberg and Potash were
elected to two-year terms on the board at Sunday's annual dinner meeting in the Social Hall. Also elected were Yale Kaplan, Gary Gross, Benjamin Wlesman, Steve RIekes and Dr. Irv Margolls. The election nominating committee members were H Lee Gendler, Mrs. Georg? Kagan, Harold Zabin, Sam Greenberg, Mrs. Joseph Guss, Merle Potash and Dean Frankel.
luncheon was enjoyed -by members and guests. A gift was presented to all mothers and a door prize was also
given. Jack Saylan sang two songs appropriate for Mothers Day. Our birthday celebrant was Bessie Margolin whose family furnished the ice cream and cake. Her son, Millard Margolin, qxike In honor of his mother and thanked the group. Lou Langer announced the engagement of his grandson Marc Delman, son ol Lou and Mollie Delman, to MItzi Friedman of St. Louis, Mo. Out-of-town guests were Abe Poska and daughter Gerry Ross from California, guests of Sam and Rose Poska; Ruth Katz, Morristown, New Jersey, guest of Eklith Lorkis; Eva Krelger of Atlanta. Ga. guest of Rose Raznick; Sarah Mays, Kansas City, Mo., guest of Fannie Lagman; Barbara Shapiro, Kansas City, Mo., guest of Anne Blatt. Frieda Kavitch was a guest of Jack and Bertie Lazar. New members are Mrs. Shirley Passer of Council Bluffs and Sam Richman. Our next meeting will be 1 p.n. Mor lay. May 26, which is Memorial Day. Please keep in mind that Sunday bus fthetiuies are to be used. The date of the Grand Island trip Is Monday, June 2. R^rvations are being, taken by Rose Raznick, 393-7972. Cost will be $3. Lunch costs tl.
G«(-waU wtilMt 10 Bernln Kalman il (UllUM H<M|llUI (ran Sua Mayar. Mr and Mn. Ma> KaU, Bartls and Jack Laxar, Famie and Carl Lagman. Ida Potarii. IMan Nawman. Raaa Kaufman. Van Farrand, Anna(ta Brown. Hekn Papier. Mnnla Zaikin. and Group CM-wen wMm to Shirley Tepar >l Maltndlil Hixpllal (ram Helen Newman and Group. In honor of fifth weddlnf anniversary o( Mr. and Mn Italph Waver from Lou andMlnCUIer. OM-mll wUliaa la Janile Hornoeln <i Bargan Marey HoapHal from (he Group Get-well wlahea to Mlimle Margolin at lAitheran Hoiptlal from Ijou and Min Cutler and Group. In honor o( faanle Lagman (rom Sarah Maya of Kanaai City To honor Ml mothen of Senior CIIMnn Group (rom Monle Zaikin To honor engagnnenl of Marr Delman from Monle Zaikin. Gratitude lor survival of Lou and Mollie Delman and all othera In tornado from Fay Sekar, Fanny Manvltx and father, Hose Kaufman and Group Birthday greetings lo Bessie Margolin from Kllas and Haullnc Widmnn, Ann Margolin; Joe and Kufli Bemstetn, Dorothy Plait; Mr and Mrs Irv Singer and chUdren; Mr and Mrs Michael Plait and children and F.lale Fogel
EVEN KIDS The Nebraska Medical Association reports that anyone can have high blood pressure, even children. Bothmrmd by... ffoocfiM, Wasps *Vat*rbvg«, Snak»Mt
Sabra Sweepstakes NEW YORK - Walter Perry, left, managing director of International Distillers of Israel, Ltd., and Richard McCarthy of Park Avenue Imports, go through some of the mail received in the recently concluded Sabra International Recipe Contest which was featured in The Jewish Press. Almost B,000 Sabra recipes were entered. Contest winner receives U.^.-Israel round trip for two, with 40 additional prizes for other contestants.'
Jowifh Community Center Pre-School Open House TtM JCC Pr»«cheel would Ilk* to InvltaiMI Int*r4Mt«d portent to com* to Op«n H6<MM on ThMrt4«y. May 29 •nytliwo from t*tO to • pan. • M—tth»%tatf • Observe maiTla\% and tacllllitt e See sllcfes of this /eor's children end ocf Ivltles e Hove your (Questions answered regarding our program content ond philosophy
Call 341-00»B I
The Jewish Pre**
ptBcwiwotwwtgi,wc.
STREITS* KINBERGS* MANISNEWrTZ • BEST* VITA* SINAI-4S* tAARPARV • BARNEYS* ELITE* LENDERS* FROUMINE* IMPERIAL • NOON *
If EVERYBODY is coming to your house for Coolc-outs and Picnics this long holiday weekend, you ought to be coming to us first!
STOCK UP ON BESrS KOSHER LOWER FAT FRANKFURTERS $ 1 70
.,tr j.fglGEHMCD
BEST'S KOSHER
OWERFAT ••st's Lowrar Pot Salami Chub«, 12 oz. alxa $1.89 |^»Ho «n4 StrmehorryWiubwb Frolt !MM. tLMoo. OiorryPtM, t1.5*o<i.«nd! {dalklotM Owrmwi Otowloto Cahoa. only L*2:i!L^. J
HotDOflwid «« s ^ ^ KVC tlOimMrger BUIIf, • Pock. 9 Z »—d»d luM, 8 pk. 63'
X'^;iS^;;KlI^..i '^yi-'^^li^'^^^^ and croom choM* on hondl
SOVO 30* lb. OH
Toffal Norwoglon Chmtm. »1.99 lb.
And Buy Enough
, ^JS:^^ PAT
l««kM'< RnMt, 2 lb. ba|, 59* Itubtn't fldtlM, la««MiM»y wrepeed In brhw. 29
fi|M,AMMi'«k Koahor Mcklos, qt. 99*
IlianSSni S DIIITomatoM,qt.85<
Dlfon Mustard, Fronch, 9*/* oz. iar 69« PrMh Potato Salad (Sav* 10<) lb. 89< Dallcleua Col* Slaw. 1 lb. 89* Iharo't etlll tima to ordor alaaant chaaoa and friHt trayt, rallfn traya, her* d'oatnrra tray* for plch-up on Sunday Omaha SSIHMM Lincoln 43S437* McM •floctlwo through TIMM.. May 37
WouK gty a7»oao»
Ooaad Monday Mamorlal Day In Omah(
DAMASCUS * IWIGDAL * DEAN'S * PR. BROWN'S * POCOHO * SOLO * STREITS • FEINBERQS* MANISHEWnZ* BEST* VITA* SINAI-48* SOLO
fmM-
Th«J«iii(iihPrtn
M»y23.1»7B
iiioi 110%; lie
•^criitMi
The Fedefstion-Heartbeat of the Community Memorial Day By ROM HoCtman Services Set DES MOINES - If you wallc down Seventh street in downtown Des Moines you might easily miss the Securities Building where, tucked away at the end of an unprestigious hallway three flights up. are located the offices' of the Jewish Welfare Federation and the neighboring office of the Jewish Family Services agency, whose activities have been described in an earlier article. This setting, simple and unassuming, is the heartbeat of the Oes Moines Jewish community. At the helm is Federation Executive Director Dr Gerald Ferman. a man whose working days are rilled with a spontaneous flurry of activity. One minute he is charting the results of a budget hearings decision, the next minute he is arranging for the vtalt of Israeli Boy Scouts, and the following moment he is leiMdldtng a meeting and eoonilnatlng materials for the Center for Jewish Life Planning Committee or preparing for a staff conference. The whole of this is Interrupted by buzzes, rings. and knocks at his office door His head ii • milliaa plMCS at once and hlf work doM not end at S o'clock. Aa "academic habit," be calls It, but wtien he finally leaves the oCflce his briefcase U fuUy packed. Often cardboard bases loaded with materials MOompaQy him to the next MP 00 the agenda, an evening mMtlng or a late nigbt't work atbome. Many weekends are devoted to his Federation duties and his out-of-town commitments are frequent. On Mondays and Fridays he squeezes minutes from his busy day to help this writer as we structure the layout for the Des Moines section of The Jevish Pren. Assisting the Dr Ferman are three full-time employees: Mrs. Gina Wicks, executive secretary: Sharon Mitdiell, steno clerk and Barb Craig, accounting clerk plus parttime assistant, Mrs. Florence Beckerman. Gina, the executive secretary and office manager, arranges meetings, and
SHUKERT'S ROmn MEATS (4M)SSM«5 We con service Des Moines and all other cities in Iowa.
USDAIwvtcted litiMsliiMiHNo.2317
r
Coll collect: (403) 558-8485 We sMp by lew* ^rcel — delivery meda feyowrrfeer.
DES MOINES - Memorial Day services will be held Monday. May 26 at I p.m. at the Jewish Glendale Cemetery. In the event of rain, services will be at Beth El Jacob Synagogue.
Dr. Firman luncheons, organizes the calendar and appointments for Dr. Ferman and is responsible for dictation and transcription -tor him and other committee and commission chairmen. Community relations Is an important pari of Gina's activity — she makes sure that visitors to the Federation office receive a warm welcome. Gina is the friendly lady with the gentle voice who reminds members of the commimity of meetings and other events. When you call die Jewish Welfare Federation, the "Boker Tov" or "Shalom" that rings pleasantly In your ear may be the freiodly greeting of Sharon MItciiett, a 1V74 Roosevelt High School graduate and winner of the secretarial departmental honors awarded the top aenhir In the office education program. Sharon operates the pdstage meter, Addressograph, mineograph and dictaphone, (lies the many papers and documents that pour Into the Federation office, handles correspondence to newcomers and prepares bulk mailings and the community calendar. Organizations and local groups wishing to have their (unctions scheduled for subsequent listing on the calendar of events, which appears weekly in Tbe Jewish Pitas, should ask for Sharon. In addition to these many and varied duties. Sharon is secretary for Lllyan Carson, executive director of Jewish Family services. Barb Craig, the accounting clerk, a native of Keosauqua. Iowa, has been with the Federation for almost two years. Barb takes her duties In stride as she balances and maintains books for the Bureau of Jewish Education, Jewish Community Center, Drake House, Jewish Family Services, Community Relations Commission, Community Action Committee. Scholarship Fund and Jewish Welfare Federation. All billings, payroll, budget preparatkMif and handling of monies for these agencies are In Barb's charge. How does she manage this colossal task? Mrs. Florence Beckerman, part-time aaslstant helps 10 hours a week doing payroll records, recording checks and deposists and much campaign work
Fnan leA to right, Floreooe Beckerman, Gina Wicks, SbantM MUcbeU, Bafl> Craig. In this office the work is shared. Each helps the other The girls work together in a spirit of cooperation and friendship which transcends their work in the office. All are close friends in personal life. When campaign time rolls around, the office fairly hums with activity. The vital pulse of Jewish life throbs here in the dedicated and capable hands of the Federation employees reaching out to the community.
Calendar of Events Bat MItzvah — Nancy Land - Tllerelh lirael Synagogue Bal MUivoh — Gall GoUeb — Temple B'nal Jeahunin
Srinfday.iiaxM Bat MlUvali - Teni Nadel — Temple B'nai Jesliunin
Sunday, May a Krolof (wedding at Beth El Jacob Synagogue — S p.m. Ttaaailay,May]7 l2:4Sp.m - Temple SItterlMnd lAincheon Bureau of Jewlih Education Hebrew School Graduation — evening WadMiday.MayM <p.m. — Beth El Jacot) sisterhood Mother. Children Dinner
rrMay,May» Jacquelln Roth ~ Bat MItivah - Temple B'nal Jethunin Salonlay.MaySl Bar MItzvah - Danny Upunan - TifereUi Israel Synagogue
Bureau Holds Graduation Exercises DES MOINES - On Tuesday evening. May 27, al 7:30 p.m. graduation exercises for the students of the Bureau of Jewish Education will take place at TIferclh Israel Clubhouse. The entire community is Invited. Twenty-four students will receive certificates for their completion of Hebrew School and nine will graduate from
the Hebrew High School. Special tribute will be given to the lormer graduates of tlie old Oes Moines Talmud Torah classes of l»23 and 1925 by Harold Leener. The following studenlt are gradiiallng from Hebrew Sdwol: Kevin Asher. Joy Belln, Evelyn Betgh. Ben Blber. Judy Brown. Judy Bartwr. Bradley Davidson. Jawn Ekelman. Darryl Finger man. Gall Golleb. Jolynn Hurwltz,
Marcia Isaacson, Andrew Kneeler. Jeffrey Kreamer, Jedrey Levine. Julie Upaman. Kathy Mandelbaum. Brian -PIdgeon. Michael PIdgeon. Rebecca Purnell. Brad Sandler. Steve Silverman. Carol Swartz and Ellen Wlnkk. » Graduating (rom Uie Hebrew High School are: Dana Davidson, Suzy Engman, Becky Kreamer, Frank Llpsman. Miriam Mtnlzer, Michael Minlzer. Joy Rablnowitt Linda Silk and Uura WInlck.
BarMitzvah DES MOINES - Mr and Mrs. Alfred Lipsnuin extend a cordial Invitation to all their friends to attend the celebration o( their son Daniel becoming a Bar MItzvah on Saturday. May 31 at 9:30 a.m. at Tifereth Israel Synagogue. A kiddish luncheon will follow the services. This announcement Is in lieu of personal invitations.
MKcsLand Seeking Barth DES MOINES - Mike Land, son of Mr. and Mrs. Melvin Land, second-time National High School champion and High School and College All-American, will be trybig out at St. Paul, Minn. In July for the Junior World Wrestling Team to represent the United States In the World Tournament to be held In Hungary In August. EL AL TOURS Pre- and post-conference tours are being offered those attending t)ie Aug. 10-14 International Conference of Jewish Communal Service In Jerusalem by El Al Airlines, official carrier of the conference
Hebrew U^ SdMMl Graduates -1*75
The Ten Commandments By Rabbi Marshal Berg We read the Ten Commandments on Shavuot. All 613 Commandments of the Torah fall under these 10 principles. How does the Decalogue apply to us today, and how can we remember these 10 words? Tbe Midrash gives us several- nuiemonic aids. The first tablet contains those commandments that are "between man and God." On the second tablet are listed those which are "between man and man." Now, the First Commandment, "I am the Lord" faces the Sixth, "Thou shall not murder," or he who kills in cold blood destroys the image of God, and does not lake upon himself an obedience to the
Highest Authority "You shall not have any other gods" faces "Don't commit adultery." Other powers, strange values are like other mates. "Don't take His name in vane" faces "Don't steal," for the thief is not concerned about swearing falsely In His Name. "Remember the Sabbath to keep it holy" faces "Don't be a false witness," for a person
who does mA believe in a God who created a world and gave us a day of rest is telling false witness against Him. "Honor your parents" (aces "You shall not covet," because a person who does not respect parents will come to desire what doesn't belong to him and eventually disposaes his neighbor's property, not showing respect for his neighbor or anything that belongs to Mm.
RISTORANTI WTDUI*TIONM.CinSIN[ 240Olnflersell Des Moines ^^^^^^^^^^T^^^^^^^^CT^^"^^
teservetlons 3S»-234«
M«v23. H7B
UJA Offers Missions; Overseas Programs Set DE:S MOINES - The 1975-78 program of United Jewish Appeal represents a major departure from past efforts. UFA wUI offer five basic ovcnew exparlanoM geared tor •peciflc eatcfyirict of participants. These five programs will be supplemented by departmental miHloni and other overseas programs developed in response to specific needs during the year. Many UJA Departments will continue to develop and conduct specialized missions for their constituents Including women, young leaders, rabbis, academicians, students, cash cbalrman, public relations directors, newspapermen and members of the t|{alional Cabinet. The basic overseas programs of UJA will Include: 1. The DMUI Md lUbtrth o( the MmUb Peopla - A twoweelc Journey, one week in Europe, one In Israel, Involving an encounter with our European heritage, the Holocaust and the meaning of the Jewish State. A scholar-inrecldence can accompany each group on the European portion. The program Is designed for people already involved In Jewish communal life who are willing to search for the most profound meaning of their Involvement. Because of the power of this Experience, communites should also consider seeking participants who have been uncommitted or only marginally involved. 1. Urael In DtfUh - This a one-week Journey involving an Intensive encounter with the major social, economic, military, and geo-political
challenges facing the State of Israel today. Briefings on each day's theme will be considered at breakfast and the balance of the day will be used for exploring that theme in field trips. The program is geared for contributors who have been to Israel liefore and want first-hand knowledge of the current situation. S. Confronting Jewish DaiUny — A lO-day mission that will explore the meaning of Israel's existence and the challenge It presents to Jews today In the context of our past as a people. EUKh individual will be allowed to deal with the issues at his own level of knowledge and past experience. Designed for people who have not been to Israel on a UJA mission. 4. From Oeoeratfcw to Oeatradan - This lO-day Israel program Is for families who wish to make Israel a shared experience. Both parents must have been in Israel before and have been recommended by their community to be eUgibie to participate in this misskm. 5. Semlnan on Wbaali - today and two-week programs conducted in Israel and-or Europe during the summer months exploring specific aspects of Jewish history, culture, religion and tradition. The programs will be oriented toward in-depth learning on location and led by recognised authorities. These special programs are primarily for key leadership or Interest groups. Seven-day programs will offer the option of a threenlay extension. All lO-day programs will offer a four-day extenakm.
De// Wagon DBS MOINES - HM "New York KoriMT Ml Wa«oii," a van owned by Drake stadanls Httcb Mallett and Larry Segal who are nMmbers of the Jewish Student Oaolar, was used in a iBlqiM swtoe program this past spring. The van. loaded with baflris, kas, and plcklas, vWtod OrtanaD OoOege oa two Sondayi. About go stndnti wcrs Irsatad lo traditional dellcatesten fidslne each trip. From ttie wagon reoordsd Jewi* murie walled as the ciuwd munrhed and raiiped together.
Des Moines Confirmands DES MOTOES - Till tonowln| •mdenU <Rra racMljr cmflniwd. hiiple - 11«n*iy, Mar IS David Brauar. KaMon S Cof^. JamW Alan rnitor. Lbu Oalr FtUitiers. JiiHc Aim rrtodnwi. Andrea Lynn Hindi, DIam RanlU Jafldlo. Amy Lynne Lcdtrman, JeKcry Alan Lalaeratti, itmH sue Mart, David JonaOiail MSkr, Sharon Ann RnMnbarg. Lindaaaarai Silk. Jean Ivy Woll
When you come to the Ak-Sar-Ben Races
JERUSALEM (JTA) - An inter-minlslerial committee of experts has recognized the Faladia* - the Black Jews of Etiriopia — as eligible for Israeli citizenship and other right under the "Law of Return." The committee, under chairmanship of Justice Ministry Director-General Zvl Terkip reached Its concluskm early in March, but It was only reported recently. The declskm was criticized by Ashkenazi Chief Rabbi Sholom Goren who maintained the Jewishness of the raladuw ought to be a strictly halacUc Issue decided by
halachic experts only. The committee was reportedly guided on the halacha by Sephardic Chief Rabbi Ovadia Yosef, who has for nuiny years maintained that the Falaahas are Jews under halacha.
Pulverente MoniNiMntCo.
Bo where the action Isshopplng, shows, fun-In oithor West Omsha (2Vt minutes from the Track) or In Council Bluffs (2 mlnutos from Downtown Omaha). Big fun for everyone, and children under 18 are free when using same accommodations. Color TV in every room..."pamper panels beolde oversized bods . . . Indoor pool .. . lounges...ganM rooms... right where the action is I ask alMut our btiihiass/ireup •Mslmg lacHKIes
-MOUIARD,.
35 Years' Experience WHhJwrish Uttering end Mamoriols
anu.Mi'
Mi-Msi
Jounion) Cooncii Muffs I Onnhi
IMk aa< BnaSmr \TlmtkHO 121-I171 11*7-1700 •r sal MS ITM m-Mt-lMI
M
The Home had a display (thanks to Mary Wine) and sold many of the Items made by the residents. They saw slides on Joslyn, all crafts and had a good time. Next week, on the28th, Gary Javltch aquatics director of the Community Center, will talk at the Home about the Senior Splash swims on Wednesday mornings. Wouldn't It be fun to Join? And that evening, the movie will be "The Jolson Story" with Larry Parks. Everyone Is invited. On May 31 is the Hadassah Oneg Sbabbat.
DON'T FORGET . . . June 1, Simday, the Residents of the Home are Inviting the entire Jewish Community to their annual Open House. One last Item . .. when you do come out, ask Keva Homstein or Abraham BIniamow to show you their gardens. They have been so busy planting . .. tomatoes, com,
cucumtwrs, cantelopes, etc. It's such fun to watch things grow . . . and these two men are having a ball doing the planting and caring. w**^
Bh^hs Dr. and Mrs. Stanley A. Greenfield of Ambler, Pa., announce the birth. May 2, of a daughter, Dedra Jeanne. Grandparents are Mr. and Mrs. Seymour Zeinfeld of Overland Park, Kan. and Mr. and Mrs' Max Greenfield of Omaha. Sgt. and Mrs. Allen B. Chandler announce the birth. May 13, In Oxford, England, of a son, Daniel Edward. The Chandlers have a daughter, Jennifer Susan. Grandparents are Dr. and Mrs. Bennett Fishbain.
/4ttMU<^^
TUvatt latMl - riMagr. Mar U JaeUyn Ban^, OiaM Diabanaliy. Randy rnpmn. Edward Hm«i. Ir vli« laaacaon. Skarai Kaya, Randy Lavanlhal, Frank Uptman, Jocr NaSDmer, Steven Ptdfno, Jody aeUi PDlaky, Suaan Rlakla. Rkky Sorla. Martin Swam. Steven Vllebaky. Ellen woir
B'nai B'rith Woman Anno«aicMiMnts DES MOINES - May » and 30, are B.B.W. Garage Sale Days. Tafca an "unwaoUMa" to Pat NcwgaanTs house, MS 45(h by May M. Help la needed 10 sort and mark. June 9 la the last Board Meeting Iflr 1)74-1975; all programming and ftaid raising lorlt7S-7( «riU be planned. ADL Caleodart are on sale at %M cents each and may be ordmd now. B B.W. Ii also selling a wtiole line of personal slalloaery product! along with New Year Cards, pboto gallertes and other Items for gUla or for yourself. Avoid the rush in the busy ssatOB and come over or call Paltl (t77-l004) for more inlonnatkin.
B/LaeJanoPareow The residents of the Dr. Philip Sher Home have been busy ... on May 12 about 40 children from Beth Israel Religious School, with Cantor I>eo Fettman, gave a Shavuot program featuring Hebrew vocal and Instrumental songs and a short play. Then, on the 16th, the "Mission Belles" of the L,utheran Churches of Omaha presented songs from "Sound of Music", "South Pacific" and gome of the wonderful oldies. The residents loved the music and had such a good time that the "Mission BeUs' promised to return in September with music from "Fiddler." On the May 14 we had a Disaster Drill.. . Just in case . .. Everyone was told where to go or taken to a safe place . . . and while It was a little hectic, it was a good lesson. Hopefully, we won't need It, but... We've started our trips ... On the Mh. Janet FIsdMr, wtth her two helpers, took about U raddeoti lo Unooln to the Junkir Zoo, then to PkMMsr Park for a pleale ... Mid on to MoRll Han to sse the planetarium, akjrriww, etc. It was s busy day, but a tun one. This week, also, was the Senior Citizens Days at.U N .0. . .. and a full busload went.
J!as»
Th«Jew>iihPfeM
BAK E R S
1
72nd & BLONDO SHOPPERS
1
Baker's 72nd & Blondo Store will re-open soon—bigger and better than ever! Until then, there are 3 other Baker's Stores close-by to serve yout * 73rd & MAPLE— Jutt 3 mlnut«s from 72nd & Blondol SEE OURNEWMIMI-DELII
* 50th & AMES— Compl«t» with a famous Bokor'i DELIl
* 90th&FOIIT— With DELI, RESTAURANT, BAKERY, FLOWER SHOP, and NEW KOSHER FOODS DEPARTMENT!
All the friendlyfoiks from Blondo will be at these 3 stores waiting to serve youl
iW
The J«»»M>i Pf—
Mmi23.1978
A Rabbi Explains: The Jewish People's Title to The Land of Israel •ylWH
ZvlMtariHi Oko BdHor-t Not*. The loltowti« Ktlele glvM one vtow of bott ttt : and mtot hMoo •< Ite Halachi sources, U U true, diiitinguisih b«(we«n the boundaries ol Ertz Yisrael atter the conquest of the Land under Joshua, and thoce (ixeit after the Return from Baliylon under Ezra and Nehemiah. but the Jewish people's title to the country |< t)eyond dispute That title was, moreover, firmJy established kmg before the Exodus from Egypt ir the divine Covenant -with the Palriardis and llieir descendants throughout the ' generations: "And 1 will bring you unto the land.. . and I will give il you (or a heritage. I am the U>rd'' I Ex 6:81 Our sages even considered those distant t>order regions which had i«>t been granted a lull measure ol holiness by the Halacha to be "suborta of Jerusalem." and this idea bat remained imbedded in the Jewish national consciousness Throughout the ages, the Jewish people regarded the whole of Eretz Yisrael as "the Holy Land.' always yearning for the day of Return and never al>andonlng its proprieturship liie (act that other peoples have periodically ocn^ited the Land In no way affects this title. A dear distinction must be drawn, therefore, betweeu coUacUve and Individual ritfits, between the iecal Md taMorIc title af Ibe Jewiiti people and the natural rl^iU o( eilstli« toliabltanU. So whik tlie larasUlcs wtfc pnpand lo make peace wttb Che Intttama popiilatloa aod to laftfuard tlitir bMk rltfiU (d. Dent, ru), iudi
Desalination Experts Due In Israel Soon JERUSALEM <JTA» - A team of American desalination experts are due in Israel to examine prospects (or erecting a sea-watersweetening plant at Aahdod. The team is being setit under Die terms ol the new economic agreement signed by U.S. Treasury Secretary William Simon and ' Israel Finance Minister Yehushua Rablnowitz in Washington last Tuesday. The U.S. undertook in that accord to contribute $20 million to a desalination plant at Ashdod with Israeli government putting up an equivalent sum.
RON GORDON with
actloa dM net altar the tMm 1 the Land wMch was the tar«U«B •< UM Jewish people a* a collective group, and helisruwl to ao other II was this Mnahakabie title to the Land - baaed on the Jewish people's age-old connection with Erelz Yisrael and on the pioneering adiievemenls of the early halutzim - that inspired the Balfour Oeclaration issued by the British Government and sot}sequenlly endorsed by the League of Nations. This Declaration clearly recognizes the judicial distinction between collective i national i and individual rights, promising "the establishment In Palestine of a natioiul home (or the Jewish people' and. at the same lime, guaranteeing "the civil and rtligiuus rights of existing nonJewish commiinities." Nowtiere in Ihe Balfour Declaration is the mention o( an Arab poptiiation only of "existing non-Jewish communities." Almost the whgle of historic Ertz Yisrael was included within the area allocated to the Jewish National Home under the Mandate entrusted to Bntain by the Ver sallies Peace Conference and the League o( Nations Under the terms of the Mandate. Palestine the Jewish National Home emcompassed ttie vast area of Trans Jordan, east of the Jordan river Only a short time, however, elapsed belore Britain unilaterally divided lis mandated territory, tiariding tl>e region east of the Jordan to the Emir Abdullah and leaving only Western Palestine at the truncated ".National Home " In this way a good lhree-<juarten> of the territory of Ertz Israel was wrested from the Jewish people by a political act that had no legal basis or Leagite of'Nations sanction. It ezplicily contravened the terms laid down by the Mandates Commissloa. Sad to say, the Ylsnuv o( lUI bad no power to resist Britain's Ulctal amputation of Trans-Jordan from Ihe area pledged to the Jetvlah people in the Balfour Declaration. Today, hall a caoiwy w nxn later, we can leak back on an anrelcatlDg Arab campalga Bttle what remakied of the origkial Natlaaal Home. The (stablMBMal of die HaAemlle Kln«lom of Jordan at Jew lah expense dkl not lead to any •i«^«Ting of Arab agltatkm agslnai allysh tai tfca period of the BlrtMi Maadalc. nor was die Arab appetite lor Jewlrii laoB ever sMMDoa oy nie BTMMI
Papers calUng tartbsr paitltkn of Uw osMohT. The Zionist leadership's readiness to discuss a terrltarlal compromise met with stony silence. It Is not surprising, therefore, that men like CYiaim Welzmann and Moshe Sharett, who were reluctaatly prepared Ip accept partition, came to view this as merely a sliort-term "solution" Better Jewish autonomy in some comer of Eretz Yisrael than further betrayal and erosion under the British Mandate But both Welzmann and Ben-Gurlon eventually sensed that even partition would not satisfy the Arabs and thai tlie territorial issue might remain alive for decades to come When the 20th iiionlst Congress decided in 1937 to accept Ihe Peel Commission's partition plan, while hoping for some more favourable modification,Ihe underlying assumption was that such a farreaching concession to Ihe Arabs would lead to peace and allow for an unobstructed development of the surviving "National Home " This was a vain hope The one desire of the Arabs then as now - was for a final and wholesale eradication of the Jewish presence in Eretz Yisrael, whether through an organized expulsion or a war of annihilation As (ar as the Arabs are concerned, there could - aod can be no "peace in return (or territories" The terrorism (Irst unleashed in the I92a's against Jewish civilians is the consistent Arab reply to whal Ihey see as the Jewish > and Israeli i weakness (or compromise and negotiation Neither the International community nor even tba e^aMMied Ar^ lUtes ever aeeorded recojiltlen to such a Ihtag at a "Paleathilan entity." nti was a wholly aborUve •ngiallni roUowIng the IMM* War of Independence, Israel's TrantJordaoiaD ndgbbour hastwwid to Incoipurale Judea and Samaria imo her lanltory, alOn^b this illegal act of aimeiatton was retojilwd aoly by Onti Britain and PakMaa. and not bgp Ibe Arab
ministration and Justlte Law, toU the Knesset that dils' was "Intended to (a appllcatioo o( Israeli I areas of Eretz Yisrael Israel Defence Fo/ liberated from (or jugation. "Jurists alao staled Iheir forth bi a memo Israel (iavemment of lAuglD, iSTlli.that 1 Tlie status of (jgypt In Ihe Gaza Strip and of Jerusalem, Judea"" was, unlil 1967, that < Invader 2 Jordan's occupation of East Jerusalem, Judea and Samaria thus entitled her to no sovereignty over the (iaza Strip. 3 The principle whereby "the acquisition of territories by act of war " is rejected, and which finds expression in the preamble of Kesoiution 242 of the UN Security Council cannot be applied in such a way as to favour states which themselves unlawfully invaded the territories in question
4 The Zionist Movement's •bouki be made anilcable to these agreement in 1947 to rellnqulah Its , areas as well. It la not by virtue of claim to a portion o( Eretz Yisrael omatgry Tugillatlnni Ihil lirad within the (ramework of the g> and 10 must It be In respect of (General Assembly's recommendalkxi iNo. Ill) of Nov 29, TTial historic right and title finds 1947, was dependent on a expresskm in a law of July 2.190, parallelagreement by the Arabs to which empowers the Government accept the samerecommendatlon. "lo make the Slate's Justice, Arab opposition to the General Jurisdiction and administration Assembly's recommendation and apply to every area oi Eretz Ihe Arab stales' Invasion of Eretz Yisrael which 11 designates." Yisrael In May I94S together The territories which have been Iruslraled the UN Partlllon Plan liberated, returned and re united Accordingly, therefore, the Jewish with those ol the Jewish Slate people's title to the whole of Eretz Eretz Yisrael - are not held by Yisrael remains vailld Hence the force of military occupation, but State of Israel reserves the right of by virtue of Israel's ancient deeds sovereignty over Eretz Yisrael, as ol entitlement whose sanction ikes that territory was comprehended in the divine promise as fully under the Mandate acknowledged both by the League StoM lb* Sta Day War. Ivari of Nations and the U.N iDd the Jewish paopia have They are ours by virtue of the ratumed to die original larrHortas words of Israel's Prophets a the Maadala - Uw bMorie which, throughout the centuries, bordon of Uw Holy LamL ns law have been universally recognized governing these liberated as the legal basts for our right to territories Is Uiai which ippUaa to return to our L.and and to establish the "aidiuits of Jcmsalem," and an independent Jewish State in our policy la railed of Jerastlem Eretz Yisrael
nGordman
SUN AND hi
According to embicnt Jurists, international law upholds llie Jewish people's rights to the areas under the Mandate that remained in force until May ». I«4S. They affirm that the SUIe of Israel has more right to claim aoverlgnty over the whole territory of Eretz Yisrael than any other state in the region. On June 27, 1M7, the Israel Minister of Justice, explaining a proposed amendment to the Ad-
Omaha's No. 1 Family Restaurant
XeyJRealEstate FEATUMNG
C«n Bon to MKUM your n«Kt mew* OHice: 333-3SM
ic IMI SMUWI FrM OMtkN ^IwfcMMlUt Haw do yev plan la took Ihls ivnwnsr? Sun-setlenof? We're here fo help . .. righl now our took-ln onif rsonary ore bvrs'ing wtlh twim 'n sun tothiom for poohlda, beach or backyard Shown hoto ore pfnghom ehtki and calico patch with ruffle Irlmi — He beck odlinl hollar — fully llnad SlMot i lo IJ oncf wfiof o prkall I
391-6a73
CARPITS HIED SERVICE Cl*an-R»pair MEWCAItPETt INSTALtED
$097 OpmevmyDmY, 11:90 A.M. TM W P.M.
RICHMAN GORDMAN
Den leriMteln
Saft-W«)r Rvi (Umtn Call 345-af S4
nu
>9M22>
Omoho • Co. Bluff* • Lincoln •
DM
Molnet • Grand blond • Topeko
M«y23,197f
Highland Country Club Scene of Nogg Wedding OMAHA - Patty I^ and Steve Nogg were married Sunday, May 18 In a 11:30 a.m. ceremony at Highland Country Club with Rdbbi Sidney Brooks officiating. Mrs. James Brantz of Boulder, Col. was her sister's matron of honor. Bridesmaids included Misses Lynne and Jane Nogg of Boston. Mass., sisters of tiie groom; Miss Judy Kordansky of Tempe. Ariz, and Mrs. Greg Wadleigh of Lincoln. Best man was Jeff Krum of Des Moines, Iowa. Ushers were Richard Lee of Council Bluffs, brother of the bride; Richard Jacobson, Mark Singer and Harvey Josin, all of Omaha. Immediately following the ceremony a reception was held at HCC Parents of the bride are Mrs. Harlan Studna of Omaha and Seymour Lee of Overland Park. Kansas. Mr. and Mrs. Ernie Nogg are the groom's parents.
Lighting Up OMAHA - AI Shrter, a rMtdent of the Dr. Philip Sher Home lor Ibe Aged, walks down one o( lite hallways In which the lighting lecently has been modemlxed. The medical wing alio was In^uded in the t2,S0l> gift project tnm the Omaha Section iiational Council of Jewish Women. Other Council projects have Included remodeling the nurses' quarters, buying a large food -freesar, redecwaUng the auditorium and refumlsUng a room. AO donatloas to the Dr. Pliilip Sber Home for the Aged MoUle Sdilmmel Ftmd are used tor projects at the Home as needed, According to Council Co-Chalrmen Mrs. Edwin E. Brodkey and Mrs. Uoyd Priedmao. (JP Photo)
f YAD Calendar]
John Kallna PHOTOOKAItHER •17 South Mth StfMt — 34S-1044
NATURAL , COLOR
And
Black and White
Jun7 Inlemallonal PoUuck Dinner. Call Jayne. 397-7322 June 21 Worlds of Fun Call Bruce. 331 6733. Junta \ Pool and steak party Call Gary. 334-1200 JulyVS Kansas City Weekend (NtasrDaiM July » - Brunch In Park, deUlls to follow July 26 - Old McSklenar's Farm. DTF Aug. t Wine Art Night. DTF. Aug 16 Car Rally and Party with Band. Aug. 17 - Zoo Day. DTF. Aug. 2324 - Camp Esther K. Newman.
LANDON'S The Midwest's Fashion Center for Men NOW TWO OF A KIND for your
SHOPPING CONVENIENCE
DOWNTOWN and OLD MILL featuring... • UNLMITEO SELECTION • SIZES FOR TME HARD TO FIT • FAMOUS BRANDS • THE HNEST TAILOMNO DEPARTMENT IN AMERICA • FASHION ORIENTEO FRIENDLY SALES PERSONNEL
Bluffs News By Sylvia Telpner The Irving Cohen Lodge of B'nal B'rith will hold the annual Memorial Day Service on Sunday, May 25 at the Jewish Cemetery in Council Bluffs. In case of rain, services will be held In the Council Bluffs Synagogue, 618 Mynster St. Veterans are urged to wear service caps. Sam Sacks and Saul Suvalsky will conduct the religious services. The Jewish War Veterans will assist in the service under the direction of Sol Lagman. Zeph Telpner. local C.P.A., will be guest speaker.
Cemetery Plan Calls for Fence OMAHA - Longestablished plans call for the replacing of the brick wall at Golden Hill Cemetery with wire fencing, according to Harry Sidman, co-chairman of the Beth Israel Cemetery Committee. A TS-foot section of the 300foot wall of the cemetery, located at 42nd and Brown Streets, collapsed a week ago Monday. Sidman said he and cochairman William Milder silkpected weather and old age contributed to the collapse of the wall, believed built around 1913. PERSIAN JEWS (ZINS) The Jewish community of Iran Is one of the oldest in the world, numbering some 65,000 souls. HILIN A. BiRNSTIlN 393-9111 333-1223 •lAL iSTATI WHh RgiDDAVItCO. SSS-2300
NOW OPEN IN OLD MILL - OUR NEW PLAZA SUITE
LANDON'S Old MM Shopping Cantor 108th and Dodg* ^m^^^^mtta^tmr
Prn^n
^iravwlTiTiiN s III th(; Omali.i FiHliT.ition Liljr.iry
KaOM WMom for Modvn Man, N.Y. Simon and Schuster, 1972. aSp. - The hibllcal books of Provertw and Ecdeslastes in modem translation. i baays la Old TsstsMSi fthlrt '?]• James L. Crenshaw, ed. N.Y. Ktav, 1974. 3S7p. — A collection of essays which seek U> answer such questions as "what does It mean lobe truly righteous in ancient Israel?" Bvaaleiby Berenice Jordan.'NY. Harper and Row, 1S74 tttp — ftiography o«)ueen Berenice, daughter of the last king of Judea. She, like Cleopatra, used her charms to further her political ambitions. No Way by Natalia GInsburg. NY. Harcourt Brace, I<n4. ISlp. - A witty, perceptive novel about a group of people, Uielr tragic and comic attempts to find meaning, to communicate, to bridge Uie generation gap and to survive In Uie ISTO's. Ihe Twriv»Year Raldi: A Social History of Nasi Oamumy un-lMS by Richard Grunberger NY, Holt. RInehart and Winston. 1»7I. 53Sp, - A comprehensive one-voluftte social history of Nazi Germany showing how Germans lived, worked. rela;ied and regarded Uiemselves and others between 1933 and 1945. Gstasof Broneby Halm Hazaz Philadelphia. J P.S., 1975.400p. - A novel about Ihe breait-up of traditional values in a little Jewish town, undermined both from within and by the edicts of the new regime.
Campus Notes Jeff Levinger. son of Mr. and Mrs. Chuck Levinger of Yankton, S.D., and grandson of Mr. and Mrs. I. H Weinerof Omaha, will graduate as valedictorian of his high school class of 230. He Is a National Merit Scholarship finalist and will attend Dart-
Library Closed OMAHA - TTie Federation Library at the Jewish Community Center will be closed Monday, May 26, for the Memorial Day holiday.
mouth College in September. Herschel E. Stoller, son of Mr. and Mrs. Leon Stoller of Chicago, Is a member of the first three-year medical class to graduate from the University of Nebraska Medical Center in ceremonies May 25. He will begin a year of residency In Internal Medicine at UNMC in July. His wife LUllan, also a medical student. Is the daughter of Mr. and Mrs. Henry Misle of Lincoln.
2 New FeaturBS, Films for JCC '7S-'76 Series OMAHA - Two new program features plus the film schedule were annoiuKed this week for the 1975-76 Jewish Community Center Film Series. One new feature will be seven summer film programs, the other feature a "series within a series" — a Jewishcontent mini-series of films. Also planned are "Surprise Shorts" and other items throughout the season. The film program, presented by the Center's Cultural and Performhig Arts Department under direction of Mark W. Zaikin, was announced by Susan Zaikin and Mil LInsman, co-chairmen of the Jewish Cultural Arts Council's Film Subcommittee. Zaikin said the four films of specifically Jewish content — "Molly," "The Life of Emile Zola," "The Dybbuk" and "Angel Levlne" — will be offered at uniform prices of $1 for adults and SO cents for children 12 and under. Regular rates are $1.75 for adults ($1 for Center members) and $1 for children 12 and imder (50 cents for members).
Alternative School Seeking Student Applications THI OPm aiMINTART SCHOOL irt Ryan High
Featuring Outstanding Women's Fashions
Downtown ItthandDodga
Mr*. Steve Nogg
The Jewish Press
School, • privotoly ownod and oporotod nondonomlnotlonol mtomotlvo grodo achoel la new occoptlng •ppllMitlona for K through 4th grado studonta. Opon doMroom atyla; Inne^ votlvo curriculum. Including tho boalca plus ^ four longuogo*. mualc. tho arts, film-making ^ and photography. Alio omphasls on •oclol •oifdovaiopmont. For Information ^ growth and •offMvaioi S4 call 344-Sg«S or S7a-SS: ISM. ^myy/yyy/^^4iiiii>tf>»imimmiiiiMMm
The Cultural and Performing Arts Department offers a Series ticket providing 10 admissions for the prlbe of eight. Contact the department at 334-8200 for details. Zalkiq^said the 1974-75 Film Series, the new Center's first, attracted nearly 3,000 to its 30 films, an average of ISO per show. The show schedule for 197576 (all shows are generally on Sundays at 7:30 p. m.): June 22 — Maltese Falcon. June 20 — Day at Uie Races. July 6 — The Singing Pool. July 13 - Molly. Aug. 10 - Dr. Jeckyl and Mr. Hyde. Aug. 17 — Intematlooal House. Aug. 24 - Buck Privates. Oct. 12 - Mutiny on the Bounty. Nov. 9 — Singing In the Rain. Nov. 16 — The Life of Emile Zola. Nov. 23 —Public Enemy. Dec. 7 - Modem Times. Dec 2425 - It's A Gift and "Sons of Desert." Jan. 4 — Blue Angel. Jan. 18 - It Happened One Night. Feb. 22 - The Dybbuk. March 7 WllsAn. March 21 - Phantom of the Opera. April 18 - Angel Levlne. April 29 — Gunga Din.. May 9 — I Am A Fugitive Horn A Chain Gang. May 23 — Dinner at Eight
Aduh Singles Group
I I
Watch for the new date for the Day at the Races and cookout. An Adult Singles tour to Israel may be In the offing by next spring. For Information call the Jewish Community Center, 334-8200, Ext. 49 from 8 a.m. to 5 p.m. Evenings call Rhoda Davis 391-6092 or Al Nogll 3317284.
Th»3m»thfnm
>I»Y23.
1876
Aquatics Notebook ByOary Javltdi
TOP TENNIS PLAYERS WILL PBRFORM Eight of the top tennis players in Nebraska, including the third-ranked singles player in the Missouri Valley, will give a doubles exhibition (or Jewish Community Center members a( 1:30pm Sunday, May 25, at the Center. ' The players include Harry Taylor, No 3 in MoValley Over 35 singles and tlie 1974 Lincoln and Fremont singles champion, who is also ranked No 2 in Nebraska singles, and Bill Foster, 1973 Nebraska Closed Singles champion and (omner No. i player in the state. John McCabe, another former No. 1 and itate ckwed champion who Is also the professhMial at Highland Country Gub and Hanscom Park, will compete as will Lincoln's Bill North, 1974 Lincoln Closed singles champ and former University of Nebraska starnetter. Kent Bond, head pro at The Tennli Club and a top Veterans League player, and Gene Starmer, the JCCs tennis pro who is the 1974 Tennis Club singles tiUlst and also a former NAIA District 11 champ, also are in the lineup. RECREATIONLAND DAY CAHP REGISTRATION Registrations are being taken for tiie Center's all-day recreation program for youngsters which will run June Z3August 1 at the Center. Bus transporation from neighborhood pickup points will be provided. For information, pall either Chuck or Mike, 334-8200 JCC ATHLETES SCHEDULED FOR AWARDS TTJC following were scheduled to be honored at the 2*th annual Center Sports Awards Night, held May 22 at the ^CC: 1. J Grtenben Memoriil Award (or Mod Inipraved Mi and 6Ui Orade Midget BukeUMll League Player. Larry Btab, Samud S. SMnbcrg Memorial Award as outilandinc Sth and 6th Gradr Midget Baikelball League Player Aady HoUaaoB, J J Greenberg Memorial Award as Outstanding Tth and Sth Grade Olympic league Baikelball Player. Keith MlUer, Harry Trustln Award ai the Outstanding Scnkir High Club HiKli School AlMele. Todd GrwitoBH, Iveille L Buckenroad Award as OuKUnding Adult Varsity Basketball Athlete Hariaa Noddle, Most Improved Male Racquelball Player Darryle Ekstrom, Outstanding Male Racquetball Player Marilyn Blatt, Most lmpro\'ed Woman RacquetlMll Player. JoAm KalhrdD, (Jut&tanding Woman Racquettull Player BUI AAley, Out-slandintt Male Jogger Lot* Utntr, Slimnaslics Woman of the Year EvaofellDe Femod, Oustandini! Woman Joiujpr Denlie Ferrari, Most ImprovedKdg '3rd Grade Gymnast. Kathleen Kunak, Outstanding Kdg -3rdGrade Gymnast JulieGordman, Most Improved4Ui-6lhGradeGymnast. Cathy Eari, Outslanding4lh«(h GradeGymnasi Cheryl WlAnaa, .Most Improved 7th-l2lhGrad<-Gymnast. Denlse Earl, Outstanding 7t)il2th Grade Gymnast SR HIGH SOFTBALL SCHEDULE FOR SiniDAY. MAY B «:» - Cbaim Weizmaan vs. AZA No 100 10:30-AZA No. vsUSTV
weekend There wtU be DO regularly scheduled classes on Monday, lilay 26 All dasaci wlil rattne Tuesday. May 27 Saturday Ipm.toiopm. Sunday 0a.m. tolOp.m. Monday OamlolOpm
Jewish Quiz Box QUESTION: Wby dOM tto Bible make It a ipedal oommandiiMDt to honor one's panolsT ANSWER: This is one of the commandments which commentaries note Is arrived at by sheer logic. However, the Torah made it a special point to Issue this commandment for a number of reasons. In honoring one's parents, t)esldes being logical, one uses it as a means of honoring God. Whatever honor one would show to God would be empty If one would not honor his parents. It is for this reason that God is often referred to as our "Father." Commentaries like Abrabranel claim thai the honor given one's parents is. therefore, a means of teaching one's children by example. Others claim that honoring one's parents Is a means of expressing gratitude tor that which one has received from others. In a way, the whole Jewish tradition is baaed upon the concept of gratitude. Our obedience to God Is based upon our indetitedness to Him to be expressed In a measure of gratitude for the many things we enjoy by His grace. Likewise, honoring one's parents is a measure of gratitude for all our parents have done for us. QUESTKWi: Wily dM* J««Wi tradition require that eane worde of Torah learning be espntaed and dieeuMed at ttw taMe when one eati? ANSWER: It is this practice which supposedly makes the difference between eating as an animal function and eating as a human enterprise. Animals liave Utile else In mind when they consume IheIr food Man. an intellectual being, an Image of the Almighty, raises his physical activity to an intellectual and spiritual level by adding words of culture and inspiration to his mealtime experience.
Registration has started at the Jewish Community Center foralldaiaes. This Is a reminder for all parents of elementary school age children that to enter an Advanced Beginner, Intermediate, or Swimmer class, a child must be tested and have a red swim
Minimized JERUSALEM (JTA) Premier Yitzhak Rabin said that President Ford's meeting with Egyptian President Anwar Sadat in Salzburg June 1-2 and his own lofthcoming meeting with Ford In Washington June 11-12 were part of the reassesament of Middle East policy now being conducted by the American government. In a tdevlson address In which he appeared to be minimizing the effects of the strained relations between Jerusalem and Washington since the' breakdown of Secretary of Stale Henry A. Kissinger's "shuttle" diplomacy last March, Rabin noted that relations with the U.S. were only "trnpemki In a partictilar area" — that of negotiating new arms contracts. Rabin stressed that arms "continue to (low In plenllfully" under contracts signed In the past. . ft REUGICH» RITUALS An introduction In the dally rituals and sacramental ot>jects of Judaism is liie subject of columns by Rat>bi Daniel B Syme appearing in "Reform Judaism" Magazine.
^»****»»**«»»*»»**»»»»»»*\ K.U. log tar brlghl, altv» fa- ^ mol* fo sdor* IMO bedroom oporfmont In lowrtocm nil senwsfer. Call ••fh. m7-«49S.
registration permit. ParenU needing that permit may come to the Center with their child any day from 4-5:30 p.m. to be tested. Plans are being made (or a Colorado River Raft Trip. This "adults only" adventure through white .water will be four days and three nights. There will be two full days on the river and two days on a ieep lour of the beautiful Mesa Grande area. The cost will cover most meals, air fare and the fantastic trip. July is the target month.
11EE.H.E.E.I T.E.E, R.K.E. sUad ioi Teokaieal Bnglnaerlag Isoellaaca. And Highly btravagant Estiaa. SisBiUni atiuipaMBt Ilka: • Salrtr front dlac brakes • Oierliaad cam onaiiM • Berllnliiu fennl buckets • Tinted gUsa • Whilawalls S*a Iha Soull Car bnert your Dalaun dealer, lor a baa last drlT*. Driva a Ditsun...tkan
BELLEVUE MOTORS raCiMiM.
Mmi.Mi.
AKTHUK WALKER. i«i49ia
Mi-aai*
**»•»»»»**»***»*»»*******•
^^S
mULTH cum MEMORIAL DAY HOintS The Health Cluh Cummilirr has announced the following special Memorial Day<iouni (or men and women .May 26 and Z7 The Health Club will lie open to men only on .Monday. May K. II a m 0:30 p.m The (acillly will be open to women only on Tuesday. May Z7.9 am-lOpm. rACnJTIESOPKN MEMOBIAL DAY Irv Yaffe. Health and Physical Education Committee chairman, announces that Hie gymnasium, track, weight exercise room and racquetball courts will be open at regular times during the Memorial Day
New Maneuver A iwin Current River current and a fallen tree provide octteinent and the need (or an unisual canoeing maneuver — •tepfring over the tree. Gary Javllcb does the tta|if>lng u Jeff Parker kee|i* « lookout during the Aquatic* Department't eipedltion earlier this month in MlMOUri. (JOG Photo)
WHrrE STTVG'SPEEDCj; SWIMSUITS
College Students Returning To Omaha and Des Moinet For the Summer Plan** notify the Jawiah Press now as to the dot* you will b« bock home for the lumnner. This will enobla us 1o eliminate duplicate moitlngs and forwarding charges. ' Please fill out the form below with your current college oddrass os it appears on your weekly Jewish Press and moil it to the Jewish Press, 333 So. 133nd. Omaha, Ne. 68154
SPORTS CORNER
Norn* Address. City
or* 01
Jtote_
Jtlp_
Effective OS of '. Thank you for your co-operation. Be sure to give us your new oddress in the fall.
WMtroflde Upper Level 39MS59 Also e Wormupe • O099IM
Jewish Press
|
https://issuu.com/jewishpress7/docs/1975-05-23
|
CC-MAIN-2018-22
|
refinedweb
| 17,852
| 63.39
|
Hello everyone! Welcome to the Part 3 of our AWS Amplify tutorial series. In this blog post, we will be adding Storage to our application and get into the details. For those who want to know more about how we came here, you can visit our previous blog posts and check the GitHub repo for our example Amplify project.
AWS Amplify is a set of tools and services that enables mobile and front-end web developers to build secure, scalable full stack applications, powered by AWS.sufle.io/blog/aws-amplify-the-ultimate-bootstrapper-part-1
The powerful development platform, AWS Amplify allows you to add authentication and roles via groups to limit resource access in your frontend application with ease.
We need storage to upload and display our book covers. Let’s add! Amplify storage uses S3 as the object storage for our content. Go on and type into your cli:
amplify add storage
Content, give your resource a name (which must be unique) and proceed to the authentication part. We need both guest and auth users to access these resources, but only authenticated users that are in the
Admins group must be able to update them.
There are three main access levels in storage:
/public,
/protected and
/private.
We need all users to access, so we will be using the
public access. Default behaviour of
Storage.put() is to upload with public access, so we don’t need to do anything else. Now go ahead to Create.js component and update it with the code:
import React, { useState, useRef } from "react"; import { API, graphqlOperation, Storage } from "aws-amplify"; import { createBook } from "../graphql/mutations"; function Create() { const [bookForm, setBookForm] = useState({ name: "", author: "", description: "", available: true, score: 0, }); const imageRef = useRef(); const handleChange = (key) => { return (e) => { setBookForm({ ...bookForm, [key]: e.target.value, }); }; }; const handleSubmit = (e) => { e.preventDefault(); var fileName = Date.now() + ".jpg"; Storage.put(fileName, imageRef.current.files[0]).then(res => { PI.graphql(graphqlOperation(createBook, { input: { ...bookForm, image: fileName }}))")} /> <input type="file" accept='image/jpg' ref={imageRef} /> <button type="submit">Add Book</button> </form> ); } export default Create;
We’ve added a file input ref. We use the Storage class from aws-amplify and upload our data using the .put method. When the upload is successful, we also add that path into our data. Now, Storage uploads all files under public access without any further data. You can specify them at the 3rd parameter object, like:
{ level: protected }
We’ve added our files as protected. Now, we need to add
image property to our GraphQL schema.
type Book @model @auth(rules: [ {allow: public, operations:[read]}, {allow: groups, groups: ["Admins"], operations: [create, read, update, delete]} ]){ id: ID! name: String! author: String!, description: String, available: Boolean!, score: Float! image: String }
Go ahead and provision our changes:
amplify push
To display those images, we will use AmplifyS3Image component from
@aws-amplify/ui-react library. Let’s import it into our code and add it to our list page:
<ul style={{display: "flex"}}> {books.map((book, index) => ( <li key={index} style={{display: "flex", flexDirection: "column"}}> <div> <AmplifyS3Image style={{"--height": "150px"}} path={book.image} /> </div> <Link to={`/book/${book.id}`}> {book.name} - {book.author} </Link> </li> ))} </ul>
You can see that we are using the
AmplifyS3Image component to display the content. For styling, we need to override css variables on the element, like
--width and
--height. We also need to add an Edit component, so that our admins can update books that don’t have covers.
Our final screen looks like this:
Go ahead and deploy your application,
amplify publish
It is amazing to experience how well AWS components are integrated into Amplify Framework and how easy it is to start using them in our frontend application. We will continue to explore AWS Amplify further! To be continued!.
|
https://www.sufle.io/blog/aws-amplify-storage-part-3
|
CC-MAIN-2022-40
|
refinedweb
| 632
| 55.84
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.