Understanding and Visualizing Convolutional Neural Networks
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 1 3 Feb 2016
A1 is graded. We’ll send out grades tonight (or so)
A2 is due Feb 5 (this Friday!): submit in Assignments tab on CourseWork (not Dropbox)
Midterm is Feb 10 (next Wednesday)
Oh and pretrained ResNets were released today
(152-layer ILSVRC 2015 winning ConvNets)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 2 3 Feb 2016
|
|
|
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 4 3
| Classification |
|
|
|
|||||||||||
|
|
|||||||||||||
CAT CAT CAT, DOG, DUCK CAT, DOG, DUCK
Single object Multiple objects
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 5 3 Feb 2016
Visualize patches that maximally activate neurons
Visualize the weights
Visualize the representation space (e.g. with t-SNE)
Occlusion experiments
Human experiment comparisons
Deconv approaches (single backward pass)
Optimization over image approaches (optimization)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 6 3 Feb 2016
Rich feature hierarchies for accurate object detection and semantic segmentation [Girshick, Donahue, Darrell, Malik]
one-stream AlexNet
pool5
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 7 3 Feb 2016
one-stream AlexNet
conv1
only interpretable on the first layer :(
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 8 3 Feb 2016
Visualize the filters/kernels (raw weights)
you can still do it for higher layers, it’s just not that interesting
(these are taken from ConvNetJS CIFAR-10 demo)
layer 1 weights
layer 2 weights
layer 3 weights
|
|
|
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 10 3 Feb 2016
fc7 layer
4096-dimensional “code” for an image (layer immediately before the classifier)
can collect the code for many images
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 11 3 Feb 2016
Visualizing the representation
t-SNE visualization
[van der Maaten & Hinton]
Embed high-dimensional points so that locally, pairwise distances are conserved
i.e. similar things end up in similar places. dissimilar things end up wherever
Right: Example embedding of MNIST digits (0-9) in 2D
|
|
|
two images are placed nearby if their CNN codes are close. See more:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 13 3 Feb 2016
[Zeiler & Fergus 2013]
(as a function of the
position of the
square of zeros in
the original image)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 14 3 Feb 2016
[Zeiler & Fergus 2013]
(as a function of the
position of the
square of zeros in
the original image)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 15 3 Feb 2016
YouTube video
https://www.youtube.com/watch?v=AgkfIQ4IGaM
(4min)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 16 3 Feb 2016
Feed image into net
how can we compute the gradient of any arbitrary neuron in the network w.r.t. the image?
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 17 3 Feb 2016
Feed image into net
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 18 3 Feb 2016
Feed image into net
Pick a layer, set the gradient there to be all zero except for one 1 for some neuron of interest
Backprop to image:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 19 3 Feb 2016
“Guided
backpropagation:” instead
Deconv approaches
Feed image into net
2. Pick a layer, set the gradient there to be all zero except for one 1 for
some neuron of interest
3. Backprop to image:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 20 3 Feb 2016
[Visualizing and Understanding Convolutional Networks, Zeiler and Fergus 2013]
[Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps, Simonyan et al., 2014]
[Striving for Simplicity: The all convolutional net, Springenberg, Dosovitskiy, et al., 2015]
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 21 3 Feb 2016
[Visualizing and Understanding Convolutional Networks, Zeiler and Fergus 2013]
[Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps, Simonyan et al., 2014]
[Striving for Simplicity: The all convolutional net, Springenberg, Dosovitskiy, et al., 2015]
Backward pass for a ReLU (will be changed in Guided Backprop)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 22 3 Feb 2016
[Visualizing and Understanding Convolutional Networks, Zeiler and Fergus 2013]
[Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps, Simonyan et al., 2014]
[Striving for Simplicity: The all convolutional net, Springenberg, Dosovitskiy, et al., 2015]
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 23 3 Feb 2016
conv6 (top) and layer conv9 (bottom) of the network trained on ImageNet.
Each row corresponds to one filter.
The visualization using “guided backpropagation” is based on the top 10 image patches activating this filter taken from the ImageNet dataset.
[Striving for Simplicity: The all convolutional net, Springenberg, Dosovitskiy, et al., 2015]
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 24 3 Feb 2016
[Visualizing and Understanding Convolutional Networks, Zeiler and Fergus 2013]
[Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps, Simonyan et al., 2014]
[Striving for Simplicity: The all convolutional net, Springenberg, Dosovitskiy, et al., 2015]
bit weird
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 25 3 Feb 2016
Zeiler & Fergus, 2013
Visualizing arbitrary neurons along the way to the top...
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 26 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 27 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 28 3 Feb 2016
can we find an image that maximizes some class score?
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 29 3 Feb 2016
Optimization to Image
score for class c (before Softmax)
can we find an image that maximizes some class score?
|
|
|
feed in zeros.
zero image
2. set the gradient of the scores vector to be [0,0,....1,....,0], then backprop to image
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 31 3 Feb 2016
Optimization to Image
feed in zeros.
zero image
set the gradient of the scores vector to be [0,0,....1,....,0], then backprop to image
do a small “image update”
forward the image through the network.
5. go back to 2.
score for class c (before Softmax)
|
|
|
1. Find images that maximize some class score:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 33 3 Feb 2016
1. Find images that maximize some class score:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 34 3 Feb 2016
Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps Karen Simonyan, Andrea Vedaldi, Andrew Zisserman, 2014
Visualize the Data gradient:
| (note that the gradient on |
|
|
| data has three channels. | ||
| Here they visualize M, s.t.: |
(at each pixel take abs val, and max over channels)
|
|
|
Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps Karen Simonyan, Andrea Vedaldi, Andrew Zisserman, 2014
Visualize the Data gradient:
(note that the gradient on data has three channels. Here they visualize M, s.t.:
(at each pixel take abs val, and max over channels)
|
|
|
Use grabcut for segmentation
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 37 3 Feb 2016
Repeat:
Forward an image
Set activations in layer of interest to all zero, except for a 1.0 for a neuron of interest
Backprop to image
Do an “image update”
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 38 3 Feb 2016
Proposed a different form of regularizing the image
More explicit scheme:
Repeat:
Update the image x with gradient from some unit of interest
Blur x a bit
Take any pixel with small norm to zero (to encourage sparsity)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 39 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 40 3 Feb 2016
|
|
|
|
|
|
|
|
|
code, is it possible to reconstruct the original image?
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 44 3 Feb 2016
Its code is similar to a given code
It “looks natural” (image prior regularization)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 45 3 Feb 2016
original image
reconstructions from the 1000 log probabilities for ImageNet (ILSVRC) classes
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 46 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 47 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 48 3 Feb 2016
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 49 3 Feb 2016
DeepDream https://github.com/google/deepdream
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 50 3 Feb 2016
|
|
|
jitter regularizer
“image update”
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 52 3 Feb 2016
inception_4c/output
DeepDream modifies the image in a way that “boosts” all activations, at any layer
this creates a feedback loop: e.g. any slightly detected dog face will be made more and more dog like over time
|
|
|
DeepDream any layer
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 54 3 Feb 2016
DeepDream modifies the image in a way that “boosts” all activations, at any layer
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 55 3 Feb 2016
Deep Dream Grocery Trip https://www.youtube.com/watch?v=DgPaCWJL7XI
Deep Dreaming Fear & Loathing in Las Vegas: the Great San Francisco Acid Wave https://www.youtube.com/watch?v=oyxSerkkP4o
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 56 3 Feb 2016
A Neural Algorithm of Artistic Style by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge, 2015] good implementation by Justin in Torch: https://github.com/jcjohnson/neural-style
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 57 3 Feb 2016
make your own easily on deepart.io
|
|
|
content targets (ConvNet activations of all layers for the given content image)
content activations
e.g.
at CONV5_1 layer we would have a [14x14x512] array of target activations
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 59 3 Feb 2016
Step 2: Extract style targets (Gram matrices of ConvNet activations of all layers for the given style image)
style gram matrices
e.g. at CONV1 layer (with [224x224x64] activations) would give a [64x64] Gram matrix of all pairwise activation covariances (summed across spatial locations)
|
|
|
The content of the content image (activations match content)
The style of the style image (Gram matrices of activations match style)
(+Total Variation regularization (maybe))
match content
match style
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 61 3 Feb 2016
Question: Can we use this to “fool” ConvNets?
spoiler alert: yeah
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 62 3 Feb 2016
[Intriguing properties of neural networks, Szegedy et al., 2013]
|
|
|
|
|
|
|
|
|
|
||||
>99.6% confidences
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 64 3 Feb 2016
>99.6% confidences
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 65 3 Feb 2016
[Exploring the Representation Capabilities of the HOG Descriptor, Tatu et al., 2011]
Identical HOG represention
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 66 3 Feb 2016
“primary cause of neural networks’ vulnerability to adversarial perturbation is their linear nature“
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 67 3 Feb 2016
(logistic regression)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 68 3 Feb 2016
| x | 2 | -1 | 3 | -2 | 2 |
|
1 |
|
|
1 | |
| w | |||||||||||
| 1 | -1 | 1 | -1 | 1 |
|
1 |
|
|
1 | ||
input example
weights
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 69 3 Feb 2016
| x | 2 | -1 | 3 | -2 | 2 |
|
1 |
|
|
1 | |
| w | |||||||||||
| 1 | -1 | 1 | -1 | 1 |
|
1 |
|
|
1 | ||
class 1 score = dot product:
= -2 + 1 + 3 + 2 + 2 - 2 + 1 - 4 - 5 + 1 = -3
=> probability of class 1 is 1/(1+e^(-(-3))) = 0.0474
i.e. the classifier is 95% certain that this is class 0 example.
input example
weights
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 70 3 Feb 2016
|
2 |
|
3 |
|
2 |
|
1 |
|
|
1 | |
|
|||||||||||
| 1 |
|
1 |
|
1 |
|
1 |
|
|
1 | ||
| adversarial x | ? |
|
? |
|
? |
|
? |
|
|
? | |
class 1 score = dot product:
= -2 + 1 + 3 + 2 + 2 - 2 + 1 - 4 - 5 + 1 = -3
=> probability of class 1 is 1/(1+e^(-(-3))) = 0.0474
i.e. the classifier is 95% certain that this is class 0 example.
input example
weights
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 71 3 Feb 2016
Lets fool a binary linear classifier:
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||||||||
| 1 |
|
|
|
|
|
|
|
|
|
||
| adversarial x |
|
|
|
|
|
|
|
|
|
|
|
input example
weights
class 1 score before:
-2 + 1 + 3 + 2 + 2 - 2 + 1 - 4 - 5 + 1 = -3
=> probability of class 1 is 1/(1+e^(-(-3))) = 0.0474
-1.5+1.5+3.5+2.5+2.5-1.5+1.5-3.5-4.5+1.5 = 2
=> probability of class 1 is now 1/(1+e^(-(2))) = 0.88
i.e. we improved the class 1 probability from 5% to 88%
|
|
|
Lets fool a binary linear classifier:
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||||||||
| 1 |
|
|
|
|
|
|
|
|
|
||
| adversarial x |
|
|
|
|
|
|
|
|
|
|
|
input example
weights
class 1 score before:
-2 + 1 + 3 + 2 + 2 - 2 + 1 - 4 - 5 + 1 = -3
=> probability of class 1 is 1/(1+e^(-(-3))) = 0.0474
-1.5+1.5+3.5+2.5+2.5-1.5+1.5-3.5-4.5+1.5 = 2
=> probability of class 1 is now 1/(1+e^(-(2))) = 0.88
i.e. we improved the class 1 probability from 5% to 88%
image has 150,528.
(It’s significantly easier with more numbers, need smaller nudge for each)
|
|
|
Recall CIFAR-10 linear classifiers:
ImageNet classifiers:
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 74 3 Feb 2016
mix in a tiny bit of
Goldfish classifier weights
+ =
100% Goldfish
|
|
|
|
|
|
|
|
|
“primary cause of neural networks’ vulnerability to adversarial perturbation is their linear nature“
(and very high-dimensional, sparsely-populated input spaces)
In particular, this is not a problem with Deep Learning, and has little to do with ConvNets specifically. Same issue would come up with Neural Nets in any other modalities.
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 78 3 Feb 2016
Summary
Backpropping to the image is powerful. It can be used for:
Understanding (e.g. visualize optimal stimuli for arbitrary neurons)
Segmenting objects in the image (kind of)
Inverting codes and introducing privacy concerns
Fun (NeuralStyle/DeepDream)
Confusion and chaos (Adversarial examples)
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 79 3 Feb 2016
Image Captioning Recurrent Neural Networks RNN Language Models
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 80 3 Feb 2016
ReLU W2 ReLU
5 2 2 4 4
W3
-2 3 3 -2 0 5
1 -2 0 -3 0
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 81 3 Feb 2016
: all +ve and -ve paths of influence through the graph interfere
W1 ReLU W2 ReLU
5 2 2 4 4
W3
-2 3 3 -2 0 5
-2 0 -3 0 positive gradient, negative gradient, zero gradient
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 82 3 Feb 2016
: cancel out -ve paths of influence at each step (i.e. we only keep positive paths of influence)
W1 ReLU W2 ReLU
5 2 2 4 4
W3
-2 3 X 3 -2 0 5
-2 0 -3 0 positive gradient, negative gradient, zero gradient
Fei-Fei Li & Andrej Karpathy & Justin Johnson Lecture 9 83 3 Feb 2016


This extension is designed to be used with the EMBL-EBI Sequence Alignment Tool
Please visit us on GitHub for more informaiton regarding this extension.


The Korean KORDA Jamo (SIL) keyboard is built to type Korean using the transliteration system KORDA (Korean Romanization for Data Application). KORDA is designed to make Latin-Korean transliteration easy, accurate, and computerizable. For more information on KORDA, see About KORDA.
The Korean KORDA Jamo (SIL) keyboard creates hangeul syllables from jamo letters each time you press Spacebar.
This keyboard includes an On Screen Keyboard view for easy reference. The On Screen Keyboard works best when associated with a QWERTY US layout.
This is a Unicode keyboard and works with any Unicode font which has support for Korean characters. Common fonts which work with this keyboard are:
The Korean KORDA Jamo (SIL) keyboard converts Korean jamo into hangeul after you press Spacebar. As you type, Korean jamo are shown. When you press Spacebar, the jamo are converted into a hangeul syllable.
Example: type sam to see 사ᄆ. Press Spacebar to get 삼.
Pressing Spacebar twice will insert a space. If you wish to insert uncombined jamo into your text, press Shift+Spacebar.
The letters c, y, and w require you to type another key to get a jamo. The letter c needs h. The letters y and w need vowels.
| Jamo | Keystroke |
|---|---|
| ᄀ | g |
| ᄁ | g+g |
| ᄂ | n |
| ᄃ | d |
| ᄄ | d+d |
| ᄅ | Initial: r Final: l |
| ᄆ | m |
| ᄇ | b |
| ᄈ | b+b |
| ᄉ | s |
| ᄊ | s+s |
| ᆼ | Initial: Automatic Final: n+g |
| ᄌ | j |
| ᄍ | j+j |
| ᄎ | c+h |
| ᄏ | k |
| ᄐ | t |
| ᄑ | p |
| ᄒ | h |
| Jamo | Keystroke |
|---|---|
| ᅡ | a |
| ᅣ | y+a |
| ᅥ | u |
| ᅧ | y+u |
| ᅩ | o |
| ᅭ | y+o |
| ᅮ | o+o |
| ᅲ | y+o+o |
| ᅳ | e+u |
| ᅵ | i |
| ᅢ | a+e |
| ᅤ | y+a+e |
| ᅦ | e |
| ᅨ | y+e |
| ᅪ | w+a |
| ᅫ | w+a+e |
| ᅬ | o+e |
| ᅯ | w+o |
| ᅰ | w+e |
| ᅱ | w+i |
| ᅴ | u+i |


New markup creation tools make Google Earth a free storytelling platform
by Abner LiIn addition to being a fun way to explore the globe, Google Earth has always been big in education. Google is now turning Earth into a platform for storytelling with new creation tools that let you markup the world.
Google wants Earth to become a “storytelling canvas” that lets you “create a map or story about the places that matter to you.” These creation tools are accessed by clicking the new “Projects” tab in the sidebar and creating one.
After adding a location by search or dragging a pin, you can attach images, text, videos, and customize other properties, including colors, pins, and choosing the right 3D view to frame. In addition to places, you can draw lines, shapes, and Street View.
All work is saved to Google Drive and supports standard collaboration. Once complete, there is a “Present” view that flies you from location-to-location while displaying all your notes on top. In addition to the web, the final project is available on mobile and tablet devices with the Google Earth app for Android or iOS.
These new capabilities — available for everyone — build on the web redesign of Google Earth in 2017 and the curated Voyager collection that’s limited to a select few. It’s also a more user-friendly version of Google Earth Studio for professionals.
For nearly 15 years, people have turned to Google Earth for a comprehensive view of our planet. But our mission has never been to just show you a static picture of the planet; we want to bring the world to life. With new creation tools now in Google Earth, you can turn our digital globe into your own storytelling canvas.
The new Google Earth creation tools have huge potential for educators assigning projects to students. Google also touts how it can be leveraged by non-profits and even individuals that want to create interactive projects where physical location plays a key role. These expanded capabilities are available today.
FTC: We use income earning auto affiliate links. More.


In each image, something has been crossed out.
Row one: XX (roman numeral for twenty), Jamie Foxx, Sexual XXXXX!
Row two: XX (chromosomes), XXXX (from Discworld)
Row three: XXXXX (acromantula danger rating)
Row four: T.J. Maxx, XXXXXXXXXXXX (twelve strikes in bowling)
Row five: Dos Equis (XX), Exxon, Rexxar, the flag of Amsterdam (XXX)
Clearly, the number of consecutive Xs in each picture is relevant. But what do we do with them? Well, the puzzle is about Xs, and X means multiply, so we multiply them together.
2 x 2 x 5 = 20 = T
2 x 4 = 8 = H
5 = 5 = E
2 x 12 = 24 = X
2 x 2 x 2 x 3 = 24 = X
So the answer to the puzzle is, fittingly enough, THE XX.


The font shorthand property lets you combine up to six different properties in one single property.
You can make text that's bold, 24 pixels in size, and sans-serif.
You can make text that's italic, bold, small-caps, 24 pixel sans-serif, which looks like a comic book font.
Or you can just keep it simple, 16 pixels and monospace.


#include <db.h>int memp_fget(DB_MPOOLFILE *mpf, db_pgno_t *pgnoaddr, u_int32_t flags, void **pagep);
The memp_fget function copies a pointer to the page with the page number specified by pgnoaddr, from the source file in the DB_MPOOLFILE, into the memory location referenced by pagep. If the page does not exist or cannot be retrieved, memp_fget will fail.
Page numbers begin at 0, i.e., the first page in the file is page number 0, not page number 1.
The returned page is size_t type aligned.
The flags argument is specified by logically OR'ing together one or more of the following values:
The DB_MPOOL_CREATE, DB_MPOOL_LAST and DB_MPOOL_NEW flags are mutually exclusive.
Created pages have all their bytes set to 0, unless otherwise specified when the file was opened.
All pages returned by memp_fget will be retained (i.e. pinned in the pool until a subsequent call to memp_fput.
The memp_fget function returns the value of errno on failure, and 0 on success.
The memp_fget function may fail and return errno for any of the errors specified for the following Berkeley DB and C library functions: DBmemp->pgin(3), DBmemp->pgout(3), abort(3), close(3), dbenv->db_paniccall(3), fcntl(3), fflush(3), fprintf(3), free(3), fstat(3), fsync(3), getenv(3), getpid(3), getuid(3), isdigit(3), log_compare, log_flush, lseek(3), malloc(3), memcmp(3), memcpy(3), memset(3), mmap(3), open(3), pread(3), pstat_getdynamic(3), pwrite(3), read(3), sigfillset(3), sigprocmask(3), stat(3), strerror(3), strlen(3), sysconf(3), time(3), unlink(3), vfprintf(3), vsnprintf(3), and write(3).
In addition, the memp_fget function may fail and return errno for the following conditions:
The DB_MPOOL_NEW flag was set and the source file was not opened for writing.
The requested page does not exist and DB_MPOOL_CREATE was not set.
More than one of DB_MPOOL_CREATE, DB_MPOOL_LAST and DB_MPOOL_NEW was set.


Class for working with localization of texts.
| Properties | |
|---|---|
|
protected
|
Internal variable for storing the paths of the additional localization files. |
|
static
protected
|
Internal variable for storing the current context. |
|
static
protected
|
Internal array for storing the list of country name translations. |
|
static
protected
|
Internal variable for storing the current language. |
|
static
protected
|
Internal variable for storing the state whether the dictionary is loaded or not. |
|
static
protected
|
Internal array for storing the list of language name translations. |
|
protected
|
Internal variable for storing the path with the localization files. |
|
static
protected
|
Internal array for storing the list of supported languages. |
|
static
protected
|
Internal array for storing the list of text translations. |
|
protected
|
Internal variable for storing the state whether the APCU should be used. |
|
protected
|
Internal variable for storing the state whether the E_USER_NOTICE is triggered in the case of missing translations. |
| Methods | |
|---|---|
|
public
|
This function should detect the current language based on cookies, browser languages etc. |
|
public
|
Returns the current context. |
|
public
|
Tries to find the country code by the given name. |
|
public
|
Provides the list of countries for the given language in the form "code" => "translation". |
|
public
|
Provides the text translation for the country name by the code for the given langauge. |
|
public
|
Returns the current language. |
|
public
|
Tries to find the language code by the given name. |
|
public
|
Provides the list of languages for the given language in the form "code" => "translation". |
|
public
|
Provides the text translation for the language name by the code for the given langauge. |
|
public
|
Returns the list of supported languages. |
|
public
|
Checks whether the text translation for the text ID for the given langauge exists. |
|
public
|
Initializes the language manager with parameters. |
|
public
|
This is internal auxiliary function for loading the translations from the source JSON file. |
|
public
|
Sets the current language. |
|
public
|
Provides the text translation for the text ID for the given langauge. |
|
public
|
Checks whether the country code is valid (has translation). |
|
public
|
Checks whether the language code is valid (has translation). |
Internal variable for storing the paths of the additional localization files.
Internal variable for storing the current context.
Internal array for storing the list of country name translations.
Internal variable for storing the current language.
Internal variable for storing the state whether the dictionary is loaded or not.
Internal array for storing the list of language name translations.
Internal variable for storing the path with the localization files.
Internal array for storing the list of supported languages.
Internal array for storing the list of text translations.
Internal variable for storing the state whether the APCU should be used.
Internal variable for storing the state whether the E_USER_NOTICE is triggered in the case of missing translations.
This function should detect the current language based on cookies, browser languages etc.
Priority:
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $context | by value | string | "default" |
The context of the application. Some applications may consist of two parts - administration console and public site. A usual example is a CMS system. For example, you are using administration console in English and editing the public site for German and French. When you open the public site for preview in German or French, you want it to be open in the corresponding language, but the administration console should remain in English. With the help of $context, you are able to maintain different languages for different parts of your application. If you do not need the $context, just do not specify it. |
Returns the current context.
Some applications may consist of two parts - administration console and public site. A usual example is a CMS system.
For example, you are using administration console in English and editing the public site for German and French. When you open the public site for preview in German or French, you want it to be open in the corresponding language, but the administration console should remain in English.
With the help of $context, you are able to maintain different languages for different parts of your application. If you do not need the $context, just do not specify it.
Returns the current context.
Tries to find the country code by the given name.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $country_name | by value | string |
The name of the country in any supported language. |
Returns the country code if it could be found, otherwise an empty string.
Provides the list of countries for the given language in the form "code" => "translation".
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $country_list | by reference | array |
Target array where the country list should be loaded. |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
| $display_first | by value | array | [] |
List of the country codes to be displayed first in the order, they appear in the list. |
Returns true if the country list is successfully retrieved, otherwise false.
Provides the text translation for the country name by the code for the given langauge.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $code | by value | string |
Country ISO code (uppercase, e.g. US, DE, FR). |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
Returns the translation text for the country name or the $code if no translation is found.
Returns the current language.
Returns the current language ISO code.
Tries to find the language code by the given name.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $lang_name | by value | string |
The name of the language in any supported language. |
Returns the language code if it could be found, otherwise an empty string.
Provides the list of languages for the given language in the form "code" => "translation".
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $language_list | by reference | array |
Target array where the language list should be loaded. |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
| $display_first | by value | array | [] |
List of the language codes to be displayed first in the order, they appear in the list. |
Returns true if the langauge list is successfully retrieved, otherwise false.
Provides the text translation for the language name by the code for the given langauge.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $code | by value | string |
Language ISO code (lowercase, e.g. en, de, fr). |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
Returns the translation text for the language name or the $code if no translation is found.
Returns the list of supported languages.
Returns the list of supported languages.
Checks whether the text translation for the text ID for the given langauge exists.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $text_id | by value | string |
Text ID |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
Returns true if the translation exists, otherwise false.
Initializes the language manager with parameters.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $parameters | by value | array |
Settings for logging as an associative array in the form key => value:
|
It might throw an exception in the case of any errors.
This is internal auxiliary function for loading the translations from the source JSON file.
It should return true if the dictoinary has been successfully loaded, otherwise false.
It might throw the following exceptions in the case of any errors:
Sets the current language.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $language | by value | string |
The language ISO code to be set. |
Returns true if the current language has been successfully set, otherwise false.
Provides the text translation for the text ID for the given langauge.
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $text_id | by value | string |
Text ID |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
| $default_text | by value | string | "" |
The default text to be used if there is no translation. |
Returns the translation text or the $default_text/$text_id if no translation is found.
Checks whether the country code is valid (has translation).
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $code | by value | string |
Country ISO code (uppercase, e.g. US, DE, FR). |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
Returns true if the country code is valid (has translation), otherwise false.
Checks whether the language code is valid (has translation).
| Name | Pass type | Value type | Default value | Description |
|---|---|---|---|---|
| $code | by value | string |
Language ISO code (lowercase, e.g. en, de, fr). |
|
| $lng | by value | string | "" |
The langauge. If it is not specified, the default langauge is used. |
Returns true if the langauge code is valid (has translation), otherwise false.


This set of classes provides free and open access to:
Unlike numerous Blackjack APIs, this implementation provides for playing using virtually all variations of basic Blackjack, including changing:
I originally wrote this library to study the mathematics of Blackjack by performing Monte Carlo simulations on various playing strategies.
You can download Monte Jack version 1.0.1, including source, in tarball and ZIP formats from garrettsmith.net.
To implement a Blackjack player, first implement the EventHandler interface, then:
double wager = 1000; // you're a high roller, right? EventHandler eventHandler = new MyEventHandler(); Blackjack blackjack = new Blackjack(); blackjack.playGame( eventHandler, wager );
You can also play Blackjack via the console (using EventHandler) by using the scripts in the bin directory.
The documentation consists only of this page, the Javadoc, and a HTML version of the source:
You may e-mail me with support questions at gsmi
Copyright (c) 2005 Garrett Smith
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


© 2017 - 2023 | PiTi - crypto-webminer.com
Chart feature © 2013-2017 Nick Downie - Released under the MIT license
Earn cryptocurrencies direct in your wallet - for your website or blog visitors
Integrate our webmining service with easy steps


Fast Arabic Actor Coding (PERSON ENTITY)
Switch To Org Entity
Total Left:
0
START
COMMIT
Skip
Start Date:
End Date:
Related Sentences


Who Is This Handsome Fellow?
Full stack web developer whose experience includes, but is not limited to, the LAMP stack, JavaScript, HTML, and CSS.
Driven by a passion for finding creative solutions to complex problems through the use of of critical thinking, teamwork, and energy drinks.
Web Dev - Funny Jokes - Mediocre Puns


New missile will be commissioned immediately and bound to selected Deployment Platform.
Deployment Platform
Loading deployment platforms list...
Missile Name
Missile Type


Toggle navigation
Admin
CTRL
Login
Register
Admin Area
Signup Account
Register
Name
Email
Password
Confirm Password
Register me
Already have an account?


Posted on May 16, 2011
Two interesting blog posts on copyright and the Bible have been put up, the first by David Ker of FutureBible: “Bible Copyrights Aren’t Evil”, and the second by Peter Kirk of Gentle Wisdom, “Love of Bible copyright is a root of all kinds of evil”.
I encourage you to read them both. My viewpoint, as might be expected, is that we should renounce our copyrights in our translations as the OEB does. As I wrote on David’s site:
*Even a liberal licence gives the owner of the copyright power over the text. It tempts them to restrict use of the text to extract badly needed money (this isn’t an accusation of greed!) or to keep the text safe from bad influences. The desired outcome is good, but the mechanism is risky. It historically leads to the powerful determining what the powerless can make their Bible look like.
The world has already translations full of all sorts of egregious errors, distortions and theologically driven misinterpretations.
And there are certainly many current public domain translations out there which fail the trust test. But this is the price we pay for the freedom to seek the truth ourselves – to approach the Bible without requiring permission, licence or payment.
We should encourage good translations and warn against errors, but not seek to use the power of the State to enforce our (merely human) opinions.*


We now turn to classes and actors, which, as we have already mentioned, have some similarities, but also major differences. We consider a classical example of an object with state, the counter.
The counter allows three operations: its value can be increased by one (the ``button'' on top), reset to zero (the knob on the right) or read (the display). The use case for this particular variant of a counter is to keep track of the number of inc's performed since the counter was last reset.
Below are two valid Acton definitions, modelling the counter. The left one is also a valid class definition in Python. We also show some simple, typical use of the definitions.
class CounterC(): actor CounterA(initval=0): def __init__(self,initval=0): var val = initval self._val = initval def inc(self): def inc(): self._val += 1 val += 1 def read(self): def read(): return self._val return val def reset(self): def reset(): self._val = 0 val = 0 actor main(env): actor main(env) c = CounterC(5) a = CounterA(5) c.inc() a.inc() c.inc() a.inc() v = c.read() v = a.read() print(v) # prints 7 print(v) # prints 7
We see striking similarities and some minor differences between the two definitions:
Thus, we can use both class and actor definitions to create objects with state that can be manipulated and accessed through methods. But the syntax and the similaritites tend to downplay the fundamental difference between the two concepts:
This difference means that the actor a can be used as a member of the community of actors comprising a program, providing the service of a shared counter. It keeps track of the number of inc messages received, for which it can be queried in a read message.
The class instance, on the other hand, can not be safely used in this way. Imagine that we could create class instance c and place it as a top level member in a community of actors. Since the operation of increasing the value of an integer variable is not thread-safe, it is conceivable that two concurrent threads, doing message processing for actors using the class instance, will execute c.inc() in parallel, both read the same _val and increase it by 1 before writing back, with the net result that the two calls will only increase the counter by one.
The conclusion is that classes and class instances do have a role to play in Acton: instances can be used as (part of) the internal state in actors, but not as replacement for actors. To illustrate this point in an exaggerated way, the following would be a legitimate and safe use of class CounterC:
actor CounterA(initval = 0): var c = CounterC(initval) def inc(): c.inc() def read(): return c.read() def reset(): c.reset()
Here, there is no risk of multiple threads causing problems, since the calls to c's methods occur within the processing of an actor message. We certainly do not recommend this design, since the example is too trivial. The internal state of the actor is as easily modelled by an integer variable, so the use of a class instance here seems to offer no advantage. For an example where a class instance would be a natural choice as state we can think of a sorted container (set, list or dictionary or ...), i.e. a container which also supports an operation to retrieve its elements in sorted order. Here some form of binary search tree would be a natural candidate to represent the state. More generally, any data structure implemented as a class can be made thread-safe by wrapping it in an actor as indicated here.
A class declaration is a template for objects. Every time we execute c = CounterC() we get a new instance of the class CounterC with its own copy of the state _val.
The situation is the same for actors. Executing a = CounterA() creates a new actor instance of the "actor class" CounterA with its own copy of the state val. However, following established terminology but maybe a bit confusing at first, we refer also to the instance just as an actor.
The syntax for sending a message to an actor b, where b is an instance of actor (class) B, is b.m(args), where m must be a method declared in B and args are suitable arguments. Thus, actor a can only send a message to actor b, if a knows the name of b. This can be obtained in only two ways:


public abstract class GraphicsDevice extends Object
GraphicsDevice
class describes the graphics devices
that might be available in a particular graphics environment. These
include screen and printer devices. Note that there can be many screens
and many printers in an instance of GraphicsEnvironment
. Each
graphics device has one or more GraphicsConfiguration
objects
associated with it. These objects specify the different configurations
in which the GraphicsDevice
can be used.
In a multi-screen environment, the GraphicsConfiguration
objects can be used to render components on multiple screens. The
following code sample demonstrates how to create a JFrame
object for each GraphicsConfiguration
on each screen
device in the GraphicsEnvironment
:
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
GraphicsConfiguration[] gc =
gd.getConfigurations();
for (int i=0; i < gc.length; i++) {
JFrame f = new
JFrame(gs[j].getDefaultConfiguration());
Canvas c = new Canvas(gc[i]);
Rectangle gcBounds = gc[i].getBounds();
int xoffs = gcBounds.x;
int yoffs = gcBounds.y;
f.getContentPane().add(c);
f.setLocation((i*50)+xoffs, (i*60)+yoffs);
f.show();
}
}
For more information on full-screen exclusive mode API, see the Full-Screen Exclusive Mode API Tutorial.
GraphicsEnvironment
,
GraphicsConfiguration
| Modifier and Type | Class and Description |
|---|---|
static class |
GraphicsDevice.WindowTranslucency
Kinds of translucency supported by the underlying system.
|
| Modifier and Type | Field and Description |
|---|---|
static int |
TYPE_IMAGE_BUFFER
Device is an image buffer.
|
static int |
TYPE_PRINTER
Device is a printer.
|
static int |
TYPE_RASTER_SCREEN
Device is a raster screen.
|
| Modifier | Constructor and Description |
|---|---|
protected |
GraphicsDevice()
This is an abstract class that cannot be instantiated directly.
|
| Modifier and Type | Method and Description |
|---|---|
int |
getAvailableAcceleratedMemory()
This method returns the number of bytes available in
accelerated memory on this device.
|
GraphicsConfiguration |
getBestConfiguration(GraphicsConfigTemplate gct)
Returns the "best" configuration possible that passes the
criteria defined in the
GraphicsConfigTemplate . |
abstract GraphicsConfiguration[] |
getConfigurations()
Returns all of the
GraphicsConfiguration
objects associated with this GraphicsDevice . |
abstract GraphicsConfiguration |
getDefaultConfiguration()
Returns the default
GraphicsConfiguration
associated with this GraphicsDevice . |
DisplayMode |
getDisplayMode()
Returns the current display mode of this
GraphicsDevice . |
DisplayMode[] |
getDisplayModes()
Returns all display modes available for this
GraphicsDevice . |
Window |
getFullScreenWindow()
Returns the
Window object representing the
full-screen window if the device is in full-screen mode. |
abstract String |
getIDstring()
Returns the identification string associated with this
GraphicsDevice . |
abstract int |
getType()
Returns the type of this
GraphicsDevice . |
boolean |
isDisplayChangeSupported()
Returns
true if this GraphicsDevice
supports low-level display changes. |
boolean |
isFullScreenSupported()
Returns
true if this GraphicsDevice
supports full-screen exclusive mode. |
boolean |
isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency translucencyKind)
Returns whether the given level of translucency is supported by
this graphics device.
|
void |
setDisplayMode(DisplayMode dm)
Sets the display mode of this graphics device.
|
void |
setFullScreenWindow(Window w)
Enter full-screen mode, or return to windowed mode.
|
public static final int TYPE_RASTER_SCREEN
public static final int TYPE_PRINTER
public static final int TYPE_IMAGE_BUFFER
protected GraphicsDevice()
public abstract int getType()
GraphicsDevice
.GraphicsDevice
, which can
either be TYPE_RASTER_SCREEN, TYPE_PRINTER or TYPE_IMAGE_BUFFER.TYPE_RASTER_SCREEN
,
TYPE_PRINTER
,
TYPE_IMAGE_BUFFER
public abstract String getIDstring()
GraphicsDevice
.
A particular program might use more than one
GraphicsDevice
in a GraphicsEnvironment
.
This method returns a String
identifying a
particular GraphicsDevice
in the local
GraphicsEnvironment
. Although there is
no public method to set this String
, a programmer can
use the String
for debugging purposes. Vendors of
the Java™ Runtime Environment can
format the return value of the String
. To determine
how to interpret the value of the String
, contact the
vendor of your Java Runtime. To find out who the vendor is, from
your program, call the
getProperty
method of the
System class with "java.vendor".
String
that is the identification
of this GraphicsDevice
.public abstract GraphicsConfiguration[] getConfigurations()
GraphicsConfiguration
objects associated with this GraphicsDevice
.GraphicsConfiguration
objects that are associated with this
GraphicsDevice
.public abstract GraphicsConfiguration getDefaultConfiguration()
GraphicsConfiguration
associated with this GraphicsDevice
.GraphicsConfiguration
of this GraphicsDevice
.public GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate gct)
GraphicsConfigTemplate
.gct
- the GraphicsConfigTemplate
object
used to obtain a valid GraphicsConfiguration
GraphicsConfiguration
that passes
the criteria defined in the specified
GraphicsConfigTemplate
.GraphicsConfigTemplate
public boolean isFullScreenSupported()
true
if this GraphicsDevice
supports full-screen exclusive mode.
If a SecurityManager is installed, its
checkPermission
method will be called
with AWTPermission("fullScreenExclusive")
.
isFullScreenSupported
returns true only if
that permission is granted.AWTPermission
public void setFullScreenWindow(Window w)
isFullScreenSupported
returns true
.
Exclusive mode implies:
Component.enableInputMethods(false)
to make a component
a non-client of the input method framework.
The simulated full-screen mode places and resizes the window to the maximum
possible visible area of the screen. However, the native windowing system
may modify the requested geometry-related data, so that the Window
object
is placed and sized in a way that corresponds closely to the desktop settings.
When entering full-screen mode, if the window to be used as a full-screen window is not visible, this method will make it visible. It will remain visible when returning to windowed mode.
When entering full-screen mode, all the translucency effects are reset for
the window. Its shape is set to null
, the opacity value is set to
1.0f, and the background color alpha is set to 255 (completely opaque).
These values are not restored when returning to windowed mode.
It is unspecified and platform-dependent how decorated windows operate
in full-screen mode. For this reason, it is recommended to turn off
the decorations in a Frame
or Dialog
object by using the
setUndecorated
method.
When returning to windowed mode from an exclusive full-screen window,
any display changes made by calling setDisplayMode
are
automatically restored to their original state.
w
- a window to use as the full-screen window; null
if returning to windowed mode. Some platforms expect the
fullscreen window to be a top-level component (i.e., a Frame
);
therefore it is preferable to use a Frame
here rather than a
Window
.isFullScreenSupported()
,
getFullScreenWindow()
,
setDisplayMode(java.awt.DisplayMode)
,
Component.enableInputMethods(boolean)
,
Component.setVisible(boolean)
,
Frame.setUndecorated(boolean)
,
Dialog.setUndecorated(boolean)
public Window getFullScreenWindow()
Window
object representing the
full-screen window if the device is in full-screen mode.null
if the device is
not in full-screen mode.setFullScreenWindow(Window)
public boolean isDisplayChangeSupported()
true
if this GraphicsDevice
supports low-level display changes.
On some platforms low-level display changes may only be allowed in
full-screen exclusive mode (i.e., if isFullScreenSupported()
returns true
and the application has already entered
full-screen mode using setFullScreenWindow(java.awt.Window)
).isFullScreenSupported()
,
setDisplayMode(java.awt.DisplayMode)
,
setFullScreenWindow(java.awt.Window)
public void setDisplayMode(DisplayMode dm)
isDisplayChangeSupported()
returns true
and may
require first entering full-screen exclusive mode using
setFullScreenWindow(java.awt.Window)
providing that full-screen exclusive mode is
supported (i.e., isFullScreenSupported()
returns
true
).
The display mode must be one of the display modes returned by
getDisplayModes()
, with one exception: passing a display mode
with DisplayMode.REFRESH_RATE_UNKNOWN
refresh rate will result in
selecting a display mode from the list of available display modes with
matching width, height and bit depth.
However, passing a display mode with DisplayMode.BIT_DEPTH_MULTI
for bit depth is only allowed if such mode exists in the list returned by
getDisplayModes()
.
Example code:
Frame frame;
DisplayMode newDisplayMode;
GraphicsDevice gd;
// create a Frame, select desired DisplayMode from the list of modes
// returned by gd.getDisplayModes() ...
if (gd.isFullScreenSupported()) {
gd.setFullScreenWindow(frame);
} else {
// proceed in non-full-screen mode
frame.setSize(...);
frame.setLocation(...);
frame.setVisible(true);
}
if (gd.isDisplayChangeSupported()) {
gd.setDisplayMode(newDisplayMode);
}
dm
- The new display mode of this graphics device.IllegalArgumentException
- if the DisplayMode
supplied is null
, or is not available in the array returned
by getDisplayModes
UnsupportedOperationException
- if
isDisplayChangeSupported
returns false
getDisplayMode()
,
getDisplayModes()
,
isDisplayChangeSupported()
public DisplayMode getDisplayMode()
GraphicsDevice
.
The returned display mode is allowed to have a refresh rate
DisplayMode.REFRESH_RATE_UNKNOWN
if it is indeterminate.
Likewise, the returned display mode is allowed to have a bit depth
DisplayMode.BIT_DEPTH_MULTI
if it is indeterminate or if multiple
bit depths are supported.setDisplayMode(DisplayMode)
public DisplayMode[] getDisplayModes()
GraphicsDevice
.
The returned display modes are allowed to have a refresh rate
DisplayMode.REFRESH_RATE_UNKNOWN
if it is indeterminate.
Likewise, the returned display modes are allowed to have a bit depth
DisplayMode.BIT_DEPTH_MULTI
if it is indeterminate or if multiple
bit depths are supported.public int getAvailableAcceleratedMemory()
ImageCapabilities
object
associated with a VolatileImage that can be used to determine
whether a particular VolatileImage has been created in accelerated
memory.Image.flush()
,
ImageCapabilities.isAccelerated()
public boolean isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency translucencyKind)
translucencyKind
- a kind of translucency supportDracula Javadoc Sample, Made with Allan Im.


Domino Design Code Injection - Part 2
In Part 1 I introduced the approach to code injection and some sample LotusScript Code to pull a design element, transform it and push it back. Missing there was the function that actually implemented that method. I'm using a Java class to do that, which I wrap into LS2J. The LotusScript function looks like this:
This LotusScript was converted to HTML using the ls2html routine,
provided by Julian Robichaux at nsftools.com.
Now let us have a quick look at the Java class.
Option Public Option Declare Uselsx "*javacon" Use "CodeInjector" Function injectCode (rawDXL As String , xPath As String , codeSnippet As String ) As String 'Dummy doesn't do anything Dim jSession As JAVASESSION Dim injectorClass As JAVACLASS Dim injector As JavaObject Set jSession = New JAVASESSION injectCode = rawDXL Set injectorClass = jSession .GetClass ( "DominoXPathInjector" ) Set injector = injectorClass . CreateObject 'Now set the document Call injector .setDocument (rawDXL ) 'and execute the function injectCode = injector .injectCode (codeSnippet , xPath , 4 ) End Function
provided by Julian Robichaux at nsftools.com.
Read more
Posted by Stephan H Wissel on 21 March 2008 | Comments (0) | categories: Show-N-Tell Thursday


At the moment, the only web feature of Nearby is a JSON REST API that hooks into the mobile Application. If there is time, a web application may also be added


"RUDDER BANDS" Ancient ships had two great broad-bladed oars for rudders. These, when not in use, were lifted out of the water and bound or tied up. When required for use, these bands were unloosed and the rudders allowed to drop into the water (Acts 27:40).
"RUDDER BANDS" Ancient ships had two great broad-bladed oars for rudders. These, when not in use, were lifted out of the water and bound or tied up. When required for use, these bands were unloosed and the rudders allowed to drop into the water (Acts 27:40).


Overview
File
Class
Tree
Index
Help
PREV NEXT
FRAMES
NO FRAMES
All Classes
A
C
D
G
N
P
R
S
U
A
app_create(name, start, cb)
- Instance method in class
nodester
app_delete(name, cb)
- Instance method in class
nodester
app_info(name, cb)
- Instance method in class
nodester
app_logs(name, cb)
- Instance method in class
nodester
app_restart(name, cb)
- Instance method in class
nodester
app_running(name, running, cb)
- Instance method in class
nodester
app_start(name, cb)
- Instance method in class
nodester
app_stop(name, cb)
- Instance method in class
nodester
appdomain_add(name, domain, cb)
- Instance method in class
nodester
appdomain_delete(name, domain, cb)
- Instance method in class
nodester
appdomain_handler(name, domain, action, cb)
- Instance method in class
nodester
appnpm_handler(name, package, action, cb)
- Instance method in class
nodester
appnpm_install(name, package, cb)
- Instance method in class
nodester
appnpm_uninstall(name, package, cb)
- Instance method in class
nodester
appnpm_update(name, package, cb)
- Instance method in class
nodester
apps_list(cb)
- Instance method in class
nodester
C
coupon_request(email, cb)
- Instance method in class
nodester
D
del(path, body, cb)
- Instance method in class
nodester
G
get(path, cb)
- Instance method in class
nodester
GLOBALS
- class
GLOBALS
N
nodester
- class
nodester
P
post(path, body, cb)
- Instance method in class
nodester
process_response(cb, errfn)
- Class method in class
GLOBALS
put(path, body, cb)
- Instance method in class
nodester
R
request(method, path, body, cb)
- Instance method in class
nodester
S
status(cb)
- Instance method in class
nodester
U
user_create(user, pass, email, rsakey, coupon, cb)
- Instance method in class
nodester
user_delete(user, cb)
- Instance method in class
nodester
user_setkey(rsakey, cb)
- Instance method in class
nodester
user_setpass(newpass, cb)
- Instance method in class
nodester
A
C
D
G
N
P
R
S
U
Overview
File
Class
Tree
Index
Help
PREV NEXT
FRAMES
NO FRAMES
All Classes
Documentation generated by
JSDoc
on Sun Feb 13 11:36:35 2011


R/AllGenerics.R
, R/makeSummarizedExperiment-methods.R
makeSummarizedExperiment.Rd
This function is a utility wrapper for SummarizedExperiment
that provides
automatic subsetting for row and column data, as well as automatic handling
of transgenes and spike-ins.
makeSummarizedExperiment(assays, ...) # S4 method for SimpleList makeSummarizedExperiment( assays, rowRanges = GRangesList(), rowData = NULL, colData = DataFrame(), metadata = list(), transgeneNames = NULL, spikeNames = NULL, sort = TRUE, sessionInfo = TRUE ) # S4 method for list makeSummarizedExperiment( assays, rowRanges = GRangesList(), rowData = NULL, colData = DataFrame(), metadata = list(), transgeneNames = NULL, spikeNames = NULL, sort = TRUE, sessionInfo = TRUE )
| assays |
|
|---|---|
| ... | Additional arguments. |
| rowRanges |
|
| rowData |
|
| colData |
|
| metadata |
|
| transgeneNames |
|
| spikeNames |
|
| sort |
|
| sessionInfo |
|
Providing rowRanges
: RangedSummarizedExperiment
.
Providing rowData
: SummarizedExperiment
.
Column and rows always return sorted alphabetically.
Updated 2019-09-09.
This function improves upon the standard constructor by slotting useful
session information into the metadata
slot by default:
date
: Today's date, returned from Sys.Date
.
wd
: Working directory, returned from getwd
.
sessionInfo
: sessioninfo::session_info()
return.
This behavior can be disabled by setting sessionInfo = FALSE
.
#> [1] "gene01" "gene02" "gene03" "EGFP"#> [1] "sample01" "sample02" "sample03" "sample04"## Counts (assay) counts <- matrix( data = seq_len(length(genes) * length(samples)), nrow = length(genes), ncol = length(samples), dimnames = list(genes, samples) ) ## Primary assay must be named "counts". assays <- SimpleList(counts = counts) print(assays)#> List of length 1 #> names(1): counts## Row data (genomic ranges) ## Note that we haven't defined the transgene here. ## It will be handled automatically in the function call. rowRanges <- emptyRanges(names = head(genes, n = length(genes) - 1L)) print(rowRanges)#> GRanges object with 3 ranges and 0 metadata columns: #> seqnames ranges strand #> <Rle> <IRanges> <Rle> #> gene01 unknown 1-100 * #> gene02 unknown 101-200 * #> gene03 unknown 201-300 * #> ------- #> seqinfo: 1 sequence from an unspecified genome; no seqlengths## Column data colData <- DataFrame( age = rep( x = c(3L, 6L), times = length(samples) / 2L ), genotype = rep( x = c("wildtype", "knockout"), times = 1L, each = length(samples) / 2L ), row.names = samples ) print(colData)#> DataFrame with 4 rows and 2 columns #> age genotype #> <integer> <character> #> sample01 3 wildtype #> sample02 6 wildtype #> sample03 3 knockout #> sample04 6 knockout#> class: SummarizedExperiment #> dim: 4 4 #> metadata(3): date sessionInfo wd #> assays(1): counts #> rownames(4): EGFP gene01 gene02 gene03 #> rowData names(0): #> colnames(4): sample01 sample02 sample03 sample04 #> colData names(0):x <- makeSummarizedExperiment( assays = assays, rowRanges = rowRanges, colData = colData, transgeneNames = "EGFP" ) print(x)#> class: RangedSummarizedExperiment #> dim: 4 4 #> metadata(3): date sessionInfo wd #> assays(1): counts #> rownames(4): EGFP gene01 gene02 gene03 #> rowData names(0): #> colnames(4): sample01 sample02 sample03 sample04 #> colData names(2): age genotype


I am super passionate about designing and creating products and experiences that are easy and fun to use, and love to apply modern technology such as machine learning or 3D printing to assist in the design process.
Whether you're a manager looking for a curious and effective developer to join your team, a musician looking for VX effects for your live shows, or a graphic artist looking to collaborate, let's connect and make it happen!


Gil
Company Seals
MGP
24 hours
3 days
1 week
1 month
3 months
6 months
1 year
Custom
1m
5m
15m
30m
1h
Custom
Normalized
Temporal
Not Attached
menu


THE SWEET HEREAFTER Grade: A (Highly Recommended)
Directed by Atom Egoyan (Exotica, The Adjuster, Family Viewing) Written for the screen by Egoyan, from the novel by Russell Banks Starring: Ian Holm (Alien), Bruce Greenwood (Nowhere Man), Alberta = Watson (Spanking the Monkey), Sarah Polley (Exotica) Year of Release: 1997 Rating: R
Deserves Recognition for: Best Picture, Director, Actor (Holm), Supporting Actor (Greenwood), Supporting Actress (Polley), Screenplay, Production Design (Philip Barker), Music (Michael Danna) - geez, can you tell that I liked this one?
Capsule Review: To audiences used to movies that tell you how to feel, director Atom Egoyan's new film may seem like a cold, lifeless ordeal. The more discerning and patient viewer, however, will find this to be a mournful, absolutely shattering cinematic experience, possibly the best of the last year. Ian Holm gives a magnificent performance as an ambulance chasing attorney whose self-serving attempts to heal a small Canadian community's pain after a horrific accident only ends up ripping new wounds. Egoyan, previously best known for the dark puzzle EXOTICA, displays an astonishing mastery of the medium here, freely mixing timelines in order to view the tragedy from all sides. (He makes an especially resonant and inspired connection with the fable of The Pied Piper of Hamlin.) The result is a film that affects the watcher in a delayed, haunting fashion; you don't realize you've been hurt until you glance down and see the blood.
Copyright 1998 by The Critic formerly known as Andrew Wright For more insanely biased reviews, check out http://www.seanet.com/~louk/ e-mail<EMAIL_ADDRESS>"Saturday Night Thing. Drunken Hillbilly Bar Fight. My Soul Rejoices."
A Haiku in honor of ROADHOUSE A9Andrew L. Wright esq.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Austin Peay claims OVC crown with 35-7 win over E. Illinois
CLARKSVILLE, Tenn. (AP) - JaVaughn Craig threw three touchdowns and ran for two more and Austin Peay beat Eastern Illinois 35-7 for the Ohio Valley Conference championship on Saturday.
Austin Peay (9-3, 7-1) owns the tiebreaker over Southeast Missouri State (9-3, 7-1) by virtue of its 28-24 win over the Redhawks on Oct. 12. Its only their second conference title, the last coming in 1977. The Governors - ranked No. 19 in FCS - set a single-season record for wins.
Craig threw a 13-yard touchdown pass to Baniko Harley with 4:51 left in the first quarter for the game’s first score. Darshon McCullough’s 47-yard TD run eight seconds into the second tied it up.  Then, his 19-yard touchdown run 68 seconds before halftime made it 21-7.
McCullough ran for 110 yards on 20 carries for the Panthers’ (1-11, 1-7) lone score.
Sign up for Daily Newsletters
Copyright © 2019 The Washington Times, LLC.
Please read our comment policy before commenting.


Coffee
Welcome to our BrickHack creation!
Home
Description
About us
Submit code
Description
A description about our team!
About us
We are...!
Submit
Please submit your code!


Filter by gene symbol
try: TIAM2, BARX2, PSMG2, LIG1, NIPSNAP3B, REPS1, PBXIP1
Gene Symbol
Gene Desc
CNA gain
CNA gain deep
CNA loss
CNA loss deep
Mutations
Positive Outliers
Negative Outliers


A year ago you found a trunk off of the side of a trail, which presumably made its way there due to the misfortune of a previous owner. Inside this trunk was a sword, and around that sword a map. The sword, "Ashbringer", is seemingly well forged, and how it found it's way into the hands of someone, so destitute as to take that perilous road is a mystery that you may never be resolved.
You followed the map and it has lead you to a village neighboring a volcano, and a recently very active one at that, it seems that not a minute goes by without an eruption of lava coming from the vast top. Strangely, the people in the village don't seem to mind the proximity, instead, they go about their day-to-day as if the volcano wasn't their in the first place.
After walking down the main road into town you came across a blacksmith's shop, and while certainly not the only place of interest in the town, it might be wise to investigate.


Tazama movies is a online movie shop that provides to the user’s latest and hottest movies and series from allover the world at one place to reduce the movements of people during this time of pandemic, bearing in mind we should stay at home to prevent spread of COVID. Our prices and quite competitive together with the amaizing offers that comes when you make a purchase from us, our customer service, wow. that’s with no doubt top notch. WELCOME!


Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset of 102 flower categories, you can see a few examples below.
The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it.
# Imports here
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, models, transforms
Here you'll use torchvision
to load the data (documentation). The data should be included alongside this notebook, otherwise you can download it here. The dataset is split into three parts, training, validation, and testing. For the training, you'll want to apply transformations such as random scaling, cropping, and flipping. This will help the network generalize leading to better performance. You'll also need to make sure the input data is resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet. For this you don't want any scaling or rotation transformations, but you'll need to crop them images to the appropriate size.
For all three sets you'll need to normalize the means and standard deviations of the images to what the network expects. For the means, it's [0.485, 0.456, 0.406]
and for the standard deviations [0.229, 0.224, 0.225]
.
train_dir = 'train'
valid_dir = 'valid'
test_dir = 'test'
data_transforms = {
'train': transforms.Compose([
transforms.RandomRotation(45),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'test': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
dirs = {'train': train_dir, 'valid': valid_dir, 'test': test_dir}
image_datasets = {x: datasets.ImageFolder(dirs[x], transform=data_transforms[x])
for x in ['train', 'valid', 'test']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=32,
shuffle=True)
for x in ['train', 'valid', 'test']}
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json
. It's a JSON object which you can read in with the json
module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
import json
with open('label_map.json', 'r') as f:
label_map = json.load(f)
Now that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from torchvision.models
to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with somene, chat with your fellow students! You can also ask questions on the forums or join the instructors in office hours.
Refer to the rubric (TODO: Link to Rubric) for guidance on successfully completing this section. Things you'll need to do:
class FFClassifier(nn.Module):
def __init__(self, in_features, hidden_features, out_features, drop_prob=0.5):
super(FFClassifier, self).__init__()
self.fc1 = nn.Linear(in_features, hidden_features)
self.fc2 = nn.Linear(hidden_features, hidden_features)
self.fc3 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(p=drop_prob)
def forward(self, x):
x = self.drop(F.relu(self.fc1(x)))
x = self.drop(F.relu(self.fc2(x)))
x = self.fc3(x)
x = F.log_softmax(x, dim=1)
return x
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
arch = 'vgg16' #available choices are 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 'vgg19',
#'vgg19_bn', 'alexnet', 'resnet101', 'resnet152', 'resnet18', 'resnet34', 'resnet50'
fc_hidden = 4096
fc_out = len(label_map)
drop_prob = 0.5
learning_rate = 0.001
model = models.__dict__[arch](pretrained=True)
for param in model.parameters():
param.requires_grad = False
if arch.startswith('vgg'):
fc_in = model.classifier[0].in_features
model.classifier = FFClassifier(fc_in, fc_hidden, fc_out, drop_prob)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate)
elif arch.startswith('alexnet'):
fc_in = model.classifier[1].in_features
model.classifier = FFClassifier(fc_in, fc_hidden, fc_out, drop_prob)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate)
elif arch.startswith('res'):
model.fc = FFClassifier(model.fc.in_features, fc_hidden, fc_out, drop_prob)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.fc.parameters(), lr=learning_rate)
model
#as the same function is used for calculating the validation and test losses and accuracies, I have used an
#argumnet 'is_test' to check whether the data is validation data or test data.
def validation(model, val_data, criterion, cuda=False, is_test=False):
val_start = time.time()
running_val_loss = 0
accuracy = 0
for inputs, labels in val_data:
inputs, labels = Variable(inputs), Variable(labels)
if cuda:
inputs, labels = inputs.cuda(), labels.cuda()
outputs = model.forward(inputs)
val_loss = criterion(outputs, labels)
ps = torch.exp(outputs.data)
_, predicted = ps.max(dim=1)
equals = predicted == labels.data
#casting to float is necessary as the torch.sum(equals) and len(equals) are both integer
accuracy += float(torch.sum(equals))/len(equals)
running_val_loss += val_loss.data[0]
val_time = time.time() - val_start
if not is_test:
#instead of diving by len(dataloaders['valid'], I have divided by len(val_data) as we are reusing the
#function to calculate both validation and training loss.
print("Validion loss: {:.3f}".format(running_val_loss/len(val_data)),
"Validation Accuracy: {:.3f}".format(accuracy/len(val_data)),
"Validation time: {:.3f} s/batch".format(val_time/len(val_data)))
else:
print("Test loss: {:.3f}".format(running_val_loss/len(val_data)),
"Test Accuracy: {:.3f}".format(accuracy/len(val_data)),
"Test time: {:.3f} s/batch".format(val_time/len(val_data)))
epochs = 10
cuda = True
print_every_n = 50
if cuda:
model.cuda()
else:
model.cpu()
model.train()
#Here I have not used the new f-strings as they are only availabel in python 3.6, instead I have used format
for e in range(epochs):
print("Epoch "+str(e+1)+'/'+str(epochs))
counter = 0
running_loss = 0
for inputs, labels in dataloaders['train']:
counter += 1
# Training pass
inputs, labels = Variable(inputs), Variable(labels)
if cuda:
inputs, labels = inputs.cuda(), labels.cuda()
optimizer.zero_grad()
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.data[0]
if counter % print_every_n == 0:
print("Step: {}".format(counter))
print("Training loss {:.3f}".format(running_loss/counter))
model.eval()
validation(model, dataloaders['valid'], criterion, cuda=cuda)
model.train()
else:
# Validation pass
train_end = time.time()
model.eval()
validation(model, dataloaders['valid'], criterion, cuda=cuda)
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
model.cuda()
model.eval()
validation(model, dataloaders['test'], criterion, cuda=True, is_test=True)
Now that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of indices to classes which you get from one of the image datasets: image_datasets['train'].class_to_idx
. You can attach this to the model as an attribute which makes inference easier later on.
Remember that you'll want to completely rebuild the model later so you can use it for inference. Make sure to include any information you need in the checkpoint. If you want to load the model and keep training, you'll want to save the number of epochs as well as the optimizer state, optimizer.state_dict
.
model.class_to_idx = image_datasets['train'].class_to_idx
model.cpu()
torch.save({'arch': arch,
'hidden': fc_hidden,
'drop_prob': drop_prob,
'state_dict': model.state_dict(),
'class_to_idx': model.class_to_idx},
'clssifier.pt')
At this point it's good to write a function that can load a checkpoint and rebuild the model.
def load_model(checkpoint_path):
checkpoint = torch.load(checkpoint_path)
model = models.__dict__[checkpoint['arch']](pretrained=True)
model.class_to_idx = checkpoint['class_to_idx']
if checkpoint['arch'].startswith('vgg'):
fc_in = model.classifier[0].in_features
model.classifier = FFClassifier(fc_in, checkpoint['hidden'], len(model.class_to_idx), checkpoint['drop_prob'])
elif checkpoint['arch'].startswith('alexnet'):
fc_in = model.classifier[1].in_features
model.classifier = FFClassifier(fc_in, checkpoint['hidden'], len(model.class_to_idx), checkpoint['drop_prob'])
elif checkpoint['arch'].startswith('res'):
model.fc = FFClassifier(model.fc.in_features, checkpoint['hidden'], len(model.class_to_idx), checkpoint['drop_prob'])
model.load_state_dict(checkpoint['state_dict'])
return model
model = load_model('classifier.pt')
Now write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called predict
that takes an image and a model, then returns the top $K$ most likely classes along with the probabilities. It should look like
probs, classes = predict(image_path, model)
print(probs)
print(classes
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
First you'll need to handle processing the input image such that it can be used in your network.
You'll want to use PIL
to load the image (documentation). It's best to write a function that preprocesses the image so it can be used as input for the model. This function should process the images in the same manner used for training.
First, resize the images where the shortest side is 256 pixels, keeping the aspect ratio. This can be done with the thumbnail
or resize
methods. Then you'll need to crop out the center 224x224 portion of the image.
Color channels of images are typically encoded as integers 0-255, but the model expected floats 0-1. You'll need to conversion, it's easiest with a Numpy array, which you can get from a PIL image like so np_image = np.array(pil_image)
.
As before, the network expects the images to be normalized in a specific way. For the means, it's [0.485, 0.456, 0.406]
and for the standard deviations [0.229, 0.224, 0.225]
. You'll want to subtract the means from each color channel, then divide by the standard deviation.
And finally, PyTorch expects the color channel to be the first dimension but it's the third dimension in the PIL image and Numpy array. You can reorder dimensions using ndarray.transpose
. The color channel needs to be first and retain the order of the other two dimensions.
from PIL import Image
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model '''
# Resize and crop out the center 224x224 square
aspect = image.size[0]/image.size[1]
if aspect > 0:
image.thumbnail((10000, 256))
else:
image.thumbnail((256, 10000))
left_margin = (image.width-224)/2
top_margin = (image.height-224)/2
image = image.crop((left_margin, top_margin, left_margin+224, top_margin+224))
# Now normalize...
image = np.array(image)/255
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = (image - mean)/std
# Move color channels to first dimension as expected by PyTorch
image = image.transpose((2, 0, 1))
return image
image_path = 'test/28/image_05230.jpg'
image = Image.open(image_path)
image = process_image(image)
Once you can get images in the correct format
To get the top $K$ largest values in a tensor use x.topk(k)
. This method returns both the highest k
probabilities and the indices of those probabilities corresponding to the classes. You need to convert from these indices to the actual class labels using class_to_idx
which hopefully you added to the model or from an ImageFolder
you used to load the data.
def predict(image_path, model, topk=5):
image = Image.open(image_path)
image = process_image(image)
# Convert to PyTorch tensor and do a forward pass
# Model expects a FloatTensor, from_numpy gives a DoubleTensor
image_tensor = torch.from_numpy(image).type(torch.FloatTensor)
inputs = Variable(image_tensor, requires_grad=False)
inputs = inputs.unsqueeze(0)
ps = torch.exp(model.forward(inputs))
top_probs, top_labels = ps.topk(topk)
#if we use gpu here, we need to use .cpu() to move the tensor to host memory first.
top_probs, top_labels = top_probs.cpu().data.numpy().squeeze(), top_labels.cpu().data.numpy().squeeze()
#top_probs, top_labels = top_probs.data.numpy().squeeze(), top_labels.data.numpy().squeeze()
# Convert indices to classes
idx_to_class = {val: key for key, val in model.class_to_idx.items()}
top_classes = [idx_to_class[each] for each in top_labels]
return top_probs, top_classes
image_path = 'test/28/image_05230.jpg'
model.eval()
model.cpu()
predict(image_path, model)
Now that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check there aren't obvious bugs. Use matplotlib
to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should look like this:
You can convert from the class integer encoding to actual flower names with the label_map.json
file.
image_path = 'test/28/image_05230.jpg'
model.eval()
top_probs, top_classes = predict(image_path, model)
image = Image.open(image_path)
image = np.array(image)
fig, (img_ax, p_ax) = plt.subplots(figsize=(4,7), nrows=2)
img_ax.imshow(image)
img_ax.xaxis.set_visible(False)
img_ax.yaxis.set_visible(False)
p_ax.barh(np.arange(5, 0, -1), top_probs)
top_cat_names = [label_map[each] for each in top_classes]
p_ax.set_yticks(range(1,6))
p_ax.set_yticklabels(reversed(top_cat_names));
fig.tight_layout(pad=0.1, h_pad=0)
images, labels = next(iter(dataloaders['test']))
def imshow(image, ax=None, title=None):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
image = image.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
image = np.clip(image, 0, 1)
ax.imshow(image)
return ax
img_idx = 20
inputs = Variable(images[img_idx,:].unsqueeze(0))
model.eval()
model.cpu()
ps = torch.exp(model.forward(inputs))
top_probs, top_classes = ps.topk(5)
idx_to_class = {val: key for key, val in model.class_to_idx.items()}
top_classes = [idx_to_class[each] for each in top_classes.data.squeeze()]
fig, (img_ax, p_ax) = plt.subplots(figsize=(4,7), nrows=2)
img_ax = imshow(inputs.data.squeeze(), ax=img_ax)
img_ax.set_title(label_map[idx_to_class[labels[img_idx]]])
img_ax.xaxis.set_visible(False)
img_ax.yaxis.set_visible(False)
p_ax.barh(np.arange(5, 0, -1), top_probs.data.numpy().squeeze())
top_cat_names = [label_map[each] for each in top_classes]
p_ax.set_yticks(range(1,6))
p_ax.set_yticklabels(reversed(top_cat_names));
fig.tight_layout(pad=0.1, h_pad=0)


In this "lie detection" experiment, we simulate a situation in which someone is trying to hide his or her identity (as e.g. a spy or a terrorist), but we suspect that we know some true personal details of this person. You will play this person, and will be simulating either a "guilty" or an "innocent" case.
Please read the instructions carefully.
The following details will provide material for the eventual test, so please answer honestly.
Your country of origin:
Your birthday:
Your favorite animal (among the presented options):
Please look through the list below, and select, in each category (countries, dates, or animals), maximum two items that seem personally important or meaningful for you, or that seem in any way different from the rest of the items: for example, a country that you have often visited, or an animal that you especially admire, etc. (These items will then not be used in the test.) If there are no such items in a given category, just select "None". You can select (or deselect) by clicking on the items.
Now comes the lie detection test. Of course, we actually know your details (country of origin, etc.), since you just selected them, but, during the entire following test, for the sake of the simulation, please act as if we did not know that these details are yours, and try to pretend that you do not recognize them.
Important: it is possible that you will really not see your own details in the test. This simply means that you are in the "innocent" condition, simulating an innocent suspect.
When you are ready to start the test, call the experiment leader.


Card title
Some quick example text to build on the card title and make up the bulk of the card's content.
Go somewhere
Card title
Some quick example text to build on the card title and make up the bulk of the card's content.
Go somewhere


{% comment %} This template renders the part with the active filters in place. For each active filter, it renders a button showing the respective filter and allowing to remove it. Required attributes: - active_filters: A list of active filters. {% endcomment %} {% load i18n %}


{% extends "global/Page.html" %} {% load otree static %} {% block title %} Instructions (Part 1) {% endblock %} {% block scripts %} {% endblock %} {% block styles %} {% endblock %} {% block content %}
In part 1, you will work on a task that consists of a sequence of arithmetic questions.
You will try to answer as many arithmetic problems as possible in {{ gameDuration }}.
Each arithmetic problem requires you to add three numbers.
Example Question: Three plus four plus seven
Correct answer: 14
Even though the question expressed numbers in a written form, you must enter your answers in numeric form,
for example `14’ rather than ‘fourteen’. You will not be able to click the submit button before you answer
each question. If you want to proceed to the next question without necessarily getting the answer right,
you can type `1’ and click submit.
There is no penalty for getting answers wrong. Your goal is to answer as many questions correctly as possible.
You will be paid based on the number of questions you answer correctly in a period of {{ gameDuration }}.
You will earn 5 cents for each correct answer.
At the end of the {{ gameDuration }}, the program will display the number of questions you attempted
and the number of questions you got right.
Good luck!