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
The Problem You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0], l2 = [0] Output: [0] Example 3: Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] Constraints: - The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 - It is guaranteed that the list represents a number that does not have leading zeros. My Tests import pytest from typing import List from .util import ListNode, toListNode, toList from .Day12_AddTwoNumbers import Solution s = Solution() @pytest.mark.parametrize( "l1,l2,expected", [ ([2, 4, 3], [5, 6, 4], [7, 0, 8]), ([0], [0], [0]), ([9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9], [8, 9, 9, 9, 0, 0, 0, 1]), ], ) def test_add_two_numbers(l1, l2, expected): list_root1 = toListNode(l1) list_root2 = toListNode(l2) assert toList(s.addTwoNumbers(list_root1, list_root2)) == expected My Solution from .util import ListNode def add(carry: int, l1: ListNode, l2: ListNode): x = l1.val y = l2.val if l2 is not None else 0 ans = x + y + carry if ans >= 10: carry = 1 ans = ans - 10 else: carry = 0 l1.val = ans l2_next = l2.next if l2 is not None else None if l2_next or carry > 0: if l1.next is None: l1.next = ListNode() add(carry, l1.next, l2_next) class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: carry = 0 add(carry, l1, l2) return l1 Analysis My Commentary Just did this one the same way I'd do it in my head. Go through each number. Add them. If the sum is great than or equal to 10, carry the one. Made a small space optimisation by storing the answer in l1. This is O(n) in space and runtime, noting that n is the larger of len(l1) or len(l2) with potentially 1 more node added at the end for a carried sum. Discussion (0)
https://dev.to/ruarfff/day-12-add-two-numbers-2kcn
CC-MAIN-2022-33
refinedweb
395
73.78
import "go.chromium.org/luci/scheduler/appengine/engine/cron" Action is a particular action to perform when switching the state. Can be type cast to some concrete *Action struct. Intended to be handled by whoever hosts the cron machine. type Machine struct { // Inputs. Now time.Time // current time Schedule *schedule.Schedule // knows when to emit invocation action Nonce func() int64 // produces nonces on demand // Mutated. State State // state of the cron machine, mutated by its methods Actions []Action // all emitted actions (if any) } Machine advances the state of the cron machine. It gracefully handles various kinds of external events (like pauses and schedule changes) and emits actions that's supposed to handled by whoever hosts it. Disable stops any pending timer ticks, resets state. The cron machine will ignore any events until Enable is called to turn it on. Enable makes the cron machine start counting time. Does nothing if already enabled. OnScheduleChange happens when cron's schedule changes. In particular, it handles switches between absolute and relative schedules. OnTimerTick happens when a scheduled timer tick (added with TickLaterAction) occurs. Returns an error if the tick happened too soon. RewindIfNecessary is called to restart the cron after it has fired the invocation action. Does nothing if the cron is disabled or already ticking. type StartInvocationAction struct { Generation int64 // value of state.Generation when the action was emitted } StartInvocationAction is emitted when the scheduled moment comes. A handler is expected to call RewindIfNecessary() at some later time to restart the cron machine if it's running on a relative schedule (e.g. "with 10 sec interval"). Cron machines on relative schedules are "one shot". They need to be rewound to start counting time again. Cron machines on absolute schedules (regular crons, like "at 12 AM every day") don't need rewinding, they'll start counting time until next invocation automatically. Calling RewindIfNecessary() for them won't hurt though, it will be noop. func (a StartInvocationAction) IsAction() bool IsAction makes StartInvocationAction implement Action interface. type State struct { // Enabled is true if the cron machine is running. // // A disabled cron machine ignores all events except 'Enable'. Enabled bool // Generation is increased each time state mutates. // // Monotonic, never resets. Should not be assumed sequential: some calls // mutate the state multiple times during one transition. // // Used to deduplicate StartInvocationAction in case of retries of cron state // transitions. Generation int64 // LastRewind is a time when the cron machine was restarted last time. // // For relative schedules, it's a time RewindIfNecessary() was called. For // absolute schedules it is last time invocation happened (cron machines on // absolute schedules auto-rewind themselves). LastRewind time.Time // LastTick is last emitted tick request (or empty struct). // // It may be scheduled for "distant future" for paused cron machines. LastTick TickLaterAction } State stores serializable state of the cron machine. Whoever hosts the cron machine is supposed to store this state in some persistent store between events. It's mutated by Machine. So the usage pattern is: * Deserialize State, construct Machine instance with it. * Invoke some Machine method (e.g Enable()) to advance the state. * Acknowledge all actions emitted by the machine (see Machine.Actions). * Serialize the mutated state (available in Machine.State). If appropriate, all of the above should be done in a transaction. Machine assumes that whoever hosts it handles TickLaterAction with following semantics: * A scheduled tick can't be "unscheduled". * A scheduled tick may come more than one time. So the machine just ignores ticks it doesn't expect. It supports "absolute" and "relative" schedules, see 'schedule' package for definitions. Equal reports whether two structs are equal. IsSuspended returns true if the cron machine is not waiting for a tick. This happens for paused cron machines (they technically are scheduled for a tick in a distant future) and for cron machines on relative schedule that wait for 'RewindIfNecessary' to be called to start ticking again. A disabled cron machine is also considered suspended. TickLaterAction schedules an OnTimerTick call at given moment in time. TickNonce is used by cron machine to skip canceled or repeated ticks. func (a *TickLaterAction) Equal(o *TickLaterAction) bool Equal reports whether two structs are equal. func (a TickLaterAction) IsAction() bool IsAction makes TickLaterAction implement Action interface. Package cron imports 3 packages (graph) and is imported by 2 packages. Updated 2019-10-14. Refresh now. Tools for package owners.
https://godoc.org/go.chromium.org/luci/scheduler/appengine/engine/cron
CC-MAIN-2019-43
refinedweb
721
60.01
Originally published at rossta.net Webpack isn't just for JavaScript. You can bundle images with it too. Webpacker makes it relatively easy to work with images, but it is admittedly confusing at first: Images in JavaScript? In this post, we'll demonstrate how to reference Webpacker images from your JavaScript, CSS, and Rails views. The following examples were created using Rails 6 and Webpacker 4, but may work with other versions as well. Pre-requisites for working with Webpacker in a Rails project also include yarn. Folder structure First, where should you put your images? It doesn't matter. The easiest place to start is under your app/javascript folder, the default source path for Webpacker, such as app/javascript/images. For the rest of this guide, we'll assume the following directory structure and files: app/javascript ├── components │ └── Taco.js ├── css │ ├── main.css ├── images │ ├── burritos.jpg │ ├── guacamole.jpg │ └── tacos.jpg └── packs └── application.js Isn't weird to put images and css in a folder called "javascript"? Depends. If you consider, from Webpack's perspective, everything is a JavaScript module, it may not be so strange. Otherwise, it's possible to rename app/javascriptor place your images elsewhere. More on that below. Images in JS To reference an image from JavaScript in your Webpacker build, simply import it like any other module. React is not required for this to work ;) // app/javascripts/components/Taco.js import TacoImage from '../images/tacos.jpg' export default function({ title }) { return ` <div> <h1>${title}</h1> <p><img src=${TacoImage}</p> </div> ` } In the example above, Webpack will import TacoImage as a url to the file. In other words, an "image module" in Webpack exports a single default value, a string, representing the location of the file. Based on the default Webpacker configuration, the filename will look something like /packs/media/images/tacos-abcd1234.jpg. Importing a image also works if you're using "CSS in JS" to style a React component. import React from 'react' import TacoImage from '../images/tacos.jpg' const styles = { backgroundImage: `url(${TacoImage})`, } export default function ({ title }) { return ( <div style={styles}> {title}! </div> ) } Interested to learn more about Webpack on Rails? I'm creating a course. Images in CSS In Sprockets, when referencing images in CSS, you would use a special image-url() helper. In Webpack, simply use the standard url() expression in CSS with a relative path. /* app/javascript/css/main.css */ .burritos { background-image: url("../images/burritos.jpg"); } The output for the style rule will, again, look something like background-image: url(/packs/media/images/burritos-efgh5678.jpg);. This technique will also work for image paths in CSS Modules. Images in CSS within NPM modules One tricky bit worth mentioning is bundling images referenced in SCSS within an imported NPM module. For example, many jQuery plugins bundle their own SCSS and image assets. When Webpack processes this vendored CSS, you may see an error like the following, like in this question on StackOverflow: Module not found: Error: Can't resolve '../img/controls.png' The problem is the path does not resolve properly relative to the output for this vendored SCSS. From the Webpacker docs: Since Sass/libsass does not provide url rewriting, all linked assets must be relative to the output. Add the missing url rewriting using the resolve-url-loader. Place it directly after the sass-loader in the loader chain. To fix this, you may need to get your hands dirty with some Webpacker configuration. Add the resolve-url-loader and configure in config/webpack/environment.js: yarn add resolve-url-loader // config/webpack/environment.js const { environment } = require('@rails/webpacker') // resolve-url-loader must be used before sass-loader environment.loaders.get('sass').use.splice(-1, 0, { loader: 'resolve-url-loader' }) This loader rule, inserted in the loader pipeline for SASS/SCSS files, will ensure the proper url is written to the CSS output by Webpack. Images in Rails views You may be accustomed to <%= image_tag 'tacos.jpg' %> to reference a image bundled in the Rails asset pipeline. Webpack has a similar tag: <!-- app/views/lunches/index.html.erb --> <%= image_pack_tag 'media/images/guacamole.jpg' %> Note, since Webpacker 4, the prefix media/ is necessary and the remaining path represents the location from your Webpack source path. There's a catch. This change may result in the following error: Webpacker::Manifest::MissingEntryError in Lunches#index Showing /path/to/project/app/views/lunches/index.html.erb where line #4 raised: Webpacker can't find media/images/guacamole.jpg in /path/to/project/public/packs/manifest.json. The guacamole.jpg image was not found by Rails, but, if we were to try rendering the tacos.jpg image in our template, i.e, <%= image_pack_tag 'media/images/tacos.jpg %>, the taco image would happily render. What gives? Your Rails app is not being selective about cuisine. The difference is, we earlier imported the tacos.jpg image in Webpack, but not guacamole.jpg. One way to fix this issue is to import the guacamole.jpg image somewhere in your Webpack dependency graph. It's not necessary to grab a reference to the imported variable because we only care about the side effect of emitting the file for Rails to reference in the view. import '../images/guacamole.jpg' Another way to fix this issue is to import all images in the app/javascript/images directory. Webpack provides a special function to import many files in a directory in one expression: require.context. You might add this to your application.js pack: // app/javascript/packs/application.js require.context('../images', true) This expression will recursively require all the files in the images directory. As a result, we can now render guacamole.jpg in a Rails view. Note: I only recommend using require.contextfor your images if you need to render them in your Rails views; require.contextis NOT necessary to import images into JS files like your React components, as illustrated earlier. Reconfiguring If you don't feel comfortable with app/javascript as the source directory for images, you can either rename the source path or add to the set of resolved paths. To rename app/javascript, rename the directory and tell Rails about it in config/webpacker.yml default: &default source_path: app/frontend To add to the set of resolved paths where Webpack should look for assets besides in app/javascript: default: &default resolved_paths: - app/assets Diving Deeper I have to admit, a few years ago, when I first heard about Webpack, I was super-confused. I understood it to be a JavaScript module bundler. How on Earth does it handles images? The short answer, of course, is it depends. Generally, Webpack will treat everything it can understand as a JavaScript module. To help Webpack understand images, projects would add a "loader" (or loaders) to the Webpack configuration. A suitable loader would know how to handle an image file and output a representation of something, like an inlined base64 string, that can be manipulated in JavaScript. To help Webpack understand images, svg files, and fonts in your Rails project, Webpacker adds the file-loader package. This package will emit the imported file as a side effect of the build and return a path to the file as the module contents. For more on how Webpack works with images, check out the asset management docs. I also put together a sample Rails 6 Webpacker demo project on GitHub for more context: Posted on by: Ross Kaffenberger I build web apps, most in Ruby and/or JavaScript. I'm lucky to work remotely. I also do triathlon and Dad jokes. Discussion We don't do this properly in the DEV codebase. Bookmarked for reference in fixing this. 😄 Great article, it was very useful!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/rossta/importing-images-with-webpacker-2302
CC-MAIN-2020-40
refinedweb
1,287
50.73
using Github and the compile result of their project does lay down a DLL library for you to reuse. So the steps can be quite simple. The developers of SumatraPDF are very diligent programmers. They keep quit a closed track with the latest development of Mupdf and update their code frequently. Therefore, you can quite well trust them and use their library instead of trying to compile your own Mupdf DLL out of the official code. Once you have the libmupdf.dll in your hands. You can begin to study the functions provided by the Mupdf library. The library is written in C. In the C programming world, the function definitions are placed in header files, which have the file extension ".h". In the SumatraPDF project, the header files of the MuPDF library are placed in the mupdf\include\mupdf folder. From the documentation section of the MuPDF official website, five header files are listed--"fitz.h", "pdf.h", "html.h", "svg.h" and "xps.h". We only need to get started with the first two of them. Then we will follow them and find out the needed functions and structures. The following lines are part of the "fitz.h" file. When we are exploring the functionalities of the MuPDF library, we will follow the #include instruction, which indicates that those referred header files are used in the library as well, and we will examine them one by one. #include #ifndef MUDPF_FITZ_H #define MUDPF_FITZ_H #include "mupdf/fitz/version.h" #include "mupdf/fitz/system.h" #include "mupdf/fitz/context.h" // the rest of the file is omitted here As we open the files listed in the fitz.h file or pdf.h file, for instance, context.h, we will see some definitions for functions and structures. The definitions of functions and structures will be essential for writing P/Invoke funtions later. To learn about the working mechanism of MuPDF, we can start with the example file "source/tools/mudraw.c" listed in the MuPDF documentation web site. By studying the code, we can learn how MuPDF works. Five key structures in fitz.h are used in the code, listed below. fz_context fz_context_s fz_document fz_document_s fz_page fz_page_s fz_pixmap fz_pixmap_s fz_device fz_device_s You don't have to care about the internal layout, we find out the following useful functions in the example file. fz_new_context_imp. Note: The chapter will show you how the P/Invoke functions are composed. If you don't care about how they came from, just skip this chapter. Once we know about what functions we are going to use, we can start writing P/Invoke functions in C#. Firstly we begin with the following code in fitz\context.h for the fz_new_context_imp function, since it creates the fz_context instance and the following of the code will rely on that object. fz_context *fz_new_context_imp(fz_alloc_context *alloc, fz_locks_context *locks, unsigned int max_store, const char *version); fz_context * fz_alloc_context * fz_locks_context * fz_new_context IntPtr.Zero max_store version Here is the P/Invoke function code for the fz_new_context_imp function. [DllImport (DLL, EntryPoint="fz_new_context_imp")] static extern IntPtr NewContext (IntPtr alloc, IntPtr locks, uint max_store, string version); Since the caller actually doesn't have to know about alloc, locks and max_store, we can add an overload function to make the method look neat. alloc locks const uint FZ_STORE_DEFAULT = 256 << 20; const string MuPDFVersion = "1.6"; public static IntPtr NewContext () { return NewContext (IntPtr.Zero, IntPtr.Zero, FZ_STORE_DEFAULT, MuPDFVersion); } But... you may ask, "Wait a minute. How do you know that we can pass two IntPtr.Zeros and a FZ_STORE_DEFAULT to the NewContext function? And what the heck is the magic string '1.6'?" Good questions. The answer for the first question is written in fitz\context.h--"when you don't need to preallocate some memory nor set locks, you can simply use NULL". In the world of P/Invoke, NULL means IntPtr.Zero, for the first two parameters. The value of FZ_STORE_DEFAULT was also mentioned there. FZ_STORE_DEFAULT NewContext '1.6' The answer to the second question can be found in fitz\context.h and fitz\version.h. At first, we see the following line in context.h: context.h #define fz_new_context(alloc, locks, max_store) fz_new_context_imp(alloc, locks, max_store, FZ_VERSION) If you study the example code provided by MuPDF or SumatraPDF, you can see that they used fz_new_context instead of fz_new_context_imp. However, as the above line of code shows, the fz_new_context is just a defined macro in C, which was not exposed to the C# world out of the DLL. We have to call fz_new_context_imp instead when we P/Invoke the library. And next, we can find out the definition to FZ_VERSION in version.h. Warning: If you pass a version number which mismatches the version of the engine, the above function will return IntPtr.Zero instead of a fz_context instance. When you are compiling your own libmupdf.dll library, you shall at least take a look at the fitz\version.h file and check whether the FZ_VERSION definition matches the version parameter we pass into the function here. FZ_VERSION Please refer to those *.h files in the fitz folder and the pdf folder when you have further questions."; const string MuPDFVersion = "1.6"; [DllImport (DLL, EntryPoint="fz_new_context")] static extern IntPtr NewContext (IntPtr alloc, IntPtr locks, uint max_store, string version); public static IntPtr NewContext () { return NewContext (IntPtr.Zero, IntPtr.Zero, FZ_STORE_DEFAULT, MuPDFVersion); } void_lookup_device_colorspace")] public static extern IntPtr Lookup straightforward.; } } // free bitmap in memory bmp.UnlockBits (imageData); NativeMethods.DropPixmap (context, pix); return bmp; } OK, everything is ALMOST done. Just run the program and see each PDF pages in test.pdf converted into PNG files. *.h files. The fourth thing to consider is running on 64-bit machines. This is one of the most common issues when using P/Invoke. The DLL provided in the download of this article, compiled from the source code of SumatraPDF is 32-bit. It must be called from the 32-bit .NET Framework. On the 64-bit machines, the default .NET Framework will be the 64-bit one, which will fail when P/Invoking the 32-bit Mupdf DLL. Rather than recompiling the Mupdf DLL as a 64-bit DLL, you can instead change the CPU platform of the C# project from Any CPU to x86. Therefore, the compiled .NET program will be forced to run on the 32-bit .NET Framework and work well with the 32-bit Mupdf DLL.).
https://www.codeproject.com/articles/498317/rendering-pdf-documents-with-mupdf-and-p-invoke-in?fid=1821195&df=90&mpp=10&sort=position&spc=none&select=4436337&tid=4449192
CC-MAIN-2017-09
refinedweb
1,064
68.06
I. I was about to suffer through the lack of objects when I happened to see an article by Steve Hanov in the C/C++ Users Journal that explained wrapping Windows with a class. So I set out to make 2 starter projects. The first a Win 32 "Hello World" app wrapped in an object and a Win 32 Dialog app wrapped in an object. In this article I take the standard Windows CE "Hello World" Win 32 application and wrap it with a class that can be inherited from. The root problem in creating a wrapper is the Windows Callback function. This function must be a static procedure so the address can be supplied to the RegisterClassEx function. To solve this the function must be a callback procedure. LRESULT CALLBACK CBaseWindow::BaseWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) Now that the Windows Procedure is part of a class, the problem is getting to the other members the class. Static member functions can't access non-static member functions without a this pointer. To supply the needed pointer to the window it can be included in the CREATESTRUCT. The structure is automatically filled in when you make the CreateWindow call (note the this pointer in the final argument). hWnd = CreateWindow( szWindowClass, szTitle, WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, (void *)this ); This CREATESTRUCT is availible in the callback procedure during the WM_CREATE message as the lParam. The pointer is retrieved from the structure and stored as user data using the Windows function SetWindowLong. LRESULT CALLBACK CBaseWindow::BaseWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { ); . . . On all subsequent messages from this window, a call to GetWindowLong will retrieve the this pointer. Now you are free to access your entire class. This method can be used when creating Dialog boxes also. In the case of a modal dialog box, the windows callback procedure is specified in the DialogBox call. To get the object pointer to the callback procedure use DialogBoxParam. The object pointer will be the final parameter. DialogBoxParam( GetInstance(), (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)pAboutWindow->BaseWndProc, (long)pAboutWindow ); To retrieve the pointer, simply grab the lParam of the call to the base window procedure during the WM_INITDIALOG message. Now save the pointer as you did before. . . . if ( msg == WM_INITDIALOG ) { CBaseWindow *pObj = reinterpret_cast<CBaseWindow *>(lParam); ::SetWindowLong( hwnd, GWL_USERDATA, lParam ); . . . A difference between a desktop version of Windows and the CE version is in the window creation process. On the desktop WM_NCCREATE is the first message so the this pointer should be captured during the its processing. In Windows CE this message doesn't exist. The first message is WM_CREATE so it must be used. Although this method is a little complex, it saves declaring static data structures that map window handles to pointers that point to the correct objects. As each window is created, it stores its own pointer to the object that owns it. Most windows are created as more specialized cases of existing windows. Using C++, objects can utilize this relationship. The base window class provides a static function that calls a virtual function. Here is a look at the base window class declaration: class CBaseWindow { public: CBaseWindow(){hInst=0;} ~CBaseWindow(){} HWND hWnd; // The main window handle BOOL DlgFlag; // True if object is a dialog window static LRESULT CALLBACK BaseWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ); protected: HINSTANCE hInst; // The current instance HWND hwndCB; // The command bar handle HINSTANCE GetInstance () const { return hInst; } virtual LRESULT WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, PBOOL pbProcessed ) { *pbProcessed = FALSE; return NULL; } }; Here you see the static function BaseWndProc that windows will use as a callback and the virtual function WndProc that will get called as the message processor for the window. In the case of the function for the base window, WndProc indicates that no messages are are processed and returns. Here is where the fun begins. The Base Class can't be used for a window by itself, but each window in the program can now inherit the Base Class in the declaration of its own class. From here on out, all of the details of managing this pointers to associate a code object to a window are hidden. Here the main window class inherits from the base class. class CMainWindow : public CBaseWindow { public: CMainWindow(){} ~CMainWindow(){} BOOL InitInstance( HINSTANCE hInstance, int nCmdShow ); protected: HWND CreateRpCommandBar( HWND ); ATOM MyRegisterClass( HINSTANCE, LPTSTR ); virtual LRESULT WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, PBOOL pbProcessed ); }; As the window needs become more specialized, you create a new class based on an old class and change the behaviors to suit the new requirements. For example, the WndProc of the CMainWindow class replaces the function by the same name in the CBaseWindow class. When you override the old function with a new virtual function you should call the inherited class first to get the inherited traits then change the processing in the way you need. Here the WndProc of the main window calls the WndProc of the CBaseWindow class before doing its message processing. LRESULT CMainWindow::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, PBOOL pbProcessed ) { int wmId, wmEvent; // call the base class first LRESULT lResult = CBaseWindow::WndProc( hWnd, message, wParam, lParam, pbProcessed ); switch ( message ) { . . . Anyone who has looked at a standard Win32 program and has seen an ordinary Windows callback procedure knows to expect this line at the end of the case table. lResult = DefWindowProc( hwnd, msg, wParam, lParam ); If the message is processed by one of the virtual functions in the chain then the function will return FALSE and the DefWindowProc will not be called. Rules are a little different if dealing with a dialog box. The DefWindowProc, if needed, is called automatically for a dialog. If the message is processed by one of the functions in the chain then TRUE is returned. This is an annoyance and a source of errors (IMHO). So I have attempted to level the window and dialog box playing field a little by compensating in my base class. To do this I set a flag to remind myself if this is for a dialog or not. This way all of the window callbacks can be coded the same. Here is the static base window callback function. LRESULT CALLBACK CBaseWindow::BaseWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { // check to see if a copy of the 'this' pointer needs to be saved ); pObj->hWnd = hwnd; pObj->DlgFlag = FALSE; if ( pObj->hInst == 0 ) pObj->hInst = MainWindow.hInst; } if ( msg == WM_INITDIALOG ) { CBaseWindow *pObj = reinterpret_cast<CBaseWindow *>(lParam); ::SetWindowLong( hwnd, GWL_USERDATA, lParam ); pObj->hWnd = hwnd; pObj->DlgFlag = TRUE; pObj->hInst = MainWindow.hInst; } BOOL bProcessed = FALSE; LRESULT lResult; // Retrieve the pointer CBaseWindow *pObj = WinGetLong<CBaseWindow *>( hwnd, GWL_USERDATA ); // call the virtual window procedure for the object stored in the // windows user data if ( pObj ) lResult = pObj->WndProc( hwnd, msg, wParam, lParam, &bProcessed ); else return ( pObj->DlgFlag ? FALSE : TRUE ); // message not processed if ( pObj->DlgFlag ) return bProcessed; // processing a dialog message return TRUE // if processed else if ( !bProcessed ) // If message was unprocessed and not a dialog, send it back to Windows. lResult = DefWindowProc( hwnd, msg, wParam, lParam ); return lResult; // processing a window message return FALSE // if processed } /* BaseWndProc */ To get the object registered as the callback function for a window, the BaseWndProc is set as the Windows callback function pointer when the class is registered. ATOM CMainWindow::MyRegisterClass( HINSTANCE hInstance, LPTSTR szWindowClass ) { WNDCLASS wc; wc.lpfnWndProc = (WNDPROC)BaseWndProc; . . . To wrap a Dialog Box with an object, the BaseWndProc is sent as the Windows callback function pointer in the call to DialogBoxParam. CAboutWindow *pAboutWindow = new( CAboutWindow ); DialogBoxParam( GetInstance(), (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)pAboutWindow->BaseWndProc, (long)pAboutWindow ); delete pAboutWindow; I've covered how to get the code for encapsulating Windows messages into objects at a basic level on a Windows CE device. Most of this should apply to the desktop versions of Windows also. This doesn't wrap everything into an object, but associating a window with an object is one of the harder and most common problems. As a result, I have the first starter application I wanted. A standard Windows CE "Hello World" Win 32 application wrapped in a class. I plan to continue by telling how I used this project as the starting point to get a dialog based application. One handy tip: Look for the Visual Studio Project Renamer by Niek Albers here on CodeProject. It works well on Embedded Visual C++ 3.0 projects also. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/mobile/ltweight.aspx
crawl-002
refinedweb
1,417
60.24
I had a junit test asserting two Double objects with the following: Assert.assertEquals(Double expected, Double result); This was was fine then I decided to change it to use the primitive double instead which turned out to be deprecated unless you also provide a delta. so what I am wondering is what is the difference between using the Double objec I'm maintaining a high performance class that can be operated on by multiple threads. Many of the fields are volatile ints, and as it turns out I need to upgrade one of those to a double. I'm curious if there is a lock free way to do this, and was wondering if the Interlocked.CompareExchange(double, double, double) works as advertised on a 32-bit OS, or are torn reads a problem. Interlocked.CompareExchange(double, double, double) Is there a way to cast an Object[] array into double[] array without using any loops. And cast Double[] array to double[] array Object[] double[] Double[] I'm porting code that uses a very large array of floats, which may trigger malloc failures from c to c++. I asked a question about whether I should use vectors or deques and Niki Yoshiuchi generously offered me this example of a safely wrapped type: template<typename T>class VectorDeque{private: enum TYPE { NONE, DEQUE, VECTOR }; std::deque& I am reading a following CSV file in java and 1191196800.681 - !AIVDM,1,1,,,13aG?N0rh20E6sjN1J=9d4<00000,0*1D Here is my code to read this CSV file and convert the 1st column of the CSV file (which is a String) to a double public class ReadCSV {public static void main(String[] args) { try { BufferedReader CSVFile std::string str = "12345679012.124678";double back = boost::lexical_cast<double>( str );std::string str2 =boost::lexical_cast<std::string>( back );//here str2 is equal to str Is it normal that there is no loss here (i.e final string = orignal string) even if number's significand digits is greater than std::numeric_limit<double>:: std::numeric_limit<double>:: I am reading a CSV file and have some values like field 1 field 2 field 31 test case1 expecting one, and "two", and three after reading file into a StringBuilder and converting toString() I split the file content by: string.split(",(?=([^"]*"[^"]*")*[^"]*$)");. StringBuilder toString() string.split(",(?=([^"]*"[^"]*")*[^"]*$)"); On iterating t I have a csv file named data_export_20130206-F.csv. It contains data that contains double quotes (") which is making it very messy to parse. File looks kind of like this (but with more fields) "stuff","zipcode""<?xml version="1.0" encoding="utf-8" ?>","90210" I want to "escape" the quotes that are within the fields so it will look lik I have question: what is the difference between these two declarations? public static void printMax(double... numbers) { ... } public static void printmax(double numbers[]) { ... } Is double... numbers the same as double numbers[]? double... numbers double numbers[]
http://bighow.org/tags/double/1
CC-MAIN-2017-39
refinedweb
482
59.13
<< FirnaelMembers Content count16 Joined Last visited Community Reputation182 Neutral About Firnael - RankMember Firnael replied to Firnael's topic in Networking and MultiplayerYes it may work for melee attacks, even with projectiles like spells or arrows if you don't wont precise collisions, but you may need them for terrain collisions. Firnael replied to Firnael's topic in Networking and MultiplayerWell I'm pretty sure I need hitboxes, without them I won't be able to detect collisions Oo I'll go simple, at least at start and do what you say, do some client-side prediction to give a smooth feeling for local player, with server-reconciliation so I don't get useless rollbacks, and see if it's satisfying enough. What I was affraid of is the time needed by the server to broadcast the new game state to other players, but let's admit it, if you got 200ms latence, any action-based game feels unplayable. I need to start testing stuff. Thanks a lot P.S. : I almost forgot, server timestep seems to be the best solution to avoid strange situation when for example you kill a unit, client-prediction shows you its dying animation, but at the time you did this prediction, the unit used a potion and healed. When the server corrects you, you'll see the unit revive and act like "I aint even mad". I think I should definetely dig on that direction. Firnael replied to Firnael's topic in Networking and MultiplayerThanks for the advices. I can easy imagine how to hide possible lag client-side with client-side prediction (at least with graphical and audio feedback of player actions). Now, I was wondering what could be best for let's say a Zelda-like but with coop (not only LAN, so you need to think about sync through the internet). This is definetely not a really fast-paced shooter which would require the best precision for ex. headshots on running ennemies, while 360 unscope, but it's not a pure RTS/Target-based mmo (AKA click on target => click on spell => spell affect target) either. I want it to be based on action and therefor need a minimum of precision (WTF BROKEN HITBOX I HIT YOU I SWEAR GOD F*CK THIS LAG). The way it's explained on the Gamasutra article you linked before seems good for a pure RTS, but is it the case for a more action-oriented gameplay ? If I understood well, all client got the exact same simulation in the same time, but they all live at least 100ms in the past. I'll read it again (english not my native language, I didn't get all ). Firnael replied to Firnael's topic in Networking and MultiplayerI have to admit, the question was more about "Do I have to implement client prediction on every network game ?". I'll check thoses RTS networking models and get back asap ^^ The goal here is to find out if lag compensation is relevent in a coop A-RPG for exemple. Firnael posted a topic in Networking and Multiplayer Firnael posted a topic in General and Gameplay Programming ! Firnael replied to Firnael's topic in General and Gameplay ProgrammingAlright, that sounds like a good idea. Now how do you update your logic with your inputs ? Does your input manager (let's say you have one for each state) needs to know your logic (so you have to pass it references of your logic objects so he can manipulate them) or does it simply return some infos on what input have been triggered, infos that the logic is able to decode and modify itself ? I would say the second one, since your input manager shouldn't be doing something else than managing inputs. Firnael posted a topic in General and Gameplay ProgrammingHi, I): [code] (method called every tick; } } [/code] [img][/img] Thanks ! - Yeah, the thing is, I use Java... - Ok so if I got this right, you must have something like a huge switch are something similar which contains your logic for your item class ?. - Thanks guys, you're like a fountain of knowledge or whatever whould say someone how knows english better than me Firnael posted a topic in General and Gameplay ProgrammingHi, - Why not, but after this, the fairy needs to go away from the player again, and the idea of a force pushing it seems great, but I don't really know how to do it. Another idea is to use the Curve class in Slick. It takes 3 parameters : start point, control point (there is 2 of them but I can just put the same value on each) and end point. The process is : you create a curve with pseudo-random values, you gather the positions of the points, each turn you move the fairy to the next point, and when you reach the last point, you take it as the new starting point for a new random curve, and you repeat the process. Have to try it, but I lose the acceleration and the velocity. - Could be a solution, but wouldn't be the movement to robotic-like ? The "chill-around" move should me smooth. I'll try and tell you if I'm happy with that, thanks. - Thanks for you reply, I'm coding with Java using the lib Slick2D. Here is my code implementing some pseudo-brownian algorithm : [CODE] public class Fairy { private Image image; private Vector2f pos; // Velocity private Vector2f v; // Acceleration private Vector2f a; public Fairy(Vector2f sc) throws SlickException { this.image = new Image("data/particle.png"); this.pos = new Vector2f(sc.x - image.getWidth()/2, sc.y - image.getHeight()/2); this.v = new Vector2f(0, 0); this.a = new Vector2f(0, 0); } public void update(Vector2f sc) { Vector2f oldPos = new Vector2f(pos); this.v.x += this.a.x; this.v.y += this.a.y; this.a.x += getAccelerationRand(); this.a.y += getAccelerationRand(); this.v.x *= 0.9f; this.v.y *= 0.9f; this.pos.x = oldPos.x + this.v.x; this.pos.y = oldPos.y + this.v.y; } public void draw() { this.image.draw(this.pos.x, this.pos.y); } private float getAccelerationRand() { float rand = (float)Math.random(); if(Math.random() < 0.5f) rand *= -1; return rand * 0.01f; } } [/CODE] It's a 2D game, and I don't really need to use Z-axis. Currently there is no bounds, the fairy goes where it want (like a particle in a fluid, colliding with smaller particles). I could indeed make the fairy stop and go back to the player location if it's gone too far, but maybe it wont be realistic and random enough, I have to test it ^^
https://www.gamedev.net/profile/200272-firnael/?tab=classifieds
CC-MAIN-2017-30
refinedweb
1,118
67.49
Steganography made simple. Lemon juice on paper never worked for me, and (as I discovered when I tried to devise a title for an earlier post). '''Digital image steganography based on the Python Imaging Library (PIL) Any message can be hidden, provided the image is large enough. The message is packed into the least significant bits of the pixel colour bands. A 4 byte header (packed in the same way) carries the message payload length. ''' import Image import itertools as its def n_at_a_time(items, n, fillvalue): '''Returns an iterator which groups n items at a time. Any final partial tuple will be padded with the fillvalue >>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X')) [(1, 2), (3, 4), (5, 'X')] ''' it = iter(items) return its.izip_longest(*[it] * n, fillvalue=fillvalue) def biterator(data): '''Returns a biterator over the input data. >>> list(biterator(chr(0b10110101))) [1, 0, 1, 1, 0, 1, 0, 1] ''' return ((ord(ch) >> shift) & 1 for ch, shift in its.product(data, range(7, -1, -1))) def header(n): '''Return n packed in a 4 byte string.''' bytes = (chr(n >> s & 0xff) for s in range(24, -8, -8)) return ('%s' * 4) % tuple(bytes) def setlsb(cpt, bit): '''Set least significant bit of a colour component.''' return cpt & ~1 | bit def hide_bits(pixel, bits): '''Hide a bit in each pixel component, returning the resulting pixel.''' return tuple(its.starmap(setlsb, zip(pixel, bits))) def hide_bit(pixel, bit): '''Similar to the above, but for single band images.''' return setlsb(pixel, bit[0]) def unpack_lsbits_from_image(image): '''Unpack least significant bits from image pixels.''' # Return depends on number of colour bands. See also hide_bit(s) if len(image.getbands()) == 1: return (px & 1 for px in image.getdata()) else: return (cc & 1 for px in image.getdata() for cc in px) def call(f): # (Used to defer evaluation of f) return f() def disguise(image, data): '''Disguise data by packing it into an image. On success, the image is modified and returned to the caller. On failure, None is returned and the image is unchanged. ''' payload = '%s%s' % (header(len(data)), data) npixels = image.size[0] * image.size[1] nbands = len(image.getbands()) if len(payload) * 8 <= npixels * nbands: new_pixel = hide_bit if nbands == 1 else hide_bits pixels = image.getdata() bits = n_at_a_time(biterator(payload), nbands, 0) new_pixels = its.starmap(new_pixel, its.izip(pixels, bits)) image.putdata(list(new_pixels)) return image def reveal(image): '''Returns any message disguised in the supplied image file, or None.''' bits = unpack_lsbits_from_image(image) def accum_bits(n): return reduce(lambda a, b: a << 1 | b, its.islice(bits, n), 0) def next_ch(): return chr(accum_bits(8)) npixels = image.size[0] * image.size[1] nbands = len(image.getbands()) data_length = accum_bits(32) if npixels * nbands > 32 + data_length * 8: return ''.join(its.imap(call, its.repeat(next_ch, data_length))) if __name__ == "__main__": import urllib droste = urllib.urlopen("").read() open("droste.png", "wb").write(droste) droste = Image.open("droste.png") while droste: droste.show() droste = reveal(droste) if droste: open("droste.png", "wb").write(droste) droste = Image.open("droste.png") The code is available via anonymous SVN access at. ☡. Keen on quines and cocoa?
http://wordaligned.org/articles/steganography
CC-MAIN-2014-10
refinedweb
521
51.65
Developers & Practitioners Intro to Kf: Cloud Foundry apps on Kubernetes While many companies are writing brand-new Kubernetes-based applications, it’s still quite common to find companies who want to migrate existing workloads. A common source platform for these applications is Cloud Foundry. However, getting an existing Cloud Foundry application running on Kubernetes can be non-trivial, especially if you want to avoid making code changes in your applications, or taking on big process changes across teams. That is, if you’re not using Kf to do a lot of that heavy lifting for you. Kf is a Google Cloud service that allows you to easily move existing Cloud Foundry workloads to Kubernetes with minimal disruption to your existing processes. Kf features a command line interface (CLI) also named kf, that replaces the existing Cloud Foundry cf command line utility. The kf CLI implements the most commonly used cf functionality, including the ability to manage bindings, services, apps, routes and more. For example, to deploy an existing application you would simply issue the kf push command. On the server side Kf is built on several open source technologies. In some cases these technologies are also the Google Cloud implementation. For instance GKE is our managed Kubernetes offering, and provides the platform for managing and running the applications. Routing and ingress is handled by Anthos Service Mesh, Google Cloud’s managed Istio-based service mesh. Finally, Tekton provides on-cluster build functionality for Kf. Developers don't have to worry about any of those technologies, as Kf abstracts them away. Kf primitives such as spaces, bindings and services are implemented as custom Kubernetes resources and controllers. The custom resources effectively serve as the Kf API and are used by the kf CLI to interact with the system. The controllers use Kf's CRDs to orchestrate the other components in the system. The beauty of this approach is that developers who are familiar with existing workflows can largely replicate those workflows with the kf CLI. On the other hand, platform operators who are more familiar with Kubernetes can use kubectl to interact with the CRDs and controllers. For instance if you wanted to list the apps running on your Kf cluster you could issue either of the following commands: kf apps kubectl get apps -n space-name Notice that CF / Kf spaces get mapped one to one to Kubernetes namespaces. To get a list of all the custom resources you can examine the api-resources in the kf.dev API group. kubectl api-resources --api-group=kf.dev With Kf developers can continue to work with a familiar interface and platform operators can use declarative Kubernetes practices and tooling such as Anthos Config Management to manage the cluster. It’s really the best of both worlds if you’re looking to manage your existing Cloud Foundry applications on Kubernetes. If you’d like to learn more about Kf check out the video I just released on YouTube. It reviews some of the concepts discussed here, and includes a short demo. If you’d like to get hands on, try the quick start. And, of course, you can always read the documentation.
https://cloud.google.com/blog/topics/developers-practitioners/intro-kf-cloud-foundry-apps-kubernetes
CC-MAIN-2022-21
refinedweb
530
53.61
Contributed By Jair Rillo Junior Netbeans 6.x brought nice features and let the web development much easier. You can create many things in a ".VS-style", in other words, drag-and-drop components on the User Interface. A good example of this it is the Visual Java Server Faces features from NetBeans 6 and the Web Service module. Netbeans also brought Glassfish Application Server as its official server. Glassfish is the the RI (Reference Implementation) from JEE 5, therefore it is the better choice when you want to work with EJB 3. [[{TableOfContentsTitle=TableOfContents} | {TableOfContents title='Table of Contents'}]] When you are installing Netbeans, you will be asked about extra-programs. One of them is the Glassfish. If you choose the Glassfish in the installation process, it will be installed/configured automatically within NetBean 6.1 To check out if Glassfish was installed successfully, open the Netbeans and go to the tab Services (left window). Expand Servers option and you should see the Glassfish there. If you want, you can start the server in this way: right mouse click on Glassfish -> Start. Let's get started the code itself. The first thing to do is to create the Enterprise Application Project, or simply, EAR. To do that, back to the tab Projects and right mouse click and select option New Project. On the new screen, select the Category Enterprise and then the project Enterprise Application, click next to go to the next screen. On the next screen select the Project name and the Project Location. (In my example, I am going to use the name Test), click next again. On the third screen, select the server (by default Netbeans brings Glasshfish), choose the Java Version (Java EE 5 by default), and select the EJB and Web module. Note: By default, the EJB module's name is "EAR name" plus "-ejb". The Web module's name is "EAR name" plus "-war". However you are free to change these names. When the projects are created, they will be shown on the Projects tab. On the Projects tab, expand the EJB module (in my case called "Test-ejb"). You will see some options, such as: Enterprise Beans, Configuration Files, Server Resources and so on. We will work around the Enterprise Beans, therefore right mouse click on Enterprise Beans -> New -> Session Bean. On the screen that will come up, choose the EJB Name, Package, Session Type and Interface. For my example, I am using "TestEJB","stateless","Stateless","Remote". Click finish when your fields are filled. After the Session Bean is created, you will see the class (and the interface) in the Source Packages section, as well as the Bean in the Enterprise Beans section. In the main tab, the TestEJBBean.java will be opened automatically. Our Stateless Session Bean was created into the stateless package, but now we have to implement it. Open it (if it is closed) with double click on the TestEJBBean from Enterprise Beans section (you can open the file directly from the Source Package as well). In the body of the class there is a comment " // Add business logic below. (Right-click in editor and choose // "EJB Methods > Add Business Method" or "Web Service > Add Operation")" So right mouse click in the editor and choose EJB Methods > Add Business Method. A new screen will come up. In your example, we will have only one method (called getMessage()) with String return. Hence, put in the field name getMessage and return type: String. Done, our first EJB3 Session Bean object has been created. To verify the code it has created, you can open the class TestEJBBean (implementation) and the interface TestEJBRemote (remote interface). Different than Eclipse, where we put ourself the interface and the class name, Netbeans uses the pattern Object Name plus Remote or Local. Of couse you can change it yourself The last thing to do is to implement the business method we just added. It is simple, only return a string message: Hello EJB World. The code looks like below: package stateless; import javax.ejb.Stateless; @Stateless public class TestEJBBean implements TestEJBRemote { public String getMessage() { return "Hello EJB World"; } } Simple, huh? We have already created the Web Module previously when the EAR has been created, so let’s use it as EJB Client. When the Web module is created, by default Netbeans already creates a file called index.jsp in the Web Pages section. Open this file to add a call to the servlet. The code looks like below: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <html> <head> <meta http- <title>JSP Page</title> </head> <body> <h2>Hello World!</h2> <a href="TestServlet">Click here to call the EJB component</a> </body> </html> As you can see, we must create a servlet called TestServlet. it will call the EJB component when the link from User Interface is clicked. To create the servlet itself, right click on Web project (in my case Test-web), New -> Servlet. On the new screen, select the Class Name and the Package. On next screen, you can keep all options and click on Finish button. The Servlet will be created and its code will appear on the Main tab. Much easier than JBoss, in Glassfish there is the annotation @EJB. When the container sees this annotation, is inject the component directly in the Servlet, Java Class, Managed Bean, whatever. (In JBoss this annotation has not been implemented yet, so you must use JNDI to call a remote component). The @EJB annotation gets inside the attribute and can be used directly in the code. The code from Servlet looks like below: package servlets; import java.io.*; import javax.ejb.EJB; import javax.servlet.*; import javax.servlet.http.*; import stateless.TestEJBRemote; public class TestServlet extends HttpServlet { //This annotation INJECTS the TestEJBRemove object from EJB //into this attribute @EJB private TestEJBRemote testEJB; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println(testEJB.getMessage()); out.println("</body>"); out.println("</html>"); } } Look at the line #13. It has the @EJB annotation. Also, look at the body of doGet method. No JNDI method was used, no code to call the EJB object was used, thus the code gets much clear than JNDI (Point to Glassfish over JBoss :) ) You can run the application right click on EAR project (in my case Test) and select option Run. Netbeans will do the deploy automatically and when the glassfish is started, the index.jsp page will be opened in your web browser. After that, click on the LINK and see in the console of Netbeans (tab Glassfish) to see the output. Note: Although the @EJB annotation is much better than JNDI calls, it only works in the Glassfish server environment. Therefore if you are creating a stand-alone application that calls a remote object, you can not use the @EJB annotation. As mentioned above, you cannot use the @EJB annotation out of a Glassfish server environment, therefore in a Stand-Alone application you must use the JNDI. Below following an example of how to call a EJB from a Java Stand-Alone client. First of all, create a Java Project. New Project -> Java -> Java Application. In this application, you must add two JARs file, as well as associate your application with the EJB module (thus your client knows about the EJB Interface). To do that, right click on Java Project, Properties -> Libraries -> Add Project (to add the Test project) and Add JAR/Folder to add the following jar files: Both jar can be located into $GLASSFISH_HOME/lib directory. By default, the appserv-rt.jar brings a jndi.properties file, but I will show you how to create one. Why? Because when you are running the client in the machine different than the app server, you must override this file. So create a file called jndi.properties file into the root of the Java project and put the following content: java.naming.factory.initial = com.sun.enterprise.naming.SerialInitContextFactory java.naming.factory.url.pkgs = com.sun.enterprise.naming java.naming.factory.state = com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl #optional. Defaults to localhost. Only needed if web server is running #on a different host than the appserver org.omg.CORBA.ORBInitialHost = localhost #optional. Defaults to 3700. Only needed if target orb port is not 3700. org.omg.CORBA.ORBInitialPort = 3700 Now, open the Main class and add the following commands: package testclient; import java.io.FileInputStream; import java.util.Properties; import javax.naming.InitialContext; import stateless.TestEJBRemote; public class Main { public static void main(String[] args) { try { Properties props = new Properties(); props.load(new FileInputStream("jndi.properties")); InitialContext ctx = new InitialContext(props); TestEJBRemote testEJB = (TestEJBRemote) ctx.lookup("stateless.TestEJBRemote"); System.out.println(testEJB.getMessage()); } catch (NamingException nex) { nex.printStackTrace(); } catch (FileNotFoundException fnfex) { fnfex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } } } } You can copy-paste the body of main method, then press Ctrl + Shift + I to Fix Imports. Also remember to add reference to your EJB project, otherwise import stateless.TestEJBRemote can not be resolved. To do this, right click on your standalone client application 'Properties -> Libraries -> Add Project and choose Test-ejb.ejb. Save it and before run this code, make sure the Glassfish is running. After you run the java class, you should see the EJB message onto the console. This topic overs here. I hope this topic be useful for anyone, as well as you can choose yourself which environment (Eclipse or Netbeans) is better for you. Note: Another alternative way to call the EJB is copying jndi.properties to the same package (testclient) of Standalone Client in this case Main class, you could use this alternative code: package testclient; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; import stateless.TestEJBRemote; /** * * @author xtecuan */ public class Main { private static final String EJB_JNDI_NAME="stateless.TestEJBRemote"; private static final String BUNDLE_CONFIG_CLASSPATH_PROPS = "/testclient/jndi.properties"; private static TestEJBRemote testEJB = getEjbReference(); private static final Properties getConfigurationProps() { Properties props = new Properties(); InputStream is = Main.class.getResourceAsStream(BUNDLE_CONFIG_CLASSPATH_PROPS); try { props.load(is); } catch (IOException e) { e.printStackTrace(); } finally { return props; } } public static TestEJBRemote getEjbReference() { TestEJBRemote ll = null; try { Properties props = getConfigurationProps(); InitialContext ctx = new InitialContext(props); ll = (TestEJBRemote) ctx.lookup(EJB_JNDI_NAME); System.out.println(ll.toString()); } catch (NamingException nex) { nex.printStackTrace(); } finally { return ll; } } public static void main(String[] args) { System.out.println(testEJB.getMessage()); } } Works with NetBeans 6.0,6.5,6.1,6.7,6.7.1 as said above. Try this out on yours bundle, and make sure to notify us if anything goes wrong! Thank you!
http://wiki.netbeans.org/CreatingEJB3UsingNetbeansAndGlassfish?intcmp=925655
CC-MAIN-2014-41
refinedweb
1,805
58.79
App Designs You Should Avoid Like the Plague Software UX/UI anti-patterns Need to write manual functional test cases and Design/UX Review Testing test cases for user stories for a new application?Only I have user stories and supporting documents for that like process flows, wireframes. Need to complete as soon as possible. ...the app. The Visits's information will include - Id - Site Id - Site's visit id (reference number) - Date - Amount - Volume - Fuel Grade - Description - Use Cases - A tennant can sign in to the app A customer can sign in to the app A support technician can sign in to the app A tennant can view all customers activity for all I need to make a desktop app... 3. Programming language of your choice 4. Microsoft’s Component Object Model (COM) (in most cases; see Figure 1) 5. Knowledge of XML is useful if you plan to use the qbXML Request Processor API. In this case, you may also want to install and use an XML parser such as Microsoft’s XML Core Services (MSXML). ../ Reporting Services). For option .. ...a an article to show how important this kind of lawyers are Complete the following code and load it to Mimir. I'll copy the grade to Blackboard after the due date: IMPORTANT!!!! You must use the following skeleton code in your code to pass the Mimir tests!!! I have loaded it here as a skeleton of main for your project! main(1).cpp Note the skeleton code is old - delete the using namespace std line Suite CRM: pull the data from JSON and insert / update the cases I am trying to learn angular js and jasmine test case. so I took a sample jasmine test cases and used it in my code sample testcase fiddle but in my fiddle when I include its breaking. in my console I see errors but not sure why its happening Uncaught ReferenceError: System is not defined Uncaught TypeError: [url removed, login to view] is not a function RangeError: ...group Y.iv. The former contains the ciphertext, and the latter the initialization vector. You only need to work on files associated with your group. You can use files for other groups as test cases, if you want.... ...transformation. Must deliver source code that compiles cleanly for use in a user exit. Code will need to be generic so that it can be ported to Linux, Microsoft and iSeries environments. At a minimum, knowledge if Unix is required. wants to transform data in numeric and alpha-numeric cases for names, social security numbers, addresses, and PII data .. ..."Transforming Corporate banking with predictive insights" The writing style needs to be professional. Images are not required but reference links (including some live use cases) would be good. Target Audience would be bankers (CXOs and Business Heads). the writer needs to have a decent knowledge of the banking technology domain. The content could ...has high priority to recover from Buyers personal assets. Please add other clauses as required. Please note that the buyer should not sue the Marketing agent. In some cases buyer simply say quality is an issue so he is not obligated to pay. so we need to protect supplier as well as buyer. So upon receiving consignment, buyer should inspect and, Software UX/UI anti-patterns Tutorial for implementing video playback on Android using different players Details about the new JavaScript binary standard
https://www.freelancer.com/job-search/use-cases/
CC-MAIN-2017-43
refinedweb
570
62.88
1 /*2 * @(#)BN.java 1 import java.io.*;38 import java.nio.channels.*;39 40 /**41 * A Blocking/Multi-threaded Server which creates a new thread for each42 * connection. This is not efficient for large numbers of connections.43 *44 * @author Mark Reinhold45 * @author Brad R. Wetmore46 * @version 1.3, 05/11/1747 */48 public class BN extends Server {49 50 BN(int port, int backlog, boolean secure) throws Exception {51 super(port, backlog, secure);52 }53 54 void runServer() throws IOException {55 for (;;) {56 57 SocketChannel sc = ssc.accept();58 59 ChannelIO cio = (sslContext != null ?60 ChannelIOSecure.getInstance(61 sc, true /* blocking */, sslContext) :62 ChannelIO.getInstance(63 sc, true /* blocking */));64 65 RequestServicer svc = new RequestServicer(cio);66 Thread th = new Thread (svc);67 th.start();68 }69 }70 }71 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/BN.java.htm
CC-MAIN-2017-17
refinedweb
146
62.14
Vue Lifecycle This guide discusses how to use the Ionic Framework Lifecycle events in an Ionic Vue application. Ionic Framework Lifecycle Methods Ionic Framework provides a few lifecycle methods that you can use in your apps: The lifecycles are defined the same way Vue lifecycle methods are - as functions at the root of your Vue component: import { IonPage } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Home', ionViewDidEnter() { console.log('Home page did enter'); }, ionViewDidLeave() { console.log('Home page did leave'); }, ionViewWillEnter() { console.log('Home page will enter'); }, ionViewWillLeave() { console.log('Home page will leave'); }, components: { IonPage } }) Composition API Hooks These lifecycles can also be expressed using Vue 3's Composition API: import { IonPage, onIonViewWillEnter, onIonViewDidEnter, onIonViewWillLeave, onIonViewDidLeave } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Home', components: { IonPage }, setup() { onIonViewDidEnter(() => { console.log('Home page did enter'); }); onIonViewDidLeave(() => { console.log('Home page did leave'); }); onIonViewWillEnter(() => { console.log('Home page will enter'); }); onIonViewWillLeave(() => { console.log('Home page will leave'); }); } }) Pages in your app need to be using the IonPagecomponent in order for lifecycle methods and hooks to fire properly. How Ionic Framework Handles the Life of a Page Ionic Framework has its router outlet, called <ion-router-outlet>. This outlet extends Vue Router's <router-view> with some additional functionality to enable better experiences for mobile devices. When an app is wrapped in <ion-router-outlet>, Ionic Framework treats navigation a bit differently. When you navigate to a new page, Ionic Framework will keep the old page in the existing DOM, but hide it from your view and transition the new page. The reason we do this is two-fold: 1) We can maintain the state of the old page (data on the screen, scroll position, etc...). 2) We can provide a smoother transition back to the page since it is already there and does not need to be created. Pages are only removed from the DOM when they are "popped", for instance, by pressing the back button in the UI or the browsers back button. Because of this special handling, certain Vue Router components such as <keep-alive>, <transition>, and <router-view> should not be used in Ionic Vue applications. Additionally, Vue Router's Scroll Behavior API is not needed here as each page's scroll position is preserved automatically. All the lifecycle methods in Vue ( mounted, beforeUnmount, etc..) are available for you to use as well. However, since Ionic Vue manages the lifetime of a page, certain events might not fire when you expect them to. For instance, mounted fires the first time a page is displayed, but if you navigate away from the page Ionic Framework might keep the page around in the DOM, and a subsequent visit to the page might not call mounted again. This scenario is the main reason the Ionic Framework lifecycle methods exist, to still give you a way to call logic when views enter and exit when the native framework's events might not fire. Guidance for Each Lifecycle Method Below are some tips on use cases for each of the life cycle events. ionViewWillEnter- Since ionViewWillEnteris called every time the view is navigated to (regardless if initialized or not), it is a good method to load data from services. ionViewDidEnter- If you see performance problems from using ionViewWillEnterwhen loading data, you can do your data calls in ionViewDidEnterinstead. However, this event will not fire until after the page is visible to the user, so you might want to use either a loading indicator or a skeleton screen such as ion-skeleton-text, so content does not flash in un-naturally after the transition is complete. ionViewWillLeave- Can be used for cleanup, like unsubscribing from data sources. Since beforeUnmountmight not fire when you navigate from the current page, put your cleanup code here if you do not want it active while the screen is not in view. ionViewDidLeave- When this event fires, you know the new page has fully transitioned in, so any logic you might not normally do when the view is visible can go here.
https://ionicframework.com/jp/docs/es/vue/lifecycle
CC-MAIN-2021-43
refinedweb
681
50.26
Adding Search to your Eleventy Static Site with Lunr I recently came back from connect.tech (one of my favorite conferences). I had the honor of giving not one, but two different talks. One of them was on static sites, or the JAMstack. This is a topic I’ve covered many times in the past, but it had been a while since I gave a presentation on it. During my presentation I covered various ways of adding dynamic features back to the static site, one of them being search. For my blog here, I make use of Google’s Custom Search Engine feature. This basically lets me offload search to Google, who I hear knows a few things about search. But I also give up a bit of control over the functionality. Oh, and of course, Google gets to run a few ads while helping find those results… To be clear, I don’t fault Google for those ads, I’m using their service for free, but it isn’t something a lot of folks would want on their site. There’s an alternative that’s been around for a while that I’ve finally made some time to learn, Lunr. Lunr is a completely client-side search solution. Working with an index of your creation (a lot more on that in a moment), Lunr will take in search input and attempt to find the best match it can. You are then free to create your search UI/UX any way you choose. I was first introduced to Lunr while working at Auth0, we used it in the docs for Extend. (Note - this product is currently EOLed so the previous link may not work in the future.) If you use the search form on the top right, all the logic of running the search, finding results, and displaying them, are all done client-side. Lunr is a pretty cool project, but let’s talk about the biggest issue you need to consider - your index. In order for Lunr to find results, you need to feed it your data. In theory, you could feed it the plain text of every page you want to index. That essentially means your user is downloading all the text of your site on every request. While caching can be used to make that a bit nicer, if your site has thousands of pages, that’s not going to scale. This is why I didn’t even consider Lunr for my blog. You also need to determine what you want to actually search. Consider an ecommerce site. Adding search for products is a no brainer. But along with text about the product, you may want to index the category of the product. Maybe a subcategory. Shoot, maybe even a bit of the usage instructions. And even after determining what you want to index, you need to determine if some parts of your index are more important than others. If you are building a support site, you may consider usage instructions for products more important than the general description. Lunr isn’t going to care what you index, but you really think about this aspect up front. I definitely recommend spending some time in the Lunr docs and guides to get familiar with the API. So, how about an example? Our Site For my test, I decided to build a simple static site using Eleventy. This is my new favorite static site generator and I’m having a lot of fun working with it. You can use absolutely any other generator with Lunr. You could also absolutely use an application server like Node, PHP, or ColdFusion. My static site is a directory of GI Joe characters sourced from Joepedia. I only copied over a few characters to keep things simple. You can see the site (including the full search functionality we’re going to build) at. Here’s an example character page. --- layout: character title: Cobra Commander faction: Cobra image: --- Not. Not much is known about him, he is a master of disguise and he has appeared as a goatee artist looking man with a son in a coma, in the Marvel comics. His appearance in the 12 inch G.I. Joe line shows him as a man with dark slicked back hair, his appearance constantly changing leaves him assumed to wear masks, even the commander can keep his identity from the people around him. And how it looks on the site: Our Search Index I decided to build my index out of the character pages. My index would include the title, URL, and the first paragraph of each character page. You can see the final result here:. So how did I build it? The first thing I did was create a custom collection for Eleventy based on the directory where I stored my character Markdown files. I added this to my .eleventy.js file. eleventyConfig.addCollection("characters", function(collection) { return collection.getFilteredByGlob("characters/*.md").sort((a,b) => { if(a.data.title < b.data.title) return -1; if(a.data.title > b.date.title) return 1; return 0; }); }); I am embarrassed to say it took me like 10 minutes to get my damn sort right even though that’s a pretty simple JavaScript array method. Anyway, this is what then allows me to build a list of characters on my site’s home page, like so: <ul> {% for character in collections.characters %} <li><a href="{{ character.url }}">{{ character.data.title }}</a></li> {% endfor %} </ul> This is also how I’m able to look over my characters to build my JSON index. But before I did that, I needed a way to get an “excerpt” of text out of my pages. The docs at Eleventy were a bit weird about this. I had the impression it was baked in via one of the tools it uses, but for the life of me I could not get it to work. I eventually ended up using a modified form of the tip on this article, Creating a Blog with Eleventy. I added his code there to add a short code, excerpt, built like so: eleventyConfig.addShortcode('excerpt', article => extractExcerpt(article)); // later in my .eleventy.js file... // function extractExcerpt(article) { if (!article.hasOwnProperty('templateContent')) { console.warn('Failed to extract excerpt: Document has no property "templateContent".'); return null; } let excerpt = null; const content = article.templateContent; // The start and end separators to try and match to extract the excerpt const separatorsList = [ { start: '<!-- Excerpt Start -->', end: '<!-- Excerpt End -->' }, { start: '<p>', end: '</p>' } ]; separatorsList.some(separators => { const startPosition = content.indexOf(separators.start); const endPosition = content.indexOf(separators.end); if (startPosition !== -1 && endPosition !== -1) { excerpt = content.substring(startPosition + separators.start.length, endPosition).trim(); return true; // Exit out of array loop on first match } }); return excerpt; } Note that I modified his code such that it finds the first closing P tag, not the last. With these pieces in place, I built my index in lunr.liquid: --- permalink: /index.json --- [ {% for character in collections.characters %} { "title":"{{character.data.title}}", "url":"{{character.url}}", "content":"{% excerpt character %}" } {% if forloop.last == false %},{% endif %} {% endfor %} ] Our Search Front-End Because I’m a bit slow and a glutton for punishment, I decided to build my search code using Vue.js. Why am implying this was a mistake? Well it really wasn’t a mistake per se, but I did run into an unintended consequence of using Liquid as my template engine and Vue.js. You see, by using Liquid on the back end (in my static site generator), I made use of a template syntax that is similar to Vue.js. So if I did {{ name }} it would be picked up by Liquid first before Vue ever got a chance to run it. The solution wasn’t too difficult, but possibly added a bit of complexity that may be something you wish to avoid in the future. Of course, using Vue was totally arbitrary here and not something you need to use with Lunr, so please keep that in mind when looking at my solution. Since my own blog also uses Liquid, I’m going to share the HTML code via an image. Note that my entire demo is available at GitHub (via the link I’ll share at the end). In the screen shot above, note the raw and endraw tags surrounding my Vue code. That’s how I was able to get it working. But as I said, let’s ignore that. ;) The code here is rather simple. A search field, a place for the results, and a simple way to handle it when no results are found. Note that my results include a url and title value. This actually takes a little bit of work, and I’ll explain why in a bit. Alright, let’s switch to the JavaScript. First, let’s look at the data and created parts of my code. data:{ docs:null, idx:null, term:'', results:null }, async created() { let result = await fetch('/index.json'); docs = await result.json(); // assign an ID so it's easier to look up later, it will be the same as index this.idx = lunr(function () { this.ref('id'); this.field('title'); this.field('content'); docs.forEach(function (doc, idx) { doc.id = idx; this.add(doc); }, this); }); this.docs = docs; }, When my Vue application loads up, I first make a request to my index data. When that’s done, it’s time to build the Lunr index. This is done via a function passed in to the constructor. The first thing I do is define the ref, or primary identifier of each thing I’m indexing, what Lunr refers to as docs. I then define the fields in my content I want indexed. Note that I could boost certain fields here if I want one to be more important than another. I then loop over each item in my index and here’s a SUPER IMPORTANT thing you need to keep in mind. When Lunr returns search matches, it only returns the ref value. If you remember, my index consists of the url, the title, and a block of text. If I want to tell my users the title of the matched document, and if I want to link to that result, I have to get that information. But I just said - Lunr doesn’t return it. So how do I get it? Since Lunr returns the ref value, I can use that as a way to look up my information in the index. My URLs are unique and I could use array methods to find my data, but if I simply use the position value, the idx above, then I’ve got a quick and easy way to get my original document. This comes together in the search method: search() { let results = this.idx.search(this.term); // we need to add title, url from ref results.forEach(r => { r.title = this.docs[r.ref].title; r.url = this.docs[r.ref].url; }); this.results = results; } I begin by just doing the search, passing your input as is. Lunr will parse it, do it’s magic, and return the results. In order for me to use the title and url values, I refer back to the original array as I loop over the results. And that’s basically it. You can test this yourself - try searching for weapon to find Destro. Finally, you can find the entire repository for this demo here:. I hope this helps, and now you know how to use client-site search with Lunr and Eleventy. And as we know… Header photo by Kayla Farmer on Unsplash
https://www.raymondcamden.com/2019/10/20/adding-search-to-your-eleventy-static-site-with-lunr?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+ColdfusionbloggersorgFeed+%28coldfusionBloggers.org+Feed%29
CC-MAIN-2019-47
refinedweb
1,941
74.08
.NET Filters - Advanced The filter tree hierarchy only displays public classes and methods. It does not show non-public classes or delegates. You can add classes or methods that are not public by manually entering them in the filter's definition file. The filter definition files, <filter_name>.xml reside in the dat\DotnetFilters folder of your installation. The available Action properties for each element are: Include, Exclude, or Totally Exclude. For more information, see .NET Recording Filter Pane. By default, when you exclude a class, the filter mechanism applies Exclude, excluding the class, but including activity generated by the excluded class. When you exclude a method, however, it applies Totally Exclude, excluding all referenced methods. For example, suppose Function A calls function B. If Function A is Excluded, then when the service calls Function A, the script will include a call to Function B. However, if function A is Totally Excluded, the script will not include a call to Function B. Function B would only be recorded if called directly—not through Function A. VuGen saves a backup copy of the filter as it was configured during the recording, RecordingFilterFile.xml, in the script's data folder. This is useful if you made changes to the filter since your last recording and you need to reconstruct the environment.
https://admhelp.microfocus.com/vugen/en/12.60/help/WebHelp/Content/VuGen/140300_c_dotnet_filters_advanced.htm
CC-MAIN-2018-39
refinedweb
218
50.43
The variable __name__ varies depending on the module you are in during the execution of the program. In the main module, its value will be equal to __main__. If you are in another imported module, then its value will be equal to the name of the main module. The if (__name__ == __main__) test makes it possible to distinguish between the two cases. This condition is used to develop a module that can both be executed directly but also is imported by another module to provide its functions. You can insert into this block of code instructions intended for the case where the module is directly executed. The python is a language that does not have a main () method, as it does in the C language. When you load a module, the code executed is the one located directly at the top level. This condition, therefore, makes it possible to group together the instructions that we want to use in the case of direct execution of the module. # myScript.py if __name__ == __main__: print (my script is executed directly) else print (my script is imported by another module) # myOtherScript.py import myScript By launching the manuscript script with the python command monScript.py, we get the message my script is executed directly. If, on the other hand, we run the myOtherScript script, which imports the myScript.py file, the message displayed will be my script is imported by another module.
https://kodlogs.com/blog/2656/what-is-__name__-in-python
CC-MAIN-2021-21
refinedweb
239
62.88
I just started using websphere 8.0 and I'm running some tests to become familiar with Java Enterprise 6.0, especially with EJB 3.1. I need advice on how to use the direct injection of data sources. Before WAS 8.0, I used to execute a direct lookup of the datasource.. and since in my projects I have several datasources that may be potentially used (actual datasource choice depends on user's profile), I was forced to declare for each EJBS in the deployment descriptor all resource refs. Now with annotation-based configuration, I'm able to write code like this: @Stateless @LocalBean public class BaseService { @Resource(name= "X", lookup= "jdbc/X") protected DataSource X; //..... @Resource(name= "Y", lookup= "jdbc/Y") protected DataSource Y; /** * Default constructor. */ public BaseService() { // TODO Auto-generated constructor stub } protected getActualConnection(String connName) { Connection conn = null; try { System.out.println( " Try to get connection...."); if(connName.equals( "X")) conn = X.getConnection(); if(connName.equals( "Y")) conn = Y.getConnection(); System.out.println( " Connection ok."); return conn; } catch(Exception e) { System.out.println( " Error : "+e.getMessage()); return null; } } } and using full-supported inheritance, I just let my ejbs extend BaseService to have centralized method to get (internally) a connection and release it after using. There are a couple of things on which I need advice... a) I noticed that without the. lookup b) What do you think about centralizing (of course, with code smarter than that I posted for example) the datasource lookup method ? I'm in doubt if this may considered a good thing or not... Thank you in advance..
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014656530
CC-MAIN-2017-13
refinedweb
265
52.15
#include <MPxPolyTrg.h> MPxPolyTrg is the the parent class for nodes which define a custom face triangulation for meshes. In order to override default maya triangulation, the user has to do the following things: Note: The number of vertices can be calculated by adding all the loop sizes. The output of this function is an array of triangle description: nbTrg = 2 trg: 0 1 2 2 3 0 Tip: Refer to the example plugin: polyTrgNode for more details on how to implement it. Once the node is defined, the user has to inform the mesh about it. For each mesh the user wants to override the default triangulation, he has to set the usertTrg attribute on the mesh to the name under which the function has been registered. Example: /code setAttr mesh.userTrg -type "string" "triangulate"; /endcode Once that attribute is set, the default maya triangulation is turned off and the one provided by the user is used to draw the mesh. Constructor. The constructor should never call any methods from MPxPolyTrg or make any calls that require the existence of the MObject associated with the user defined node. The postConstructor method should be used to do any initialization of this kind. Destructor. Post constructor. Internally maya creates two objects when a user defined node is created, the internal MObject and the user derived object. The association between the these two objects is not made until after the MPxPolyTrg constructor is called. This implies that no MPxPolyTrg member function can be called from the MPxPolyTrg constructor. The postConstructor will get called immediately after the constructor when it is safe to call any MPxPolyTrg member function. Reimplemented from MPxNode. This method should be overridden in user defined nodes. However, fror this particaular node we don't need to to do anything in the compute functione. Therefore, all we do is return MS:kSuccess in the derive class. Reimplemented from MPxNode. Each new node has to implement that fuction. It returns false since this is not an abstract class. Reimplemented from MPxNode. Register a triangulation function with maya. The name provided as a first argument is the name under which the function is registered. This name has to be used when setting 'userTrg' attribute on a mesh.
http://download.autodesk.com/us/maya/2009help/API/class_m_px_poly_trg.html
crawl-003
refinedweb
375
64.2
Creating Zoo Plugins This guide discusses how to create plugins for Zoo. Overview Zoo lets third party plugin developers add licensing support for their products to the Zoo. Zoo plugins are .NET Framework 4.0 assemblies. To create a plugins for Zoo,. Writing a Zoo Plugin The general steps required to create a Zoo plugin are: - Make sure you have Zoo installed. - Launch Microsoft Visual Studio 2010. - Create a new Class Library project using either Visual C# or Visual Basic .NET. - Add a reference to ZooPlugin.dll, which is found in the Zoo installation folder. Make sure to set the reference’s Copy Local property to False. - Create a new public class that inherits from the IZooPlugininterface. - Implement the interface members. (For detailed information about the interface members, see the sample Zoo plugin listed below.) - Build your plugin. - Digitally sign your plugin. Installing a Zoo Plugin Once you have built your Zoo plugin, you can install it and test it: - Run ZooAdmin.exe and make sure the Zoo licensing service has stopped. - Copy your plugin assembly (.dll) and any dependent support libraries to the Zoo’s plugin folder (i.e. C:\Program Files\Zoo 5.0\Plugins). - Restart the Zoo license service. - When the service has restarted, click the Add License button. Y our product should be one of the available products for which to add a license.
http://developer.rhino3d.com/guides/rhinocommon/creating_zoo_plugins/
CC-MAIN-2016-30
refinedweb
228
70.7
. 1. Variable and types Command:Grasshopper->Maths->Script->Python Place a Python component in your GH document. If you double-click the python component, an editor will appear. Type a=1 print a print type(a) a="Hello" print a print type(a) Hit the Test button. Check if the output is |1 |<type 'int'> |Hello |<type 'str'> Congraturation :) **Note that the type of the variable a changed. Python is "dynamic typing", whereas C, C++, Java, C# are "static typing" If you connect a Panel component to the "out" slot of the python component, you can see the output like this. 2. Inputs and outputs, basic arithmetic operations Zoom in to the GhPython component and add b to the output variables. Connect sliders to the slots whose names are x and y. Tyy a=x+y b=x*y You may get 3. import math "import something" syntax enables functions provided by the module "something" input: x output: cosX, sinX import math cosX=math.cos(x) sinX=math.sin(x) 4. import rhinoscriptsyntax as rs input "import LooooongTeeeeerm as LT" can define an alias (short name) of the module "LoooooongTeeeeerm" **rhinoscriptsyntax is very important in that it provides almost all the geometric manipulations supported by Rhino. input: x output: a import math import rhinoscriptsyntax as rs cosX=math.cos(x) sinX=math.sin(x) a=rs.AddPoint(cosX,sinX,0) Now, you can see a point geometry around the origin. Congraturation! You can connect many sliders like this. Then, you get this. 5. Playing around rhinoscriptsyntax (Circles) import math import rhinoscriptsyntax as rs circle1=rs.AddCircle(C,x) circle2=rs.AddCircle3Pt(P1,P2,P3) 5. Playing around rhinoscriptsyntax (Polyline) [(1,2,3),(2,2,3),(3,4,3),(5,3,4)] will be further discussed in later sessions. import rhinoscriptsyntax as rs a=rs.AddPolyline([(1,2,3),(2,2,3),(3,4,3),(5,3,4)])
http://mikity.wikidot.com/2013winterpython1
CC-MAIN-2018-22
refinedweb
317
56.35
Dear Jason, Please find enclosed the admin/ directory as well as the autogen.sh script. This allows Kdevelop3 to work seemlessly with the project. Could it be committed to CVS? Kind regards, Jean-Michel Dear all, I created a basic project with latest Kdevelop3 and copied the latest admin/ directory to Kdenlive base. I renamed bootstrap to autogen.sh (as it can be triggered by Kdevelop automatically). These scripts are like black boxes to me as they are generated automatically. you were right, Jason. I was not able to analyse the diff between admin (new version) and admin2_ (old version) because there are a lot of minor differences (use of [ and ]). After compilation and installation, there was still this crazy window problem. Would it be possible to remove the old admin_ folders and commit the new admin/ directory with autogen.sh script? Can I send them to you? Then, the Debian package will follow, probably tomorrow. Kind regards, Jean-Michel >. I did ./configure --prefix=/usr > Have you installed an older version of Kdenlive in the past? Yes. >. I removed .kdeliverc several times. The simple fact to change PIAVE location is the preferences recreates the file and the windows go boom. Sudenly, all panes can dissapear and you are left without even a menu. Please find attached a screenshot. Kind regards, Jean-Michel Le Vendredi 8 Octobre 2004 07:24, Ruslan Popov a =C3=A9crit : > There is a problem with ffmpeg: > > Compilation error: > dtsdec.c:27:17: dts.h: No such file or directory > > file dtsdec.c: > #include <dts.h> > > What library I need to install for DTS? Under Debian, the library is called libdts-dev (0.0.2-svn-1). Please find=20 enclosed a small readme file. I wonder if the library is really needed. The= =20 source code can only be checked out by SVN. Kind regards, Jean-Michel On Thursday 07 October 2004 23:46, Jean-Michel POURE wrote: > Dear friends, > > After creating a Debian package for PIAVE, I was able to checkout and > install Kdenlive from CVS. > > Kdenlive seems to work, but its windows become mad (each pane splits in > several windows, the menu dissapears). After removing /home/jmpoure/.kde/ > share/config/kdenliverc, the project comes back to its defaults. I cannot visualize theeffect you mean; can you post a screenshot? (max post size is 50K before it needs to be admin'ed, or you can link to a screenshoton the web). Have you installed an older version of Kdenlive in the past?. Cheers, Jason -- Jason Wood I guess I am unlucky :( Getting libdca not to infringe on DTS Inc.'s trademark. Ruslan Hello There is a problem with ffmpeg: Compilation error: dtsdec.c:27:17: dts.h: No such file or directory file dtsdec.c: #include <dts.h> What library I need to install for DTS? Ruslan > From: Jean-Michel POURE [mailto:jm@...] > ffmpeg cvs version can handle DV and mpeg-4 quite nicely (0.48 and > 0.49-pre1 are broken). Here is my daily ffmpeg compilation script: > > cvs update -C -P -d > make clean > ./configure --prefix=/usr --enable-shared --enable-mp3lame --enable-vorbis > --enable-faad --enable-faac --enable-gpl --enable-pthreads --enable-xvid > --enable-a52 --enable-pp --enable-dts > make
https://sourceforge.net/p/kdenlive/mailman/kdenlive-devel/?viewmonth=200410&viewday=8
CC-MAIN-2018-17
refinedweb
537
69.07
On Thu, Nov 17, 2005 at 01:55:31PM -0800, Ovid wrote: : In (in response to :), Rob Kinyon wrote that in his : understanding of Perl 6 Roles, anything a role can do the class "doing" : the role should also be able to do. : : Is this correct? Advertising Only sorta. A role has its own lexical scope that the class is not privy to, and lately we're trying to manage privacy via lexical scoping as much as possible. : I'm getting bitten with Class::Trait because some of : my traits import helper functions and constants from other packages. : The classes implementing the traits should *not* care about how the : trait does something, but those functions and constants are getting : flattened into my classes and this has been causing all sorts of : problems. In Perl 6 imports are lexical by default, so that shouldn't be a problem. : For the time being, I have rewritten all of my traits to not import : anything in the trait namespace, but I intend to modify Class trait so : each method can be defined thusly: : : sub some_method : Public { ... } : : In the original traits definition, as I understood them, a trait should : specify what it requires *and* what it provides. Are Perl 6 roles : really going to blindly export everything they contain? This seems a : serious mistake. I didn't see anything addressing this issue in : Please don't rely on perl.com for the latest design docs. I just checked in a new S12 to svn.perl.org a few minutes ago that hopefully covers most of the questions raised here and on perlmonks. Doubtless there will be more issues, but that's the nature of the beast. I'll need to go and install some Update sections in A12, but bein's as it's 2:00 in the morning I'm going to bed... Larry
https://www.mail-archive.com/perl6-language@perl.org/msg22711.html
CC-MAIN-2018-34
refinedweb
311
70.84
My Haskell TronBot for the Google AI Challenge Published on March 1, 2010 under the tag haskell This is the code for my entry in the Google AI Challenge 2010. It turned out to be the best Belgian and the best Haskell bot (screenshot), so I thought some people might be interested in the code. Luckily, I have been writing this bot in Literate Haskell since the beginning, for a few reasons: - I always wanted to try Literate Haskell for something “more serious”. - This will force me to keep the code more or less readable and clean. - I am going to keep the code in one file, so it’s quite easy to maintain as well. module Main where This is the actual code of my bot, as submitted in the contest. The only changes made after the deadline are: - Cleanup (mostly removing Debug.tracestatements). - Adding more explanations and comments. Anyway, some disclaimers. Disclaimer 1: This is quite a large source file/blogpost. If you’re not interested at all, this could be a boring read. Disclaimer 2: This code is unfinished. There are some situations in which this bot will make very bad decisions. Possibly, there are situations that can crash him, which leads us to disclaimer 3. Disclaimer 3: I cannot be held responsible if my bot initiates a nuclear attack in an attempt to wipe out the human race. Before we begin, our Bot uses three important strategies: - Evaluation of a minimax game tree, including (deep) Alpha-beta pruning. - Iterative deepening to stay within our time limit. - A flood fill-based technique to determine space left. We start, as always, by importing the needed modules. import System.Time import System.IO import Control.Monad import Control.Applicative ((<$>)) import Data.Ord (comparing) import Data.List (transpose, nub, sortBy) import qualified Data.Set as S import Data.Set (Set, (\\)) import qualified Data.Array.Unboxed as UA import Data.Array.Unboxed ((!)) import Control.Concurrent import Data.Maybe (fromJust, isNothing, isJust, listToMaybe) To represent Tiles – positions on the 2D grid – we use a simple tuple. type Tile = (Int, Int) Because of this, we can write a very concise function to find the adjacent tiles. As you can see, I inline this function here to avoid some overheads. I use this on several places throughout the code. adjacentTiles :: Tile -> [Tile] = [ (x, y - 1) adjacentTiles (x, y) + 1, y) , (x + 1) , (x, y - 1, y) , (x ]{-# INLINE adjacentTiles #-} There’s a simple formula for calculating the Pythagorean distance between tiles. We use this in combination with the “real” distance (the distance when taking walls etc. into account). We can leave this distance squared, not taking the sqrt is a little faster, and we only have to compare distances, and x^2 < y^2 implies x < y, because distances are always non-negative. distanceSquared :: Tile -> Tile -> Int = (x1 - x2) ^ 2 + (y1 - y2) ^ 2distanceSquared (x1, y1) (x2, y2) Now, we need a data structure for the board. data BoardBase = BoardBase { baseWidth :: Int baseHeight :: Int , baseWalls :: UA.UArray Tile Bool , baseBotPosition :: Tile , baseEnemyPosition :: Tile ,deriving (Show) } However, we also want a board structure that can be adjusted very quickly. We will therefore wrap the BoardBase in another structure, capable of making a few quick adjustments. This Board will be used to consider “possible” moves. When we make a move on this Board type, we just have to add a wall to the Set, and an element to the list of positions. data Board = Board { boardBase :: BoardBase boardAdditionalWalls :: Set Tile , boardBotPositionList :: [Tile] , boardEnemyPositionList :: [Tile] ,deriving (Show) } We can create a Board from a BoardBase very quickly. boardFromBase :: BoardBase -> Board = Board { boardBase = base boardFromBase base = S.empty , boardAdditionalWalls = [baseBotPosition base] , boardBotPositionList = [baseEnemyPosition base] , boardEnemyPositionList } Now, let’s define some easy functions we can apply on a Board. The positions of the bot and the enemy are determined by the last move added to their list of moves. boardBotPosition :: Board -> Tile = head . boardBotPositionList boardBotPosition {-# INLINE boardBotPosition #-} boardEnemyPosition :: Board -> Tile = head . boardEnemyPositionList boardEnemyPosition {-# INLINE boardEnemyPosition #-} Later on, we will construct “possible” next Boards. Given such a Board, we want to determine the first move our Bot made, since that would be the move our AI will choose. This might give no result, so we wrap it in a Maybe type. boardBotMove :: Board -> Maybe Tile = listToMaybe . tail . reverse . boardBotPositionListboardBotMove Checking if a certain tile is a wall is quite simple – but we need to remember we also have to check the additional walls in the Board. We first check for boundaries to prevent errors, then we check in the walls first, because Array access is faster than Set access here. Also, we really want to inline this function, because it is called over 9000 times. isWall :: Board -> Tile -> Bool @(x, y) = x < 0 || x >= baseWidth base isWall board tile|| y < 0 || y >= baseHeight base || (baseWalls base) ! tile || tile `S.member` boardAdditionalWalls board where = boardBase board base {-# INLINE isWall #-} What now follows is the function with which we read the Board from a number of lines. This is quite boring code, so you can safely skip it. readBoard :: Int -> Int -> [String] -> Board = boardFromBase readBoard width height lines' BoardBase { baseWidth = width = height , baseHeight = walls , baseWalls = find '1' , baseBotPosition = find '2' , baseEnemyPosition }where = concat $ transpose $ map (take width) lines' string = UA.listArray ((0, 0), (width - 1, height - 1)) string matrix = UA.amap (== '#') matrix walls = head [ i | i <- UA.indices matrix, matrix ! i == c ] find c Although we do not use the next function in the AI, it is quite handy for testing reasons, when playing around with ghci. readBoardFromFile :: FilePath -> IO Board = do readBoardFromFile file <- openFile file ReadMode h <- hGetLine h line let [width, height] = map read $ words line <- hGetContents h contents return $ readBoard width height (lines contents) Next is a function to inspect the entire Board, to determine it’s value later on. It uses a flood fill based approach. It starts one flood fill starting from the enemy, and one starting from our bot. This determines the space left for each combatant. Also, when the two flood meet, we have found a path between them. This double flood fill is illustrated here in this animation: The function returns: - The free space around the bot. - The free space around the enemy. - The distance between the bot and the enemy, or Nothingif there is no path from the bot to the enemy. inspectBoard :: Board -> (Int, Int, Maybe Int) = inspectBoard board floodFill (S.singleton botPosition, S.singleton enemyPosition)0, 0) 0 Nothing S.empty (where = boardBotPosition board botPosition = boardEnemyPosition board enemyPosition Because we have to make all decisions in under one second, we have a depth limit for our flood fill. When this limit is reached, the result will be the same as if we encountered walls in all directions. = 25 maxDepth This is a small auxiliary function that extends isWall with the enemy and bot positions - we do not want to fill any of those two positions. = isWall board tile isBlocked tile || tile == botPosition || tile == enemyPosition This is the main queue-based flood fill function. It’s arguments are: - A tuple of two Sets, containing the neighbour tiles of the bot’s flood, and those of the enemy’s flood. - A Setof already flooded tiles. - A tuple of two Ints, containing the number of tiles filled by the bot, and the number of tiles filled by the enemy. - The current depth of our search. - The best distance from the bot to the enemy, or Nothingif not found yet. It works in a fairly straightforward recursive way. floodFill :: (Set Tile, Set Tile) -> Set Tile -> (Int, Int) -> Int -> Maybe Int -> (Int, Int, Maybe Int) floodFill (neighbours1, neighbours2) set (fill1, fill2) currentDepth currentDistance If we reached our search limit, or we have no more tiles to inspect, we just return what we currently have. | (S.null neighbours1 && S.null neighbours2) || maxDepth <= currentDepth = (fill1, fill2, currentDistance) Otherwise, we expand our search. | otherwise = floodFill (validNext1, validNext2) newSet+ S.size validNext1, fill2 + S.size validNext2) (fill1 + 1) distance (currentDepth where The next tiles to add are those adjacent to the current neighbours of the flood. = S.filter (not . isBlocked) . S.fromList getNext . concatMap adjacentTiles . S.toList = getNext neighbours1 next1 = getNext neighbours2 next2 If the enemy is in the next set of neighbours, we have found our distance. If there is no intersection at all, we haven’t reached the enemy yet. We have to do a little trickery here, because the distance could be even or odd. = if S.null (next1 `S.intersection` next2) odd' then Nothing else Just (2 * currentDepth + 1) = if S.null (next1 `S.intersection` neighbours2) && even' `S.intersection` neighbours1) S.null (next2 then Nothing else Just (2 * currentDepth) = currentDistance `mplus` odd' `mplus` even' distance Now, we enlarge our Set of already added tiles and remove them from the next tiles to add (since they are already added). We also filter out the non-accessible Tiles, and we make sure no Tiles appear in both validNext1 and validNext2. = set `S.union` neighbours1 `S.union` neighbours2 newSet = next1 \\ newSet validNext1 = next2 \\ newSet validNext2 The algorithm needs to be able to determine the “best” choice in some way or another. So we need to be able compare two games. To make this easier, we can assign a Score to a game - and we then make these Scores comparable. data Score = Win | Loss | Draw In theory, these are the only possible outcomes. In reality, these values are often situated at the bottom of our game tree – and we can’t look down all the way. Therefore, we also have a Game score – describing a game in progress. The Game constructor simply holds some fields so we can determine it’s value: - Free space for the bot, as determined by a flood fill. - Free space for the enemy, as determined by a flood fill. Just dif dis the distance to the enemy. If the enemy cannot be reached, or is to far away to be detected, this will be Nothing. - The number of adjacent walls next to the bot, after the first move. - The Pythagorean distance to the enemy (squared). | Game Int Int (Maybe Int) Int Int deriving (Eq, Show) To choose the best game, we need a way to compare games. That’s why we implement the Ord class. A win is always the best, and a loss is always the worse. instance Ord Score where Win <= _ = False Loss <= _ = True We only see a draw as worse if our bot would have less space otherwise. This is a quite pessimistic view, but well, we can’t risk too much. Draw <= (Game botSpace enemySpace _ _ _) = >= enemySpace botSpace Comparing two games is harder, since we have to make “guesses” here. Game bs1 es1 ds1 aw1 pd1) <= (Game bs2 es2 ds2 aw2 pd2) ( When there is a space difference: choose direction with most free space. | sp1 /= sp2 = sp1 <= sp2 When the enemy is not reachable: choose direction with most adjacent walls, as this fills our space quite efficiently. | isNothing ds1 && isNothing ds2 = aw1 <= aw2 When the enemy is reachable from both situations, we choose smallest distance. First we try the “real” distance, then the Pythagorean distance. | isJust ds1 && isJust ds2 = if ds1 /= ds2 then fromJust ds1 >= fromJust ds2 else pd1 >= pd2 Now, there are some edge cases left. We prefer to create situations were we “lock up” the other bot, but only if it means we have more space than the other bot. | isJust ds1 && isNothing ds2 = bs2 >= es2 | isNothing ds1 && isJust ds2 = bs1 >= es1 where The free space mentioned is determined as the bot space minus the enemy space. = bs1 - es1 sp1 = bs2 - es2 sp2 We’re not going to write everything twice, so if pattern matching failed, try the other way around: <= b = b >= a a Okay, when building our game tree, we need to find out if a certain node in the Alpha-Beta tree is a leaf. A leaf means the game ends - so there’s either a collision, or a draw. gameIsLeaf :: Board -> Bool = botPosition == enemyPosition gameIsLeaf board || isWall board botPosition || isWall board enemyPosition where = boardBotPosition board botPosition = boardEnemyPosition board enemyPosition If the game is a leaf, the value is trivial to determine: gameLeafValue :: Board -> Score gameLeafValue board| botPosition == enemyPosition = Draw | botCrashed && enemyCrashed = Draw | botCrashed = Loss | enemyCrashed = Win | otherwise = error "Not a leaf node." where = boardBotPosition board botPosition = boardEnemyPosition board enemyPosition = isWall board botPosition botCrashed = isWall board enemyPosition enemyCrashed If the game is not a leaf, we have to make an estimate of the value. This is basically just calling some functions to fill in the fields of the Game constructor of Score. gameNodeValue :: Board -> Score = gameNodeValue board Game botSpace enemySpace distance numberOfAdjacentWalls distanceSquared' where = boardBotPosition board botPosition = boardEnemyPosition board enemyPosition = distanceSquared botPosition enemyPosition distanceSquared' = nub $ adjacentTiles =<< boardBotPositionList board allAdjacent = length (filter (isWall board) allAdjacent) numberOfAdjacentWalls = inspectBoard board (botSpace, enemySpace, distance) Now, we have a function to create the child values of a node in the game tree. This function creates 4 new boards, with all the directions the bot (or the enemy, if isBot is False) can move to. gameNodeChildren :: Board -> Bool -> [Board] = do gameNodeChildren board isBot <- adjacentTiles position adjacent if isBot then return board = walls { boardAdditionalWalls = adjacent : botPositionList , boardBotPositionList = enemyPositionList , boardEnemyPositionList }else return board = walls { boardAdditionalWalls = botPositionList , boardBotPositionList = adjacent : enemyPositionList , boardEnemyPositionList }where = (if isBot then boardBotPosition else boardEnemyPosition) board position = position `S.insert` boardAdditionalWalls board walls = boardBotPositionList board botPositionList = boardEnemyPositionList board enemyPositionList We now have our main minimax search function. The maxDepth argument gives us a depth limit for our search, and also indicates if it’s our turn or the enemy’s turn (it’s our turn when it’s even, enemy’s turn when it’s odd). The contact argument tells us if there is a way for our bot to reach the enemy. If the enemy cannot be reached, we do not have to consider it’s turns, sparing us some valuable resources. This function uses a simple form of (deep) Alpha-beta pruning. I’m pretty sure botSearch and enemySearch could be written as one more abstract function, but I think it’s pretty clear now, too. For one unfamiliar with minimax trees or Alpha-beta pruning, this function simply returns the possible Board with the best Score. searchGameTree :: Board -> Int -> Bool -> (Score, Score) -> (Board, Score) searchGameTree parent maxDepth contact (lower, upper)| gameIsLeaf parent && isBot = (parent, gameLeafValue parent) | maxDepth <= 0 = (parent, gameNodeValue parent) | otherwise = if isBot then botSearch children (lower, upper) parent else enemySearch children (lower, upper) parent where = maxDepth `mod` 2 == 0 isBot = gameNodeChildren parent isBot children = (current, l) botSearch [] (l, _) current : xs) (l, u) current = botSearch (x let newDepth = if contact then maxDepth - 1 else maxDepth - 2 = searchGameTree x newDepth contact (l, u) (board, value) in if value >= u then (board, value) else if value > l then botSearch xs (value, u) board else botSearch xs (l, u) current = (current, u) enemySearch [] (_, u) current : xs) (l, u) current = enemySearch (x let (board, value) = searchGameTree x (maxDepth - 1) contact (l, u) in if value <= l then (board, value) else if value < u then enemySearch xs (l, value) board else enemySearch xs (l, u) current First, we want to make a quick (but stupid) decision, in case we’re on a very slow processor or if we don’t get a lot of CPU ticks. The following function does that, providing a simple “Chaser” approach. simpleDecision :: Board -> Tile simpleDecision board In case we really have no valid options, we just go north. | null valid = head directions If there are some non-wall options, we pick the first one in the list, which will conveniently be the Tile closest to the enemy. | otherwise = head valid where We take the adjacentTiles of the botPosition, and sort them according to distance to the enemy. That way, we get our “Chaser” behaviour. = boardBotPosition board botPosition = sortBy (comparing distance) $ adjacentTiles botPosition directions = filter (not . isWall board) directions valid = distanceSquared (boardEnemyPosition board) distance The next function performs one turn, meaning: - It reads the current board state from stdin. - It builds a game tree and determines the best option. - It prints that option back to stdout. takeTurn :: IO () = dotakeTurn The first line tells us the board dimensions. We then take the next height lines and read the board from it. <- (map read . words) <$> getLine [width, height] <- readBoard width height <$> replicateM height getLine board We have an MVar to hold our decision. We begin by filling it by something simple and then improve that simple result in another thread. <- newMVar $ simpleDecision board mvar <- forkIO $ makeMinMaxDecision board mvar calculationThread We wait 900 ms. After that time has passed, our MVar should contain a reasonably smart decision. We take it and finish off our calculation thread. $ 900 * 1000 threadDelay <- takeMVar mvar result killThread calculationThread Now, all that is left is printing the direction our AI made. putStrLn $ tileToDirection board result where This is the function that is executed in another thread. It simply tries to calculate a smart decision using minMaxDecision and then puts it in the MVar. We also do a simple inspectBoard to determine if there is a path between us and the enemy. It also uses a form of iterative deepening; first, the best decision for depth 2 is calculated. Then, we try to find the best decision for depth 4, then 6, and so on. Tests seemed to show that it usually gets to depth 8 or 10 before it is killed. = makeMinMaxDecision' 2 makeMinMaxDecision board mvar where = inspectBoard board (_, _, distance) = isJust distance contact = do makeMinMaxDecision' depth let (best, _) = searchGameTree board depth contact (Loss, Win) = boardBotMove best move $ swapMVar mvar (fromJust move) >> return () when (isJust move) $ depth + 2 makeMinMaxDecision' We need to determine the direction of a tile from it’s coordinates, because the game engine is expecting a direction - and we only have a Tile. tileToDirection board position| position == (x, y - 1) = "1" | position == (x + 1, y) = "2" | position == (x, y + 1) = "3" | position == (x - 1, y) = "4" | otherwise = "Error: unknown move." where = boardBotPosition board (x, y) Our main function must set the correct buffering options and then loop forever. At this point, it’s very cool we have a stateless bot, since we can now just forever takeTurn. main :: IO () = do main LineBuffering hSetBuffering stdin LineBuffering hSetBuffering stdout forever takeTurn An auxiliary function to help timing. We only take the seconds and the picoseconds into account, because when we’re taking more than minutes, well, we’re fucked anyway. toMs :: ClockTime -> ClockTime -> Int = let d = diffClockTimes t2 t1 toMs t1 t2 in tdSec d * 1000 + fromIntegral (tdPicosec d `div` 1000000000) That’s it. As always, all criticism and questions are welcome. By the way, you can find the .lhs file here.
https://jaspervdj.be/posts/2010-03-01-my-tron-bot.html
CC-MAIN-2022-33
refinedweb
3,113
62.48
I have 2 txt files with different strings and numbers in them splitted with ; Now I need to subtract the ((number on position 2 in file1) - (number on position 25 in file2)) = result Now I want to replace the (number on position 2 in file1) with the result. I tried my code below but it only appends the number in the end of the file and its not the result of the calculation which got appended. def calc f1 = File.open("./file1.txt", File::RDWR) f2 = File.open("./file2.txt", File::RDWR) f1.flock(File::LOCK_EX) f2.flock(File::LOCK_EX) f1.each.zip(f2.each).each do |line, line2| bg = line.split(";").compact.collect(&:strip) bd = line2.split(";").compact.collect(&:strip) n = bd[2].to_i - bg[25].to_i f2.print bd[2] << n #puts "#{n}" Only for testing end f1.flock(File::LOCK_UN) f2.flock(File::LOCK_UN) f1.close && f2.close end
http://www.howtobuildsoftware.com/index.php/how-do/sFa/ruby-file-file-io-append-ruby-how-to-subtract-numbers-of-two-files-and-save-the-result-in-one-of-them-on-a-specified-position
CC-MAIN-2018-47
refinedweb
152
58.99
Custom actions provide the easy way of implementing server code that is being invoked by dynamic AJAX user interface of Data Aquarium Framework applications. No AJAX or ASP.NET programming experience is required. Suppose you have generated ASP.NET application based on Data Aquarium Framework with Code OnTime Generator for the Northwind database. If you run this web application and select Products in the drop down at the top of the page, and click on Actions menu option then a view similar to the one displayed in the picture will be displayed. Let's write some custom server code, which will execute when the My Command action selected. We will learn how to implement custom server code that will validate the entered data just before it is submitted to the database. We will also write server code to invoke the client-side script to interact with the AJAX views. Open your project in Visual Studio 2008 or Visual Web Developer Express 2008, expand Controllers folder, and open Products.xml data controller descriptor. Scroll to the bottom of the file and find custom command with MyCommand argument. This is the only entry, which is needed to have your custom command displayed on the action bar of the views managed by the Products data controller. Set up your own custom header text and description to reflect the purpose of the action. You can create additional action groups with the scope of ActionBar, Form, and Grid. The ActionBar action are displayed as menu option in the action bar. The Form action is displayed as a button in the data entry form. The Grid action will be displayed as an option in the grid view row context menu, which pops up when you click on the drop down arrow next to the value in the first column of the row. You can additional supply the context of previously executed command via whenLastCommandName attribute. For example, you might want certain actions to be available only when user has started editing the record, or when a new record is being created. You can also specify user roles to automatically show/hide actions based on users security credentials. This feature is integrated with ASP.NET security infrastructure and required no coding at all. Add a class to the App_Code folder of your application. Specify that you are using Northwind.Data namespace if you have entered Northwind as a default namespace when you have generated the code with Code OnTime Generator. Also specify that the class will inherit it's functionality from the ActionHandlerBase class that is a part of Data Aquarium Framework. Now we need to hook the custom action handler Class1 into the Data Aquarium Framework. Scroll to the top of the Products data controller file and enter the class name as a value of the actionHandlerType attribute as show in the picture. Override the ExecuteAction method in Class1: protected override void ExecuteAction(ActionArgs args, ActionResult result) { if (args.CommandName == "Custom" && args.CommandArgument == "MyCommand") result.NavigateUrl = " } If the action is selected in the form view then the current record information is provided in the action argument values. If your action has been specified in the scope of the grid then the current row field values are passed alone to your code. Use command name and argument to process multiple actions within the same action handler. Last command name can also be of use if you need to further alter the action behavior. Let's add some data validation code to prevent users from making changes to some sensitive information that we care about. For example, we will raise an exception if a user is trying to change the Chai product. Override the BeforeSqlAction method in the Class1. Notice that we are using Linq to query the values of the action arguments. protected override void BeforeSqlAction(ActionArgs args, ActionResult result) { if (args.CommandName == "Update") { string s = (string)( from c in args.Values where c.Name == "ProductName" select c.OldValue).First(); if (s == "Chai") throw new Exception("Can't edit Chai"); } } Locate the Chai record in the Products screen, change any field of the record, and select Save in the action bar, in the grid context menu, or in the form edit view. The following error message is displayed at the top of the screen to the end user. If an exception is raised before the execution of the SQL command then the SQL command is canceled. You can also cancel command by invoking the Cancel method of result parameter. This may be useful if you would like to execute your own data update instead of relying on the automatic dynamic SQL generation feature of Data Aquarium Framework. You can use Values property of the action argument and inspect individual fields via their Name, Value, NewValue, and OldValue properties. You can supply a custom client-side Java Script expression, which will be evaluated upon the completion of execution of your server code. This works for both custom and data manipulation actions. Suppose you want to allow uses to enter multiple products with the minimum number of clicks. When user selects the New action from the action bar and enters the first product you want the data view to stay in the New Products form until the uses decides to cancel. Enter the following method in the Class1. protected override void AfterSqlAction(ActionArgs args, ActionResult result) { if (args.CommandName == "Insert") { result.ClientScript = String.Format(@" alert('Product {0} has been created.'); $find('{1}').executeCommand( {{commandName:'New',commandArgument: 'createForm1'}});", (from c in args.Values where c.Name == "ProductName" select c.NewValue).First(), args.ContextKey); } } Our custom code will kick in whenever the Insert command is executed and will assign a Java Script expression to be evaluated when the result is returned to the client-side data view. The alert method call will display a confirmation telling the user that the record has been created indeed. The $find method call will find the client side Ajax component identified by ContextKey passed in the action arguments. Method executeCommand belongs to the DataView JavaScript class and will execute the client side command New, which will result in the createForm1 view to be displayed again. From the user perspective the New Products form simply remains in place when the record creation confirmation is dismissed. Exceptionally flexible server-side programming support in applications based on Data Aquarium Framework provides great number of customization options to programmers with any degree of experience with ASP.NET and AJAX. It allows real separation of the business logic from the presentation. Your web application sends asynchronous JSON requests to the stateless server application that are being processed with all the power of the Microsoft.NET framework without any need to know ASP.NET or AJAX programming techniques. Start being productive now.
https://codeontime.com/blog/2008/07/creating-custom-action-handlers-in-data
CC-MAIN-2022-21
refinedweb
1,131
56.35
These ElasticsearchIntegrationTest. As soon as you inherit, there is no need for you to start any elasticsearch nodes manually in your test anymore, though you might need to ensure that at least a certain number of nodes is up. The number of shards used for indices created during integration tests is randomized between 1 and 10 unless overwritten upon index creation via index settings. Rule of thumb is not to specify the number of shards unless needed, so that each test will use a different one all the time. There are a couple of helper methods in ElasticsearchIntegrationTest, which will make your tests shorter and more concise. The TestCluster class is the heart of the cluster functionality in a randomized test and allows you to configure a specific setting or replay certain types of outages to check, how your custom code reacts. In order to execute any actions, you have to use a client. You can use the ElasticsearchIntegrationTest.client() method to get back a random client. This client can be a TransportClient or a NodeClient - and usually you do not need to care as long as the action gets executed. There are several more methods for client selection inside of the TestCluster class, which can be accessed using the ElasticsearchIntegrationTest.cluster()Nodes=1) public class CustomSuggesterSearchTests extends ElasticsearchIntegrationTest { // ... tests go here } The above sample configures the test to use a new cluster for each test method. The default scope is SUITE (one cluster for all test methods in the test). The numNodes settings allows you to only start a certain number of nodes, which can speed up test execution, as starting a new node is a costly and time consuming operation and might not be needed for this test. nodeSettings() method from the ElasticsearchIntegrationTest class and change the cluster scope to SUITE. @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.settingsBuilder() .put("plugin.types", CustomSuggesterPlugin.class.getName()) .put(super.nodeSettings(nodeOrdinal)).build(); }
https://www.elastic.co/guide/en/elasticsearch/reference/1.7/integration-tests.html
CC-MAIN-2017-26
refinedweb
323
51.89
Layouts in ScrollViews Hello, I have some Problems using Layouts in Scrollviews, probably more on how ScrollViews in general work. My Layout always has the width and height of 0, although the ScrollView has something around 1300x700 (which is my Laptop screen - some margins ...) import QtQuick 2.10 import QtQuick.Controls 2.3 import QtQuick.Layouts 1.3 ScrollView { id: root anchors.fill: parent RowLayout { anchors.fill: parent Rectangle { Layout.fillWidth: true Layout.fillHeight: true color: "blue" } Component.onCompleted: { console.log(width); console.log(height) } } Component.onCompleted: { console.log(root.width); console.log(root.height) } } It would be great if anyone could explain me, why the width and height are 0 and therefore the rectangle does not fill the screen. Just to explain my goal. In the End, there should be two Components inside the ScrollView next to each other filling the screen width, but having only the height as necessary (implicit height). -> A Textarea with lineNumbers ... I tried several possibilities and one worked, but it wasn't perfect. In General, the difficulty is that the TextArea has to be attached to a Flickable or directly inside a ScrollView for autoscroll and things like this. From the docs: " A TextArea that is placed inside a ScrollView does the following: Sets the content size automatically Ensures that the background decoration stays in place Clips the content " -> I don't know how to achieve this behaviour if there are lineNumbers next to the Textarea (which of course should scroll automatically too). Thanks for any advice! Greetings Leon
https://forum.qt.io/topic/90409/layouts-in-scrollviews
CC-MAIN-2022-27
refinedweb
255
58.38
Hello! I have a table on my dashboard. There are some fields on this table with are partially filled, And I would want to let the user fill them manually. For this case I thought about storing the manually edited data on a lookup table (csv), join those fields to my search, and present it in my table. I tried to think about a way of letting the user edit those fields, so I setted a drilldown, which set a token with the selected row key, and an input, in which the user can edit the fields values. After filling those values, the user clicks on submit input button, and the data is written to the lookup table, using a hidden search on the page (which use outputlookup) Here is an example of how it looks like: The problem is - I can't update the values on the table after clicking on submit, what makes this a bad solution to my problem. (Well, I can by re-running the query, but I don't want to search again and again every time the user changes a single row (+ splunk doesn't let me re run search on submit unless there is a change in the query, and there isn't)). I hope someone have a solution or even a better way to solve my problem. Thanks! You need to have your search end in something like this: ... | lookup IPtoVersion.csv IP OUTPUT Version AS VersionFromLookup | eval Version = coalesce(Version, VersionFromLookup) | fields - VersionFromLookup Then you have to allow people edit this lookup file IPtoVersion.csv. I suggest you use the Lookup Editor App for this. Here are the steps to move lookup Editor Related code to your own Splunk App: 1) Copy Lookup Editor's static folder contents (has sub folders) from $SPLUNK_HOMEetc/apps/lookup_editor/appserver/static to your app $SPLUNK_HOMEetc/apps/<yourAppName>/appserver/static 2) Similarly copy controller folder over to your app i.e. $SPLUNK_HOMEetc/apps/lookup_editor/appserver/controller to your app $SPLUNK_HOMEetc/apps/<yourAppName>/appserver/controller (PS: I have not checked whether it is absolutely necessary to copy this over or not) 3) Create a new dashboard in your App with Lookup Edit dashboard code from Lookup Editor App. Following are the changes I have made i) hideEdit="false" so that we can easily edit the dashboard ii) Set the token/form token for owner (like admin), Splunk app name (like search), lookup file name (like test.csv) and lookup file type will be csv. iii) CSS Override to reduce height of panel to display CSV and Change position of Submit Button. 4) Restart Splunk or refresh/bump Splunk <dashboard script="lookup_edit.js" stylesheet="lookup_edit.css" hideEdit="false"> <label>My Dashboard with imported Lookup Edit</label> <init> <set token="form.owner">yourOwnerName</set> <set token="form.namespace">yourSplunkAppName</set> <set token="form.lookup">yourCSVFileName.csv</set> <set token="form.type">csv</set> <set token="owner">yourOwnerName</set> <set token="namespace">yourSplunkAppName</set> <set token="lookup">yourCSVFileName.csv</set> <set token="type">csv</set> </init> <row depends="$alwaysHideCSS$"> <panel> <html> <style> button#save{ margin-left: 10px !important; position: absolute !important; top: -15px !important; } .row-fluid .span2:first-child{ visibility:hidden !important; } #lookup-table{ height:250px !important; } </style> </html> </panel> </row> <row> <html> <div id="lookups_editor"></div> </html> </row> </dashboard> hi @niketnilay , @woodcock , @kamlesh_vaghela I need your help,In the above xml code i donn't want hard to hard code csv ,appaname in init tokens. I want csv ,appname which csv i have imported pls help for this .. @harishalipaka I am not sure how you can dynamically link lookup file with KV Store? However, you can pull names for either one using REST APIs like the following: | rest /services/data/lookup-table-files | rest /services/kvstore/ You them in single or multiple Dropdown to generate your Search query instead of static search query. @niketnilay I got this what i want but here am using two buttons shall i do it with one button.. And it is for only one csv and one lookup i want to do it for any csv and any kv_store . @niketnilay require.config({ paths: { lookup_edit: "../app/lookup_editor/js/views/LookupEditView" } }); require([ "jquery", "underscore", "backbone", "splunkjs/mvc/searchmanager", "lookup_edit", "splunkjs/mvc/simplexml/ready!" ], function( $, _, Backbone, SearchManager, LookupEditView ) { var lookupEditView = new LookupEditView({ el: $('#lookups_editor') }); lookupEditView.render(); var mysearch = new SearchManager({ id: "mysearch", autostart: "false", search: "| inputlookup harish.csv |outputlookup hari_kvstore_collection" }); $("#run_query").on("click", function (){ var ok = confirm("Yahoo!"); if ( ok==true ){ mysearch.startSearch(); alert("ran query"); } else { alert('user did not click ok!'); } }); }); @omerl based on your use case, best option for you is to use KV Store so that you can modify only the value required. Refer to the link provided to see an example of KV Store Implementation. This will create kind of a form for your Users to correct Version of specific IP. You second preference could be the Lookup Editor App , which will allow you to edit CSV file. I am attaching a third option using Simple XML. There is a Dropdown for IP Address to be pulled from CSV file using inputlookup command from lookup file ipaddress_splunkversion.csv. You can then use text box to update the value of a particular IP which gets updated back to the lookup file using outputlookup command. PS: Tabbing out of TextBox updates the lookup. Please try one of the options and confirm! <form> <label>Lookup File Editing</label> <fieldset submitButton="false"> <input type="dropdown" token="textIPAddress"> <label>IP Address</label> <fieldForLabel>IPAddress</fieldForLabel> <fieldForValue>IPAddress</fieldForValue> <search> <query>| inputlookup ipaddress_splunkversion.csv | fields IPAddress</query> </search> <change> <eval token="tokIPAddress">if(len(trim($value$))>0,$value$,"")</eval> <unset token="textSplunkVersion"></unset> <unset token="form.textSplunkVersion"></unset> <set token="tokSplunkVersion"></set> </change> </input> <input type="text" token="textSplunkVersion"> <label>Splunk Version</label> <change> <condition match="tokIPAddress="""> <!-- IP Address Needs to be changed first --> <set token="tokSplunkVersion"></set> </condition> <condition> <eval token="tokSplunkVersion">if(len(trim($value$))>0,$value$,"")</eval> </condition> </change> </input> </fieldset> <row> <panel> <table> <search> <query>| inputlookup ipaddress_splunkversion.csv | evalprogressbar</option> </table> </panel> </row> </form> Thank you for the suggestions! I think that what I'm trying to achieve is not what splunk was built for. What I need is more like Excel, where I can edit the data right on the table, without the need of an external inputs form and without re running a search on each edit. I am familiar with the lookup editor app, but I wanted to work on a regular dashboard, using splunk's table (better UI and UX). Thanks anyway! @omerl, Using KV Store Implementation you can build an HTML Dashboard in Splunk which can give you exact features of Excel File Editor, however, that would be significant amount of coding. The developer should know Splunk Web Framework and Splunk App Development along with handsome knowledge of HTML/CSS/JS. Alternatively, if you want you can move the static files for Lookup Editor App to your own Splunk App and then create a Dashboard for editing specific lookup file using form tokens set inside the dashboard. Let me document the steps required for this once I get the chance. Yes, I thought that would be the only solution. As a developer, I don't really like the idea of significant amount of coding on splunk, as it is harder to maintain and less reuseable. Do you think that the Excel layout of the Lookup Editor can fit a dashboard panel? I think this Excel layout merged with splunk table visualization would be the best. Thank you! I slightly disagree, as a developer, I want to code as much as possible to create reusable component. Imaging Lookup editor is actually based on KV Store which has 21K + downloads. So definitely re-usability depends on how well we code. Meanwhile refer to my other answer I have updated on steps to migrate lookup editor to your Splunk App and then dashboard elements required to have Lookup Editor pull a csv file for editing and display as a panel on top. Please try out and confirm. Hello, May be can help, <form> <label>Edit_Element_Tabl</label> <fieldset submitButton="true"> <input type="text" token="ipAdresses" searchWhenChanged="false"> <label>ipAdresses</label> </input> <input type="text" token="SplunkVersion" searchWhenChanged="false"> <label>SplunkVersion</label> </input> </fieldset> <row> <panel> <table> <search> <query> | inputlookup ipSplunkVersion.csv | appendpipe[ | eval100</option> <option name="dataOverlayMode">none</option> <option name="drilldown">none</option> <option name="percentagesRow">false</option> <option name="rowNumbers">false</option> <option name="totalsRow">false</option> <option name="wrap">true</option> </table> </panel> </row> </form> Regards Youssef Thanks, This solution only lets me edit one row at a time, and then I have to re run the whole search. The problem with this solution is that I want to append the lookups values to an existing search, which means every time I edit a row, I have to wait for the new search results (my table presents indexed data, where some of the fields should be added manually, and those manually added fields values is what I'm trying to achieve by the lookup). @omerl, you would need to add more details. What do you imply by "partially filled"? You have two fields in the example, can the users fill in data for both or are they supposed to modify the Splunk Version alone? Can they fill in new record i.e. new IP Address and corresponding Splunk Version? Can the lookup have duplicates? Is IP Address going to be unique? Your question seems to be with regards to KV Store Implementation rather than csv lookup based solution. Refer to the comparison between KV Store and CSV Lookup You should also check out the Lookup File Editor app on Splunkbase. If KV Store or Lookup File Editor would not cater to your needs, do provide the details for the questions above and we would be happy to assist. Hey, As the example shows, I have 2 fields - IP and Version. Lets take the IP as the key of the table, and say that the Version colomn is partially filled - as in some of the rows are blank. The data I have comes from an index, but the source of this index does not have the data about all the IPs, which means I need a way to let the user complete the missing data manually. What is, in your opinion, the (hopefully best) way to achieve that? Thanks
https://community.splunk.com/t5/Dashboards-Visualizations/How-to-create-editable-table-on-dashboard/m-p/375621/highlight/true
CC-MAIN-2020-50
refinedweb
1,739
53.21
The following sources include a class, a function and a template. %%python code=''' #include <iostream> #include <typeinfo> /// A trivial class class A { public: A(); ~A(); }; /// A trivial function int CountCharacters(const std::string s); /// A trivial template template<class T> class B { public: B() { std::cout << "The typeid name of the template argument is " << typeid(T).name() << std::endl; } }; ''' with open('myLibrary.h','w') as f_out: f_out.write(code) %%python code=''' #include "myLibrary.h" A::A() { std::cout << "This is the constructor of A" << std::endl; } A::~A() { std::cout << "This is the destructor of A" << std::endl; } int CountCharacters(const std::string s) { return s.size(); } ''' with open('myLibrary.cc','w') as f_out: f_out.write(code) %%bash g++ -o libmyLibrary.so -shared -fPIC myLibrary.cc %%bash ls *so libmyLibrary.so So far, so good. Now we'll see how easy it is to use this library from within Python thanks to ROOT. In order to interact with the C++ entities contained in the library, we need to carry out to tasks: In code: import ROOT ROOT.gInterpreter.ProcessLine('#include "myLibrary.h"') ROOT.gSystem.Load("./libmyLibrary.so") Welcome to JupyROOT 6.07/07 0 That's it! We can now start exploring the content of the library. If you are wondering what a return code equal to 0 means, ROOT is telling us that the loading of the library happened without problems! a = ROOT.A() This is the constructor of A del a This is the destructor of A b_doublePtr = ROOT.B("double*")() The typeid name of the template argument is Pd Notice how the "impedence mismatch" generated by the concept of templates is ironed out in this case. The template parameter is specified as string in parentheses. ROOT.CountCharacters("This interactivity without bindings is really impressive.") 57 %%cpp A a; This is the constructor of A
http://nbviewer.jupyter.org/github/dpiparo/swanExamples/blob/master/notebooks/CppFromPython_pycpp.ipynb
CC-MAIN-2018-13
refinedweb
307
60.01
Hi, I'm having a problem assigning my mesh a collider. I've tweaked the CrumpleMesh scene (from the procedural examples package) and now have a flat plane that, on run time, is deformed by Perlin noise. I can assign the mesh itself a collider but this does not follow the contours of the deformed mesh (e.g. the hills and troughs). So- in light of the above, what would be the best way of assigning a collider to my mesh after it has been deformed (I imagine I need to add something to the script, but can't quite work out what). FYI, I'm using the C# version of the script: using UnityEngine; using System.Collections; using Graphics.Tools.Noise; using Graphics.Tools.Noise.Primitive; using Graphics.Tools.Noise.Filter; public class CrumpleMesh : MonoBehaviour { public float scale = 1f; public float speed = 0f; public bool recalculateNormals = false; private Vector3[] _baseVertices; private IModule3D _noise; //seed private Mesh _mesh; static private System.Random _rnd = new System.Random(999); /// <summary> /// /// </summary> void Start () { _mesh = GetComponent<MeshFilter>().mesh; }//end Start /// <summary> /// /// </summary> void Update () { if (_noise == null){ CreatePrimitive(); }//end if if (_baseVertices == null){ _baseVertices = _mesh.vertices; }//end if Vector3[] vertices = new Vector3[_baseVertices.Length]; float timex = Time.time * speed + 1.2584f; float timey = Time.time * speed + 40.6584f; float timez = Time.time * speed + 1.6518f; for (int i = 0; i < vertices.Length; i++){ Vector3 vertex = _baseVertices[i]; vertex.x += _noise.GetValue(timex + vertex.x, timex + vertex.y, timex + vertex.z) * scale; vertex.y += _noise.GetValue(timey + vertex.x, timey + vertex.y, timey + vertex.z) * scale; vertex.z += _noise.GetValue(timez + vertex.x, timez + vertex.y, timez + vertex.z) * scale; vertices[i] = vertex; }//end for _mesh.vertices = vertices; if(recalculateNormals){ _mesh.RecalculateNormals(); }//end if _mesh.RecalculateBounds(); }//end Update /// <summary> /// /// </summary> private void CreatePrimitive(){ SimplexPerlin primitive = new SimplexPerlin(); primitive.Seed = (int)(_rnd.Next() * _rnd.Next()); SinFractal filter = new SinFractal(); filter.OctaveCount = 10f; filter.Primitive3D = primitive; _noise = primitive; }//end CreatePrimitive }//end class Thank you for any responses. Answer by Eric5h5 · Dec 15, 2011 at 12:13 AM Copy the generated mesh to the meshcollider's mesh. i.e., GetComponent<MeshCollider>().mesh = _mesh;. Keep in mind that updating a mesh collider is very slow, and not actually something you want to do in Update. GetComponent<MeshCollider>().mesh = _mesh; This is what I was looking for-. Trouble with Inaccurate Mesh Collider 0 Answers Multiple Cars not working 1 Answer Save previous state of mesh procedurally 1 Answer Generate a highpoly sphere with mesh collider procedurally 2 Answers How to subdivide a single face on a mesh? 0 Answers
http://answers.unity3d.com/questions/195336/mesh-collider-on-procedurally-generated-mesh.html
CC-MAIN-2016-18
refinedweb
430
53.98
Official blog for the Windows Live Digital Memories Experience team. - pixblog PingBack from Actually got the update dialog in gallery today, but when I followed all the links to Nikon, the page was empty and said the download was not yet available. Good news... it looks like Nikon has issued the patch to fix tagging of NEF's in Vista. > Good news... it looks like Nikon has issued the patch to fix tagging of NEF's in Vista. > Files modified by Nikon's new 1.01 NEF codec are still broken for me in Photoshop Bridge CS2. Details: Open D70 NEF file in Vista's Windows Photo Gallery. Add a tag. NEF is no longer properly displayed by Photoshop Bridge CS2 v. 1.04. Opening with Adobe Camera RAW 3.2 or 3.7 works OK. OK in Adobe Lightroom 1.0. OK in Photoshop Bridge CS3 Beta 2. OK in Photoshop CS3 Beta (ACR 4.0x168). I've installed this Codec without installation errors on Windows XP SP2. I have a small C# program that converts image files to compressed TIFF. When the program creates a bitmap from the Nikon .NEF file, the bitmap dimensions are very wrong. First, the code ... using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Imaging; class Example_SetJPEGQuality { public static void Main(string[] args) { for (int i = 0; i < args.Length; i++) { Bitmap myBitmap; ImageCodecInfo myImageCodecInfo; Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; // MessageBox.Show("Number of args =" + args.Length); // MessageBox.Show("First arg is " + args[0]); string filename = args[i]; string TiffFilename = filename.Substring(0, filename.LastIndexOf(".")) + "_lzw.tiff"; string ext = filename.Substring(filename.LastIndexOf(".") + 1); if (!ext.ToLower().Equals("tiff")) { // Create a Bitmap object based on a BMP file. myBitmap = new Bitmap(filename); // Get an ImageCodecInfo object that represents the TIFF codec. myImageCodecInfo = GetEncoderInfo("image/tiff"); // Create an Encoder object based on the GUID // for the Quality parameter category. myEncoder = Encoder.Compression; // Create an EncoderParameters object. // An EncoderParameters object has an array of EncoderParameter // objects. In this case, there are two // EncoderParameter object in the array. myEncoderParameters = new EncoderParameters(2); // Save the bitmap as a TIFF file with LZW compression. myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionLZW); myEncoderParameters.Param[0] = myEncoderParameter; // Save the bitmap as a TIFF file with 24bit color. myEncoder = Encoder.ColorDepth; myEncoderParameter = new EncoderParameter(myEncoder, 24L); myEncoderParameters.Param[1] = myEncoderParameter; myBitmap.Save(TiffFilename, myImageCodecInfo, myEncoderParameters); } else MessageBox.Show("Invalid file type - must not be .TIFF"); } }; } This program is run against the file DSCN0001.NEF whose dimensions are 2576 x 1924 according the the Windows Photo Viewer, yet the variable myBitmap receives an image whose dimensions are 160 x 120. Anyone else see this? -- Peter Nikon has posted an updated version of its RAW codec for Windows Vista. Nikon and Microsoft had received Hi pquirk ! I've tried your program, but it didn't work at me. OK I see the problem, it's work! pQuirk - I have noticed the same problem while trying to read nef files into the bitmap object. Did you find a solution to this problem? I am also trying to read the meta data from the file but without success.
http://blogs.msdn.com/pix/archive/2007/02/12/nikon-raw-codec.aspx
crawl-002
refinedweb
527
53.68
Atom Hopper: An ATOM Server Written in Java Atom Hopper: An ATOM Server Written in Java Join the DZone community and get the full member experience.Join For Free Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat. Atom Hopper is a Java based ATOM publishing server based on Apache Abdera. You can read some of my previous articles here and the full source code can be found here as well as the up to date wiki. Today I’m going to discuss some of the new features that have been added and what is happening in general. As of the date of this article we are actively testing the latest build of Atom Hopper which we are calling a release candidate at this point. As you can tell by the release notes we’ve been incrementally fixing bugs and adding features. Whats New? - We moved the configuration files application-context.xml (used for the Hibernate settings) and the atom-server.cfg.xml (used mostly for namespaces and feeds) to a common folder: /etc/atomhopper - Bugs involving HTTP/HTTPS configuration, servlet URL pattern and feed names were fixed - We completed some initial benchmarks that can be seen here - There are instructions now on how to configure Atom Hopper to use multiple database servers per feed. In fact, if you know a little about Hibernate configuration then you can see that using the default data adapter with Atom Hopper gives you a lot of flexibility. - There has been a lot of work to get the documentation fully updated and migrated over from a private wiki where a lot of information originally existed - A lot of work has gone into the RPM build system in order to allow for easier deployments of Atom Hopper. These settings are in the POM and you can branch the source code and modify the settings to suit your environment When you’re setting up Atom Hopper make sure those files exist in the /etc/atomhopper folder and that the user running Atom Hopper (most likely the Tomcat user) has access to that folder What does the future hold? There are several things on the list for Atom Hopper, I won’t discuss everything as we have a full year planned out in upcoming work but I will touch on a couple things. We are looking at integrating a NoSQL backend, possibly MongoDB or Cassandra. Atom Hopper ships with a default data adapter that uses Hibernate and has been tested with MySQL, PostgreSQL, and H2. The default data adapter can easily be swapped out for another one that supports a different datastore. A second feature we are working on is getting the log file to go to a standard location which will be: /var/log/atomhopper This will keep the Atom Hopper log messages from going into places like Apache Tomcat’s catalina.out file. The Atom Hopper 1.0 release will be coming up shortly. Right now we have Atom Hopper undergoing final QA and we are working to address any remaining issues. From Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/atom-hopper-atom-server
CC-MAIN-2018-34
refinedweb
560
58.32
Swift UI is newly supported from XCode11. - View creation is by Code - Can preview with XCode for each View Start Swift UI Project We need to select Swift UI support when we create App project Default files Recommend Directory Structure From Apple Samples, we can consider following directory structure Project |- Models : Data Model(Struct, Class) |- Supporting Views : SubViews Component Level View |- Resources : Same as general iOS app(Save resources) |- AppDelegate.swift Let’s check default codes SceneDelegate.swift This is part of codes // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } Create ContentView object and registered ContentView.swift import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } import SwiftUI is for Swift UI. This is required View is struct. body is actual UI code, this contains all View code in View. In this example, add Text ContentView_Previews is for Preview not this code, you can see preview “Resume” button You can see preview This is an example コメント
https://daiji110.com/2020/06/07/swift-ui-get-started/
CC-MAIN-2021-43
refinedweb
203
58.58
In this PyGame and Python programming tutorial video, we cover how to draw shapes with PyGame's built in drawing functionality. We can do things like draw specific pixels, lines, circles, rectangles, and any polygon we want by simply specifying the points to draw between. Let's get started! import pygame pygame.init() white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) gameDisplay = pygame.display.set_mode((800,600)) gameDisplay.fill(black) Typical stuff above, now let's cover what would be used to draw a pixel: pixAr = pygame.PixelArray(gameDisplay) pixAr[10][20] = green Alright, so what have we done above? What we're doing is assigning the entire pixel array to a value, referencing it using pygame.PixelArray. So what this function does is it returns the pixel array of the specified surface (which is the entire display in our case). Then, we're able to modify it. So, we specify pixAr[10][20], which means the pixel residing at (10,20), then we're able to re-assign it. In our case, we call it green. pygame.draw.line(gameDisplay, blue, (100,200), (300,450),5) Drawing lines, above, is easy enough. The function just asks where do we want to draw it, what color do we want it, and then we specify the two coordinate pairs that we want to draw a line between. pygame.draw.rect(gameDisplay, red, (400,400,50,25)) We've already extensively covered the drawing of rectangles in this series, but this specific "drawing things" tutorial wouldn't be complete without it. This function asks where to draw, what color, and then asks for a final tuple that contains: the top right x and y, followed by width, then height. pygame.draw.circle(gameDisplay, white, (150,150), 75) Here we draw a circle. This function asks where to draw, what color, what is the center point of the circle, and what is the radius. There is another parameter that you can add which is width. pygame.draw.polygon(gameDisplay, green, ((25,75),(76,125),(250,375),(400,25),(60,540))) Finally, we have polygons. This function asks where to draw, what color, and then asks for a long tuple, of tuples, containing the points of the polygon. Now for some canned stuff to make our game actually run: (if you don't understand this, revisit some of the earlier tutorials..) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() pygame.display.update() There are a few other drawing functions, though these are the ones that I find myself actually using. You can find more in the PyGame documentation. I may also cover some of the others later on.
https://pythonprogramming.net/pygame-drawing-shapes-objects/
CC-MAIN-2019-26
refinedweb
464
74.08
Doodling is fun with the open source DoodlePad for Windows Phone!. ... Full Source The full source code to the game is publicly available on BitBucket: - A single file playable script version is also available on F# Snippets: - One interesting thing was how it scaled. For example, here's the app snapped, where it remained fully playable; Here's a snap of the Solution, showing off how F# and C# were mixed, using a Portable Library project. One of the meta items in the project was how F# was used to generate the PacMan logo's/images. #if INTERACTIVE #r "System.Drawing.dll" #endif open System open System.IO open System.Drawing open System.Drawing.Imaging let drawPacman (bitmap:Bitmap, x:int, y:int, size:int) = let width, height = bitmap.Width, bitmap.Height let graphics = Graphics.FromImage(bitmap) do graphics.Clear(Color.Black) graphics.FillEllipse(Brushes.Yellow,x,y,size,size) let points = let right = x + size [|right,y + size/2 - size/4;right,y + size/2 + size/4; x + size/2, y + size/2|] |> Array.map (fun (x,y) -> PointF(float32 x,float32 y)) graphics.FillPolygon(Brushes.Black,points) open System.Windows.Forms let show (bitmap:Bitmap) = let form = new Form() let box = new PictureBox(Image = bitmap) box.Width <- bitmap.Width box.Height <- bitmap.Height form.Width <- bitmap.Width form.Height <- bitmap.Height + 32 form.Controls.Add(box) form.Show() //let root = @"C:\Users\Moon\Documents\Visual Studio 2010\Projects\pacman\PacMan.Xaml\Assets\" let root = @"C:\Users\Phil\Documents\Visual Studio 2012\Projects\pacman\PacMan.Xaml\Assets\" do // Logo let path =root + "Logo.png" let bitmap = new Bitmap(path) drawPacman(bitmap, 42, 38, 64) bitmap.Save("PacMan_Logo.png", ImageFormat.Png) do // SmallLogo let path = root + "SmallLogo.png" let bitmap = new Bitmap(path) drawPacman(bitmap, 3, 3, 24) bitmap.Save("PacMan_SmallLogo.png", ImageFormat.Png) do // StoreLogo let path = root + "StoreLogo.png" let bitmap = new Bitmap(path) drawPacman(bitmap, 5, 5, 40) bitmap.Save("PacMan_StoreLogo.png", ImageFormat.Png) do // SplashScreen let path = root + "SplashScreen.png" let bitmap = new Bitmap(path) drawPacman(bitmap, 200, 42, 214) bitmap.Save("PacMan_SplashScreen.png", ImageFormat.Png) do // Icon 16x16 let bitmap = new Bitmap(16,16) drawPacman(bitmap, 1, 1, 14) bitmap.Save("Icon16x16.png", ImageFormat.Png) do // Icon 32x32 let bitmap = new Bitmap(32,32) drawPacman(bitmap, 2, 2, 28) bitmap.Save("Icon32x32.png", ImageFormat.Png) do // Icon 48x48 let bitmap = new Bitmap(48,48) drawPacman(bitmap, 3, 3, 42) bitmap.Save("Icon48x48.png", ImageFormat.Png) do // Icon 128x128 let bitmap = new Bitmap(128,128) drawPacman(bitmap, 8, 8, 112) bitmap.Save("Icon128x128.png", ImageFormat.Png) show bitmap Okay, what about for the non-Metro dev's? Well there's VS2010/SilverLight, Windows Phone and XAML fun for you too! If you're looking to expand your development language repertoire and looking for fun way to do it, looking for examples of how to mix and match C# and F#, looking for examples of F# and SilverLight or finally F# in a Metro world, this project has all that and more... Oldies, but goldies...
https://channel9.msdn.com/coding4fun/blog/PacMetroMan-Recreating-PacMan-for-Metro-with-a-little-help-from-F
CC-MAIN-2017-51
refinedweb
508
52.05
This article will introduce four different ways you can use HTTP handlers. The end result is the same, but I hope you will also find that by exploring different ways of using them you will also gain a better understanding of how things work. I will also show a typical error when using HTTP handlers from assemblies that are stored in the Global Assembly Cache (GAC). When to use HTTP handlers? I commonly use HTTP handlers to serve pictures from Web applications. Why would I need that? Pictures are often manipulated before being sent to the client. Such manipulation can include adding a watermark, resizing or applying other image transformations and manipulations. By applying these dynamically, I do not need to modify the original images: the application dynamically applies these modifications, and sends the modified content to the client. A good example could be generating thumbnails for an image gallery. Why bother doing this beforehand, when your application can just as well do it dynamically. Of course usually the result can be cached, to improve performance - all transformations in an image gallery for example can be cached, because they will be the same, regardless of visitor. But it is not only image manipulation that can be achieved. If you have your images stored in a database, those too can be published in a web application by using HTTP handlers. And handlers are not restricted to images, any content can be served using them. In fact (in case you do not know) the way ASP.NET serves ASPX pages is by the way of HTTP handlers. The Page class itself implements IHttpHandler that gets loaded and called for all pages with the .ASPX extension. The Greetings Picture Before we begin with the actual handlers, I want to show a very simple image manipulation class. What this does is create a new 640x120 sized bitmap with some greeting text written into it. It clears the background with white and writes in black Arial letters onto the surface. This is a very simple example, but you could do any image manipulation here. using System.Drawing; using System.Drawing.Imaging; namespace MyLibrary { public static class ImageBuilder { public static Image CreateGreeting(string name) { Bitmap bmp = new Bitmap(640, 120, PixelFormat.Format32bppRgb); using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(Brushes.White, new Rectangle(0, 0, 640, 120)); g.DrawString(string.Format("Hello {0}!", name), new Font( "Arial", 28 ), Brushes.Black, new Point(10, 10)); } return bmp; } } } This piece of code will be used by all of the examples I will present. To begin with, create a new ASP.NET Web Application (project), and add the above code to the project (ImageBuilder.cs). Also note that I have tested the examples with VS 2010 and .NET 4.0. The traditional code behind .ASHX The easiest and fastest way to create an HTTP handler is by selecting Generic Handler to be added to the project. This will create an .ASHX file and an .ASHX.CS file. Whenever you request the .ASHX file, the code-behind file will be invoked. However, in this case there are no controls, there are no predetermined content - you are in charge what you return. Normally you override the ProcessRequest() method, and return any content from within there. Now that you have create your Web Application project (where you saved ImageBuilder, see above) add a new Generic Handler to it. Call it Handler1. This will add Handler1.ashx and Handler1.ashx.cs. You do not need to modify the ASHX file for now (we will get to its contents later). Now add the following code to the code behind file: using System.Drawing; using System.Drawing.Imaging; using System.Web; namespace HttpHandlerTesting { public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; string name = "Anonymous"; if (context.Request.QueryString["Name"] != null ) { name = context.Request.QueryString["Name"]; } Image img = MyLibrary.ImageBuilder.CreateGreeting(name); img.Save(context.Response.OutputStream, ImageFormat.Jpeg); } public bool IsReusable { get { return false; } } } } AS you can see the class is derived from IHttpHandler. I will ignore the IsReusable property here, you can read more about that in MSDN. This code will generate an image with a greeting to either "Anonymous" or to the name specified in the QueryString parameter Name. It will then return this image in the response. Notice that the ContentType of the response is set manually to the MIME type of JPG images. This is needed so the browser can interpret the response. After this is done, the image is written to the [n]OutputStream of the response, thus sending the JPG data back to the client. Try invoking it by starting your application and navigating to Handler1.ashx?Name=Lenard. This will return an image with the text Hello Lenard!. (because the image contains white background and black text, it might not be obvious it is an image. Feel free to use a tool like Fiddler to verify it is indeed a JPG file! Alternatively, you could try to draw colorful lines and shapes in the background, but I leave that exercise to you As you can see we only needed to add some files to the project to have a very simple handler. But there are more ways to use handlers, so let us process to Step #2. A single .ASHX file So now that you saw the code-behind version, lets merge the two files into a single file. But before we get started, lets examine the ASHX file. Open the Handler1.ashx file. Simply double clicking might not work, right click on it and select view markup in this case. <%@ WebHandler Language="C#" CodeBehind="Handler1.ashx.cs" Class="HttpHandlerTesting.Handler1" %> The ASHX file is very similar to that of an .ASPX or .ASCX file. But it does not declare a Page, it declares a WebHandler. The file is empty except for this one line, which declares the class to use and the code behind file where the class can be found. Now to make a single file handler, add Handler2.ashx to the project. Maybe the easiest way to achieve this is to select to add a Text document to the project in Visual Studio, and then type Handler2.ashx as the name. <%@ WebHandler Language="C#" Class="Handler2" %> public class Handler2 : System.Web.IHttpHandler { public void ProcessRequest(System.Web.HttpContext context) { context.Response.ContentType = "image/jpeg"; string name = "Anonymous"; if (context.Request.QueryString["Name"] != null ) { name = context.Request.QueryString["Name"]; } System.Drawing.Image img = MyLibrary.ImageBuilder.CreateGreeting(name); img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } public bool IsReusable { get { return false; } } } It is really not that different from the original version. We simply removed the CodeBehind attribute and included the class definition in the body of the ASHX file. Is this solution better than the first? I will let you decide that Code in another assembly A more complex system could include the handler logic (the code) in another assembly, separate from the actual Web pages. In this case you can still use the .ASHX file to register your handler. I find this easier to do than getting dirty and registering your handler in the Web.config file - rest assured the next section will show you how to to that. To proceed, add a Class Library to the Solution, we will call it MyLibrary. You will have to move ImageBuilder to this new library. Then, proceed to add a new C# class to this new library, which we will call Handler3: using System.Drawing.Imaging; using System.Web; namespace MyLibrary { public class Handler3 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; string name = "Anonymous"; if (context.Request.QueryString["Name"] != null) { name = context.Request.QueryString["Name"]; } System.Drawing.Image img = ImageBuilder.CreateGreeting(name); img.Save(context.Response.OutputStream, ImageFormat.Jpeg); } public bool IsReusable { get { return false; } } } } As you can see this is pretty much the same code we have been using before. Now comes the modification to the .ASHX file. Add Handler3.ashx to the web project: <%@ WebHandler Language="C#" Class="MyLibrary.Handler3" %> Here we specify the namespace and the class. From here there are two ways to proceed. In case MyLibrary is just your regular .NET class library (no strong names, etc), you can just add a reference to it to your web project. This will include MyLibrary.dll in the bin\ folder of the web application. It will also take care of the rest, and the above handler delcaration will work. However, if your library has a strong name and you store it in Global Assembly Cache, you will get an ASP.NET error saying it does not find the library. As it turns out, for automatic binding to work the class that you refer to in the Class attribute must be found in an assembly that is in your bin\ folder. This error happens even if you have created a reference to the library. To solve this problem, we simply need to add a reference to the assembly into the .ASHX file: <%@ WebHandler Language="C#" Class="MyLibrary.Handler3" %> <%@ Assembly Name="MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e4433e4487bd68da" %> Of course make sure you use the correct identifier for the particular assembly you are working with. This will solve the problem with the reference, and now our handler works even from the GAC. You might wonder when can you run into this problem? In SharePoint if you want to use an ASHX file and the handler code in a DLL, you will probably end up having this problem. Handlers in Web.config Having an ASHX file will make it easy to use handlers, because you do not need to register them. You can however register your handlers in Web.config. This gives you finer control over when your handler is called, what extensions it will serve, etc. To finnish this example let's create the fourth version of the handler. Let's add this to the external class library project - MyLibrary - as well. We will call this class Handler4. using System.Drawing.Imaging; using System.Web; namespace MyLibrary { public class Handler4 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; string name = "Anonymous"; name = System.IO.Path.GetFileNameWithoutExtension(context.Request.Path); System.Drawing.Image img = ImageBuilder.CreateGreeting(name); img.Save(context.Response.OutputStream, ImageFormat.Jpeg); } public bool IsReusable { get { return false; } } } } In this handler I changed the name fetching code. Instead of the QueryString parameter, we use the name of the request. Without extensions. As you will soon see, when we are registering a handler in Web.config, we can use a "star" name, and are not locked into a single name. Now comes the change to Web.config. You will have to register the handler in either of two places (or perhaps both). If you use IIS 6 or the Development Web Server in VS2008/2010, you will need to add this to the system.web section: <system.web> <httpHandlers> <add verb="GET" path="*.jpg" type="MyLibrary.Handler4, MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e4433e4487bd68da"/> </httpHandlers> </system.web> If you use IIS 7, 7.5 , you will need to add this to system.webServer: <system.webServer> <handlers> <add name="MyHandler" verb="GET" path="*.jpg" type="MyLibrary.Handler4, MyLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e4433e4487bd68da"/> </handlers> </system.webServer> In either case you tell ASP.NET to map all request to *.jpg (that is all jpg files) that are HTTP GET requests to our handler. If you now request Lenard.jpg from the server, you will actually get our dynamic greeting image, which reads Hello Lenard!. There is nothing preventing you from simply specifying "Handler4.ashx" as the path attribute, but let's admit that would not be as much fun Conclusion HTTP handlers can be a lot of fun, and they are very lightweight (compared to the regular ASP.NET Page pipeline). With them, you can completely customize the way your application functions, because as you saw you can even return dynamic content when a "regular" file, like a .jpg image is requested from the server. As you saw, there are many ways to use a handler, and you should pick the one that fits the situation at hand best. @ Saturday, 28 January 2012 15:05 Thanks for sharing !
http://blog.rebuildall.net/2010/09/20/Variations_on_Http_Handlers
CC-MAIN-2018-17
refinedweb
2,056
59.5
Using The Past To Predict The Future Part 3 of 3, Creating a Regression Model in Python Introduction to this series of blogs see: . Now let’s get started! Before diving into the topic at hand, lets review the 4 assumptions that need to hold true prior to releasing your model into a production environment. Pre-Model Assumptions — Covered in Blog 1 1. Linearity between Target and Features 2. No Multicollinearity between Features Post Model Assumptions- Covered here 3. Homoscedasticity in the Residual Error 4. Normality in the Residual Error. We will be covering points 3 & 4 in this blog. 3. Homoscedasticity in the Residuals When our model is created using linear regression, we are using OLS. For more information on OLS see here. The difference between the actual and predicted value is technically an error in our ability to predict the price accurately but we refer to those errors as residuals. When a residual does not have a constant random variance against the best fit line across your features (x axis), the model is said to be heteroscedastic. This explanation is certainly difficult to conceptualize without visuals — See the above theoretical examples. Each blue dot represents the price of the home on the x and the residuals (actual — predicted) on the y axis. The goal is to have residuals = 0 as that would mean your model made a perfect prediction. When the residuals look like graphs A, or B you can see that the variance in residuals form a pattern. In graph A, as prices get larger so do the errors. In graph B, as prices gets larger the errors get smaller. In graph C, the errors are consistently random “the same” across the predictions. In graphs A and B there is most likely a missing feature from the model that we could use to account for those errors. We also saw an indication of this bias in our model in blog 2 with the points in the red circle on the scatter plot showing our predicted vs. actual prices. Recognizing the violation of homoscedasticity is related to the confidence we have in the models ability to make accurate predictions for all data points in which the model was optimized. Remember the exercise here is linear regression, meaning as you increase or decrease your features, there is a clear corresponding relationship in output. Heteroscedasticity impacts the standard error that is built into creating the coefficients and pvalues associated with accepting your coefficients as significant. Said more plainly, heteroscedastic data should cause us to question our confidence in a model’s ability to consistently explain the variability in the data. So what does our data look like? Is our data hetero or homoscedastic? See below: From the above our data looks heteroscedastic. So how do we tell definitively if our data is hetero or homoscedastic? Option 1. Plotting our data as shown above. With x axis as predicted price and the y axis as residuals: #Graph our residuals against our predictions, this will give us a sense if our model is off for certain priced homes plt.scatter(df_predictions["price_Predicted"], df_Regression_No_Outliers_With_ScaledData["price_Residuals"]).plot(df_predictions["price_Predicted"], [0 for i in range(len(df_predictions["price_Predicted"]))],color="r"); plt.show() Option 2. Breusch-Pagan or Goldfeld-Quandt. (Breusch-Pagan shown below) We can also use two statistical tests: Breusch-Pagan or Goldfeld-Quandt. In either test the null hypothesis assumes homoscedasticity and a p-value below .05 indicates we should reject the null in favor of heteroscedasticity. # het_breuschpagan suggests heteroscedasticity in the data P-value> .05, null = homoscedasticity vs. heteroscedasticity from statsmodels.compat import lzip import statsmodels.stats.api as sms name = ['LM Statistic', 'LM-Test p-value', 'F-Statistic', 'F-Test p-value'] test = sms.het_breuschpagan(model.resid, predictors_int) lzip(name,test) As you can see from the highlight, given our pvalue is much lower than .o5, we would reject the null that our data is homoscedastic and instead accept that our data is heteroscedastic. So what should we do? For the sake of brevity, I will not look to fix heteroskedasticity in this post. See the following post for options on how to fix heteroscedastic datasets. 4. Normality in Distribution of Residuals The 4th assumption in linear regression modeling is that the residuals from our model are independent and normally distributed. If the residuals are not exactly normally distributed, but the sample size is large enough then the Central Limit Theorem says that predictions from our model will still be approximately correct. Therefore, this issue is really only relevant for small sample sizes. However, to test for normality in our residuals we can use formal tests such as Shapiro-Wilk and or visual tests such as the QQPlots. I will use the QQPlot for this blog. For details on the Shapiro-Wilk test in python see here. What does QQ plot tell us? A Q-Q plot tells us if our data comes from a specified distribution (normal in our case) by looking at your provided data, breaking it into quantiles (z scores) and then developing another “theoretical” set of data mimicking your data and then calculating the quantiles/ z-scores for that data, sort ordering from lowest to biggest and then using those points to create a scatter plot. I realize that is a mouth full. Our points, if normally distributed, will form a straight line on the 45-degree angle. Each point is paired between our data and the theoretical data. See the graphs below for examples of normally distributed vs. non-normally distributed datasets and their impact on the QQPlots. As you can see the ideal QQPlot is shown in graph B. The datapoints fall along the 45-degree. Each point in that dataset has a corresponding point coming from the other dataset. If our data does not match the theoretical in terms of points per quantile, you get a data point plotted beyond the 45-degree line (lower graphs A, C). So how do our QQPlots look for our data and how do we create these using python? See below: # Import appropriate libraries import statsmodels.api as sm import scipy.stats as stats import pylab#Plot Histogram and QQP fig,axes=plt.subplots(1,2) sns.histplot(model.resid,ax=axes[0]) sm.graphics.qqplot(data=model.resid, dist=stats.norm, line='45', fit=True, ax=axes[1]) axes[0].set_title('Histogram of Residuals') axes[0].set_xlabel("Residuals") axes[1].set_title('QQP of Residuals') axes[1].set_ylabel("Residual Z Scores") pylab.show() As you can see from the highlights, our data is not 100% normal, but overall our errors looks fairly normally distributed. I would say, for this assumption, we have passed and would be okay to proceed. For additional details on how to understand and make a QQP see these two great sources Statistics How To , In The World Are QQ Plots? Conclusion Above I covered the steps to review the post-model creation assumptions associated with linear regression modeling. I also provided additional resources to explore each of the topics further. Through this 3 part series on linear regression I showed you how to process your data prior to model creation and check for the first two assumptions of linear regression. In blog 2, I showed you how to create a model using Statsmodel and how to reuse your model with new data. Lastly, here I finished the series with checking post model creation assumptions. Hopefully you have benefited from this 3 part series, I know I have benefited from writing it! I look forward to seeing you soon! Next Stop — DATA ALCHEMY!
https://rgpihlstrom.medium.com/using-the-past-to-predict-the-future-bb373268d20f
CC-MAIN-2021-31
refinedweb
1,268
57.16
So, I don't know what is causing your problem, but foo will not do what you want even with lazy ST. foo y = do x <- something xs <- foo (y+1) return (x:xs) Desugaring: foo y = something >>= \x -> foo (y+1) >>= \xs -> return (x:xs) = something >>= \x -> something >>= \x2 -> foo (y+2) >>= \xs2 -> return (x2:xs2) >>= \xs -> return (x:xs) = something >>= \x -> something >>= \x2 -> foo (y+2) >>= \xs2 -> return (x:x2:xs2) You see that there is an infinite chain of "foo" calls; the lazy ST still needs to thread the state through that chain; so in the case of foo 0 >>= something_else, the state is _|_ for something_else and you will fail if you use read/write/newSTRef after that point. In fact, I'm not sure that lazy ST is very useful :) My guess is that you want one of (1) mdo, when the effects in 'something' only matter once, or (2) unsafeInterleaveST, if you just want to be able to traverse the (x:xs) list lazily and the references it uses are dead after calling foo. -- ryan On Sun, May 3, 2009 at 10:27 AM, Tobias Olausson <tobsan at gmail.com> wrote: > Hello! > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > >
http://www.haskell.org/pipermail/haskell-cafe/2009-May/060887.html
CC-MAIN-2014-23
refinedweb
209
65.09
Java 5 brought generics to the Java language. In this article, I introduce you to generics and discuss generic types, generic methods, generics and type inference, generics controversy, and generics and heap pollution. What are generics? Generics are a collection of related language features that allow types or methods to operate on objects of various types while providing compile-time type safety. Generics features address the problem of java.lang.ClassCastExceptions being thrown at runtime, which are the result of code that is not type safe (i.e., casting objects from their current types to incompatible types). Consider the following code fragment, which demonstrates the lack of type safety (in the context of the Java Collections Framework’s java.util.LinkedList class) (instead of the compiler) to discover. Generics help the compiler alert the developer to the problem of storing an object with a non- Double type in the list by allowing the developer to mark the list as containing only Double objects. This assistance is demonstrated below: Double values (and I refer to them throughout this article). For example, java.util.Set<E> is a generic type, <E> is its formal type parameter list, and E is the list’s solitary type parameter. Another example is java.util.Map<K, in Java Declaring a generic type involves specifying a formal type parameter list and accessing these type parameters throughout its implementation. Using the generic type involves passing actual type arguments to its type parameters when instantiating the generic type. See Listing 1. Listing 1: 1 1 ( javac GenDemo.java). The (E[]) cast causes the compiler to output a warning about the cast being unchecked. It flags the possibility that downcasting from Object[] to E[] might violate type safety because Object[] can store any type of object. Note, however, that there is no way to violate type safety in this example. It’s simply not possible to store a non- E object in the internal array. Prefixing the Container(int size) constructor with @SuppressWarnings("unchecked") would suppress this warning message. Execute java GenDemo to run this application. You should observe the following output: North South East West Bounding type parameters in Java by using the 2:; @SuppressWarnings("unchecked") 2 interface 2 ( javac GenDemo.java) and run the application ( java GenDemo). You should observe the following output: George Smith: 15.20 Jane Jones: 25.60 John Doe: 35.40 Considering wildcards Let’s say you want to print out a list of objects, regardless of whether these objects are strings, employees, shapes, or some other type. Your first attempt might look like what’s shown in Listing 3. Listing 3: GenDemo.java (version 3) import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class GenDemo { public static void main(String[] args) { List<String> directions = new ArrayList(); directions.add("north"); directions.add("south"); directions.add("east"); directions.add("west"); printList(directions); List<Integer> grades = new ArrayList(); grades.add(new Integer(98)); grades.add(new Integer(63)); grades.add(new Integer(87)); printList(grades); } static void printList(List:
https://www.infoworld.com/article/3543252/how-to-use-java-generics-to-avoid-classcastexceptions.html
CC-MAIN-2020-45
refinedweb
509
51.44
Hide Forgot Created attachment 1187468 [details] Upgrade from 7.0 to 7.3 Description of problem: Errors noticed during ipa server upgrade task from 7.0.z to 7.3. Version-Release number of selected component: ipa-server-4.4.0-4.el7.x86_64 How reproducible: Always Steps to Reproduce: 1. Setup system with RHEL 7.0.z version with respective repos for 7.0 version. 2. Setup IPA server to it. 3. Now setup repos for RHEL 7.3. 4. Initiate upgrade process by "yum -y update 'ipa*' sssd" Actual results: 1. During the upgrade process following errors are observed: Cleanup : libdhash-0.4.3-22.el7.x86_64 258/260 Cleanup : libsss_idmap-1.11.2-68.el7_0.6.x86_64 259/260 Cleanup : libsss_nss_idmap-1.11.2-68.el7_0.6.x86_64 260/260 27, in <module> from requests.packages.urllib3.exceptions import InsecureRequestWarning ImportError: No module named packages.urllib3.exceptions Verifying : libsemanage-2.5-3.el7.x86_64 1/260 Verifying : ipa-server-common-4.4.0-4.el7.noarch 2/260 Verifying : python-custodia-0.1.0-2.el7.noarch 3/260 Verifying : slapi-nis-0.56.0-3.el7.x86_64 4/260 Verifying : custodia-0.1.0-2.el7.noarch 5/260 2. The yum command completes and ipa-server is upgraded successfully Expected results: No error messages should be observed during ipa-server upgrade process. Additional Information: There errors are not observed during ipa-upgrade for paths: 1. 7.2.z > 7.3 2. 7.1.z > 7.3 The ImportError is from pki module File "/usr/lib/python2.7/site-packages/pki/client.py", line 27, in <module> Moving BZ to PKI component Endi believe that this may be satisfied by simply adding a runtime dependency on RHEL: * python-urllib3 and for Fedora24 and later: * python2-urllib3 * python2-urllib3 Upstream ticket: (In reply to Matthew Harmsen from comment #4) > Endi believe that this may be satisfied by simply adding a runtime > dependency on RHEL: > * python-urllib3 > and for Fedora24 and later: > * python3-urllib3 > * python2-urllib3 Created attachment 1188022 [details] Added python-urllib dependencies checked into master: * b04707631a362581804574edd0641a3fdbc16565 Also noticed similar errors during upgrade path from 7.1 to 7.3 IPA server version: ipa-server-4.4.0-7.el7.x86_64 PKI version: pki-ca-10.3.3-5.el7.noarch Tested the bug with following observations: 1. Tested that IPA configured on RHEL 7.0 is upgraded to latest version on RHEL 7.3. (in my case upgraded to ipa-server-4.4.0-7.el7.x86_64). 2. Noticed that errors are still displayed during the upgrade. 3. Also noticed error while updating selinux policy: Updating : selinux-policy-targeted-3.13.1-93.el7.noarch 89/261 Re-declaration of type pkcsslotd_t Failed to create node Bad type declaration at /etc/selinux/targeted/tmp/modules/400/pkcsslotd/cil:1 semodule: Failed! 4. Refer the attached log "Console_log_1364071.txt". Thus on the basis of above observations, marking status of bug to "ASSIGNED" This issue seems to be a root cause/duplicate for several other IPA's bugs: - bug 1365572 (dup) - bug 1365507 (dup) - bug 1286635 (different bug, but verification suffers from it) - bug 1286635 (different bug, but verification suffers from it) Adding test blocker keyword given that verification of other bugs is blocked by this one Please also see: bug 1365572, comment 7 and then subsequent 8 with attachment - it seems that python-urllib3 is present on the affected system. This could be a packaging bug in RHEL. Python requests bundles some libraries internally, e.g. urllib3. 'requests.packaging' is the name space for the internal packages. In the past some package maintainers un-did the bundling. Fedora and RHEL both unbundle urllib3 and have a meta-importer to requests.packages.urllib3 to urllib3: /usr/lib/python2.7/site-packages/requests/packages/__init__.py sys.meta_path.append(VendorAlias(["urllib3", "chardet"])) I have python-requests-2.6.0-1.el7_1.noarch on my RHEL 7.3 test box. It is sufficient to require a recent version of python-requests. On RHEL it will automatically pull recent urllib3. Checked into master: * fdd5e984874a3f6b31e0509f646785428d643ece The following was checked in to DOGTAG_10_3_RHEL_BRANCH: commit f9be6d209b0367a5725016d593eaf2e1b3da7e5f Author: Matthew Harmsen <mharmsen@redhat.com> Date: Tue Aug 23 10:08:21 2016 -0600 Resolve python-requests dependencies appropriately by adding minimum require - PKI TRAC Ticket #2431 - Errors noticed during ipa server upgrade. 1) IPA server version: ipa-server-4.4.0-8.el7.x86_64 2) 7.0 > 7.3> pki versions: # rpm -qa python-requests python-urllib3 python-urllib3-1.10.2-2.el7_1.noarch python-requests-2.6.0-1.el7_1.noarch # rpm -qa | grep pki* pki-base-10.3.3-7.el7.noarch krb5-pkinit-1.14.1-26.el7.x86_64 pki-base-java-10.3.3-7.el7.noarch pki-ca-10.3.3-7.el7.noarch pki-tools-10.3.3-7.el7.x86_64 pki-kra-10.3.3-7.el7.noarch pki-symkey-10.0.5-3.el7.x86_64 pki-server-10.3.3-7.el7.noarch 3) 7.1 > 7.3 pki versions: ]# rpm -qa python-requests python-urllib3 python-requests-2.6.0-1.el7_1.noarch python-urllib3-1.10.2-2.el7_1.noarch # rpm -qa | grep pki* pki-ca-10.3.3-7.el7.noarch pki-tools-10.3.3-7.el7.x86_64 krb5-pkinit-1.14.1-26.el7.x86_64 pki-server-10.3.3-7.el7.noarch pki-base-java-10.3.3-7.el7.noarch pki-base-10.3.3-7.el7.noarch pki-kra-10.3.3-7.el7.noarch.
https://partner-bugzilla.redhat.com/show_bug.cgi?format=multiple&id=1364071
CC-MAIN-2020-10
refinedweb
926
52.66
I was experimenting with some datetime code in python so I could do a time.sleep like function on one piece of code, while letting other code run. Here is my code: import datetime, pygame pygame.init() secondtick = pygame.time.Clock() timestr = str(datetime.datetime.now().time()) timelist = list(timestr) timex = 1 while timex <= 6: timelist.pop(0) timex += 1 timex2 = 1 while timex2 <= 7: timelist.pop(2) timex2 += 1 secondstr1 = str("".join(timelist)) while 1: timestr = str(datetime.datetime.now().time()) timelist = list(timestr) timex = 1 while timex <= 6: timelist.pop(0) timex += 1 timex2 = 1 while timex2 <= 7: timelist.pop(2) timex2 += 1 secondstr2 = str("".join(timelist)) x = 1 if int(secondstr2) - x == int(secondstr1): print(x) x += 1 C:\Python32\python.exe "C:/Users/depia/PycharmProjects/testing/test.py" Traceback (most recent call last): File "C:/Users/depia/PycharmProjects/testing/test.py", line 31, in <module> timelist.pop(2) IndexError: pop index out of range Process finished with exit code 1 -- code -- time.sleep(1) secondstr2 = str("".join(timelist)) -- more code -- C:\Python32\python.exe "C:/Users/depia/PycharmProjects/testing/test.py" 1 You can use pygame.time.get_ticks to control time. To delay your event for 1 second (1000ms) first you set end_time = pygame.time.get_ticks() + 1000 and later in loop you check if pygame.time.get_ticks() >= end_time: do_something() or even (to repeat it every 1000ms) if pygame.time.get_ticks() >= end_time: do_something() end_time = pygame.time.get_ticks() + 1000 #end_time = end_time + 1000 It is very popular method to control times for many different elements in the same loop. Or you can use pygame.time.set_timer() to create own event every 1000ms. First set pygame.time.set_timer(pygame.USEREVENT+1, 1000) and later in loop you check for event in pygame.event.get(): if event.type == pygame.USEREVENT+1: do_something() It is useful if you have to do something periodicaly BTW: use 0 to turn off event pygame.time.set_timer(pygame.USEREVENT+1, 0)
https://codedump.io/share/aJnwFNXFR1Jf/1/pygame-datetime-troubles
CC-MAIN-2017-26
refinedweb
325
63.66
, John! Funny thing, I, too, recently installed Glade! That's = it! Best, Dave >>>>> "Nordquest," == Nordquest, David A <NORDQUES001@...> writes: Nordquest> BTW, if I do the pygtk test ( >>>import pygtk >>> Nordquest> pygtk.require('2.0') >>>> import gtk ) once, I get an error message. If I do it again >>>> without changing anything, I get no error message. This reimport situation you describe is expected. If you import a module a second time, python simply ignores it. So if it failed the first time, it will fail silently the next times. You should exist python and start over. The problem you are experiencing is definitely with gtk and not matplotlib. In these situations, the best thing to do is go into DOS or a command shell (Start->Run->command ENTER). Write a little script test.py that contains only import pygtk pygtk.require('2.0') import gtk Then go into the shell, an cd into the dir containing test.py. Manually set your PATH, something like (depends on which windows platform you are on) c:> set PATH=c:\GTK\bin;C:\GTK\lib;C:\Python23;C:\windows\command c:> python test.py I know you've checked your path ad nauseum, but there is still a decent change is the cause of your problem, 9 times out of 10. Hey, didn't you solve this once before :-) ? Is this a new platform for you? Did you reinstall GTK, if so to where? What does c:> dir c:\GTK\bin reveal? I assume you've reread 100 times. There is a long thread on the pygtk mailing list where Cousing Stanley got his gtk corrupted by installing glade, which writes some older libgtk versions into the windows system dir. Do a file search for libgtk and make sure nothing shows up outside of your GTK install tree. Read this thread, which is filled with good advice. Good luck! JDH >>>>> "Peter" == Peter Groszkowski <pgroszko@...> writes: Peter> plot(date_in_some_format, data) Are the dates strings, python datetime instances, mx datetime instances, or what? Here is a thread on python-list you may be interested in Peter> I suppose an alternative would be to convert the times to Peter> say seconds, create a plot and manually add the actual Peter> date/time label (text). This would be tedious but doable. Currently this is the best way. It would not be too much work to write a function called plotdate which took, for example, python2.3 datetime instances as the x arg, arbitrary y values, and a datetime format string as an optional arg, and did all the conversions for you, set the tick labels, etc... If you want to do it, I think it would be a nice addition to matplotlib. JDH Hi everyone: I am interested in plotting data in the form: 2004/01/29 15:29:17.161621101 5 2004/01/29 15:29:18.161621061 6 2004/01/29 15:29:19.161621021 7 2004/01/29 15:29:20.161620981 8 2004/01/29 15:29:21.161620941 9 2004/01/29 15:29:22.161620901 0 2004/01/29 15:29:23.161620861 1 ... In some cases I will have data every second, other times every minute or hour.. and so on.. Ideally I would like the x-axis of my plots to show the time/dates as the units. Is this currently possible with matplotlib? So in other words could I call on: plot(date_in_some_format, data) I suppose an alternative would be to convert the times to say seconds, create a plot and manually add the actual date/time label (text). This would be tedious but doable. Thanks. -- Peter Groszkowski Gemini Observatory Tel: +1 808 974-2509 670 N. A'ohoku Place I've checked my path several times and all seems to be as it should be. = However when I try to use pygtk and the latest gtk runtime and = matplotlib under Win98, I get the following error: >>> import pygtk >>> pygtk.require('2.0') >>> import gtk >>> from matplotlib.matlab import * Traceback (most recent call last): File "<pyshell#6>", line 1, in -toplevel- from matplotlib.matlab import * File "D:\PROGRA~1\PYTHON23\Lib\site-packages\matplotlib\matlab.py", = line 124, in -toplevel- from backends import new_figure_manager, error_msg, \ File = "D:\PROGRA~1\PYTHON23\Lib\site-packages\matplotlib\backends\__init__.py",= line 12, in -toplevel- from backend_gtk import \ File = "D:\PROGRA~1\PYTHON23\Lib\site-packages\matplotlib\backends\backend_gtk.p= y", line 15, in -toplevel- from gtk import gdk ImportError: cannot import name gdk I'm probably overlooking something obvious but would be grateful for = suggestions. BTW, if I do the pygtk test ( >>>import pygtk >>> pygtk.require('2.0') >>> import gtk ) once, I get an error message. If I do it again = without changing anything, I get no error message. Dave I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=200402&viewday=7
CC-MAIN-2016-30
refinedweb
840
76.32
You can subscribe to this list here. Showing 1 results of 1 David, > > That is a good point. It is true that today overflow notification > > is requested via the PMC and not the PMD. The implementation assumes > > (wrongly) that PMCx corresponds to PMDx. The flag is recorded in > > the PMD related structure. Hence, it would seem more natural to > > pass the flags for RANDOM/OVFL_NOTIFY via PFM_WRITE_PMDS. I did it > > via PFM_WRITE_PMCS because I considered those flags as part of the > > configuration of the counters, hence they would go with PMC. For the > > PPC64, it looks like you are in a situation similar to P4, where > > multiple config registers are used to control a counter. We could > > move the flags to PFM_WRITE_PMDS. > > I think that would make more sense. Or maybe even a different > mechanism entirely. How would you support performance monitor event > that aren't counter overflows, for those CPUs that have such? >. I also assume that the PMC selection determines the PMD. Certain events can be measured on any PMC register. No matter what, I think a tool would need to find out the association PMC -> PMD. This can be provided by a user level library. I think your proposal makes sense. The Itanium PMU model is very clean in that regards, making work fairly simple for tools. I guess I will have to revise this in my tools/libraries.). > > > PFM_WRITE_PMCS > > > > > > The documentation says that the PFM_MAX_PMD_BITVECTOR can vary between > > > PMU models. But what the value of this is for the current PMU model > > > is not exported anywhere. Varying by architecture doesn't make much > > > sense, since PMU model details vary only mildly more between > > > architectures than they do within CPU models of one architecture. > > > > > The PFM_MAX_PMD_BITVECTOR is exported in the perfmon.h header file. > > At this point, it is provided by each architecture. When the > > processor architecture is nice, then the PMU framework is specified > > there and it makes the job of software easier. For instance, on Itanium, > > the architecture says you can have up to 256 PMC and 256 PMD registers. > > Having this kind of information is very useful to size data structures > > approprietely. You don't want to have to copy large data structures > > (think copy_user) if you don't have to. Are you advocating that this > > be a PMU model specific size? > > Having it per-architecture doesn't really make a lot of sense, since > PM units vary only slightly less between CPUs of the same architecture > than they do between CPUs of different architectures. The PM unit may Well, I would cite Pentium III/Pentium M vs. P4/Xeon, that's is quite a drastic change. Yet this is inside the same processor family. > well not be defined by the architecture specification (if such exists) > at all, so I don't think you can count on there being a definitive > limit on the number of PMDs in general. On Itanium there is an architected limit. That is quite nice. I don't think having a per PMU-model limit is manageable. It would be hard to manage all the variations for the data structures. How would you handle the X86 family that way: one size for PIII, one size for P4. Yet the kernel support files would probably be the same, in fact the same kernel boots on both. > > The greatest number of PMDs on any PowerPC so far is 8, and I'm not > aware of any plans for CPUs with more, but it wouldn't surprise me if > it happened some day. Since this size can never be changed, without > breaking the ABI, we would have to leave room for expansion, and > there's no real guidance as to how much. > > So I think this should either be PM model dependent, or it should be > truly global - per-architecture is a bad compromise. The latter, > obviously, is much simpler to implement. Another thing to take into account is that you may want to use virtual PMDs to access software resources. For instance, take perfctr, there is TSC (timestamp) that could be mapped to a logical PMD. That way, it would be easy to specify it as part of the registers/resource to record in a sample (via the smpl_pmds[] mask). On Itanium, the debug registers are used by the PMU to restrict the code/data range where to monitor. In the old interface I had a specific call to program the IBR/DBR. In the revised document, you will see that I have logical PMC to do that. It simplifies the code and makes the interace more uniform, after all in this situation the debug registers are really use the configure the PMU. You can imagine mapping some kernel resources to PMD, such as amount of free memory, the PID of the current process. To make this work, it is really nice to have an upper bound for the physical PMU registers. Then you can add on top. That's what I did for Itanium.. Picking a single value would be good. Let's say you pick 256 for max physical PMC and max physical PMD. Assuming there are no big holes in the namespace. I think that is a pretty safe limit. Then logical PMD/PMC could be added above that. Of course if all really have is a set of 4 PMC, then you pay the copy cost for larger than needed data structures. But, the ABI would be preserved when the number of registers grow. > > > PFM_LOAD_CONTEXT > > > > > > I'm not sure I see the point of the load_set argument. What > > > can be accomplished with this that can't be with appropriate use of > > > PFM_START_SET? > > > > > You don't want to merge START and load. that is not because you attach > > to a thread/CPU that you want monitoring to start right away. > > But I think you have a good point. the interface guarantees that on > > PFM_LOAD_CONTEXT, monitoring is stopped. You need explicit START to > > activate. This is true even if you detached while monitoring was active. > > I need to check to see if there is something else involved here. > > Sorry, I don't fully follow what you're saying here (I can't parse the > first sentence, in particular). My point is it's not clear to me that > there's anything useful you can accomplish with: > CREATE <do stuff> LOAD START > that can't be done with > CREATE+ATTACH <do stuff> START > It depends on what you do in <stuff>. I assume that is where you program the PMU with PFM_WRITE_PMDS/PFM_WRITE_PMCS. I think you will see that the first model makes sense if you want to support batching: for(i=0; i < N ; i++) { c = CREATE PFM_WRITE_PMCS(c); PFM_WRITE_PMDS(c); } forearch(c) { ATTACH to target thread PFM_start. > > > PFM_CREATE_EVTSET / PFM_DELETE_EVTSET / PFM_CHANGE_EVSET > > > > > > Is there really a need to incrementally update the event sets? Would > > > a PFM_SETUP_EVTSETS which acts like PFM_CREATE_EVTSET, but replaces > > > all existing event sets with the ones described suffice. This > > > approach would not only reduce the number of entry points, but could > > > also simplify the kernel's parameter checking. For example at the > > > moment deleting an event set which is reference by another sets > > > set_id_next must presumably either fail, or alter those other event > > > sets to no longer reference the deleted event set. > > > > > This has been trimmed down to two calls in the new rev: > > PFM_CREATE_EVTSETS and PFM_DELETE_EVTSETS. If the event set > > already exist, PFM_CREATE_EVTSETS updates it. This is useful > > for set0 which always exists. > > > > As for delete/create, those operations can only happen when > > the context is detached. Checking of the validity of the event > > set chain is deferred until PFM_LOAD_CONTEXT because at this > > point it is not possible to modify the sets. If there set_id_next > > is invalid, PFM_LOAD_CONTEXT fails. > > But again, is there a real reason to allow incremental updates? If > there was a single operation which atomically changed all the event > sets it would mean one less entry point, *plus* we could do the error > checking there (earlier error checking is always good). And we > wouldn't even need user allocated id numbers, the array position would > suffice. > Keep in mind that PFM_CREATE_EVTSETS can be used to create multiple event sets at a time. This command can be called as many times as you want. If the set exists it is modified. You can create and delete event sets at will as long as the context is not attached. to anything. The set number determines its position in the list of sets. That list determines the DEFAULT switch order. Letting the user pick set number could be useful because it may correspond to some indexing scheme. The interface supports an override for the next set, this is the explicit next set. Why is this useful? This is interesting when the explicit link is pointing backwards. You can thus create sublists of sets. There is an example in the document.. > > > PFM_GET_CONFIG / PFM_SET_CONFIG > > > > > > Again, these definitely don't belong on the multiplexor. They don't > > > use the fd, and since they set the permission regime for the > > > mutliplexor itself, they logically belong outside. Under Linux these > > > definitely ought to be sysctls. If this is ever ported to other OSes, > > > I still don't think they belong here. Setting up the permission > > > regime for all the other calls is, I think a logically OS-specific > > > operation and doesn't belong in the core API. As far as I can tell > > > it's unlikely you would use these operations in the same programs > > > using the rest of perfmon. > > > > > As discussed earlier, on Linux, these operations could as well be > > implemented with sysctls. > > Yes, and I don't think having a cross-platform operation for this is > worthwhile. This is a system administrator operation, not an > operation for the users of perfmon, so I don't think having it > platform specific is a problem at all. > Fine with me. I'll switch to a pure sysctl approach then. > > In terms of porting, I am getting closer to being able to send you > > a skeleton header/C file with the required callbacks. Please let me > > know of any special PPC64 special behavior. For instance, looking > > at Opteron and Pentium 4: > > - on counter overflow, does PPC freeze the entire PMU > > Optional, IIRC, depending on some control bits in MMCR0. > Ok, at least there is something. > > - HW counters are not 64-bits, what are the values of > > the upper bits for counters. Should they be all 1 or all 0. > > The counter registers are 32 bits wide, but can only be effectively > used as 31-bit counters (see below). > > > - How is a counter overflow detected? When the full 64 bits > > of the counter overflow or when there is a carry from bit > > n to n+1 for a width on n. > > The interrupts occur on (32 bit) counter negative, rather than > overflow, per se. The only way to determine which counters have > overflowed is to look at the sign bits. Furthermore, the sign bit > must be cleared in order to clear the interrupt condition (hence only > 31-bit counters, effectively). Ok, that's fine. > > Another issue which I ran into for perfctr is that interrupts can't be > individually enabled or disabled for each counter. There is one > control bit which determines if PMC1 generates an interrupt on counter > negative, and another control bit which determines if other PMCs cause > an interrupt. I think that's fine also. For 64-bit software emulation you need to have overflow intr enabled for every counter anyway. > > Because the events for the counters are generally selected in groups, > rather than individually, you need to be able to deal with overflow > interrupts for a counter you don't otherwise care about. > > Performance monitor interrupts can also be generated from the > timebase. These occur on 0-1 transitions on bit 0, 8, 12 or 16 > (selectable) of the (64 bit) timebase. Timebase frequency is not the > same as CPU core frequency, and depends on the system, not just the > CPU (it can be externally clocked). The timebase is guaranteed to > have a fixed frequency, even on systems with variable CPU frequency, > so the ratio to CPU core frequency can also vary. > > > - Are there any PPC64 PMU registers which can only be used by > > one thread at a time (shared). Think hyperthreading. > > Not as far as I'm aware. That's good. > > > - Is there a way to stop monitoring without having to modify > > all used PMC registers. > > Yes, there is a "freeze counters" (FC) bit in MMCR0 which will stop > all the counters. > Ok. Thanks for your feedback. i am sure I'll come up with other PMU-specific questions. -- -Stephane
http://sourceforge.net/p/lse/mailman/lse-tech/?viewmonth=200503&viewday=31&style=flat
CC-MAIN-2015-32
refinedweb
2,112
73.58
Nylon Technology Presentation: Introduction To XSLT And XmlTransform() In ColdFusion Disclaimer: I am very new to XSLT. This is the stuff that I have worked out in my head. Some it might be incomplete. Some of it might be dead wrong. XSL stands for "Extensible Stylesheet Language". XSL Transformation (XSLT) provides us with a way to convert any XML document into another XML document. Apparently, there are parts of the XSL language that have to do with formatting, but for our purposes, we are going to concentrate on the transformation aspects only. ColdFusion And XSLT ColdFusion supports a subset of the XSLT functionality. While many features of the XSLT language are implemented in ColdFusion, there are a number of functions that are not supported. I am not sure exactly if the set of supported features is listed anywhere, but we should be able to do some really complex stuff without the entire feature set at our disposal. XSLT And XPath Before you do anything in XSLT (ColdFusion or otherwise), you are going to need to have a firm grasp on XPath. XPath is a way to pull nodes out of an XML document and it is only through XPath that we can find the XML nodes we wish to include in our transformations. Basic XSLT Elements There are more XSLT elements than the ones listed below, but with just these few elements, we can perform every high level transformations. NOTE: All XSLT elements (and all XML elements) should be all lower case when part of an XSLT document; I am simply camel casing them here for my own preference. Transform This is the root element of the XSLT document. It provides information about the transformation including the namespace of the XSLT nodes. Template This defines rules to be applied to nodes within the XML document. You can think of this as being somewhat equivalent to a ColdFusion custom tag. Apply-Templates This applies a template to the selected nodes. You can think of this as being somewhat equivalent to a ColdFusion CFModule tag that executes a custom tag (see Template above). Value-Of This outputs the selected value of the selected or current node. You can think of this as being somewhat equivalent to a ColdFusion CFOutput tag. For-Each This loops over the nodes in the selected node set. You can think of this as being somewhat equivalent to a ColdFusion CFLoop tag. If This tests to see if a condition is true. There is no ELSE element. If you need to check multiple conditions, see Choose (below). You can think of this as being somewhat equivalent to a ColdFusion CFIF tag. Choose / When / Otherwise These tags work in conjunction to test for multiple conditions. These take the place of an IF / ELSE statement and you can think of these as being somewhat equivalent to the ColdFusion CFSwitch / CFCase / and CFDefaultCase tags respectively. Text This tag allows you output text literals. You can think of this as being somewhat equivalent to an XHTML PRE tag. Element / Attribute These tags allow you to build dynamic nodes in the resulting XML document. Transforming XML In ColdFusion Using XSLT ColdFusion provides the XmlTransform() function as a way to apply XSL Transformations to an XML document. While the XmlTransform() function takes three parameters, we will only cover the first two for this introduction: XML: The first argument must be either a ColdFusion XML document object or properly formatted XML string. XSLT: The second argument must be one of the following: - An XSLT string. - A ColdFusion XML document object containing XSLT elements. - An absolute or relative path to an XSLT file (document containing and XSLT string). - A URL (including protocol ex. http) for an XSLT file. ColdFusion will take the two arguments and return the transformed XML document (in string format). For the examples in this introduction, we are going to be working off of this ColdFusion XML document object: - <!--- Define ColdFusion XML document object. ---> - <cfxml variable="xmlFoot"> - <foot> - <toes> - <toe isbigtoe="true"> - <name>Christina</name> - </toe> - <toe> - <name>Julia</name> - </toe> - <toe> - <name>Maria</name> - </toe> - <toe> - <name>Kim</name> - </toe> - <toe iscute="true"> - <name>Kit</name> - </toe> - </toes> - </foot> - </cfxml> Here, we have nested elements, element nodes, attribute nodes, and text nodes; this should give us plenty to test with. For the examples, we are not going to show the Transformation taking place or, in most cases, the Transform element, but it would be something like this: - <!--- Define ColdFusion XML document object (XSLT). ---> - <cfxml variable="xmlTransform"> - <xsl:transform - version="1.0" - xmlns: - <!--- Match root element of XML document. ---> - <xsl:template - <!--- ... more code here ... ---> - </xsl:template> - </xsl:transform> - </cfxml> - <!--- Tranform xmlFoot using xmlTransform XSLT. ---> - <cfoutput> - #HtmlEditFormat( - XmlTransform( - xmlFoot, - xmlTransform - ) - )# - </cfoutput> Notes On "Select" And "Match" Many of the XSLT elements use either a Select or Match attribute. These take XPath paths that return a set of nodes. What is done with those returned nodes depends on the element in question. Transform Each XSLT document must contain one and only one Transform element (can also be swapped with a Stylesheet element) and it must be the root element. - <xsl:transform - version="1.0" - xmlns: - <!--- Rest of XSLT elements go in here. ---> - </xsl:transform> Here we are defining the root node and the namespace of all the XSLT elements as being "xsl". This is simply "boiler plate" and needs to be done for every XSLT document (it doesn't need to be exactly like this, but this is a good place to start). Template In order for the transformation to result in any useful output, at least one template must be applied to the incoming XML document. The most basic attribute (that we will be looking at) of the Template element is the Match attribute. The Match attribute tells the transformation engine which nodes to which the template should be applied. The Transformation engine will iterate over the XML document in a depth-first approach and apply templates when possible. If the Transformation hits a text node and no template has been applied, it will simply echo the text node value in the resulting document. Here, we can use the XPath "/" to match the root element of the XML document: - <!--- Match root element. ---> - <xsl:template - Here - </xsl:template> This will be executed only once as there is only one root element (outputting the text "Here" once). Note that none of the text node values are echoed because the Transformation engine must apply the template before it gets to the text nodes. If we define a template that matches more than one node, it will be executed for every matching node in the selected node set. Here, we can use the match "name" to match "name" element nodes anywhere in the XML document: - <!--- Match name elements. ---> - <xsl:template - HERE - </xsl:template> This will be executed once for each of the "name" element nodes and will result in "Here" being output 5 times. The values of the Match attribute can be complex, but do not support all XPath values. here are some additional Match attribute values that are supported: - <!--- Wild cards. ---> - <xsl:template - <!--- Descendents. ---> - <xsl:template - <!--- Any parent. ---> - <xsl:template - <!--- Text nodes. ---> - <xsl:template - <!--- Predeciate matching. ---> - <xsl:template Apply-Templates Using the Template element, we can get ColdFusion to apply implicit transformations based on patterns (match attribute). However, most of the time we are going to want to explicitly execute templates from within other templates. Apply-Templates allows us to do just that. The Apply-Templates element uses the Select attribute to define which templates to execute (based on which nodes are returned in the Select attribute XPath value). If you exclude the Select element, the Transformation engine will attempt to execute a template for each DIRECT descendent of the context node (the one matched by the currently executing template). In the following example, we are going to implicitly execute the "toes" template. Then, from within that template, we are going to explicitly execute the "toe" template for each of the toe child nodes: - <!--- Match toes element. ---> - <xsl:template - <!--- Apply template to all the toe nodes. ---> - <xsl:apply-templates - CLOSE-TOES - </xsl:template> - <!--- Match toe element. ---> - <xsl:template - TOE - </xsl:template> This results in the output: OPEN-TOES TOE TOE TOE TOE TOE CLOSE-TOES. Notice that OPEN-TOES appears once, then the Apply-Templates element selects all 5 toe nodes, executing the "toe" template for each node (based on the template Match attribute), and then outputs the CLOSE-TOES text. The Select attribute of the Apply-Templates node doesn't have to select a direct descendent of the context node. It doesn't even have to select any descendent of the context node. All it has to have is a valid XPath value. In the following example, we will select all name nodes of the XML document: - <!--- Match toes element. ---> - <xsl:template - <!--- - Apply template to all the name nodes that - are anywhere in the XML document (having nothing - to do with the "toes" context node). - ---> - <xsl:apply-templates - CLOSE-TOES - </xsl:template> - <!--- Match name element. ---> - <xsl:template - NAME - </xsl:template> Using this transformation, we get the following output: OPEN-TOES NAME NAME NAME NAME NAME CLOSE-TOES. The Select attribute doesn't just have to match Element nodes; it can also match attribute nodes. Here, we are going to match all IsCute attributes of the descendent toe nodes: - <!--- Match toes element. ---> - <xsl:template - <!--- Get all cute toe attributes. ---> - <xsl:apply-templates - </xsl:template> - <!--- Match iscute Attribute node. ---> - <xsl:template - A CUTIE! - </xsl:template> Notice that our Apply-Templates' Select attribute is using an XPath path that selected an attribute node. Also, notice that our Template element matches on the attribute node, @iscute. Running the above transformation, we get the following output: A CUTIE! Value-Of Using the Template and Apply-Templates elements, we can apply templates to nodes within the given ColdFusion XML document during the XSL transformation, but it is through the use of the Value-Of element that we can actually reference values within the XML data. Using Value-Of, we can output the value of an XML node, wether it is a text node or attribute node (and I am sure other node types work as well). It has two attributes: Select and Disable-Output-Escaping. The Select attribute uses XPath to determine which node value to get. The Disable-Output-Escaping attribute turns off the escaping of special characters. This is especially useful when we are outputting CDATA values. By default, the Transformation engine will escape special values like "<" and ">"; when outputting CDATA (or node data in general), we want those value to come through as-is so that XHTML can be stored in an XML document and therefore can set the Disable-Output-Escaping value to "yes". In the following example, we are going to implicitly match all the toe nodes. Once inside the toe node, we are going to output the name of the toe: the text node within the nested name element node. - <!--- Match toe element. ---> - <xsl:template - <!--- Output name of toe. ---> - <xsl:value-of - </xsl:template> This gives us the output: Christina Julia Maria Kim Kit. Just like the Apply-Templates element, the Value-Of Select attribute does not have to be relevant to the context node. By default, it is relevant to the context node, but it could certainly use an XPath path that selects from anywhere in the current XML document. If you want to select an attribute value, all you would need to do is use an XPath path to select the attribute node. The following code will output the @IsBigToe attribute value. - <!--- Match toe element. ---> - <xsl:template - <!--- Output big toe flag. ---> - [<xsl:value-of] - </xsl:template> Performing this transformation, we get the following output: [true] [] [] [] []. I have included the brackets to demonstrate that while the toe template still matches all 5 toes, the Value-Of only gets one value. Notice that is does NOT throw an error if the context node in question does NOT have the desired attribute. Value-Of always returns a string; this string might be empty a lot of the time. For-Each The For-Each element allows us to loop over the selected nodes. This is like applying a template to a set of nodes without having to leave the currently executing template. The For-Each element has only one attribute - Select - which defines the node set over which we will iterate. In this example, we are going to apply a toes template. Then, from within that template, we are going to loop over each toe node and output the name of the toe. - <!--- Match toes element. ---> - <xsl:template - <!--- Loop over each toe. ---> - <xsl:for-each - <!--- Output name of the context toe. ---> - [<xsl:value-of] - </xsl:for-each> - </xsl:template> Running this, we get the following output: [Christina] [Julia] [Maria] [Kim] [Kit]. For each iteration of the For-Each loop, the Transformation engine takes the current "toe" node and makes it the context node. If The If element allows us to run code based on conditions. The If element has only one attribute, test, which must evaluate to true or false. What is considered True can be a bit confusing. It can be any valid XPath or expression such a function return or even the existence of a nested element. For example, in the following code, we are only going to show the name of toes that actually have a nested name element. - <!--- Match toes element. ---> - <xsl:template - <!--- Loop over each toe. ---> - <xsl:for-each - <!--- - Only output names of toe elements that - have a nested name element. - ---> - <xsl:if - <!--- Output name of the context toe. ---> - [<xsl:value-of] - </xsl:if> - </xsl:for-each> - </xsl:template> Here, as we are looping over the toes, we use the test condition "name" to make sure the context toe has a nested name element. If it does, we then execute that transformation code within the If element. Choose / When / Otherwise XSLT does not allow the ELSE part of a traditional IF-ELSE condition. Furthermore, it has no ElseIF statement. To perform this kind of conditional testing, we have to use the XSLT equivalent of a Switch statement which uses the Choose, When, and Otherwise elements. Here, we are going to apply a template for each toe node and describe the toe. The description of the toe will be based on the existence of certain attributes: - <!--- Match toe element. ---> - <xsl:template - <!--- Describe toe. ---> - <xsl:choose> - <xsl:when - Big! - </xsl:when> - <xsl:when - Cute! - </xsl:when> - <xsl:otherwise> - N/A - </xsl:otherwise> - </xsl:choose> - </xsl:template> Running the above transformation, we get the following output: Big! N/A N/A N/A Cute! Text White space output that is generated during an XSL transformation can be a little confusing. I don't fully understand the rules. Sometimes it outputs white space, sometimes it does not. I think it has to do with a combination of which XSLT elements you are using and what text literals you are using. You can use the Text element to make sure all characters get output as-is in the resultant transformation. The Text element has one attribute: Disable-Output-Escaping. Like the Value-Of element, this attribute flags whether or not to escape special output characters (defaults to "no"). Other than that, it simply outputs the text contained within its open and close tags. If we run this transformation: - <!--- Match toes element. ---> - <xsl:template - <!--- Loop over toes. ---> - <xsl:for-each - <xsl:value-of - </xsl:for-each> - </xsl:template> We get the following output: ChristinaJuliaMariaKimKit. Notice that none of the white space between the XSLT elements was carried through. Now, we can modify that to add explicit white space: - <!--- Match toes element. ---> - <xsl:template - <!--- Loop over toes. ---> - <xsl:for-each - <xsl:value-of - <xsl:text> - </xsl:text> - </xsl:for-each> - </xsl:template> Here, we are adding a dash between elements and we get the following output: Christina - Julia - Maria - Kim - Kit -. Element / Attribute In ColdFusion, it is easy to build dynamic XHTML elements; all you have to do is put CFIF tags within the XHTML tag markup. This kind of thing cannot be done quite as easily in XSLT. Instead of putting conditional statements inside the markup of a tag, you can use the Element and Attribute elements to build nodes one an attribute at a time. For example, if we wanted to convert the toes XML node to an XHTML unordered list (OL), including the attributes, we would have to do something like this: - <!--- Match toes element. ---> - <xsl:template - <ul> - <!--- Loop over toes. ---> - <xsl:for-each - <!--- Build an LI element. ---> - <xsl:element - <!--- Check for class. ---> - <xsl:if - <xsl:attribute - <xsl:text>bigtoe</xsl:text> - </xsl:attribute> - </xsl:if> - <!--- Output this value for the LI text. ---> - <xsl:value-of - </xsl:element> - </xsl:for-each> - </ul> - </xsl:template> As you can see, building a dynamic XHTML element is no easy task in XSL transformations. So there you go. I am not sure how I feel about XSL Transformation just yet. There is certainly some cool stuff here, but I am not sure if the overhead of its complexity makes it worth while; I feel like many of the things it does can be more easily done in ColdFusion. I think the real power here lies in the Template matching - it has some very nice recursive possibilities. I think now that I have a better understanding of XSLT, it will start to look like a solution in more places. Reader Comments Good article with all the transformation related tags,attributes explained. Very helpful. Thanks, Raghuram Reddy Gottimukkula Adobe Certified Professional in Advanced ColdFusion Hyderabad India
https://www.bennadel.com/blog/952-nylon-technology-presentation-introduction-to-xslt-and-xmltransform-in-coldfusion.htm
CC-MAIN-2018-26
refinedweb
2,943
65.32
Schemas for easy editing of properties in Apostrophe objects This module is for Apostrophe 0.5.x only. In Apostrophe 2.x, schemas are standard equipment. Table of Contents apostrophe-schemas adds support for simple schemas of editable properties to any object. Schema types include text, select, apostrophe areas and singletons, joins (relationships to other objects), and more. This module is used by the apostrophe-snippets module to implement its edit views and can also be used elsewhere. In any project built with the apostrophe-site module, every module you configure in app.js will receive a schemas option, which is a ready-to-rock instance of the apostrophe-schemas module. You might want to add it as a property in your constructor: self._schemas = options.schemas; If you are not using apostrophe-site... well, you should be. But a reasonable alternative is to configure apostrophe-schemas yourself in app.js: var schemas = require('apostrophe-schemas')({ app: app, apos: apos }); schemas.setPages(pages); // pages module must be injected And then pass it as the schemas option to every module that will use it. But this is silly. Use apostrophe-site. A schema is a simple array of objects specifying information about each field. The apostrophe-schemas module provides methods to build schemas, validate submitted data according to a schema, and carry out joins according to a schema. The module also provides browser-side JavaScript and Nunjucks templates to edit an object based on its schema. Schema objects have intentionally been kept simple so that they can be send to the browser as JSON and interpreted by browser-side JavaScript as well. The simplest way to create a schema is to just make an array yourself: var schema =name: 'workPhone'type: 'string'label: 'Work Phone'name: 'workFax'type: 'string'label: 'Work Fax'name: 'department'type: 'string'label: 'Department'name: 'isRetired'type: 'boolean'label: 'Is Retired'name: 'isGraduate'type: 'boolean'label: 'Is Graduate'name: 'classOf'type: 'string'label: 'Class Of'name: 'location'type: 'string'label: 'Location'}); However, if you are implementing a subclass and need to make changes to the schema of the superclass it'll be easier for you if the superclass uses the schemas.compose method, as described later. Currently: string, boolean, integer, float, url, date, time, slug, area, singleton Except for area, all of these types accept a def option which provides a default value if the field's value is not specified. The integer and float types also accept min and max options and automatically clamp values to stay in that range. The select type accepts a choices option which should contain an array of objects with value and label properties. In addition to value and label, each choice option can include a showFields option, which can be used to toggle visibility of other fields when being edited. The date type pops up a jQuery UI datepicker when clicked on, and the time type tolerates many different ways of entering the time, like "1pm" or "1:00pm" and "13:00". For date, you can specify select: true to display dropdowns for year, month and day rather than a calendar control. When doing so you can also specify yearsFrom and yearsTo to give a range for the "year" dropdown. if these values are less than 1000 they are relative to the current year. You may even use an absolute year for yearsFrom and a relative year for yearsTo. The url field type is tolerant of mistakes like leaving off http:. The password field type stores a salted hash of the password via apos.hashPassword which can be checked later with the password-hash module. If the user enters nothing the existing password is not updated. The tags option accepts a limit property which can be used to restrict the number of tags that can be added. When using the area and singleton types, you may include an options property which will be passed to that area or singleton exactly as if you were passing it to aposArea or aposSingleton. When using the singleton type, you must always specify widgetType to indicate what type of widget should appear. Joins and arrays are also supported as described later. For the most part, we favor sanitization over validation. It's better to figure out what the user meant on the server side than to give them a hard time. But sometimes validation is unavoidable. You can make any field mandatory by giving it the required: true attribute. Currently this is only implemented in browser-side JavaScript, so your server-side code should be prepared not to crash if a property is unexpectedly empty. If the user attempts to save without completing a required field, the apos-error class will be set on the fieldset element for that field, and schemas.convertFields will pass an error to its callback. If schemas.convertFields passes an error, your code should not attempt to save the object or close the dialog in question, but rather let the user continue to edit until the callback is invoked with no error. If schemas.convertFields does pass an error, you may invoke: aposSchemas.scrollToError($el) To ensure that the first error in the form is visible. If you are performing your own custom validation, you can call: aposSchemas.addError($el, 'body') To indicate that the field named body has an error, in the same style that is applied to errors detected via the schema. One lonnnnng scrolling list of fields is usually not user-friendly. You may group fields together into tabs instead using the groupFields option. Here's how you would do it if you wanted to override our tab choices for the blog: modules:'apostrophe-blog':groupFields:// We don't list the title field so it stays on topname: 'content'label: 'Content'icon: 'content'fields:'thumbnail' 'body'name: 'details'label: 'Details'icon: 'metadata'fields:'slug' 'published' 'publicationDate' 'publicationTime' 'tags' Each group has a name, a label, an icon (passed as a CSS class on the tab's icon element), and an array of field names. In app.js, you can simply pass groupFields like any other option when configuring a module. The last call to groupFields wins, overriding any previous attempts to group the fields, so be sure to list all of them except for fields you want to stay visible at all times above the tabs. Be aware that group names must be distinct from field names. Apostrophe will stop the music and tell you if they are not. Let's say you're managing "companies," and each company has several "offices." Wouldn't it be nice if you could edit a list of offices while editing the company? This is easy to do with the array field type: name: 'offices'label: 'Offices'type: 'array'minimize: trueschema:name: 'city'label: 'City'type: 'string'name: 'zip'label: 'Zip'type: 'string'def: '19147'name: 'thumbnail'label: 'Thumbnail'type: 'singleton'widgetType: 'slideshow'options:limit: 1 Each array has its own schema, which supports all of the usual field types. You an even nest an array in another array. The minimize option of the array field type enables editors to expand or hide fields of an array in order to more easily work with longer lists of items or items with very long schemas. It's easy to access the resulting information in a page template, such as the show template for companies. The array property is... you guessed it... an array! Not hard to iterate over at all: <h4>Offices</h4><ul>{% for office in item.offices %}<li>{{ office.city }}, {{ office.zip }}</li>{% endfor %}</ul> Areas and thumbnails are allowed in arrays. In order to display them in a page template, you'll need to use this syntax: {% for office in item.offices %}{{ aposSingleton({ area: office.thumbnail, type: 'slideshow', more options... }) }}{% endfor %} For an area you would write: {% for office in item.offices %}{{ aposArea({ area: office.body, more options... }) }}{% endfor %} Since the area is not a direct property of the page, we can't use the (page, areaname) syntax that is typically more convenient. Areas and thumbnails in arrays can be edited "in context" on a page. For most field types, you may specify: autocomplete: false To request that the browser not try to autocomplete the field's value for the user. The only fields that do not support this are those that are not implemented by a traditional HTML form field, and in all probability browsers won't autocomplete these anyway. This is really easy! Just write this in your nunjucks template: {% include 'schemas:schemaMacros.html' %}<form class="my-form">{{ schemaFields(schema) }}</form> Of course you must pass your schema to Nunjucks when rendering your template. All of the fields will be presented with their standard markup, ready to be populated by aposSchemas.populateFields in browser-side JavaScript. You may want to customize the way a particular field is output. The most future-proof way to do this is to use the custom option and pass your own macro: {% macro renderTitle(field) %}<fieldset data-special awesome title: <input name="{{ field.name }}" /></fieldset>{% endmacro %}<form>{{schemaFields(schema, {custom: {title: renderTitle}})}}</form> This way, Apostrophe outputs all of the fields for you, grouped into the proper tabs if any, but you still get to use your own macro to render this particular field. If you want to include the standard rendering of a field as part of your custom output, use the aposSchemaField helper function: aposSchemaField(field) This will decorate the field with a fieldset in the usual way. Note that the user's current values for the fields, if any, are added by browser-side JavaScript. You are not responsible for that in your template. You also need to push your schema from the server so that it is visible to browser-side Javascript: self_apos; Now you're ready to use the browser-side JavaScript to power up the editor. Note that the populateFields method takes a callback: var schema = aposdatamymoduleschema;aposSchemas; $el should be a jQuery object referring to the element that contains all of the fields you output with schemaFields. object is an existing object containing existing values for some or all of the properties. And, when you're ready to save the content: aposSchemas This is the same in reverse. The properties of the object are set based on the values in the editor. Aggressive sanitization is not performed in the browser because the server must always do it anyway (never trust a browser). You may of course do your own validation after calling convertFields and perhaps decide the user is not done editing yet after all. Serializing the object and sending it to the server is up to you. (We recommend using $.jsonCall.) But once it gets there, you can use the convertFields method to clean up the data and make sure it obeys the schema. The incoming fields should be properties of data, and will be sanitized and copied to properties of object. Then the callback is invoked: schemas The third argument is set to 'form' to indicate that this data came from a form and should go through that converter. Now you can save object as you normally would. For snippets, the entire object is usually edited in a modal dialog. But if you are using schemas to enhance regular pages via the apostrophe-fancy-pages module, you might prefer to edit certain areas and singletons "in context" on the page itself. You could just leave them out of the schema, and take advantage of Apostrophe's support for "spontaneous areas" created by aposArea and aposSingleton calls in templates. An alternative is to set contextual to true for such fields. This will keep them out of forms generated by {{ schemaFields }}, but will not prevent you from taking advantage of other features of schemas, such as CSV import. Either way, it is your responsibility to add an appropriate aposArea or aposSingleton call to the page, as you are most likely doing already. You may use the join type to automatically pull in related objects from this or another module. Typical examples include fetching events at a map location, or people in a group. This is very cool. "Aren't joins bad? I read that joins were bad in some NoSQL article." Short answer: no. Long answer: sometimes. Mostly in so-called "webscale" projects, which have nothing to do with 99% of websites. If you are building the next Facebook you probably know that, and you'll denormalize your data instead and deal with all the fascinating bugs that come with maintaining two copies of everything. Of course you have to be smart about how you use joins, and we've included options that help with that. You might write this: addFields:name: '_location'type: 'joinByOne'withType: 'mapLocation'idField: 'locationId'label: 'Location'} (How does this work? apostrophe-schemas will consult the apostrophe-pages module to find the manager object responsible for mapLocation objects, which will turn out to be the apostrophe-map module.) Now the user can pick a map location. And if you call schema.join(req, schema, myObjectOrArrayOfObjects, callback), apostrophe-schemas will carry out the join, fetch the related object and populate the _location property of your object. Note that it is much more efficient to pass an array of objects if you need related objects for more than one. Here's an example of using the resulting ._location property in a Nunjucks template: {% if item._location %}<a href="{{ item._location.url | e }}">Location: {{ item._location.title | e }}</a>{% endif %} The id of the map location actually "lives" in the location_id property of each object, but you won't have to deal with that directly. Always give your joins a name starting with an underscore. This warns Apostrophe not to store this information in the database permanently where it will just take up space, then get re-joined every time anyway. Currently after the user has selected one item they see a message reading "Limit Reached!" We realize this may not be the best way of indicating that a selection has already been made. So you may pass a limitText option with an alternative message to be displayed at this point. What if you want to allow the user to pick anything at all, as long as it's a "regular page" in the page tree with its own permanent URL? Just use: withType: 'page' This special case allows you to easily build navigation menus and the like using schema widgets and array fields. You can also join back in the other direction: addFields:name: '_events'type: 'joinByOneReverse'withType: 'event'idField: 'locationId'label: 'Events' Now, in the show template for the map module, we can write: {% for event in item._events %}<h4><a href="{{ event.url | e }}">{{ event.title | e }}</a></h4>{% endfor %} "Holy crap!" Yeah, it's pretty cool. Note that the user always edits the relationship on the "owning" side, not the "reverse" side. The event has a location_id property pointing to the map, so users pick a map location when editing an event, not the other way around. "Won't this cause an infinite loop?" When an event fetches a location and the location then fetches the event, you might expect an infinite loop to occur. However Apostrophe does not carry out any further joins on the fetched objects unless explicitly asked to. "What if my events are joined with promoters and I need to see their names on the location page?" If you really want to join two levels deep, you can "opt in" to those joins: addFields:name: '_events'// Details of the join, then...withJoins: '_promoters' This assumes that _promoters is a join you have already defined for events. "What if my joins are nested deeper than that and I need to reach down several levels?" You can use "dot notation," just like in MongoDB: withJoins: '_promoters._assistants' This will allow events to be joined with their promoters, and promoters to be joined with their assistants, and there the chain will stop. You can specify more than one join to allow, and they may share a prefix: withJoins: '_promoters._assistants' '_promoters._bouncers' Remember, each of these later joins must actually be present in the configuration for the module in question. That is, "promoters" must have a join called "_assistants" defined in its schema. Joins are allowed in the schema of an array field, and they work exactly as you would expect. Just include joins in the schema for the array as you normally would. And if you are carrying out a nested join with the withJoins option, you'll just need to refer to the join correctly. Let's say that each promoter has an array of ads, and each ad is joined to a media outlet. We're joing with events, which are joined to promoters, and we want to make sure media outlets are included in the results. So we write: addFields:name: '_events'// Details of the join, then...withJoins: '_promoters.ads._mediaOutlet' Events can only be in one location, but stories can be in more than one book, and books also contain more than one story. How do we handle that? Consider this configuration for a books module: addFields:name: '_stories'type: 'joinByArray'withType: 'story'idsField: 'storyIds'sortable: truelabel: 'Stories' Now we can access all the stories from the show template for books (or the index template, or pretty much anywhere): <h3>Stories</h3>{% for story in item._stories %}<h4><a href="{{ story.url | e }}">{{ story.title | e }}</a></h4>{% endfor %} Since we specified sortable:true, the user can also drag the list of stories into a preferred order. The stories will always appear in that order in the ._stories property when examinining a book object. "Many-to-many... sounds like a LOT of objects. Won't it be slow and use a lot of memory?" It's not as bad as you think. Apostrophe typically fetches only one page's worth of items at a time in the index view, with pagination links to view more. Add the objects those are joined to and it's still not bad, given the performance of v8. But sometimes there really are too many related objects and performance suffers. So you may want to restrict the join to occur only if you have retrieved only one book, as on a "show" page for that book. Use the ifOnlyOne option: 'stories':addFields:name: '_books'withType: 'book'ifOnlyOne: truelabel: 'Books' Now any call to schema.join with only one object, or an array of only one object, will carry out the join with stories. Any call with more than one object won't. Hint: in index views of many objects, consider using AJAX to load related objects when the user indicates interest rather than displaying related objects all the time. Another way to speed up joins is to limit the fields that are fetched in the join. You may pass options such as fields to the get method used to actually fetch the joined objects. Note that apos.get and everything derived from it, like snippets.get, will accept a fields option which is passed to MongoDB as the projection: 'stories':addFields:name: '_books'withType: 'book'label: 'Books'getOptions:fields: title: 1 slug: 1 If you are just linking to things, { title: 1, slug: 1 } is a good projection to use. You can also include specific areas by name in this way. We can also access the books from the story if we set the join up in the stories module as well: addFields:name: '_books'type: 'joinByArrayReverse'withType: 'book'idsField: 'storyIds'label: 'Books'} Now we can access the ._books property for any story. But users still must select stories when editing books, not the other way around. What if each story comes with an author's note that is specific to each book? That's not a property of the book, or the story. It's a property of the relationship between the book and the story. If the author's note for every each appearance of each story has to be super-fancy, with rich text and images, then you should make a new module that subclasses snippets in its own right and just join both books and stories to that new module. You can also use array fields in creative ways to address this problem, using joinByOne as one of the fields of the schema in the array. But if the relationship just has a few simple attributes, there is an easier way: addFields:name: '_stories'label: 'Stories'type: 'joinByArray'withType: 'story'idsField: 'storyIds'relationshipsField: 'storyRelationships'relationship:name: 'authorsNote'type: 'string'sortable: true Currently "relationship" properties can only be of type string (for text), select or boolean (for checkboxes). Otherwise they behave like regular schema properties. Warning: the relationship field names label and value must not be used. These names are reserved for internal implementation details. Form elements to edit relationship fields appear next to each entry in the list when adding stories to a book. So immediately after adding a story, you can edit its author's note. Once we introduce the relationship option, our templates have to change a little bit. The show page for a book now looks like: {% for story in item._stories %}<h4>Story: {{ story.item.title | e }}</h4><h5>Author's Note: {{ story.relationship.authorsNote | e }}</h5>{% endfor %} Two important changes here: the actual story is story.item, not just story, and relationship fields can be accessed via story.relationship. This change kicks in when you use the relationship option. Doing it this way saves a lot of memory because we can still share book objects between stories and vice versa. You can do this in a reverse join too: addFields:name: '_books'type: 'joinByArrayReverse'withType: 'book'idsField: 'storyIds'relationshipsField: 'storyRelationships'relationship:name: 'authorsNote'type: 'string' Now you can write: {% for book in item._books %}<h4>Book: {{ book.item.title | e }}</h4><h5>Author's Note: {{ book.relationship.authorsNote | e }}</h5>{% endfor %} As always, the relationship fields are edited only on the "owning" side (that is, when editing a book). "What is the relationshipsField option for? I don't see story_relationships in the templates anywhere." Apostrophe stores the actual data for the relationship fields in story_relationships. But since it's not intuitive to write this in a template: {# THIS IS THE HARD WAY #}{% for story in book._stories %}{{ story.item.title | e }}{{ book.story_relationships[story._id].authorsNote | e }}{% endif %} Apostrophe instead lets us write this: {# THIS IS THE EASY WAY #}{% for story in book._stories %}{{ story.item.title | e }}{{ story.relationship.authorsNote | e }}{% endif %} Much better. Sometimes you won't want to honor all of the joins that exist in your schema. Other times you may wish to fetch more than your schema's withJoin options specify as a default behavior. You can force schemas.join to honor specific joins by supplying a withJoins parameter: schemas; The syntax is exactly the same as for the withJoins option to individual joins in the schema, discussed earlier. You can override templates for individual fields without resorting to writing your own new.html and edit.html templates from scratch. Here's the string.html template that renders all fields with the string type by default: {% include "schemaMacros.html" %}{% if textarea %}{{ formTextarea(name, label) }}{% else %}{{ formText(name, label) }}{% endif %} You can override these for your project by creating new templates with the same names in the lib/modules/apostrophe-schemas/views folder. This lets you change the appearance for every field of a particular type. You should only override what you really wish to change. In addition, you can specify an alternate template name for an individual field in your schema: { type: 'integer', name: 'shoeSize', label: 'Shoe Size', template: 'shoeSize' } This will cause the shoeSize.html template to be rendered instead of the integer.html template. You can also pass a render function, which receives the field object as its only parameter. Usually you'll find it much more convenient to just use a string and put your templates in lib/modules/apostrophe-schemas/views. You can add a new field type easily. On the server side, we'll need to write three methods: The converter's job is to ensure the content is really a list of strings and then populate the object with it. We pull the list from data (what the user submitted) and use it to populate object. We also have access to the field name ( name) and, if we need it, the entire field object ( field), which allows us to implement custom options. Your converter must not set the property to undefined or delete the property. It must be possible to distinguish a property that has been set to a value, even if that value is false or null or [], from one that is currently undefined and should therefore display the default. Here's an example of a custom field type: a simple list of strings. // Earlier in our module's constructor...self_apos;// Now self.renderer is availableschemas; We can also supply an optional indexer method to allow site-wide searches to locate this object based on the value of the field: {var silent = fieldsilent === undefined ? true : fieldsilent;texts;} And, if our field modifies properties other than the one matching its name, we must supply a copier function so that the subsetInstance method can be used to edit personal profiles and the like: {// Note: if this is really all you need, you can skip// writing a copiertoname = fromname;} The views/schemaList.html template should look like this. Note that the "name" and "label" options are passed to the template. In fact, all properties of the field that are part of the schema are available to the template. Setting data-name correctly is crucial. Adding a CSS class based on the field name is a nice touch but not required. <fieldset class="apos-fieldset my-fieldset-list apos-fieldset-{{ name | css}}" data-<label>{{ label | e }}</label>{# Text entry for autocompleting the next item #}<input name="{{ name | e }}" data-autocomplete{# This markup is designed for jQuery Selective to show existing list items #}<ul data-list<li data-item><span class="label-and-remove"><a href="#" class="apos-tag-remove icon-remove" data-remove></a><span data-label>Example label</span></span></li></ul></fieldset> Next, on the browser side, we need to supply two methods: a displayer and a converter. "displayer" is a method that populates the form field. aposSchemas.populateFields will invoke it. "converter" is a method that retrieves data from the form field and places it in an object. aposSchemas.convertFields will invoke it. Here's the browser-side code to add our "list" type: aposSchemas; This code can live in site.js, or in a js file that you push as an asset from your project or an npm module. Make sure your module loads after apostrophe-schema. For many applications just creating your own array of fields is fine. But if you are creating a subclass of another module that also uses schemas, and you want to adjust the schema, you'll be a lot happier if the superclass uses the schemas.compose() method to build up the schema via the addFields, removeFields, orderFields and occasionally alterFields options. Here's a simple example: schemas; This compose call adds two fields, then removes one of them. This makes it easy for subclasses to contribute to the object which a parent class will ultimately pass to compose. It often looks like this: var schemas = ;// Superclass has title and age fields, also merges in any fields appended// to addFields by a subclass{var self = this;optionsaddFields =name: 'title'type: 'string'label: 'Name'name: 'age'type: 'integer'label: 'Age';self_schema = schemas;}// Subclass removes the age field, adds the shoe size field{var self = this;MySuperclass;} You can also specify a removeFields option which will remove some of the fields you passed to addFields. This is useful if various subclasses are contributing to your schema. removeFields: 'thumbnail' 'body'} When adding fields, you can specify where you want them to appear relative to existing fields via the before, after, start and end options. This works great with the subclassing technique shown above: addFields:name: 'favoriteCookie'type: 'string'label: 'Favorite Cookie'after: 'title' Any additional fields after favoriteCookie will be inserted with it, following the title field. Use the before option instead of after to cause a field to appear before another field. Use start: true to cause a field to appear at the top. Use start: end to cause a field to appear at the end. If this is not enough, you can explicitly change the order of the fields with orderFields: orderFields: 'year' 'specialness' Any fields you do not specify will appear in the original order, after the last field you do specify (use removeFields if you want a field to go away). Although required: true works well, if you are subclassing and you wish to require a number of previously optional fields, the requiredFields option is more convenient. This is especially handy when working with apostrophe-moderator: requireFields: 'title' 'startDate' 'body' You can specify the same field twice in your addFields array. The last occurrence wins. There is also an alterFields option available. This must be a function which receives the schema (an array of fields) as its argument and modifies it. Most of the time you will not need this option; see removeFields, addFields, orderFields and requireFields. It is mostly useful if you want to make one small change to a field that is already rather complicated. Note you must modify the existing array of fields "in place." refine Sometimes you'll want a modified version of an existing schema. schemas.refine is the simplest way to do this: var newSchema = schemas.refine(schema, { addFields: ..., removeFields ..., etc }); The options are exactly the same as the options to compose. The returned array is a copy. No modifications are made to the original schema array. subset If you just want to keep certain fields in your schema, while maintaining the same tab groups, use the subset method. This method will discard any unwanted fields, as well as any groups that are empty in the new subset of the schema: // A subset suitable for people editing their own profilesvar profileSchema = schemas; If you wish to apply new groups to the subset, use refine and groupFields. newInstance The newInstance method can be used to create an object which has the appropriate default value for every schema field: var snowman = schemas; subsetInstance The subsetInstance method accepts a schema and an existing instance object and returns a new object with only the properties found in the given schema. This includes not just the obvious properties matching the name of each field, but also any idField or idsField properties specified by joins. var profileSchema = schemas;var profile = schemas;
https://www.npmjs.com/package/apostrophe-schemas
CC-MAIN-2017-04
refinedweb
5,151
63.29
Suppose I have a shop selling shoes and want to keep track of my competitor's prices. I could go to my competitor's website each day to compare each shoe's price with my own, however this would take a lot of time and would not scale if I sold thousands of shoes or needed to check price changes more frequently. Or maybe I just want to buy a shoe when it is on sale. I could come back and check the shoe website each day until I get lucky, but the shoe I want might not be on sale for months. Both of these repetitive manual processes could instead be replaced with an automated solution using the web scraping techniques covered in this book. In an ideal world, web scraping would not be necessary and each website would provide an API to share their data in a structured format. Indeed, some websites do provide APIs, but they are typically restricted by what data is available and how frequently it can be accessed. Additionally, the main priority for a website developer will always be to maintain the frontend interface over the backend API. In short, we cannot rely on APIs to access the online data we may want and therefore, need to learn about web scraping techniques. Web scraping is in the early Wild West stage, where what is permissible is still being established. If the scraped data is being used for personal use, in practice, there is no problem. However, if the data is going to be republished, then the type of data scraped is important. Several court cases around the world have helped establish what is permissible when scraping a website. In Feist Publications, Inc. v. Rural Telephone Service Co., the United States Supreme Court decided that scraping and republishing facts, such as telephone listings, is allowed. Then, a similar case in Australia, Telstra Corporation Limited v. Phone Directories Company Pty Ltd, demonstrated that only data with an identifiable author can be copyrighted. Also, the European Union case, ofir.dk vs home.dk, concluded that regular crawling and deep linking is permissible. These cases suggest that when the scraped data constitutes facts (such as business locations and telephone listings), it can be republished. However, if the data is original (such as opinions and reviews), it most likely cannot be republished for copyright reasons. In any case, when you are scraping data from a website, remember that you are their guest and need to behave politely or they may ban your IP address or proceed with legal action. This means that you should make download requests at a reasonable rate and define a user agent to identify you. The next section on crawling will cover these practices in detail. Note You can read more about these legal cases at,, and. Before diving into crawling a website, we should develop an understanding about the scale and structure of our target website. The website itself can help us through their robots.txt and Sitemap files, and there are also external tools available to provide further details such as Google Search and WHOIS. Most websites define a robots.txt file to let crawlers know of any restrictions about crawling their website. These restrictions are just a suggestion but good web citizens will follow them. The robots.txt file is a valuable resource to check before crawling to minimize the chance of being blocked, and also to discover hints about a website's structure. More information about the robots.txt protocol is available at. The following code is the content of our example robots.txt, which is available at: # section 1 User-agent: BadCrawler Disallow: / # section 2 User-agent: * Crawl-delay: 5 Disallow: /trap # section 3 Sitemap: In section 1, the robots.txt file asks a crawler with user agent BadCrawler not to crawl their website, but this is unlikely to help because a malicious crawler would not respect robots.txt anyway. A later example in this chapter will show you how to make your crawler follow robots.txt automatically. Section 2 specifies a crawl delay of 5 seconds between download requests for all User-Agents, which should be respected to avoid overloading their server. There is also a /trap link to try to block malicious crawlers who follow disallowed links. If you visit this link, the server will block your IP for one minute! A real website would block your IP for much longer, perhaps permanently, but then we could not continue with this example. Section 3 defines a Sitemap files are provided by websites to help crawlers locate their updated content without needing to crawl every web page. For further details, the sitemap standard is defined at. Here is the content of the robots.txt file: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns=""> <url><loc></loc></url> <url><loc></loc></url> <url><loc></loc></url> ... </urlset> This sitemap provides links to all the web pages, which will be used in the next section to build our first crawler. Sitemap files provide an efficient way to crawl a website, but need to be treated carefully because they are often missing, out of date, or incomplete. The size of the target website will affect how we crawl it. If the website is just a few hundred URLs, such as our example website, efficiency is not important. However, if the website has over a million web pages, downloading each sequentially would take months. This problem is addressed later in Chapter 4, Concurrent Downloading, on distributed downloading. A quick way to estimate the size of a website is to check the results of Google's crawler, which has quite likely already crawled the website we are interested in. We can access this information through a Google search with the site keyword to filter the results to our domain. An interface to this and other advanced search parameters are available at. Here are the site search results for our example website when searching Google for site:example.webscraping.com: As we can see, Google currently estimates 202 web pages, which is about as expected. For larger websites, I have found Google's estimates to be less accurate. We can filter these results to certain parts of the website by adding a URL path to the domain. Here are the results for site:example.webscraping.com/view, which restricts the site search to the country web pages: This additional filter is useful because ideally you will only want to crawl the part of a website containing useful data rather than every page of it. The type of technology used to build a website will effect how we crawl it. A useful tool to check the kind of technologies a website is built with is the builtwith module, which can be installed with: pip install builtwith This module will take a URL, download and analyze it, and then return the technologies used by the website. Here is an example: >>> import builtwith >>> builtwith.parse('') {u'javascript-frameworks': [u'jQuery', u'Modernizr', u'jQuery UI'], u'programming-languages': [u'Python'], u'web-frameworks': [u'Web2py', u'Twitter Bootstrap'], u'web-servers': [u'Nginx']} We can see here that the example website uses the Web2py Python web framework alongside with some common JavaScript libraries, so its content is likely embedded in the HTML and be relatively straightforward to scrape. If the website was instead built with AngularJS, then its content would likely be loaded dynamically. Or, if the website used ASP.NET, then it would be necessary to use sessions and form submissions to crawl web pages. Working with these more difficult cases will be covered later in Chapter 5, Dynamic Content and Chapter 6, Interacting with Forms. For some websites it may matter to us who is the owner. For example, if the owner is known to block web crawlers then it would be wise to be more conservative in our download rate. To find who owns a website we can use the WHOIS protocol to see who is the registered owner of the domain name. There is a Python wrapper to this protocol, documented at, which can be installed via pip: pip install python-whois Here is the key part of the WHOIS response when querying the appspot.com domain with this module: >>> import whois >>> print whois.whois('appspot.com') { ... "name_servers": [ "NS1.GOOGLE.COM", "NS2.GOOGLE.COM", "NS3.GOOGLE.COM", "NS4.GOOGLE.COM", "ns4.google.com", "ns2.google.com", "ns1.google.com", "ns3.google.com" ], "org": "Google Inc.", "emails": [ "[email protected]", "[email protected]" ] } We can see here that this domain is owned by Google, which is correct—this domain is for the Google App Engine service. Google often blocks web crawlers despite being fundamentally a web crawling business themselves. We would need to be careful when crawling this domain because Google often blocks web crawlers, despite being fundamentally a web crawling business themselves. In order to scrape a website, we first need to download its web pages containing the data of interest—a process known as crawling. There are a number of approaches that can be used to crawl a website, and the appropriate choice will depend on the structure of the target website. This chapter will explore how to download web pages safely, and then introduce the following three common approaches to crawling a website: Crawling a sitemap Iterating the database IDs of each web page Following web page links To crawl web pages, we first need to download them. Here is a simple Python script that uses Python's urllib2 module to download a URL: import urllib2 def download(url): return urllib2.urlopen(url).read() When a URL is passed, this function will download the web page and return the HTML. The problem with this snippet is that when downloading the web page, we might encounter errors that are beyond our control; for example, the requested page may no longer exist. In these cases, urllib2 will raise an exception and exit the script. To be safer, here is a more robust version to catch these exceptions: import urllib2 def download(url): print 'Downloading:', url try: html = urllib2.urlopen(url).read() except urllib2.URLError as e: print 'Download error:', e.reason html = None return html Now, when a download error is encountered, the exception is caught and the function returns None. Often, the errors encountered when downloading are temporary; for example, the web server is overloaded and returns a 503 Service Unavailable error. For these errors, we can retry the download as the server problem may now be resolved. However, we do not want to retry downloading for all errors. If the server returns 404 Not Found, then the web page does not currently exist and the same request is unlikely to produce a different result. The full list of possible HTTP errors is defined by the Internet Engineering Task Force, and is available for viewing at. In this document, we can see that the 4xx errors occur when there is something wrong with our request and the 5xx errors occur when there is something wrong with the server. So, we will ensure our download function only retries the 5xx errors. Here is the updated version to support this: def download(url, num_retries=2): print 'Downloading:', url try: html = urllib2.urlopen(url).read() except urllib2.URLError as e: print 'Download error:', e.reason html = None if num_retries > 0: if hasattr(e, 'code') and 500 <= e.code < 600: # recursively retry 5xx HTTP errors return download(url, num_retries-1) return html Now, when a download error is encountered with a 5xx code, the download is retried by recursively calling itself. The function now also takes an additional argument for the number of times the download can be retried, which is set to two times by default. We limit the number of times we attempt to download a web page because the server error may not be resolvable. To test this functionality we can try downloading, which returns the 500 error code: >>> download('') Downloading: Download error: Internal Server Error Downloading: Download error: Internal Server Error Downloading: Download error: Internal Server Error As expected, the download function now tries downloading the web page, and then on receiving the 500 error, it retries the download twice before giving up. By default, urllib2 will download content with the Python-urllib/2.7 user agent, where 2.7 is the version of Python. It would be preferable to use an identifiable user agent in case problems occur with our web crawler. Also, some websites block this default user agent, perhaps after they experienced a poorly made Python web crawler overloading their server. For example, this is what currently returns for Python's default user agent: So, to download reliably, we will need to have control over setting the user agent. Here is an updated version of our download function with the default user agent set to 'wswp' (which stands for Web Scraping with Python): def download(url, user_agent='wswp', num_retries=2): print 'Downloading:', url headers = {'User-agent': user_agent} request = urllib2.Request(url, headers=headers) try: html = urllib2.urlopen(request).read() except urllib2.URLError as e: print 'Download error:', e.reason html = None if num_retries > 0: if hasattr(e, 'code') and 500 <= e.code < 600: # retry 5XX HTTP errors return download(url, user_agent, num_retries-1) return html Now we have a flexible download function that can be reused in later examples to catch errors, retry the download when possible, and set the user agent. For our first simple crawler, we will use the sitemap discovered in the example website's robots.txt to download all the web pages. To parse the sitemap, we will use a simple regular expression to extract URLs within the <loc> tags. Note that a more robust parsing approach called CSS selectors will be introduced in the next chapter. Here is our first example crawler: def crawl_sitemap(url): # download the sitemap file sitemap = download(url) # extract the sitemap links links = re.findall('<loc>(.*?)</loc>', sitemap) # download each link for link in links: html = download(link) # scrape html here # ... Now, we can run the sitemap crawler to download all countries from the example website: >>> crawl_sitemap('') Downloading: Downloading: Downloading: Downloading: ... This works as expected, but as discussed earlier, Sitemap files often cannot be relied on to provide links to every web page. In the next section, another simple crawler will be introduced that does not depend on the In this section, we will take advantage of weakness in the website structure to easily access all the content. Here are the URLs of some sample countries: We can see that the URLs only differ at the end, with the country name (known as a slug) and ID. It is a common practice to include a slug in the URL to help with search engine optimization. Quite often, the web server will ignore the slug and only use the ID to match with relevant records in the database. Let us check whether this works with our example website by removing the slug and loading: The web page still loads! This is useful to know because now we can ignore the slug and simply iterate database IDs to download all the countries. Here is an example code snippet that takes advantage of this trick: import itertools for page in itertools.count(1): url = '' % page html = download(url) if html is None: break else: # success - can scrape the result pass Here, we iterate the ID until we encounter a download error, which we assume means that the last country has been reached. A weakness in this implementation is that some records may have been deleted, leaving gaps in the database IDs. Then, when one of these gaps is reached, the crawler will immediately exit. Here is an improved version of the code that allows a number of consecutive download errors before exiting: # maximum number of consecutive download errors allowed max_errors = 5 # current number of consecutive download errors num_errors = 0 for page in itertools.count(1): url = '' % page html = download(url) if html is None: # received an error trying to download this webpage num_errors += 1 if num_errors == max_errors: # reached maximum number of # consecutive errors so exit break else: # success - can scrape the result # ... num_errors = 0 The crawler in the preceding code now needs to encounter five consecutive download errors to stop iterating, which decreases the risk of stopping the iteration prematurely when some records have been deleted. Iterating the IDs is a convenient approach to crawl a website, but is similar to the sitemap approach in that it will not always be available. For example, some websites will check whether the slug is as expected and if not return a 404 Not Found error. Also, other websites use large nonsequential or nonnumeric IDs, so iterating is not practical. For example, Amazon uses ISBNs as the ID for their books, which have at least ten digits. Using an ID iteration with Amazon would require testing billions of IDs, which is certainly not the most efficient approach to scraping their content. So far, we have implemented two simple crawlers that take advantage of the structure of our sample website to download all the countries. These techniques should be used when available, because they minimize the required amount of web pages to download. However, for other websites, we need to make our crawler act more like a typical user and follow links to reach the content of interest. We could simply download the entire website by following all links. However, this would download a lot of web pages that we do not need. For example, to scrape user account details from an online forum, only account pages need to be downloaded and not discussion threads. The link crawler developed here will use a regular expression to decide which web pages to download. Here is an initial version of the code: import re def link_crawler(seed_url, link_regex): """Crawl from the given seed URL following links matched by link_regex """ crawl_queue = [seed_url] while crawl_queue: url = crawl_queue.pop() html = download(url) # filter for links matching our regular expression for link in get_links(html): if re.match(link_regex, link): crawl_queue.append(link) def get_links(html): """Return a list of links from html """ # a regular expression to extract all links from the webpage webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE) # list of all links from the webpage return webpage_regex.findall(html) To run this code, simply call the link_crawler function with the URL of the website you want to crawl and a regular expression of the links that you need to follow. For the example website, we want to crawl the index with the list of countries and the countries themselves. The index links follow this format: The country web pages will follow this format: So a simple regular expression to match both types of web pages is /(index|view)/. What happens when the crawler is run with these inputs? You would find that we get the following download error: >>> link_crawler('', 'example.webscraping.com/(index|view)/') Downloading: Downloading: /index/1 Traceback (most recent call last): ... ValueError: unknown url type: /index/1 The problem with downloading /index/1 is that it only includes the path of the web page and leaves out the protocol and server, which is known as a relative link. Relative links work when browsing because the web browser knows which web page you are currently viewing. However, urllib2 is not aware of this context. To help urllib2 locate the web page, we need to convert this link into an absolute link, which includes all the details to locate the web page. As might be expected, Python includes a module to do just this, called urlparse. Here is an improved version of link_crawler that uses the urlparse module to create the absolute links: import urlparse def link_crawler(seed_url, link_regex): """Crawl from the given seed URL following links matched by link_regex """ crawl_queue = [seed_url] while crawl_queue: url = crawl_queue.pop() html = download(url) for link in get_links(html): if re.match(link_regex, link): link = urlparse.urljoin(seed_url, link) crawl_queue.append(link) When this example is run, you will find that it downloads the web pages without errors; however, it keeps downloading the same locations over and over. The reason for this is that these locations have links to each other. For example, Australia links to Antarctica and Antarctica links right back, and the crawler will cycle between these forever. To prevent re-crawling the same links, we need to keep track of what has already been crawled. Here is the updated version of link_crawler that stores the URLs seen before, to avoid redownloading duplicates: def link_crawler(seed_url, link_regex): crawl_queue = [seed_url] # keep track which URL's have seen before seen = set(crawl_queue) while crawl_queue: url = crawl_queue.pop() html = download(url) for link in get_links(html): # check if link matches expected regex if re.match(link_regex, link): # form absolute link link = urlparse.urljoin(seed_url, link) # check if have already seen this link if link not in seen: seen.add(link) crawl_queue.append(link) When this script is run, it will crawl the locations and then stop as expected. We finally have a working crawler! Now, let's add some features to make our link crawler more useful for crawling other websites. Firstly, we need to interpret robots.txt to avoid downloading blocked URLs. Python comes with the robotparser module, which makes this straightforward, as follows: >>> import robotparser >>> rp = robotparser.RobotFileParser() >>> rp.set_url('') >>> rp.read() >>>>>>> rp.can_fetch(user_agent, url) False >>>>> rp.can_fetch(user_agent, url) True The robotparser module loads a robots.txt file and then provides a can_fetch() function, which tells you whether a particular user agent is allowed to access a web page or not. Here, when the user agent is set to 'BadCrawler', the robotparser module says that this web page can not be fetched, as was defined in robots.txt of the example website. To integrate this into the crawler, we add this check in the crawl loop: ... while crawl_queue: url = crawl_queue.pop() # check url passes robots.txt restrictions if rp.can_fetch(user_agent, url): ... else: print 'Blocked by robots.txt:', url Sometimes it is necessary to access a website through a proxy. For example, Netflix is blocked in most countries outside the United States. Supporting proxies with urllib2 is not as easy as it could be (for a more user-friendly Python HTTP module, try requests, documented at). Here is how to support a proxy with urllib2: proxy = ... opener = urllib2.build_opener() proxy_params = {urlparse.urlparse(url).scheme: proxy} opener.add_handler(urllib2.ProxyHandler(proxy_params)) response = opener.open(request) Here is an updated version of the download function to integrate this: def download(url, user_agent='wswp', proxy=None, num_retries=2): print 'Downloading:', url headers = {'User-agent': user_agent} request = urllib2.Request(url, headers=headers) opener = urllib2.build_opener() if proxy: proxy_params = {urlparse.urlparse(url).scheme: proxy} opener.add_handler(urllib2.ProxyHandler(proxy_params)) try: html = opener.open(request).read() except urllib2.URLError as e: print 'Download error:', e.reason html = None if num_retries > 0: if hasattr(e, 'code') and 500 <= e.code < 600: # retry 5XX HTTP errors html = download(url, user_agent, proxy, num_retries-1) return html If we crawl a website too fast, we risk being blocked or overloading the server. To minimize these risks, we can throttle our crawl by waiting for a delay between downloads. Here is a class to implement this: class Throttle: """Add a delay between downloads to the same domain """ def __init__(self, delay): # amount of delay between downloads for each domain self.delay = delay # timestamp of when a domain was last accessed self.domains = {} def wait(self, url): domain = urlparse.urlparse(url).netloc last_accessed = self.domains.get(domain) if self.delay > 0 and last_accessed is not None: sleep_secs = self.delay - (datetime.datetime.now() - last_accessed).seconds if sleep_secs > 0: # domain has been accessed recently # so need to sleep time.sleep(sleep_secs) # update the last accessed time self.domains[domain] = datetime.datetime.now() This Throttle class keeps track of when each domain was last accessed and will sleep if the time since the last access is shorter than the specified delay. We can add throttling to the crawler by calling throttle before every download: throttle = Throttle(delay) ... throttle.wait(url) result = download(url, headers, proxy=proxy, num_retries=num_retries) Currently, our crawler will follow any link that it has not seen before. However, some websites dynamically generate their content and can have an infinite number of web pages. For example, if the website has an online calendar with links provided for the next month and year, then the next month will also have links to the next month, and so on for eternity. This situation is known as a spider trap. A simple way to avoid getting stuck in a spider trap is to track how many links have been followed to reach the current web page, which we will refer to as depth. Then, when a maximum depth is reached, the crawler does not add links from this web page to the queue. To implement this, we will change the seen variable, which currently tracks the visited web pages, into a dictionary to also record the depth they were found at: def link_crawler(..., max_depth=2): max_depth = 2 seen = {} ... depth = seen[url] if depth != max_depth: for link in links: if link not in seen: seen[link] = depth + 1 crawl_queue.append(link) Now, with this feature, we can be confident that the crawl will always complete eventually. To disable this feature, max_depth can be set to a negative number so that the current depth is never equal to it. The full source code for this advanced link crawler can be downloaded at. To test this, let us try setting the user agent to BadCrawler, which we saw earlier in this chapter was blocked by robots.txt. As expected, the crawl is blocked and finishes immediately: >>>>>>> link_crawler(seed_url, link_regex, user_agent='BadCrawler') Blocked by robots.txt: Now, let's try using the default user agent and setting the maximum depth to 1 so that only the links from the home page are downloaded: >>> link_crawler(seed_url, link_regex, max_depth=1) Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: Downloading: As expected, the crawl stopped after downloading the first page of countries. This chapter introduced web scraping and developed a sophisticated crawler that will be reused in the following chapters. We covered the usage of external tools and modules to get an understanding of a website, user agents, sitemaps, crawl delays, and various crawling strategies. In the next chapter, we will explore how to scrape data from the crawled web pages.
https://www.packtpub.com/product/web-scraping-with-python/9781782164364
CC-MAIN-2021-17
refinedweb
4,428
62.48
03 August 2012 05:45 [Source: ICIS news] By Helen Yan ?xml:namespace> SINGAPORE Spot prices shed $100/tonne (€82/tonne) or 4% in three weeks to $2,400/tonne CFR (cost and freight) northeast (NE) Downstream synthetic rubber producers deem BD prices above $2,300/tonne CFR NE Asia as not workable given current poor market conditions in the tyre industry. BD is a raw material used to make synthetic rubbers, which go into production of tyres for the automotive industry. “The automotive and tyre industries are very weak and demand for synthetic rubber has dropped, a synthetic rubber producer said. “Our margins are being eroded by high BD costs and BD prices have to drop to around $2,200/tonne CFR for the synthetic rubber makers to post any margins,” he added. But demand for tyres has been falling in view of softening auto sales in Europe, as well as in Asia’s huge emerging markets such as Chinese and Indian tyre makers decided to cut operating rates at their production facilities and this has weighed down on consumption of synthetic rubber. Non-oil grade 1502 styrene butadiene rubber (SBR) prices fell to $2,650-2,750/tonne CIF (cost, freight and insurance) China in the week ended 1 August, down by about $100/tonne in the past month, according to ICIS. Prices of non-oil grade 1502 SBR need to be at least $400/tonne higher than BD, for the SBR producers to generate profits, industry sources said. Synthetic rubber producers are insisting for lower BD prices at around $2,200/tonne CFR NE Asia as at current offers of $2,400/tonne CFR NE Asia for their production feedstock, hardly any margin can be generated. Downward price pressures, however, may ease somewhat as supply will be shaved in Major Taiwanese cracker operator, Formosa Petrochemical Corp (FPCC), will be shutting down its 1.03m tonne/year naphtha cracker in Mailiao for safety inspection in mid-August. Safety checks at the production facilities at the Mailiao petrochemical complex are being required by the Taiwanese government following a string of fire incidents that occurred at the site last year. “We have no spot BD cargo, as we will shut down the No 2 cracker in mid-August for 30 days for safety checks,” a company source said. FPCC runs three crackers at Mailiao, with BD capacities totalling some 450,000 tonnes/year. Currently FPCC’s No 2 cracker and its 1.2 m tonne/year No 3 cracker are running at full capacity, industry sources said. The company’s third cracker – a 700,000 tonne No 1 unit – is currently being restarted after completing a turnaround from 19 June. ($1 = €0
http://www.icis.com/Articles/2012/08/03/9583531/asia-bd-may-extend-falls-tight-taiwan-supply-to-temper-decline.html
CC-MAIN-2014-49
refinedweb
452
54.97
Build .apk using monaca CLI or cordova CLI Can I build an .apk in my computer (with Andorid SDK) using monaca CLI or cordova CLI? Thank you. - munsterlander 侍 last edited by @giov Yes, by using the remote build command. Here is a full list of commands: create … create a new Monaca project preview … runs a local web server for preview debug … run app on device using Monaca Debugger remote build … build project on Monaca Cloud login … sign in to Monaca Cloud logout … sign out from Monaca Cloud clone … clone project from the Monaca Cloud import … import project from the Monaca Cloud upload … upload project to Monaca Cloud download … download project from Monaca Cloud plugin … manage installed plugins proxy … configure proxy to use when connecting to Monaca Cloud I want to build without remote building but using Android SDK installed in my pc. Can I build using CLI or if also possible using Visual Studio 2015? Thank you. - munsterlander 侍 last edited by munsterlander - Leonardo Augusto 侍 last edited by @giov Yes its possible (Build with Visual Studio) I have made all my applications using visual studio 2015 and Onsen UI (And Onsen UI 2 ) templates for Visual Studio 2015 It’s very easy to build an apk. I have a complete tutorial to help you Thank you. I have a project exported from Monaca IDE, I copied the www folder in an empty cordova project and then “run android” but it doesn’t work. I recieved this error BUILD FAILED Total time: 40.681 secs FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':transformClassesWithDexForDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files (x86)\Java\jdk1.7.0_55\bin\java.exe'' finished with non-zero exit value 1 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Error: Error code 1 for command: cmd with args: /s,/c,"C:\Users\asus\Desktop\prova\platforms\android\gradlew cdvBuildDebug -b C:\Users\asus\Desktop\prova\platforms\android\build.gradle -PcdvBuildArch=arm -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true" - Leonardo Augusto 侍 last edited by Leonardo Augusto @giov To be honest, i guess in the output window we have also, other problem (Drawable /icon.png not found) I have always this problem. So check also if you have a Drawable folder. But if your problem is this , how you told me: Perhaps you need to fix the build.gradle adding : android { compileSdkVersion buildToolsVersion ' ' defaultConfig { ... targetSdkVersion multiDexEnabled true } } I created a splitter template in VS 2015 but i have a error that says error of distribution (impossible to find specificated file). With cordova CLI the same project run on my device. - Leonardo Augusto 侍 last edited by Leonardo Augusto @giov Seems a problem to find your Keystore Do you have one? Set the keystore file Build.json file (If your Cordova CLI version is greater than 5.0) { "android": { "release": { "keystore":"c:\\Yourkeyfile.keystore", "storePassword":"123456", "alias":"YourAlias", "password":"123456", "keystoreType":"" } } } ant.properties file (If your Cordova CLI version is less than 5.0) key.store=c:\\Yourkeyfile.keystore key.alias=YourAlias key.store.password= 123456 key.alias.password= 123456 With cordova CLI app runs. In VS 2015 i have a deploy error. I installed again Android Studio (with SDK) but nothing - Leonardo Augusto 侍 last edited by @giov do you have java jdk ? Show me the error.when I started with VS and Cordova I had many problems also , but nowadays I have everything working out. jdk 1.8 If i use VS 2015 my app can’t deploy on device. But with cordova CLI app can deploy and runs.
https://community.onsen.io/topic/557/build-apk-using-monaca-cli-or-cordova-cli
CC-MAIN-2021-21
refinedweb
622
56.35
use Azure and Appfabric at the same time - 22 Şubat 2012 Çarşamba 23:29 My application already uses Apfabric Server for its caching and WCF services hosting, Now I want to use the the Azure Service Bus for my chat messaging app that levrages signnalIR but it seems you cannot use Apfabric Server in conjunction with Azure (Thanks MSFT) there are namespace conflicts it seems they conflict I guess. To make matters worse I did not know you are not supposed to develop Appfabric Server and Azure based solutions on the same box since you can get namespace conflicts so now my development box is borked lol It makes no sense to me why they use the same Namespaces for the core libraries when Azure and Appfabric cannot coexist. How can I intergrate the Azure Service Bus (only thing i need from Azure) with an exsiting web application that uses Appfabric Server. and In case you are wondering , we prefer to keep our distributed Cache local and not In Azure for performance reasons. thanks Tüm Yanıtlar - 23 Şubat 2012 Perşembe 15:02Moderatör Which namespaces seem to be conflicting? Are you talking about needing different versions of the Azure SDK on the same box? Thanks, If this answers your question, please use the "Answer" button to say so | Ben Cline - 23 Şubat 2012 Perşembe 15:57 assemblyref://Microsoft.ApplicationServer.Caching.Client version 1.0.0.0 now when I install the Azure Dev kit version 1.6 it puts assemblyref://Microsoft.ApplicationServer.Caching.Client version version 101.0.0 in the gac and my application stops working I would have though I could leverage the Azure Service Bus and leave my current Appfabric Caching Intact Right now I am just doing normal MVC development on my visual studio 2010 box .Net framework 4.0 sp1REL I tried to install the Azure SDK and it breaks my app on that Caching.Client Reference. ANy ideas - 23 Şubat 2012 Perşembe 18:02Moderatör It seems like something that could be handled by updating the assembly binding redirection settings, although I am not sure if the problem is just with the reference in your application or if the updated version breaks the caching runtime too. I think other people have reported this issue over on the Service Bus EAI forum. Thanks, If this answers your question, please use the "Answer" button to say so | Ben Cline - Düzenleyen Ben Cline1MVP, Moderator 23 Şubat 2012 Perşembe 18:03 -
http://social.msdn.microsoft.com/Forums/tr-TR/dublin/thread/69969dec-5481-460d-916e-43930f66a37b
CC-MAIN-2013-20
refinedweb
411
56.69
1. If it is dynamically generated xml, you must set the Content-Type of "text / xml", otherwise the default is the text of the. 2.xml must be closed Example: <packet version="1.0.0"> <status>success</status> <data& Page code: <! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN" " "> <html> <head> <title> jquery xml parsing </ title> <script type="text/j / / Initial load page $ (Document). Ready (function () { / / Get a single value for the mouse click event button up $ ("# GetMessage"). Click (function () { $. GetJSON ("jsontest! ReturnMessage.action", function (data) { / / Pass. Data Accessories Simple <script type="text/javascript"> function text() { var xmldoc = "<xml><first><filename>111</filename><filename>222</filename></first></xml>"; $(xmldoc).find("first filename" xml file structure: books.xml <? Xml <Name> layman extjs </ name> <Author> Joe Smith </ author> <Price> 88 </ pric 1, the initial contact with jquery and json, hope a little help Foreground application to the background to get json data ajax $.ajax({ type: "POST", url: "ResourseAction!showTables.action", data:"", success: function(jsonDat common.js: $(function(){ $('#submit').click(function(){ $.ajax({ type: "POST", url: "do.php", data: $('#myform').serialize(), success: function(msg){ var obj = jQuery.parseJSON(msg); alert(obj.data1+obj.data2+obj.data3+obj.data4+obj.da // Get a byte array byte[] bytes = new byte[]{(byte)0x12, (byte)0x0F, (byte)0xF0}; // Create a BigInteger using the byte array BigInteger bi = new BigInteger(bytes); // Format to binary String s = bi.toString(2); // 100100000111111110000 // Format to /* *author Benjamin *date 2013-11-24 *content seajs+easyui使用 */ /** * 首先来看看在seajs中jquery和jquery插件如何使用 */ 1.jquery.js define(function(require,exports,module)){ //原jquery.js代码 module.exports = $.noConflict(true); } 2.jquery.combobox.js 依赖关系如下: jquery.c 1, Content-Type Often can not resolve the problem is that Content-Type. If the XML file itself is, skip this step. Dynamically generated XML be sure to set it to text / xml, otherwise the default is text / html is plain text. Common language, set the Stock entity bean: Stock.java as follows: package bean; / / Save the stock for basic information public class Stock ( / / Yesterday's closing price private double yesterday; / / Today's opening price private double today; / / Current price private do This example involves the knowledge of the main points are: 1. To complete the functions of the background simulation of Stocks 2. To share the information assembled into JSON format 3. With red and green stock price changes, real-time display 4. Too 在该系列之前的文章使用 jQuery:UI 项目中,我介绍了使用 jQuery 代码中的插件来提高 web 应用程序的效率. 但必须知道,这些插件不是自己凭空产生的,它们是由开发人员编写.测试并完善的,这些人员为 jQuery 社区奉献了自己的业余时间.我们做这些都是免费的,是出于对自己代码的热爱.本文主要关注您如何回报这个伟大的社区,即如何编写自己的插件并上传到 jQuery 的插件页面.这可以让所有人使用您创建的插件,可以让整个 jQuery 开发社区变得更好.今年您也做出自己的贡献吧. 在 1, JSON What is this? JSON stands for JavaScript Object Notation, is a lightweight data interchange format. JSON and XML with the same characteristics, such as easy-to-person writing and reading, easy-to-machine generation and parsing. However, more I am novice, welcome to criticize the correction! This article aims to achieve a linkage of the two "professional name" drop-down list of menu choices, the basic idea is as follows: 1, the "professional class", "professional name& After a period of use and learning, found that jQuery with Struts2 is relatively easy to configure, and summarize: 1 Action achieved ModelDriver after, Form field names no longer needed Entity.Property way, and ord Jeditable - Edit In Place Plugin For jQuery, is a JQuery plug-in-place editing. That is, click on the page you need to edit the content, it will automatically become a text box for editing. It's official website is Use JQuery in javascript:; "target =" _self "> ajax ways to access web services. 1.ajax methods are required to complete: JScript. Code <! - Code highlighting produced by Actipro CodeHighlighter (freeware) Chapter 1 jQuery Getting Started 1 1.1 jQuery can do a 1.2 jQuery Why are they so good 2 1.3 The first jQuery documentation 3 1.3.1 download jQuery 3 1.3.2 Setting HTML Document 4 1.3.3 write jQuery code 6 1.4 Summary 9 Chapter 2 selectors - Get ever 1, Jquery head position title The first line <script src="jquery.js" type="text/javascript"> </ script> The second line of custom tag <script src="alice.js" type="text/javascript"> </ script> JSON data format: {"users":[ {"uid":"123","displayName":"User 123","mail":"123@example.com"}, {"uid":"456","displayName":"User 456","mail&qu var arr1 = [ "one", "two", "three", "four", "five"]; $. each (arr1, function () ( alert (this); )); Output: one two three four five var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] $. each (arr2, function (i, 1, with the former must have official website: API: Current Version: 1.5.5 Need JQuery version: 1.2.6 +, Compatibility 1.3.2 <script JSON data format: {"users":[ {"uid":"123","displayName":"User 123","mail":"123@example.com"}, {"uid":"456","displayName":"User 456","mail&qu 1, with the former must have the official website: API: Current version: 1.5.5 Need JQuery version: 1.2.6 +, Compatibility 1.3.2 <scr Preparation conditions: 1, in Java, get the correct JSONObject, need to import the JSON in JAVA Support Package "json-lib-2.3-jdk15.jar", it is necessary to import the JSON dependencies "commons-logging-1.0.4.jar", "commons-lang . Learning the jquery validate.js this is jquery plug-ins, I think Mody, used jquery to change the habit of many of our programming, we are accustomed to traditional authentication methods, the validation js pages written form, or extracted , written i Double salary1 = 10000.0; Double salary2 = 10000.12345; Double salary3 = 10000.1289; Int salary4 = 10000; string salary5 = "10000"; string salary6 = "10000.12345"; string salary7 = "10000.1289" Convert.ToDouble (salary1). ToS <%@ page <html> <head> <title>JQuery Menu </title> <me 1. JS sum of the values in the string var a = '2 .1 '; var b = '13'; var c = a + b; the c value of 2.113, because the + symbol in the string is connected between. If required a and b, and then the first should a, b with the parseFloat () or parseInt Tried it before a reception with jquery (1.3.2), the background with a spring (3.0), with the json data exchange between, Then write a chapter summary jquery (1.3.2) <- json -> spring (3.0), there are several heroes made the background check, I also Extremely popular the jQuery Javascript framework is dedicated to the page program design, it adopted an elegant way to make our pages easier to operate freely without fear of all the elements of the browser version and compatibility issues. Inspired 1, preparations to JQuery version: 1.2.6 +, Compatibility 1.3.2 Official website address: Latest version: 1.5.5 Local Download: jquery.validate.zip Second, the default validation rules (1 Function Description: Use jQuery analysis has defined the content of the xml file 1.xml file: menu.xml <? Xml version = "1.0" encoding = "gb2312"?> <menus> <menu> <id> 1 </ id> <name> system </ na jquery.validate.js is a verification under jquery plugin, features more powerful, but one does not already have heard of hands used, and now is able to look up. Here is reproduced an article written by the older generation, in my own understanding of package com.bpsoft.servlet; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache jQuery is the most extensive in the field of popular JavaScript framework, unfortunately this time he added ECShop on a very troublesome problem encountered. ECShop the AJAX event and JSON parsing modules on the common / transport.js being, you can View results Download jQuery ui.ariaSorTable support paging table component, refresh the page to a friend-free must look at the jQuery ui plug-in, you realize there is a powerful multi-function table to provide information. In addition to paging, thi The default validation rules (1) required: true losing field (2) remote: "check.php" using ajax method call check.php validate input values (3) email: true must enter the correct e-mail format (4) url: true must enter the correct URL format (5) jQuery's $. getJSON () method uses the experience of Depressed, because you want to use jQuery to get the json document, has not get the results. Debugging of the day, only just solution, therefore the experience to write about. To get the json file jquery.validate is a very good based on jquery validation framework, we can quickly verify that some of the common input, and can expand their own authentication methods, but also has very good international support. jquery.validate official website: jquery.validate.js is a verification under jquery plugin, features more powerful, but one does not already have heard of hands used, and now is able to look up. Here is reproduced an article written by the older generation, in my own understanding of Recent use in the project to verify, so re-read a verification under the jquery framework. On the official website has been updated to 1.7: A jQuery inline form validation, because validation is a Mess This version is the bluespring + 1.7 on the basi JQuery Plugin plug-in, if we do not understand what is JQuery plug-in, or are not sure how to write can view their official website: jQuery Authoring Guidelines Well, here are some of my plug-ins that want to be a good requirement should be: 1, in th Work involves the need to function with input prompts (such as google search for tips like) to find some information online, the best selection of jquery autocomplete to achieve, here what has been used, the project encountered a problem writing inde Found a time to read the next EasyUI plug-in, plug it felt very comfortable, specially most of Easy UI functionality to do about property summary. This attribute list, please control jQuery EasyUI 1.0.5, for more information on its pounding here . Pr jQuery.validate use necessary jQuery 2010-04-15 10:04:09 read 493 comments 0 font size: large, medium Subscribe jQuery.validate is a very good form validation tool, simple and approachable technology and experience to achieve good results, although l CodeWeblog.com 版权所有 黔ICP备15002463号-1 processed in 0.040 (s). 8 q(s)
http://www.codeweblog.com/stag/jquery-parse-decimal/
CC-MAIN-2015-48
refinedweb
1,692
58.79
KDE: Breaking the Network Barrier 475 comforteagle writes "In this month's KDE: From the Source, entitled Breaking the Network Barrier George Staikos takes us on a walk-through of KDE's desktop networking protocol handlers in the vein of sftp:// webdav:// and a few really nifty ones I wasn't aware of like info:/ perldoc:/ and tar:/. The entire KDE desktop environment is decked out like this, and as George puts it, 'Microsoft Windows and Mac OS X have a long way to go to catch up with the robust, transparent functionality that KDE has provided since version 2.0.'" What a relief. (Score:5, Funny) a walk-through of KDE's desktop networking protocol handlers in the vein of sftp:// webdav:// and a few really nifty ones I wasn't aware of like info:/ perldoc:/ and tar:/ Good thing the Christmas Island people have made it safe for the goatse:/ handler. Re:What a relief. (Score:5, Funny) Re:What a relief. (Score:5, Informative) Re:What a relief. (Score:4, Funny) Re:What a relief. (Score:3, Funny) Re:What a relief. (Score:3, Funny) Marketspeak (Score:3, Insightful) I'm sorry, but to me that bit just reduced a potentially informative article to yet another trivial Slashvertisement. Re:Marketspeak (Score:5, Insightful) Perhaps you should just read the article and not pay attention to the slashblurb? Whether it's Slashvertising or not, it's still interesting. Re:Marketspeak (Score:3, Insightful) Re:Marketspeak (Score:5, Informative) The useful thing is for example: - Writing a webpage in Quanta and uploading it directly to your webserver simply by typing in the file save dialog. - Streaming your movios from an smb share directly to Kaffeine without needing to use smbmount or anything similar. Or stream directly from http or ftp or ssh servers - Opening an mp3 song from an audio CD. You simply type audiocd:// in the file open dialog and you'll be able to find a virtual mp3 on there. You open it from amaroK and you get an mp3 encoded on the fly. OK, not the most useful usage and not sure if it works, but you get the drift The point is, if it works from Konqueror, it works from EVERYWHERE in KDE. Automatically. Re:Marketspeak (Score:3, Informative) Basically its an extensible system that allows for any protocol to be used. No one else has that yet. Re:Marketspeak (Score:3, Informative) I hope they fix this in Tiger. 10.3 is way better than 10.1 in this respect though. Kwel (Score:5, Funny) GNOME compatibility? (Score:2, Informative) Errr.... security? (Score:3, Insightful) Re:Errr.... security? (Score:5, Insightful) Re:Errr.... security? (Score:3, Insightful) Ok, could be added security to avoid some of this tricks, but now you are in a position of unsafe by default unless you take every possible protection measure. Re:Errr.... security? (Score:2) We're not talking about integrating scripting engines or even anything that would follow links to other sources. Just plain old accessing files in any location with any program as if they were locally stored. Re:Errr.... security? (Score:3, Informative) In a word, NO. (Score:3, Insightful) kde is pretty good, but... (Score:2, Insightful) The one thing that I do not like about it, is how long it takes to boot. Windows (and probably mac, never really used it) have linux/kde beat for loading times. I really wish there was a distro that could integrate kde into the booting process rather then boot linux then kde - like back in the dos/win days... Re:kde is pretty good, but... (Score:2) Re:kde is pretty good, but... (Score:2) Re:kde is pretty good, but... (Score:2) Combining your messages: My P3/600, 128MB ram ... takes over 3 minutes to boot Windows '98 into a viewable state If that's the case, you've either seriously messed up your computer with spyware and viruses, tried loading a thousand programs at boot, or you've got a nasty hardware problem, like a failing drive or defective memory. Seriously, there's no reason why Win98 should be taking that long to boot up. I just finished cleaning up my sister's Win98 machine, which is a P2-233 with 64MB of memory, and i Re:kde is pretty good, but... (Score:2, Interesting) the stability advantage (Score:2) Re:kde is pretty good, but... (Score:2) (shrug) I usually boot my linux boxes every year or so, and never really thought about booting times being a problem... If you really want a fast boot, there is a linux bios project that allows a system to come from a powered off state to "ready for login" in a few seconds... User friendliness is still the issue (Score:3, Insightful) And the entire Windows OS is decked out with enough user friendliness for most people to use, and, as I put it, 'KDE has a long way to go to catchup with the userfriendliness of Mac OSX and Windows. Windows, as much as everyone hates it, is still more user friendly than KDE. If they'd spend more time on user friendliness and less on robust (aka confusing, complex) features, they'd find more people willing to try it out. Re:User friendliness is still the issue (Score:2, Insightful) Re:User friendliness is still the issue (Score:3, Insightful) (See how easy that is? How is this "Insightful"?) Re:User friendliness is still the issue (Score:5, Insightful) Let's not even get into the illogical nonsense which Windows fans still defend as user-friendly. For example, if I minimise a program, there are THREE different places it can go. It can go to the taskbar (the only LOGICAL place), it can go to the system tray, or it can be minimised to one of the application launch buttons on the panels. Now how the hell is this friendly and useful, when I have to thing three times before finding my minimised program? Windows usability is SERIOUSLY overrated, get over it. Use KDE for a while and when you get used to it, you will see that it's a much more usable environment. Re:What a lame response (Score:3, Interesting) Re:User friendliness is still the issue (Score:2) Actually, I find KDE a whole lot more friendly than windows. It might be because I have been using it for a very long time, but when I go back to windows, I simply don't understand how/where the options and controls are located. Compare a usable windows machine (with applications actually installed so you can do your job) with a stock KDE install (where you can still do your job). The menus have a much better organisation in KDE. Graphic-related programs are grouped together, and so are multimedia, devel Don't forget DCOP (Score:5, Interesting) Also worth noting however, is the DCOP [ibm.com] system integrated into KDE. The protocol handlers and DCOP can and do make a powerful combination. MacOS _should_ have these things. (Score:5, Interesting) The network transparency of KDE is brilliant. I'm not sure where the holdup for OSX is, but I would kill to be able to open a location with cmd-k, fish://user@myhost I suspect that for Apple to add these bits would require some OS level work as well as some finder work. I hope they'd take that opportunity to update the finder to be a cocoa application. (As a side note, the Finder continues to bother me. My Mac savvy friends and I joke that the Finder, Mail.app, and Quicktime teams are Microsoft moles trying to take Apple down from the inside). Anyone have any speculation as to why Apple hasn't already done some of the truly nifty network protocols? They've already got a finder view for FTP (which, unfortunately is dog-slow). Still, Apple has proven itself as a very agile software company. They've got a track record for adding features correctly and quickly, but the lack of an SSH handler is baffling to me. -Peter Re:MacOS _should_ have these things. (Score:2) Re:MacOS _should_ have these things. (Score:5, Informative) FUSE KIO Gateway (Score:3, Informative) Not necessarily..... Re:MacOS _should_ have these things. (Score:3, Insightful) If you mean the kernel VFS layer, then Apple is not doing it right: this sort of functionality does not belong in the kernel. And Apple has not even managed to make the Carbon and Cocoa views of the world entirely consistent. KDE's I/O slaves are not real filesystems and are not accessible by all applications. True, and that is bad. But there is a middle ground between KDE's pi Should KDE implement OS features? (Score:4, Interesting) In my mind there are two ways to look at it. You've presented one way: KDE must have this feature, and if the OSes won't provide it, then KDE must provide it in some suboptimal way. The alternate approach is to say that mounting a fish or whatever is a feature that belongs in the OS, and if a particular OS supports it, then KDE will get that for free. If an OS doesn't support it, then KDE won't have that feature when running on that OS. Re:MacOS _should_ have these things. (Score:2) Re:RTFM- there's no "holdup", it's done it since 1 (Score:4, Informative) SSH+SCP would be really nice. fish:// on the other hand, is shear brilliance. It uses Perl on the server side to do some things that are not possible with just SSH+SCP. Those are great fallbacks, but fish:// is innovative. But, I'd be happy with just SSH+SCP. As far as I can tell, it doesn't exist in OSX. This brings me to another annoyance with OSX: It doesn't tell you when it doesn't know about a protocol. I can tell my OS X 10.3 machine to connect to a server. For a URL I type in "bogusprotocol://foo@foo.foo". The Finder tells me, "Connection Failed. No response from the server. Please try again." WTF? I'd prefer something like, "You moron, you've just typed in a protocol name that doesn't exist." Please don't say, "Sorry, but we couldn't connect to this perfectly valid URL because the host wasn't available." -Peter Pretty slick (Score:5, Insightful) Being able to do all of these things from a web browser is definitely a nice parlor trick, but in reality it's not a very easy way to use a computer. The real power of these protocol handlers is unleashed when they're used within various KDE applications. Any of these protocols can be used from the KDE file dialog, allowing files to be opened from or saved to any protocol! I must say, as much as I don't really like KDE, that's really slick, and potentially very useful. Nice job guys. (I'll even withold bashing and pro-gnome comments for the sake of sanity) Re:Pretty slick (Score:2) I might not understand what you're trying to say, but that's the whole point of kioslaves. You simply type into any KDE file save dialog and KDE does the rest for you. Re:Pretty slick (Score:4, Informative) Re:Pretty slick (Score:2) What are you talking about? I can do "fish://ssh_alias_for_some_server"[*] in the directory edit field, press Enter, get a nice dialog for password, browse to the file I need in the Open dialog and open it. [*] ssh host al OS X has a long way to go to catch up? (Score:2, Interesting) useless protocols? (Score:4, Informative) Re:useless protocols? (Score:4, Informative) The key advantage of KDE's IOSlaves over protocol handlers in Windows is that in KDE they are transparent and available to every application. This is not the case in Windows or OSX. Gnome-VFS does have this advantage as well, but is nowhere near as extensive. Old Unix philosophy (Score:5, Interesting) Correct me if I'm wrong, but wouldn't the old way of doing this be something like What was the reason for not implementing these as devices? Re:Old Unix philosophy (Score:2, Informative) In fact there is a module for the FUSE system that allows you to use the KDE plugins in the way you suggest. Re:Old Unix philosophy (Score:4, Informative) Because KDE is a cross platform desktop, and devices are too tightly tied to a specific kernel. A Linux device doesn't help a FreeBSD, Solaris or AIX user. Microsoft Doesn't Need to Catch Up (Score:3, Insightful) ...yet. Microsoft won't see any need to add new features as long as it's users don't find out, and it's market share remains 90%-ish. Once it DOES feel threatened though, it'll pour resources and add all the features to it's OS that it thinks will maintain it's dominance. (think Mac/Windows, Netscape/IE, Java/C#). But it'll probably ultimately fail this time. I'm a Windows fan, but I'm realistic: Linux will win in the long run. wrong layer (Score:4, Interesting) can one "cat perldoc://someuri/perldoc1" ? if not then it is at the wrong layer to be "transparent" plan's approach of a unified file system approach is far more transparent a daemon runs and serves the appropriate files in the namespace as regular filenames cat grep bunny etc. Re:wrong layer (Score:3, Funny) Re:wrong layer (Score:2) Now, as you may or not recall, a couple months ago there was a giant flamewar on the Linux kernel mailing list about Reiser4, files-as-directories, plugins, and all the stuff that would make such things transparent at the filesystem level, and the net result was, "it's not going in right now." KDE programmers aren't kernel hackers, a Re:wrong layer (Score:3, Interesting) if not then it is at the wrong layer to be "transparent" plan's approach of a unified file system approach is far more transparent a daemon runs and serves the appropriate files in the namespace as regular filenames cat grep bunny etc. Sure, no problem. [ground.cz] It's still a work-in-progress, though. Re:wrong layer (Score:3, Informative) I don't see why this has to be at the kernel level - why not just make programs that use kioslave functions instead of open() (or whatever)? Not only that, but some protocols are very slow or don't work with directories well, and wouldn't be sutable to be treated like local folders. Putting this in the kernel is asking for a lot more root (and not just user) exploits. And finally, everything that uses tradi Difference from OSX ... (Score:5, Interesting) But the downside is that these 'fancy' network filesystems are comparatively sparse relative to KDEs. And we're still waiting for, oh, say, webdav over SSL support (making it actually worthwhile for an intranet filesystem solution). IF OSX could have retainted the 'filesystem drivers as userspace processes' mantra of the microkernel design philosophy, then we could have the best of both worlds. Especially if we could retain, say, HPFS, FFS, etc. as kernel resident drivers for efficency . does gnome do this? (Score:2) I just recently installed "ubuntu" (gnome 2.6).. which I must say is a really nice looking slim UI/theme. All around good distro. But does gnome have integrated webdav support? I would think they'd be on the ball to mimic any lil kde features that pop-up. --Zaq Re:does gnome do this? (Score:2) apparently in the filebrowser "Nautilus" there is a connect to server option which supports webdav. for fun, in OSX (Score:2) x-man-page://some_command where some_command is the command you want to see. I get a man page in a terminal. In fact for any given URL registered on my box, I get the Right Thing(tm) happening. I use the Default App pref pane () and thus have pretty fine control over what happens when various URLs are clicked/activated. Well, I can't make new ones, something about the craptacular IE vestiges that control URLs by default, maybe, I'm not s Wha? (Score:2, Informative) Like what kind of catching up? Like this? KDE on Mac OS X [kde.org] Don't be a hater (Score:5, Interesting) You don't really appreciate it until you use it and then forced to work without it. I present a real world example: a colleague wants some help with the IE CSS scrollbar colors. I open up KWrite, the "simple" text editor, select "Open" from the "File" and plug in the FTP url, with embedded password and all, into the open file dialog. A half a second later I was browsing their directory structure point-and-click in the open file dialog. I find the ".css" file and open it in the editor. I then make my simple changes and hit CTRL-S. The file was saved and uploaded back onto the web server in one simple keystroke combo. And that was it. Mind you all of this was done in KDE's most trivial of text editors and this feature is part of the desktop architecture meaning all KDE apps can employ this feature. Try doing something like that with the default install of Windows/MacOSX/Be/whathaveyou. And that was the simplest of examples of the network transparency within KDE. And that's just the network transparency aspect of it. The KIO architecture allows for some really amazing features on the local side as well. If you don't already know about the audiocd:/ slave then look it up or even use it. It will blow your mind. Don't just take my word for it. Try it before you bash it. Please. Re:Don't be a hater (Score:5, Informative) Yes, the Amiga. Just put the file "" in DEVS:, mount FTP: and every single application can now use say as if it was a local disk. was written in the early 90s but the backend technology was there in 1986... Bloat Critics (Score:5, Interesting) And it works *great* in Amarok, my audio player of choice. I no longer have to keep porting around my mp3 collection: I simply fish to my server and play them from there -- from anywhere. The only downfall, is that I need to force it to go to the next track after it gets to the end of a track, instead of automatically doing so, but it's a minor compared to the above ease-of-use. But regular people don't think this way (Score:3, Insightful) Saying Windows and MacOS has to catch up implies that these are feature people want, or would want if given the option. I think treating compressed files like folders like they already do is more intuitive and makes more sense. I think they got a little carried away with this. Re:But regular people don't think this way (Score:3, Informative) Microsoft has to catch up? (Score:4, Informative) mk-its: is used in the HTML help system, and ms-help: is used with the MSDN, and there are probably a few others that most people have never heard of. But like I said, why is it up to MS? Anyone in the open source community could write APPs for Windows to add this kind of functionality if there were a demand for it, so I suspect there's little or no demand for it. Put it in the shell? (Score:2, Flamebait) needs to be standardized and broken out (Score:2) What is needed is for the Gnome, KDE, and libc developers to get together and talk about how to unify this functionality, break it out c Wow, you're fast! (Score:4, Insightful) KDE is pretty damned easy to use and consistent too, it's just that not all applications are written in QT, just as not all Gnome apps are written in GTK. So, you get some apps that don't fall in line with the look and feel of the rest of the OS. So is the way of the Linux desktop right now, and you can't single out KDE for that. Re:Wow, you're fast! (Score:4, Insightful) I don't see how this commentary is "garbage" There is a real problem with consistency and polish on the linux desktop, it's ugly and clunky compared to OS X or even windows. " it's just that not all applications are written in QT, just as not all Gnome apps are written in GTK. So, you get some apps that don't fall in line with the look and feel of the rest of the OS. " So you're agreeing with me, but not with where I am placing the blame? Fair enough, maybe blaming KDE isn't fair, but it's still a huge problem. Re:Wow, you're fast! (Score:3, Insightful) Maybe compared to OS X, but certainly not in comparison to Windows. Both GNOME and KDE are more consistent than either OS X or Windows, and in terms of usability, GNOME is fairly close to OS X. There is a reason for this --- GNOME emulates the MacOS classic HIG. In terms of usability, GNOME is far superior to Windows. Re:Wow, you're fast! (Score:2) Maybe the OS itself, but not the way that applications run on it. OS X has done a really nice job of making sure that applications written in cocoa and carbon behave the same. (it's been worse in the past, and gotten much better.) Maybe it's a testament to the Mac application developers, but linux apps on GNOME and KDE are nothing if not inconsistent with each other and the OS. Re:Wow, you're fast! (Score:3, Insightful) Re:Wow, you're fast! (Score:3, Interesting) Re:Wow, you're fast! (Score:2) Re:Wow, you're fast! (Score:3, Interesting) 1) Visual consistency. Within KDE, I only use KDE apps, and in GNOME, I only use GNOME apps. As a result, all my apps look the same. They theme the same, use the same color scheme, etc. This is not true in Windows. The major Microsoft apps use different toolkits, so Visual Studio.NET doesn't look like Internet Explorer, and neither look like Office XP. 2) UI simplicity. In GNOME, the UI is very simple and streamlined. This is a direct result of the MacOS-influenced GNOME HIG. For You missed the point. (Score:3, Insightful) I admit, you don't sound quite as unresonable as some Zealots, but you did post that just the same. The article nor slashdot post wasn't about usability, it was about resource transparency. And to proclaim that KDE is "ugly and clunky compared to OS X or even windows" - such an objective thing say that you can't just preach it like it's fact. Personally, I feel too confined in OS X. It's okay I guess, and I Re:uh huh. (Score:4, Interesting) Don't start going about MacOS-X usability until you really look into it a lot deeper. They went all out for high 'walk-up-and-use' value, but not so much for actual usability. Many of the OS-X choices detracted significantly from usability that was present in earlier versions, giving apparent usability rather than actual usability. This isn't to say their choice was wrong, but they were targetting new users and home users, not pro users. In very many ways, KDE is far more usable than OS-X, it mostly just depends on how talented the user is and what they are trying to do. Re:uh huh. (Score:3, Insightful) Here they are most of "Connect to server" server connections don't work, example ftp:// one version asks for password, but latest OSX patch does not. Copying files doesn't work as it should. Network interface was simple. Chooser and that was it. Now there is trashed all over the place. Network in finder supporting SMB only??? Start menu has gone bad since OSX. Mail has fatal flaws. (Besides its fatal unusability) You can't control with keys on dialogs or popdowns. (Buttons I mean) Theme Re:What's the difference? (Score:5, Informative) The KDE feature discussed here is a compatibility layer that allows users to treat a files located elsewhere as if it is on the local disk. Instead of having to use sftp to download a file from a site, or wget to download a file from the webserver or even evolution to download a file from the mail server, you can just use one common interface for all files reguardless of their storage or access method. This means a tighter and more consistent user experience. SO there! Re:What's the difference? (Score:2) Re:What's the difference? (Score:2) Re:What's the difference? (Score:2) Because I can now use it from all my applications? Like Mozilla, bash, PINE, Java Swing applications, in the save-file dialog box of any video game, my Perl scripts, and everywhere else? No? Well, then we have a very different idea what "consistent" means. Re:What's the difference? (Score:3, Informative) The only way to get this across every single application is to include it at the filesystem level. First, the KDE developers aren't kernel hackers, so they probably don't have the expertise to write such an extension. Second, even if they did, it would probably incite a giant debate in the Linux kernel mailing list when they presented it (like with Reiser4), and the net result would be that it wouldn't be in anyway. So it'd be a bunch of patches and you'd have to use a special Re:What's the difference? (Score:3, Informative) But do they have the expertise to write a user-mode NFS server that uses the protocol in question as the back end? There'd still be some platform-dependent crap to do the NFS mount (probably using a port other than 2049, if the platform's NFS client supports that), and there might be some fil Re:What's the difference? (Score:2) This is *not* about file extensions or otherwise (Unix has done this right since day one, which is why you don't need to put Windows and OSX are a long way from this. They just about understand http, and even then on at the application level. Re:What's the difference? (Score:3, Insightful) Correct, although... ...that doesn't mean that suffixes aren't needed at all on UN*X - try calling a C source file "foo.f" and see how eager GCC, for example, is to compile it: At the desktop GUI level, some UN*X desktops, suc Re:What's the difference? (Score:2) I was under the impression that KDE used something similar to Gnome's VFS. Meaning it doesn't launch a webdav client when you open a webdav:// url, it uses a VFS module to do it. This is very different than what you are talking about. This allows applications to open and save files to webdav, afs://, smb://, ftp:// just like any other file. For i Re:What's the difference? (Score:2) Can you open the save dialog in MS Word and save your document on a remote ssh server via the fish protocol without doing anything special? Who's playing catchup again, huh? Re:What's the difference? (Score:2) Re:Robust? (Score:2) I've looked at a lot of code in my time and I'd rate 1% of it as actually 'good'. It's particularly tragic when people 'update' perfectly good apps with a piece of unmanageable spagetti.. I tend to just keep my distance when that happens. Re:Robust? (Score:3, Insightful) Re:A little frightening. (Score:2) Re:Crackhead of the year (Score:3, Interesting) Re:Windows has had since since at least 98SE (Score:3, Insightful) Re:Oh wow (Score:5, Interesting) Re:bleh:// (Score:4, Informative) ...and ctrl-x probably works in a lot of them as well. And, given that Qt switched in Qt 3 to the closest thing to a standard way of handling the PRIMARY and CLIPBOARD selections in X [freedesktop.org], and that a number of other toolkits, including GTK+, have always done that, it would probably work even between applications using different toolkits in most if not all cases. I.e., bitching about copy-and-paste in X11 is getting a bit old, at least for complaints about it not working at all, even for text. Perhaps for non-text formats there needs to be a bit more work in the toolkits and applications, but, as I remember, the selections mechanism in the ICCCM does have a mechanism to register data types and to have a recipient of data find out the types in which data in a selection is available, so they can choose the "best" type (e.g., it might be available as rich text or plain text, so that a word processor would fetch the rich-text version but a terminal window would fetch the plain-text version).
http://tech.slashdot.org/story/04/10/29/1544210/kde-breaking-the-network-barrier?sdsrc=prev
CC-MAIN-2014-42
refinedweb
4,945
72.26
help needed for compiling error Hey I am just wondering if someone can tell if this compiling error has something to do with needing GCC4.0: /boot/home/Desktop/nasm-2.03.01>make gcc -c -g -O2 -W -Wall -pedantic -DHAVE_CONFIG_H -I. -I. -o nasm.o nasm.c In file included from /boot/develop/headers/posix/limits.h:5, from /boot/develop/tools/gnupro/lib/gcc-lib/i586-pc-haiku/2.95.3-haiku-080323/include/limits.h:117, from /boot/develop/tools/gnupro/lib/gcc-lib/i586-pc-haiku/2.95.3-haiku-080323/include/syslimits.h:7, from /boot/develop/tools/gnupro/lib/gcc-lib/i586-pc-haiku/2.95.3-haiku-080323/include/limits.h:11, from /boot/develop/headers/posix/stdlib.h:11, from /boot/home/Desktop/nasm-2.03.01/nasm.c:13: /boot/home/Desktop/nasm-2.03.01/float.h:18: warning: comma at end of enumerator list /boot/home/Desktop/nasm-2.03.01/float.h:20: parse error before `uint8_t' In file included from /boot/home/Desktop/nasm-2.03.01/nasm.c:20: /boot/home/Desktop/nasm-2.03.01/nasm.h:78: warning: comma at end of enumerator list /boot/home/Desktop/nasm-2.03.01/nasm.h:180: warning: comma at end of enumerator list /boot/home/Desktop/nasm-2.03.01/nasm.h:191: warning: comma at end of enumerator list In file included from /boot/home/Desktop/nasm-2.03.01/preproc.h:12, from /boot/home/Desktop/nasm-2.03.01/nasm.c:25: /boot/home/Desktop/nasm-2.03.01/pptok.h:97: warning: comma at end of enumerator list /boot/home/Desktop/nasm-2.03.01/nasm.c:91: warning: comma at end of enumerator list /boot/home/Desktop/nasm-2.03.01/nasm.c: In function `define_macros_early': /boot/home/Desktop/nasm-2.03.01/nasm.c:232: warning: ANSI C does not support the `ll' length modifier make: *** [nasm.o] Error 1 Re: help needed for compiling error The problem is here: /boot/home/Desktop/nasm-2.03.01/float.h:20: parse error before `uint8_t' You need to check that header file - float.h and figure out why you're getting a parse error around line 20. This might be the cause or a clue: /boot/home/Desktop/nasm-2.03.01/float.h:18: warning: comma at end of enumerator list Newer compiler may work better with the code because it understands newer syntax better. You could use GCC 3.4, from Bebits, for C code ( .c ), but NOT for C++ ( .cc and cpp ). Re: help needed for compiling error Although I haven't tried 3.4 due to a sever error for the download link on bebits(the sever disconnects every 10 secs, flashgot seems to be able to handle it even if it is going so very slow), I still think it won't work as gcc's website says c99 is only really supported in gcc4.0 and a double set of commas as in line 18 of float.h is a sign of c99 code. Re: help needed for compiling error Well, I decided to try it out myself. NASM compiles with gcc 3.4.3 in Haiku. I can't really say about c99 but when using gcc3.4; configure reports: checking if gcc accepts -std=c99... yes For gcc2.95, configure says accepts std=c99... no. There is a test directory but the Makefiles don't compile the tests. I believe NASM will work fine but without doing tests or checks I can't say for sure. ( I had trouble getting the test programs to work right but spent a few minutes only ). PS This is just one example of why going to GCC4.x would be a good thing - make it easier to compile programs. ( Firefox 3 requires 4.x & I believe WebKit too, etc. ) GCC 4.3.1 - latest, June 2008 GCC 3.4.3 - released Nov 2004 GCC 2.95.3 - released March 2001 Re: help needed for compiling error edit float.h; add in: #include "/boot/develop/headers/posix/stdint.h" #include "nasm.h" that helped me compile it. Try that & see what you get with gcc2.95. Be sure to give the right path to stdint.h Re: help needed for compiling error should be: #include <stdint.h> (btw, stupid drupal doesn't escape those automatically) Re: help needed for compiling error you're right Urias, should be: #include <stdint.h> but when I compile it never finds stdint.h when I put in either: #include <stdint.h> or <posix/stdint.h> Neither of these work. I must not have my development set up right ( not sure what I'm missing; maybe environment variables? ). That's why I like using the full path because it works for sure but the way you say to do it is the proper and standard method - the right way. Also, I have to set CFLAGS="-I/boot/develop/headers/posix" for configure to find stdint.h - that's how I know something is not right. I notice BEINCLUDES has /boot/develop/headers/posix. What am I missing? Re: help needed for compiling error Yeah, I'm not sure what's wrong there :( - I ran into a similar problem the other day trying to get headers in /boot/home/config/include to work. I may take a look at it myself if I get a chance. Even better would be to get someone at HaikuPorts to take a stab at it, as they're pretty good at getting stuff updated and producing patches to submit back upstream. - Urias Re: help needed for compiling error No worries, I actually think it only relates to gcc3.4. I'm testing with gcc2.95 and it seems to find stdint.h without issues. So, seems like gcc3.4 does NOT link properly to the header directories - something to watch out for. I haven't tested this but your issue may relate to BEINCLUDES; /boot/home/config/include is not listed in there. You can check with: env | grep BEINCLUDES or env | grep /boot/home/config/include This *may* fix it but I haven't tested: export BEINCLUDES="$BEINCLUDES; /boot/home/config/include" You'd either have to run that every time before compiling or put it into one of the startup scripts. I don't know why but BEINCLUDES uses ; ( semi-colon ) to seperate whereas other PATHS use : ( colon ) Re: help needed for compiling error I haven't tested this but your issue may relate to BEINCLUDES; /boot/home/config/include is not listed in there. You can check with: Yeah, I noticed that also. I did try adding it, but it didn't seem to work. Since I was in a hurry at the moment, I ended up just copying the header I needed to the /boot/develop/headers/3rdparty location instead which worked just fine. Perhaps it's a bug of some kind - I'll look into it again soon :) Let me know if you happen to test this yourself and it works fine (email me privately if you want). Stuff like that should go into a UserSetupEnvironment script (I assume that's what you meant by "startup scripts". IIRC, mmu_man told me at the time I ran into it that "/boot/home/config/include" was *supposed* to be in the BEINCLUDES already - so maybe that is something we should report on Trac. Re: help needed for compiling error Does those gcc's even understand BEINCLUDES and use it? I suspect, but don't know, that they have no clue about BEINCLUDES. When I crosscompile Firefox with gcc4.12 I flattened the include tree for those includes that where included with <stdint.h> instead of <posix/stdint.h>. So at least the crosscompiler does not handle it. Re: help needed for compiling error Fredrick. GCC wouldn't know about BEINCLUDES unless the person that compiled GCC changed the code & made it aware. ( my guess - because gcc3.4 wasn't aware of headers/posix folder even though it is listed in BEINCLUDES ). gcc2.95 knows about /boot/develop/headers/posix but it could be a path or link and not because of BEINCLUDES. It's unlikely that adding /boot/home/config/include to BEINCLUDES will make gcc aware of this directory but nothing lost in trying it out. You're cross compiling GCC4 Firefox? Right? I'm having trouble with cross compiling GNU's hello with GCC4. I get a symbol error for __fpending when I run the program on GCC4 Haiku. Can you cross compile then run GCC4 hello on GCC4 Haiku & let me know if it works for you? This way I can try to figure out what is going on. Thanks. Re: help needed for compiling error Here are my build instructions, these I was going to write for Crosscompiling Firefox over at Bebits wiki anyways. First, a working cross-compiler setup: (Reusing the one we built for Haiku crosscompiling). Only needed to be done once. Read the script and modify as appropriate first. ./setup_compiler.sh Second, setup environment for crosscompiling: export PATH=/home/frho/haiku/haiku-compiler/bin:$PATH Third, run configure for crosscompiling: ./configure --prefix /home/frho/projects/hello/ --host i586-pc-haiku Build and install And then you need to include it in your Haiku build. Edit build/jam/UserBuildConfig to include: CopyDirectoryToHaikuImage home hello : /home/frho/projects/hello/bin : : -L ; If i recall correctly the -L was to follow symlinks or something. I'll post result after reboot and testing. Re: help needed for compiling error I got the same error. So the app needs to be ported to Haiku, probably just link to libroot.so or libhaiku(?).so . Re: help needed for compiling error Thanks for the info & trying out Hello World compile, Fredrick. __fpending is listed in stdio_ext.h, which I believe is part of glibc. I use grep to find symbols in libs - it works well and lets me know which libs to link in ( when programs don't compile right, ie: link errors ). I don't believe any libs had __fpending ( or fpending ) when I grepped them. I'm fairly sure that this symbol is not in any of the libs. I think gcc2.95 compiled and ran the Hello program fine. No fpending with gcc2.95 ( & for gcc3.4 either? ). No worries, so long as I avoid programs that require stdio_ext.h I should be fine with gcc4.x compiling for Haiku - I think. Bye, Re: help needed for compiling error While __fpending() is located in the stdio_ext.h in the haiku repo, i found out after submitting a stdio_ext.h patch that it isn't actually implemented in haiku's glibc. In fact, the only methods from stdio_ext.h that are actually implemented are __fsetlocking() and a weak alias for _flushlbf() So, until someone implements that, software relying on it won't be compiling. stdio_ext.h only represents extensions to stdio, so posix compliant software shouldn't necessarily rely on these - and should utilize other methods when they're missing.
https://www.haiku-os.org/community/forum/help_need_for_compiling_error
CC-MAIN-2015-40
refinedweb
1,858
68.26
for connected embedded systems The Bones of a Resource Manager This chapter includes: Under the covers. Under the client's covers When a client calls a function that requires pathname resolution (e.g. open(), rename(), stat(), or unlink()), the function sends messages to both the process manager and the resource manager to obtain a file descriptor. Once the file descriptor is obtained, the client can use it to send messages to the device associated with the pathname, via the resource manager.: Under-the-cover communication between the client, the process manager, and the resource manager. - The client's library sends a “query” message. The open() in the client's library sends a message to the process manager asking it to look up a name (e.g. /dev/ser1). - The process manager indicates who's responsible and it returns the nd, pid, chid, and handle that are associated with the pathname prefix.: - 0 - Node descriptor (nd). - 47167 - Process ID (pid) of the resource manager. - 1 - Channel ID (chid) that the resource manager is using to receive messages with. - 0 - Handle given in case the resource manager has registered more than one name. The handle for the first name is 0, 1 for the next name, etc. - 0 - The open type passed during name registration (0 is _FTYPE_ANY). - /dev/ser1 - The pathname prefix.. If another resource manager had previously. - The client's library sends a “connect” message to the resource manager. To do so, it must create a connection to the resource manager's channel: (e.g. are you trying to write to a read-only device?). - The resource manager generally responds with a pass (and open() returns with the file descriptor) or fail (the next server is queried). - When the file descriptor is obtained, the client can use it to send messages directly to the device associated with the pathname.. Under the resource manager's covers multithreaded: - Receives the message. - Examines the message to verify that it's an _IO_READ message. - Calls your io_read handler.. Layers in a resource manager A resource manager is composed of some of the following layers: - thread pool layer (the top layer) - dispatch layer - resmgr layer - iofunc layer (the bottom layer) Let's look at these from the bottom up. The iofunc layer This. The iofunc layer QNX Neutrino Library Reference. The resmgr layer This layer manages most of the resource manager library details. It: - examines incoming messages - calls the appropriate handler to process a message QNX Neutrino Library Reference. You can use the resmgr layer to handle _IO_* messages. The dispatch layer This layer acts as a single blocking point for a number of different types of things. With this layer, you can handle: - _IO_* messages - It uses the resmgr layer for this. - Processes that do TCP/IP often call select() to block while waiting for packets to arrive, or for there to be room for writing more data. With the dispatch layer, you register a handler function that's called when a packet arrives. The functions for this are the select_*() functions. - Pulses - As with the other layers, you register a handler function that's called when a specific pulse arrives. The functions for this are the pulse_*() functions. - Other messages - You can give the dispatch layer a range of message types that you make up, and a handler. So if a message arrives and the first few bytes of the message contain a type in the given range, the dispatch layer calls your handler. The functions for this are the message_*() functions. . The thread pool layer This layer allows you to have a single- or multithreaded. Simple examples of device resource managers The following are complete but simple examples of a device resource manager: - single-threaded device resource manager - multithreaded device resource manager - Using MsgSend() and MsgReply() The first two of these simple device resource managers model their functionality after that provided by /dev/null (although they use /dev/sample to avoid conflict with the “real” /dev/null): - an open() always works - read() returns zero bytes (indicating EOF) - a write() of any size “works” (with the data being discarded) - lots of other POSIX functions work (e.g. chown(), chmod(), lseek()) The chapters that follow describe how to add more functionality to these simple resource managers. Single-threaded device resource manager the dispatch interface - Initialize the resource manager attributes - Initialize functions used to handle messages - Initialize the attribute structure used by the device - Put a name into the namespace - Start the resource manager message loop Initialize the dispatch interface /* the resource manager attributes When you call resmgr_attach(), you pass a resmgr_attr_t control structure to it. Our sample code initializes this structure like this: /* initialize resource manager attributes */ memset(&resmgr_attr, 0, sizeof resmgr_attr); resmgr_attr.nparts_max = 1; resmgr_attr.msg_max_size = 2048; In this case, we're configuring: - how many IOV structures are available for server replies (nparts_max) - the minimum receive buffer size (msg_max_size) For more information, see resmgr_attach() in the QNX Neutrino Library Reference. Initialize functions used to handle messages /* initialize functions for handling messages */ iofunc_func_init(_RESMGR_CONNECT_NFUNCS, &connect_funcs, _RESMGR_IO_NFUNCS, &io_funcs); Here we supply two tables that specify which function to call when a particular message arrives: - connect functions table - I/O functions table Instead of filling in these tables manually, we call iofunc_func_init() to place the iofunc_*_default() handler functions into the appropriate spots. Initialize the attribute structure used by the device /* initialize attribute structure used by the device */ iofunc_attr_init(&attr, S_IFNAM | 0666, 0, 0); The attribute structure contains information about our particular device associated with the name /dev/sample. It contains at least the following information: - permissions and type of device - owner and group ID Effectively, this is a per-name data structure. In the Extending the POSIX-Layer Data Structures chapter, we'll see how you can extend the structure to include your own per-device information. Put a name into the namespace To. - device name - Name associated with our device (i.e. /dev/sample). - open type - Specifies the constant value of _FTYPE_ANY. This tells the process manager that our resource manager will accept any type of open request — we're not limiting the kinds of connections we're going to be handling. Some resource managers legitimately limit the types of open requests they handle. For instance, the POSIX message queue resource manager accepts only open messages of type _FTYPE_MQUEUE. - flags - Controls the process manager's pathname resolution behavior. By specifying a value of zero, we indicate that we'll accept only requests for the name “/dev/sample”. Allocate the context structure /* QNX Neutrino Library Reference. Start the resource manager message loop /* and sends it. Multithreaded device resource manager Here's the complete code for a simple multithreaded'll cover only those parts that aren't described above. Also, we'll go into more detail on multithreaded resource managers later in this guide, so we'll keep the details here to a minimum.Here's an outline of the steps we'll cover: - Define THREAD_POOL_PARAM_T - Initialize thread pool attributes - Allocate a thread pool handle - Start the threads For this code sample, the threads are using the dispatch_*() functions (i.e. the dispatch layer) for their blocking loops. Define THREAD_POOL_PARAM_T /* *'s defined as a resmgr_context_t, but since this sample is using the dispatch layer, we need it to be a dispatch_context_t. We define it prior to the include directives above, since the header files refer to it. Initialize thread pool attributes /*'ll go into more detail on these attributes when we talk about multithreaded resource managers in more detail later in this guide. Allocate a thread pool handle /* allocate a thread pool handle */ if((tpp = thread_pool_create(&pool_attr, POOL_FLAG_EXIT_SELF)) == NULL) { fprintf(stderr, "%s: Unable to initialize thread pool.\n", argv[0]); return EXIT_FAILURE; } The thread pool handle is used to control the thread pool. Among other things, it contains the given attributes and flags. The thread_pool_create() function allocates and fills in this handle. Start the threads /*. From this point on, your resource manager is ready to handle messages. Since we gave the POOL_FLAG_EXIT_SELF flag to thread_pool_create(), once the threads have been started up, pthread_exit() will be called and this calling thread will exit. Using MsgSend() and MsgReply() You don't have to use read() and write() to interact with a resource manager; you can use the path that a resource manager registers to get a connection ID (coid) that you can use with MsgSend() to send messages to the server. This example consists of simple client and server programs that you can use as the starting point for any similar project. There are two source files: one for the server, and one for the client. Note that you must run server as root — a requirement in order to use the resmgr_attach() function. A bit of history QNX Neutrino. The server Let: - The server calls dispatch_block(), which waits for incoming messages and pulses. - Once there's data available, we call into dispatch_handler() to do the right thing based on the message data. It's inside the dispatch_handler() call that our message_callback() routing will be invoked, when messages of the proper type are received.(). The client The client is much simpler: /* * Message Client Process */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/neutrino.h> #include <sys/iofunc.h> #include <sys/dispatch.h> typedef struct { uint16_t msg_no; char msg_data[255]; } client_msg_t; int main( int argc, char **argv ) { int fd; int c; client_msg_t msg; int ret; int num; char msg_reply[255]; num = 1; /* Process any command line arguments */ while( ( c = getopt( argc, argv, "n:" ) ) != -1 ) { if( c == 'n' ) { num = strtol( optarg, 0, 0 ); } } /* Open a connection to the server (fd == coid) */ fd = open( "serv", O_RDWR ); if( fd == -1 ) { fprintf( stderr, "Unable to open server connection: %s\n", strerror( errno ) ); return EXIT_FAILURE; } /* Clear the memory for the msg and the reply */ memset( &msg, 0, sizeof( msg ) ); memset( &msg_reply, 0, sizeof( msg_reply ) ); /* Set up the message data to send to the server */ msg.msg_no = _IO_MAX + num; snprintf( msg.msg_data, 254, "client %d requesting reply.", getpid() ); printf( "client: msg_no: _IO_MAX + %d\n", num ); fflush( stdout ); /* Send the data to the server and get a reply */ ret = MsgSend( fd, &msg, sizeof( msg ), msg_reply, 255 ); if( ret == -1 ) { fprintf( stderr, "Unable to MsgSend() to server: %s\n", strerror( errno ) ); return EXIT_FAILURE; } /* Print out the reply data */ printf( "client: server replied: %s\n", msg_reply ); close( fd ); return EXIT_SUCCESS; } The client uses the open() function to get a coid (the server's default resmgr setup takes care of all of this on the server side), and performs a MsgSend() to the server based on this coid, and then waits for the reply. When the reply comes back, the client prints the reply data. You can give the client the command-line option -n# (where # is the offset from _IO_MAX) to use for the message. If you give anything over 2 as the offset, the MsgSend() will fail, since the server hasn't set up handlers for those messages. This example is very basic, but it still covers a lot of ground. There are many other things you can do using this same basic framework: - Register different message callbacks, based on different message types. - Register to receive pulses, in addition to messages, using pulse_attach(). - Override the default I/O message handlers so that clients can also use read() and write() to interact with your server. - Use a thread pool to make your server multithreaded. Many of these topics are covered later in this guide.
http://www.qnx.com/developers/docs/6.4.1/neutrino/resmgr/skeleton.html
crawl-003
refinedweb
1,917
53.92
03 November 2008 10:12 [Source: ICIS news] SINGAPORE (ICIS news)--China’s Yankuang Cathay Coal Chemicals started trial runs at its new 300,000 tonne/year acetic acid line in Tengzhou City, eastern Shandong province, as planned last week despite poor market conditions, a company official said on Monday. “We will ramp up operations gradually in November depending on the market situation,” he added. Yankuang operates an existing 300,000 tonne/year acetic acid plant at the same site. The company also plans to start-up its new 100,000 tonne/year downstream ethyl acetate plant later this month. The official did not provide details. Chinese domestic acetic acid fell yuan (CNY) 100-200/tonne ($14.62-29.24/tonne) to a 10-year low of CNY2,800-3,100/tonne ex-tank in eastern ?xml:namespace> Major acetic acid producers in ($1 = CNY 6.84) For more on acetic
http://www.icis.com/Articles/2008/11/03/9168120/yankuang-cathay-coal-starts-up-acetic-acid-line.html
CC-MAIN-2014-41
refinedweb
151
65.62
Hi, Please properly subscribe to the mailing list so that the community can receive email notifications for your messages. To subscribe, send empty email to user-subscr...@ignite.apache.org and follow simple instructions in the reply. Advertising pmazumdar wrote > I am trying to count number of rows in ignite cache that has a particular > string value in a column but it doesn't return any result while the data > set has many records for that value. > > Here's what I am doing - > > String countQuery = "SELECT COUNT(*) FROM Table1 WHERE LOWER(columnName) = > LOWER(?)"; > SqlFieldsQuery cQuery = new SqlFieldsQuery(countQuery); > List<List<?>> resCount = > IgniteSession.getCache().query(cQuery.setArgs("abc")).getAll(); > return (Long) resCount.get(0).get(0); > > Am I doing something wrong here? I can't reproduce this. Can you provide the whole test with your model classes, configurations, code that loads the data and the data itself? -Val -- View this message in context: Sent from the Apache Ignite Users mailing list archive at Nabble.com.
https://www.mail-archive.com/user@ignite.apache.org/msg06560.html
CC-MAIN-2017-17
refinedweb
164
58.28
Hi, I just took a tutorial on making a flashlight and it's pretty much done except I want it to disappear when it's off and appear when it's turned on. I have pretty much done this too, but since I don't know much of either scripts except for how they work and I am still learning javascript. I just have one compiler error and it uses terms I don't know of. Here is the compiler error. Assets/Game Project/Scripts/flashlight.cs(20,59): error CS0119: Expression denotes a value', where a method group' was expected value', where a Here is the script: using UnityEngine; using System.Collections; public class flashlight : MonoBehaviour { private bool FlashlightOn = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetButtonDown("Flashlight") && FlashlightOn == false) { FlashlightOn = true; light.intensity = 1; MeshRenderer otherScript = GetComponent<MeshRenderer>(); otherScript.renderer.enabled = true(); } else if (Input.GetButtonDown("Flashlight") && FlashlightOn == true) { FlashlightOn = false; light.intensity = 0; MeshRenderer otherScript = GetComponent<MeshRenderer>(); otherScript.renderer.enabled = false(); } } } I know that it has to do with these lines (I think) otherScript.renderer.enabled = false(); otherScript.renderer.enabled = true(); What do I correct? Answer by Drakestar · May 07, 2012 at 10:49 PM Get rid of the round brackets after true and false. Wow. It worked. Thanks :) But now I am getting a different error, it still compiles but it prevents the script from working. NullReferenceException: Object reference not set to an instance of an object flashlight.Update () (at Assets/Game Project/Scripts/flashlight.cs:27) It appeared while I was testing it out. What line is 27? It's telling you that you're trying to interact with an object that doesn't actually exist. otherScript.renderer.enabled = false; It also says the same for the other one: otherScript.renderer.enabled = true; The script is attatched to the spotlight which is a child of the actual flashlight object, which is a child of the main camera which is a child of the first person controller, just so you know. Answer by gjf · May 08, 2012 at 02:39 AM at first glance, "true();" should just be "true;". similarly "false();" should be "false;" - it's not a function. the error message is telling. Game object with animations 0 Answers What do I add to the LOD Renderer in MonoBehaviour? 2 Answers Do gameobjects not have a mesh component by default? 2 Answers Multiple Cars not working 1 Answer Renderer on object disabled after level reload 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/249659/turning-off-renderer-in-other-game-object-c.html
CC-MAIN-2021-17
refinedweb
425
58.18
Search: Search took 0.02 seconds. - 14 May 2008 8:34 AM - Replies - 6 - Views - 4,472 I have enough event handlers from the Store to do what I need to do, so it's not a big deal to me, I just wasn't sure if it was by design or not. Also, the add event does return an array of... - 14 May 2008 6:41 AM - Replies - 6 - Views - 4,472 Yes. No. And looking at the source code for Store, I noticed that the loadRecords function(callback from the reader to add records to the store) doesn't fire the add event... // private... - 14 May 2008 6:29 AM - Replies - 6 - Views - 4,472 Ext.data.Store: (v2.02) The add event does not fire when records are being added after a call to Store.load(). Is this by design or is this a bug? - 12 May 2008 4:35 PM Not sure why some cant'get to the page. The server that the page is running on does suck and I'm gonna take swell joe up on his offer. - 11 May 2008 12:21 AM - Replies - 97 - Views - 80,154 I was having this problem and used the override. When I did something like: myPanel.cascade(function(cmp){ if(cmp.isFormField) myPanel.remove(cmp,true);}); I was getting a some Container C[T]... - 10 May 2008 2:02 AM - Replies - 6 - Views - 4,529 I love this widget, it's beautiful and easy to use. The only problem I had is that it tries to change the color of the container during the render and in my case, I don't want a default value in... - 10 May 2008 12:17 AM Cool, I look forward to your message. I just tested converting the images to match the theme and it looks good. I just need somewhere to host the app now. Thanks!! :D Yep!! I definitely plan... - 9 May 2008 5:48 PM - Replies - 4 - Views - 2,418 I just bumped into this problem too... :D - 9 May 2008 11:09 AM new version posted... Someone create a center panel that will be a good demo of the stylesheet changes!! - 8 May 2008 6:18 PM I'm considering making a theme creation tool and as a first step, I had a little fun here. This app will generate an ext color scheme based on an offset to ext's default blue theme, or you can opt... - 7 May 2008 3:53 PM - Replies - 10 - Views - 10,648 Works well in a toolbar! :) I tried using renderTo config property on it and that caused problems... *shrug* - 7 May 2008 3:52 PM - Replies - 35 - Views - 64,398 Solid! - 7 May 2008 11:02 AM - Replies - 3 - Views - 4,407 Here's a checklist that ties to and auto updates your store. It could use some work, but it satisfies my current needs. If you have requests or updates, just let me know and I'll add em in. Here's... - 6 May 2008 3:30 PM - Replies - 40 - Views - 28,542 I don't think newer versions of Firefox or IE follow the RFC in this respect. The two connection rule in the RFC is recognized as an old design. - 5 May 2008 11:46 AM - Replies - 4 - Views - 1,916 Hey Evant, I never got around to saying thanks... :) Thanks, your solution works. - 4 May 2008 11:58 AM Great information guys! Thank you... :) - 2 May 2008 6:00 PM If you're just looking at displaying different stores within a grid, maybe you can look at GridPanel's reconfigure method. Hey Animal, how come render should never be called? - 1 May 2008 6:23 PM The way I do it(I'm not sure if this is the best practice) is to use contentEl to designate a <div> to display in the region. eg.: Ext.onReady(function(){ // create namespace... - 1 May 2008 4:30 PM Yep, that's the first thing that came across. - 1 May 2008 11:00 AM When I said multiple cards, I meant that I was doing a card layout and only one card can be seen at a time. I have a viewport with a card layout, the first card has a panel that displays the grid, an... - 1 May 2008 10:14 AM Thanks for the reply. Is there an easy way to do this within the ExtJS widgets' or is this something that will have to be done using Ext.DomHelper or something similiar? I ask, because I believe the... - 1 May 2008 9:59 AM I'm not sure if I've taken the wrong approach or I'm just missing something here. I have widgets that have been rendered in one place and that I want to reuse in another. As an example, I have a... - 29 Apr 2008 4:32 PM - Replies - 4 - Views - 1,916 Hiya devnull, thanks for taking the time to respond to another one of my questions. The reason why I'm doing this is because I've created a global form to be used in several places throughout my app,... - 29 Apr 2008 4:26 PM - Replies - 2 - Views - 2,149 In the tradition of this forum, I'll put some effort in to help others, like I've been helped. With small modifications - your code works. Here's the revision: // reference local blank... - 29 Apr 2008 2:19 PM - Replies - 4 - Views - 1,916 When I've rendered a component to a container how can I take that same component and render it into another container? Calling render() alone doesn't seem to do it... Results 1 to 25 of 60
https://www.sencha.com/forum/search.php?s=2860eb8fe30a05960da378d48eb10043&searchid=11964289
CC-MAIN-2015-27
refinedweb
955
81.33
Internet Engineering Task Force (IETF) D. Lewis Request for Comments: 6832 D. Meyer Category: Experimental D. Farinacci ISSN: 2070-1721 Cisco Systems V. Fuller January 2013 Interworking between Locator/ID Separation Protocol (LISP) and Non-LISP Sites Abstract .............................................5 3. LISP Interworking Models ........................................6 4. Routable EIDs ...................................................7 4.1. Impact on Routing Table ....................................7 4.2. Requirement for Sites to Use BGP ...........................7 4.3. Limiting the Impact of Routable EIDs .......................7 4.4. Use of Routable EIDs for Sites Transitioning to LISP .......7 5. Proxy Ingress Tunnel Routers ....................................8 5.1. Proxy-ITR EID Announcements ................................8 5.2. Packet Flow with Proxy-ITRs ................................9 5.3. Scaling Proxy-ITRs ........................................11 5.4. Impact of the Proxy-ITR's Placement in the Network ........11 5.5. Benefit to Networks Deploying Proxy-ITRs ..................11 6. Proxy Egress Tunnel Routers ....................................12 6.1. Packet Flow with Proxy-ETRs ...............................12 7. LISP-NAT .......................................................13 7.1. Using LISP-NAT with LISP-NR EIDs ..........................14 7.2. LISP Sites with Hosts Using RFC 1918 Addresses Sending to Non-LISP Sites .........................................15 7.3. LISP Sites with Hosts Using RFC 1918 Addresses Sending Packets to Other LISP Sites ...............................15 7.4. LISP-NAT and Multiple EIDs ................................16 8. Discussion of Proxy-ITRs, LISP-NAT, and Proxy-ETRs .............16 8.1. How Proxy-ITRs and Proxy-ETRs Interact ....................17 9. Security Considerations ........................................17 10. Acknowledgments ...............................................18 11. References ....................................................18 11.1. Normative References .....................................18 11.2. Informative References ...................................18 1. Introduction This document describes interoperation mechanisms between LISP [RFC6830] sites that use EIDs that are not globally routed,) that do not run LISP an intermediate LISP Ingress Tunnel Router (ITR) for non-LISP-speaking hosts. The second mechanism adds a form of Network Address Translation (NAT) functionality to Tunnel Routers (xTRs, where "xTR" refers to either an ITR or ETR), to substitute routable IP addresses for non-routable EIDs. The final network element is the LISP Proxy Egress Tunnel Router (Proxy-ETR), which acts as an intermediate Egress Tunnel Router (ETR) for LISP sites that need to encapsulate LISP packets destined to non-LISP sites. More detailed descriptions of these mechanisms and the network elements involved may be found in the following sections: - Section 2 defines terms used throughout this document. - Section 3 describes the different cases where interworking mechanisms are needed. - Section 4 describes the relationship between the new EID-Prefix space and the IP address space used by the current Internet. - Section 5 introduces and describes the operation of Proxy-ITRs. - Section 6 introduces and describes the operation of Proxy-ETRs. - Section 7 defines how NAT is used by ETRs to translate non-routable EIDs into routable IP addresses. -. will be hard to deploy or may have unintended consequences to applications. 2. Definition of Terms Default-Free Zone: The Default-Free Zone (DFZ) refers to the collection of all Internet autonomous systems that do not require a default route to route a packet to any destination. (Proxy-ITR): Proxy-ITRs are used to provide connectivity between sites that use LISP EIDs and those that do not. They act as gateways between those parts of the Internet that-NAT is described in Section 7. LISP Proxy Egress Tunnel Router (Proxy-ETR): Proxy-ETRs provide a LISP (routable or non-routable EID) site's ITRs with the ability to send packets to non-LISP sites in cases where unencapsulated packets (the default mechanism) would fail to be delivered. Proxy-ETRs function by having an ITR encapsulate all non-LISP destined traffic to a pre-configured Proxy-ETR. LISP Proxy-ETRs are described in Section [RFC6830]. 3. LISP Interworking Models There are 4 unicast connectivity cases that [RFC6830], that has the action 'Natively-Forward'. There could be some situations where (unencapsulated) packets originated by a LISP site may not be forwarded to a non-LISP site. These cases are reviewed in Section that cannot forward it (due to lack of a default route), at which point the traffic is dropped. For traffic not to be dropped, some mechanism to make this destination EID routable must be in place. Sections 5 (Proxy-ITRs) and 7 (LISP-NAT) describe two such mechanisms. Case 4 also applies to non-LISP packets (as in Case 3) that are returning to the LISP site. (and namespaces used for the path computation, and thus decrease global routing system overhead. Another goal is to achieve the benefits of improved aggregation as soon as possible. Individual sites advertising their own routes for LISP EID-Prefixes into the global routing system is therefore not recommended. That being said, single-homed sites (or multihomed" (Provider-Assigned) (PI) prefix(es) is of course under the. 5. Proxy Ingress Tunnel Routers Proxy Ingress Tunnel Routers (Proxy-ITRs) allow sites rather than close to LISP sites. Such deployment not only limits the scope of EID-Prefix route advertisements but also allows the: Internet DFZ .--------------------------------. / \ | Traffic Encap'd to Site's | | +-----+ RLOC(s) | LISP Site: | |P-ITR|=========> | | +-----+ +--+ +-----+ | | | |PE+------+CE 1 |-| | | Originated Route +--+ +-----+ | +----+ | the destination and gets 192.0.2.1 in return. 2. The source host has a default route to outer source address of this encapsulated packet is the Proxy-ITR's RLOC. 6. The Proxy-ITR looks up the RLOC and forwards the will not encapsulate the returning packet (see [RFC6830] Proxy-ITR's Placement in the Network There are several approaches that a network could take in placing Proxy-ITRs. Placing the Proxy-ITR near the source of traffic allows the communication between the non-LISP site and the LISP site to have the least "stretch" (i.e., the least number of forwarding hops when compared to an optimal path between the sites). Some proposals, for example the Core Router-Integrated Overlay [CRIO], have suggested grouping Proxy-IT Proxy-ITRs When packets destined for LISP-NR sites arrive and are encapsulated at a Proxy-ITR, a new LISP packet header is prepended. This causes the packet's destination to be set to the destination ETR's RLOC. Because packets are thus routed towards RLOCs, it can potentially better follow the Proxy-ITR network's Traffic Engineering policies (such as closest exit routing). This also means that providers that are not default-free and do not deploy Proxy-ITRs end up sending more traffic to expensive transit links (assuming their upstreams have deployed Proxy-ITRs) rather than to the ETR's RLOC addresses, to which they may well have cheaper and closer connectivity (via, for example, settlement-free peering). A corollary to this would be that large transit providers deploying Proxy-ITRs may attract more traffic, and therefore more revenue, from their customers. 6. Proxy Egress Tunnel Routers Proxy Egress Tunnel Routers (Proxy-ETRs) allow to Proxy-ETR. There are two primary reasons why sites would want to utilize a Proxy-ETR: Avoiding strict Unicast Reverse Path Forwarding (uRPF) failures: Some providers'). Proxy-ETRs can allow this LISP site's data to 'hop over' this by utilizing LISP's support for mixed-protocol encapsulation. 6.1. Packet Flow with Proxy-ETRs Packets from a LISP site can reach a non-LISP site with the aid of a Proxy-ETR. An ITR is simply configured to send all non-LISP traffic, which it normally would have forwarded natively (non-encapsulated), to a Proxy-ETR. In the case where the ITR uses one or more Map-Resolvers, Proxy-ETR should verify the (inner) source EID of the packet at Proxy-ETR. In this example, the LISP-NR (or LISP-R) site is given the EID-Prefix 192.0.2.0/24, and it is trying to reach a host at a non-LISP site with the IP prefix. a rough overview of what could be done and is not an exhaustive guide to IPv4 NAT. sites. Note that LISP-NAT is not needed in the case of LISP-R (routable global EIDs) sources. This case occurs when a site is announcing its prefix into both the LISP mapping system and the Internet DFZ. This is because the LISP-R source's address is routable, and return packets will be able to natively reach the site.R's implementation of the EID-to-RLOC mapping system used (see, for example, [RFC6836]).. that is doing address translation only (not port translation). The ITR providing the NAT service must use LISP-R EIDs for its global address pool and also provide all the standard NAT functions required today. Note that the RFC 1918 addresses above are private addresses and not EIDs, and that these RFC 1918 addresses are not found in the LISP mapping system. The source of the packet must be translated to a LISP-R EID in a manner similar to that discussed in Section 7, and this packet must be forwarded to the ITR's next hop for the destination, without LISP encapsulation. the source and destination ITR and ETRs continues as described in [RFC6830]. an RFC 1918 address of 192.168.1.2. In order to utilize LISP-NAT, the site also has been provided the LISP-R EID-PrefixR's implementation of the EID [RFC6830] forwards it to the proper host. 7.4. LISP-NAT and Multiple E Proxy-ITRs can mitigate this problem, because the LISP-NR EID can be reached in all cases. 8. Discussion of Proxy-ITRs, LISP-NAT, and its that are already using Proxy-ITRs. 8.1. How Proxy-ITRs and Proxy-ETRs Interact There is a subtle difference between symmetrical (LISP-NAT) and asymmetrical (Proxy-ITR and Proxy-ETR) interworking techniques. Operationally, Proxy-ITRs and Proxy-ET. 9. Security Considerations Like any router or LISP ITR, Proxy-ITRs will have the opportunity to inspect traffic at the time that they encapsulate. The location of these devices in the network can have implications for discarding malicious traffic on behalf of ETRs that request this behavior (by setting the ACT (action) bit in Map-Reply packets [RFC6830] to "Drop" multihomes that the quality of service meets the site's expectations. Proxy-ITRs and Proxy-ETRs share many of the same security issues as those discussed for ITRs and ETRs. For further information, see the security considerations section of [RFC6830]. the source IP address. These EIDs may not be recognized by their ISP option, which is more secure, that the outer IP source address is the site's RLOC). 10. Acknowledgments Thanks go to Christian Vogt, Lixia Zhang, Robin Whittle, Michael Menth, Xuewei Wang, and Noel Chiappa, who have made insightful A special thanks goes to Scott Brim for his initial brainstorming of these ideas and also for his careful review. 11. References 11.1. Normative References [RFC1918] Rekhter, Y., Moskowitz, R., Karrenberg, D., Groot, G., and E. Lear, "Address Allocation for Private Internets", BCP 5, RFC 1918, February 1996. . 11.2. Informative References [CRIO] Zhang, X., Francis, P., Wang, J., and K. Yoshida, "CRIO: Scaling IP Routing with the Core Router-Integrated Overlay", November 2006. [RFC2993] Hain, T., "Architectural Implications of NAT", RFC 2993, November 2000. Authors' Addresses Darrel Lewis Cisco Systems David Meyer Cisco Systems Dino Farinacci Cisco Systems Vince Fuller Previous: RFC 6831 - The Locator/ID Separation Protocol (LISP) for Multicast Environments Next: RFC 6833 - Locator/ID Separation Protocol (LISP) Map-Server Interface
http://www.faqs.org/rfcs/rfc6832.html
CC-MAIN-2015-32
refinedweb
1,871
54.22
On 01/26/2011 02:04 PM, John Linn wrote:>> -----Original Message----->> From: Grant Likely [mailto:glikely@secretlab.ca] On Behalf Of Grant>>>> It's been a while since these patches have been circulated for review.>> Much has changed since the last posting and there are no longer any>> ugly hacks or workarounds to it working. From my viewpoint, these>> patches are complete and ready to be used.>>>>. Right now those patches depend>> on the common struct clk patches that Jeremy is working on, so I'm not>> going to post them yet. Rather, this series is a stable base that>> other engineers can use to start working on device tree support for>> their platforms.>>>> Tested on Versatile (qemu) and nVidia Tegra Harmony. Kernel compiles>> an boot with CONFIG_OF both on and off, both with and without passing>> a device tree blob.>> Tested on Xilinx platform. Did see an issue with loading the device> tree blob into higher memory. At address 0 there was no issue.>I have a fix for this. The issue is the early mmu page table needs to map the dtb. I later realized this is also may be problem for ATAGs as well, so I planned to re-work to make it unconditional and work for ATAGs. Or perhaps ATAGs only get accessed with the MMU on later than the dtb and everything is okay?This applies to the DT patch set prior to the one Grant sent outthis week, so it may need updates.From: Rob Herring <rob.herring@calxeda.com>Date: Tue, 5 Oct 2010 10:32:51 -0500Subject: [PATCH] arm/dt: map devtree blob in initial page tableIf the DTB is not in 1st 1MB of RAM, it will not be mapped beforememblock is setup, so map it early. We assume the dtb is less than1MB and map 2MB so it can be at any alignment.Some assembly optimizations from Nicolas Pitre.Signed-off-by: Rob Herring <rob.herring@calxeda.com>--- arch/arm/kernel/head.S | 13 +++++++++++++ 1 files changed, 13 insertions(+), 0 deletions(-)diff --git a/arch/arm/kernel/head.S b/arch/arm/kernel/head.Sindex 0480f25..1fcb962 100644--- a/arch/arm/kernel/head.S+++ b/arch/arm/kernel/head.S@@ -228,6 +228,19 @@ __create_page_tables: .endif str r6, [r0]+#ifdef CONFIG_OF_FLATTREE+ /* Make sure DT blob is mapped */+ adr r0, __devtree_pointer+ ldr r0, [r0]+ mov r0, r0, lsr #20+ mov r0, r0, lsl #20+ add r3, r0, #PAGE_OFFSET+ add r3, r4, r3, lsr #18+ orr r6, r7, r0+ str r6, [r3]+ add r6, r6, #0x100000+ str r6, [r3, #4]+#endif #ifdef CONFIG_DEBUG_LL #ifndef CONFIG_DEBUG_ICEDCC /*--
https://lkml.org/lkml/2011/1/26/468
CC-MAIN-2017-22
refinedweb
434
73.07
Archived:Flash Lite UI Kit There are many screen resolutions for mobile devices, it makes the development of graphic user interface more difficult than should be. Many languages provide a lot of components for build graphic interfaces easily, like Java ME, Python for Symbian or WRT. A set of components is a Kit for development of graphic user interfaces. In Flash Lite there is no Kit for the development of graphic user interfaces. Normally the developers use the Flash native components, but they are made for web or desktop and they are so much heavy for mobile devices. In this article is proposed a Flash Lite Kit for development of graphic user interfaces. The following will show the basic features of this kit, the download of the first beta release and how to use it. Basic Features - It has to work in many screen resolutions. - Details as color, font and format must be configurable. Basic Components In the first beta version of the Kit two basic components were developed (TextBox and Button); they are the only components available in this version. Future Releases In future releases more and more components will be added and existing components will be upgraded. This version is just a proof-of-concept of the Kit. How to Install and Use it The Kit consists of a set of Action Script classes that must be imported in a Flash Lite project (It can be downloaded ()here ). After being imported, the use of them is very simple, like shown below: import flkit.components.ui.*; //Creates two instances of TextBox UI component of the Flash Lite UI Kit var tx1:TextBox = new TextBox("tx1","FirstName",""); var tx2:TextBox = new TextBox("tx2","SurName",""); //Creates two instances of Button UI component of the Flash Lite UI Kit var bt1:Button = new Button("bt1","send"); var bt2:Button = new Button("bt2","load"); //Defines the event when a click on button SAVE occurs bt1.onClick = function(){ trace("click on button SAVE"); } //Defines the event when a click on button LOAD occurs bt2.onClick = function(){ trace("click on button LOAD"); } //Creates a new UIManager, this is the base class of the Flash Lite UI Kit. All UI components must be in this instance. //The constructor parameter is the MovieClip where all components will be added. var uiManager:UIManager = new UIManager(_root); //Adding all UI components uiManager.addUIComponent(tx1); uiManager.addUIComponent(tx2); uiManager.addUIComponent(bt1); uiManager.addUIComponent(bt2); //Builds the graphic interface uiManager.build(); This code produces the same effect in two different screen resolutions, as shown in the pictures below. Contributions The code is Open Source and any contribution will be appreciated. This is a good article showcasing some basic components to use in FlashLite applications. When creating the mobile applications it is necessary to consider the deployment to different screen resolution and change the look of the application. And as the components provided can change the dimension according to the screen resolution, this is very useful.
http://developer.nokia.com/community/wiki/Flash_Lite_UI_Kit
CC-MAIN-2014-10
refinedweb
494
53.41
In this tutorial, we will look at different ways to select a random item from a list. Let's assume you have a list with multiple Twitter user names and you are trying to select a random Twitter user. Below is a sample list of Twitter user names: twitter_user_names = [ '@rahulbanerjee99', '@python_engineer', '@FCBarcelona', '@FerranTorres20', '@elonmusk', '@binance', '@SpaceX' ] Random Library The random library is a built-in Python library, i.e, you do not have to install it. You can directly import it. We will look at 3 different ways to select a random item from a list using the random library. 1. Random Index import random num_items = len(twitter_user_names) random_index = random.randrange(num_items) winner = twitter_user_names[random_index] print(winner) Output: @binance random.randrange(num_items) returns a random number between 0 and num_items - 1. So we basically get a random index that we can use to access an element from our list. 2. Single Random Element winner = random.choice(twitter_user_names) print(winner) Output: @SpaceX random.choice takes a sequence like a list as a parameter and returns a random element from the list. In our case, we simply pass the twitterusernames list. 3. Multiple Random Element winners = random.sample(twitter_user_names, 2) print(winners) Output: ['@python_engineer', '@rahulbanerjee99'] random.sample is similar to random.choice, the main difference being that you can specify the number of random elements you want. In the above code snippet, I got two random Twitter user names. random.sample returns a list. In some cases, you might want the same random element(s) to be returned by the random library. The following line of code ensures that the same random element(s) will be generated whenever you run your script. This can be useful when you are debugging and want your script to produce consistent outputs. random.seed(0) random.seed takes an integer parameter. If you pass a different parameter other than 0, you will get a different random element(s). Secrets library The Secrets library is preferred over the Random library since it is more secure. Like the random library, it is a built-in python library and you do not have to install any dependencies. However if you are using a version below Python 3.6, you will have to install a backport of the secrets module. You can read more about it here. 1. Random Index import secrets random_index = secrets.randbelow(num_items) winner = twitter_user_names[random_index] print(winner) Output: @binance This is similar to random.randrange. We get a random index between 0 and num_items - 1 and use it to access an element from our Twitter user names list. 2. Single Random Element winner = secrets.choice(twitter_user_names) print(winner) Output: @binance This is similar to random.choice and returns a random element from the list passed as a parameter. 3. Multiple Random Elements winners = secrets.SystemRandom().sample(twitter_user_names, 2) print(winners) Output: ['@SpaceX', '@binance'] This is similar to random.sample and lets you pass the number of rand items you want as a parameter. This method returns a list. Unlike random.seed, you can not use a seed to keep the random element(s) generated by the secrets library consistently.
https://www.python-engineer.com/posts/randomly-select-item/
CC-MAIN-2022-21
refinedweb
523
51.14
On Montag, 12. Februar 2018 00:41:54 CET Christian Schudt wrote: > - Generally I am unsure if using the "xml:lang" and „name" from the > identities is a good idea at all, because these two attributes should not > change the capabilities of an entity. Name and language is just for humans. > I.e. if a server sends german identities for one user and english > identities for the next user (depending on their client settings/stream > header), the server still has the same identities, which should result in > the same verification string, shouldn’t it? First of all, I think previously, an entity answering a disco#info request always sent all translated identities, so that would not have been an issue. You’re touching on a more general thing though which I’d like to discuss. We could separate the hash into three hashes, one for identities, one for features and one for forms (or maybe two: identities and forms+features). This has the upside that human readable identifiers don’t interfere with protocol data (features/forms) in many cases (I think the identities are more rarely used in protocols, but I might be wrong). The obvious downside is that we need to transfer more data in the presence (twice or thrice the amount for ecaps2). I’d like to know what you people think of it. Since this is still Experimental, I’d be fine with bumping the namespace and getting this done. But I’m afraid that the bandwidth costs will outweigh the advantages. We have ~100 bytes for a 256 bit hashsum (including wrapper XML). We would end up with more than half a kilobyte (~0.6 kB) for ecaps2 if we split the hashes and assume that each entity uses two hash functions with 256 bits each (which I think is a reasonable assumption). If we have caps optimization, the impact would probably be neglectible, but I’m not sure if we can assume that. I’d like to get input from you folks on that. kind regards, Jonas signature.asc Description: This is a digitally signed message part. _______________________________________________ Standards mailing list Info: Unsubscribe: standards-unsubscr...@xmpp.org _______________________________________________
https://www.mail-archive.com/standards@xmpp.org/msg18634.html
CC-MAIN-2018-47
refinedweb
363
62.58
Get the highlights in your inbox every week. Maximizing web performance with Varnish Cache Getting started with web app accelerator Varnish Cache Subscribe now Varn. And sometimes that means explaining how to use Varnish Cache and get out all the bells and whistles that make it a unique, "lifesaving" (at least for websites and applications), and cool technology. The nitty-gritty "weirdness" of Varnish Cache Varnish Cache is an HTTP server with an HTTP backend that can serve files. It has a threaded architecture, but no event loop. Because the write code can use blocking system calls, it's easier to use than Apache or NGINX, where you have to deal with an event loop. Varnish Cache has a weird way of logging to shared memory, not disk. It's designed this way because logging 10,000 HTTP transactions per second to rotating hard drives is very expensive. Varnish logs everything—approximately 200 lines per request—to memory. If no one is looking for that information, it gets overwritten. Varnish is the only application that does that. Flexibility: Help yourself to some VCL The big differentiator for Varnish Cache is its configuration language. Varnish Configuration Language (VCL) was created 10 years ago to support Varnish Cache 1.0. Unlike Apache or other programs, Varnish Cache does not have a traditional configuration. Instead, it has a set of policies written in this specific language. These policies are compiled into native (binary) code, and the native code is loaded and then run. Varnish Cache architect Poul-Henning Kamp says VCL was built as a box with a set of tools that can be used as needed, not a fixed product that fits nicely in a box. Today, VCL has 100 modules available that are simple to use. In fact, our Varnish Summits always include a workshop that teaches people to write modules. We hear time and again that VCL is one of the big reasons people love and even grow to be fiercely protective of Varnish Cache. Its flexibility opens the door to do virtually anything someone wants, throwing traditional program constraints out the window. So what are the major tools in the VCL toolbox, and how can they be best put to use? Purging Varnish doesn't support content purging out of the box. You can't just download, install, and purge right away—some assembly is required. Instead of shipping this code with a default configuration, Varnish Cache requires that its users get some dirt under their fingernails. However, the configuration to set up purging is simple, and you can get exactly what you want from it. sub vcl_recv { if (req.method == "PURGE") { return (purge); } } If you don't want anyone out on the Internet to purge content from your cache, we set up an ACL limit access to purging to this specific thing: acl purge { "localhost"; "192.168.55.0"/24; } sub vcl_recv { if (req.method == "PURGE") { if (!client.ip ~ purge) { return(synth(405,"Not allowed.")); } return (purge); } } Adding a "feature" to Varnish Cache: Throttling hot linking The Varnish framework allows every user to implement the features they need for themselves. The first contributed feature is to use VCL to limit hot linking. Hot linking is stealing someone else's resources on the web, writing a brief post on it, then using their images to illustrate your point so that they end up paying the bandwidth bill. Varnish allows servers to block this process when hot linking is unlawfully using their resources. For example, Varnish can cap the number of times per minute this can happen by leveraging a VMOD (Varnish module)—vsthrottle—to add throttling. The user simply imports and loads the throttling module. The VCL snippet below shows a way to limit hot linking. In this example we apply three rules. The first rule checks whether the requested URL starts with "/assets/." The second and third rule protect your assets from hot linking. This is done by checking whether the referrer is other than what you expect, and whether other domains have requested your assets more than 10 times within 60 seconds. That's the throttle function. The URL is used as the key for throttling. The permit equals 10 times per 60 seconds. We are allowed to serve the URL under assets that don't have this as their refer, and if that hits we just throw error 403 with hot linking prohibited. Throttling can also expand to use memcache instead, so that the user gets the central accounting in its cluster. import vsthrottle; (..) if (req.url ~ "^/assets/" && (req.http.referer !~ "^") && vsthrottle.is_denied(req.url, 10, 60s) { return(error(403,"Hotlinking prohibited"); } Dealing with cookies Varnish will not cache content requested with cookies. Nor will it deliver a cache hit if the request has a cookie associated with it. Instead, the VMOD is used to strip the cookie. Real men and women will use the regular expression to filter out the cookies. For the rest of us, Varnish offers a cookie module that looks like this: import cookie; sub vcl_recv { cookie.parse ("cookie1: value1; cookie2: value2"); cookie.filter_except("cookie1"); // get_string() will now yield // "cookie1: cookie2: value2;"; } Varnish doesn't like the set cookie header either. If it sees the backend is sending a set cookie header, it will not cache that object. The solution is to remove the set cookie header or to fix the backend. - Set-Cookie headers deactivate cookies. - Solution: Remove Set-Cookie or fix the backend. Grace Mode: Keeping the thundering herd at bay Grace Mode allows Varnish to serve outdated content if new content isn't available. It improves performance by asynchronously refreshing content from the backend. When Varnish 1.0 was first introduced as the caching solution for the online branch of the Norwegian tabloid newspaper Verdens Gang, there were massive problems with threading pileups. The newspaper front page was delivered 3,000 times/second, but its content management system (CMS) was slow and took three seconds to regenerate the front page. At some sites, if you follow the RFCs, the proxy cache will invalidate that front page or it will time out. Then a user comes along and a new version of the front page needs to be fetched. Varnish does this with cache coalescing. As new users come along, they are placed on a waiting list. (Other caches send users to the backend, which kills the backend.) If 3,000 more users are being added to the waiting list every second, after three seconds, 9,000 users are waiting for the backend to deliver the content. Initially, Varnish would take that piece of content, talk to its 9,000 threads, and try to push it out all at once. We called this scenario a thundering herd, and it instantly killed the server. To solve this problem, Varnish decided to simply use the old front page instead of waiting for the server to regenerate the content. Unless you're serving up real-time financial information, no one cares if content is 20 seconds out of date. The semantics of Grace have changed slightly over the years. In Varnish 4.0 (if enabled) it looks like this: sub vcl_backend_response { set beresp.grace = 2m; } Grace is set on the backend response object. If set to two minutes, Varnish will keep an object two minutes past its TPL. If it is requested in that time, it will prefer to serve something that is in cache over something out of cache. It will use the object, then asynchronously refresh the object. Opening the hood Varnish Cache doesn't require users to read source code, but instead provides a default VCL where they can try to put as much of the semantics as they can. With a feature like Grace users can read the VCL and see what it does. Insert code (fetch); } If the object VCL is more than zero seconds, it has a positive TTL. Return and deliver. Serve it. If TTL and Grace is more than zero seconds, it is in Grace and Varnish will deliver it. If TTL and Grace is less than zero seconds, we block and fetch it. Modifying Grace semantics Organizations that are scaling with financial instruments and reluctant to serve something that is out of date might want to modify Grace semantics. The first bit here is unchanged. The second part is rewritten if the backend is not healthy and TTL and Grace more than zero seconds do deliver. sub vcl_hit { if (obj.ttl >= 0s) { // A pure unadulterated hit, deliver it return (deliver); } if (!std.healthy(req.backend_hint) && (obj.ttl + obj.grace > 0s)) { return (deliver); } // fetch & deliver once we get the result return (fetch); } A couple of things you might wonder about: - beresp is the backend request object. - req is the request object. Use in vcl_recv. - bereq is the backend request object. Use in vcl_backed_fetch. - beresp is the backend response. Use in vcl_backend_response. - resp is the response object. Use in vcl_deliver. - obj is the original object in memory. Use in vcl_hit. - man(7) vcl for details. The state machine Every request goes through states. Custom code is run at each use to modify request objects. After user-specific code is run, Varnish will decide if it is a hit or a miss and then run VCL hit or VCL miss. If it's a hit, VCL delivers. A miss goes to backend fetch. 90% of user-specific changes happen here. Quick guide to tuning on Linux Tunables in Linux are very conservatively set. The two that we find most annoying are SOMAXCONN and TCP_MAX_SYN_Backlog. When we listen to socket, Varnish will take a couple seconds to listen to the call. If those threads get busy, the kernel will start to queue up. That queue is not allowed to grow beyond SOMAXCONN. Varnish will ask for 1024 connection in the listen depth queue, but the kernel overrides that and you get 928. Because Varnish runs with root privileges it should be able to decide its own listen depth, but Linux knows best. Users may want to increase that limit if they want to reduce the risk of rejecting connections when out of listen depth. They have to decide if it is better to fail and deliver an error page to the user. TCP_MAX_SYN_Backlog defines how many outstanding connections can be within the three-way handshake before the kernel assumes that it is being attacked. The default is 128. However, if a flash mob forms on the Internet and goes to your site, you might have more than 128 new TCP connections per second. Don't mess with tcp_tw_recycle. Take care when Googling these things. There are a lot of demons associated with them. Work spaces in Linux In Varnish, local memory is in each thread. Because rollback is expensive, we don't roll back every time we need a bit of memory. Instead, we pre-allocate memory to each thread if a user has a lot of VCL manipulating strings back and forth that will burn up all the workspace. Varnish does not do connection tracking; the contract module is dead slow. The default is to run with five threads. It's relatively quick to spin up new threads, but if planning on doing 1,000 connections per second = 1,000 threads, then you have the parameter for pre-allocating threads. To recap: - Be aware of workspaces. - Don't do connection tracking. - Up the threads to one req/sec per thread. The weird-cool balance of Varnish Cache The powerful flexibility and benefits of Varnish Cache don't come prepackaged in a square box (which may strike some as weird), and in that way it might not be the right solution for everyone. Its flexibility, though, can be game-changing when looking for ways to customize and control web performance and scalability.
https://opensource.com/business/16/2/getting-started-with-varnish-cache
CC-MAIN-2020-34
refinedweb
1,974
74.29
Opened 9 years ago Closed 9 years ago #7100 closed (invalid) breadcrumb UnicodeEncodeError Description Non ascii str string raise UnicodeEncodeError in breadcrumbs render in django/contrib/admin/templates/admin/change_form.html 14 {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %}{{ original|truncatewords:"18" }}{% endif %} when editing an object. I purpose change django/contrib/admin/views/main.py 403 - 'original': manipulator.original_object, 403 + 'original': smart_str(manipulator.original_object), or, if original can't be changed, we can just add another variable in the Request 404 + 'original_str': smart_str(manipulator.original_object), and change reference in the template - django/contrib/admin/templates/admin/change_form.html 14 - {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %}{{ original|truncatewords:"18" }}{% endif %} 14 + {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %}{{ original_str|truncatewords:"18" }}{% endif %} Attachments (1) Change History (6) comment:1 Changed 9 years ago by comment:2 Changed 9 years ago by Changed 9 years ago by comment:3 Changed 9 years ago by Sorry by the missing patch. I tried other approach now as showed in the patch. I'm still in doubt if the check for to_str in _dec function is really necessary, but i'm sure that for now it have little impact over other stringfunctions decorated functions. comment:4 Changed 9 years ago by There is also the workaround of use unicode function in the model but i think that a generic solution is better. comment:5 Changed 9 years ago by I've verified truncatewords handles unicode properly. The problem seems to be a Model that returns a non-ASCII data via an __str__() function instead of a __unicode__() function. Having a __unicode__ function in your model is not a workaround, it is the generic solution for having your models return non-ASCII representations of themselves. If I have misunderstood how you ran into this problem please reopen with specifics of the Model involved, data contained in it, and a traceback of the error you are seeing. The one I can recreate is definitely a user error of not having a __unicode__ method on a model that needs one. Next time, please attach a proper patch file, since it will include context in the even that line 402 or 403 changes before we get to the ticket. This looks like a bug, but the proposed fix isn't the right approach. Instead, truncatewords should be fixed to work with unicode strings. And we don't need to go overboard here; we'll still consider "words" to be whitespace-separated sequences of characters, rather than teaching it to understand all the constraints of all the languages in the world.
https://code.djangoproject.com/ticket/7100
CC-MAIN-2017-34
refinedweb
433
54.42
In this tutorial you will learn how to: Note The explanation below belongs to the book Computer Vision: Algorithms and Applications by Richard Szeliski Two commonly used point processes are multiplication and addition with a constant: The parameters and are often called the gain and bias parameters; sometimes these parameters are said to control contrast and brightness respectively. You can think of as the source image pixels and as the output image pixels. Then, more conveniently we can write the expression as: where and indicates that the pixel is located in the i-th row and j-th column. #include <cv.h> #include <highgui.h> #include <iostream> using namespace cv; double alpha; /**< Simple contrast control */ int beta; /**< Simple brightness control */ int main( int argc, char** argv ) { /// Read image given by user Mat image = imread( argv[1] ); Mat new_image = Mat::zeros( image.size(), image.type() ); /// Initialize values std::cout<<" Basic Linear Transforms "<<std::endl; std::cout<<"-------------------------"<<std::endl; std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha; std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta; /// Do the operation new_image(i,j) = alpha*image(i,j) + beta for( int y = 0; y < image.rows; y++ ) { for( int x = 0; x < image.cols; x++ ) { for( int c = 0; c < 3; c++ ) { new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta ); } } } /// Create Windows namedWindow("Original Image", 1); namedWindow("New Image", 1); /// Show stuff imshow("Original Image", image); imshow("New Image", new_image); /// Wait until user press some key waitKey(); return 0; } We begin by creating parameters to save and to be entered by the user: double alpha; int beta; We load an image using imread and save it in a Mat object: Mat image = imread( argv[1] ); Now, since we will make some transformations to this image, we need a new Mat object to store it. Also, we want this to have the following features: Mat new_image = Mat::zeros( image.size(), image.type() ); We observe that Mat::zeros returns a Matlab-style zero initializer based on image.size() and image.type() Now, to perform the operation we will access to each pixel in image. Since we are operating with RGB images, we will have three values per pixel (R, G and B), so we will also access them separately. Here is the piece of code: for( int y = 0; y < image.rows; y++ ) { for( int x = 0; x < image.cols; x++ ) { for( int c = 0; c < 3; c++ ) { new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta ); } } } Notice the following: Finally, we create windows and show the images, the usual way. namedWindow("Original Image", 1); namedWindow("New Image", 1); imshow("Original Image", image); imshow("New Image", new_image); waitKey(0); Note Instead of using the for loops to access each pixel, we could have simply used this command: image.convertTo(new_image, -1, alpha, beta); where convertTo would effectively perform new_image = a*image + beta. However, we wanted to show you how to access each pixel. In any case, both methods give the same result.
http://docs.opencv.org/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html
CC-MAIN-2014-41
refinedweb
518
53.41
From: "H. Peter Anvin" <hpa@zytor.com>Date: Fri, Apr 23, 2010 at 11:06:15AM -0700> On 04/23/2010 07:09 AM, Borislav Petkov wrote:> > > > Ok, looking at the k8.o object it is 507 bytes so I don't think> > compiling it in would hurt embedded people too much:> > > > text data bss dec hex filename> > 379 104 24 507 1fb arch/x86/kernel/k8.o> > > > So how about the following? It should apply cleanly on top and it> > survived a bunch of randconfigs here so far.> > > > I have to say I think that's pretty ridiculous for someone who cares so> much about size that they have disabled CONFIG_PCI that they can just> add another half-kilobyte of code that is going to do absolutely> nothing. Think about the kind of x86 CPUs that could even consider> disabling CONFIG_PCI -- we're talking pretty deep embedded by now.Yep, true story.> So, no, I don't think this is an option. Force-enabling CONFIG_PCI on> x86 would be a more realistic option, and I honestly don't know how many> people would object to that, but not right now.Well, after looking at 1ac97018169c5a13feaa90d9671f2d6ba2d9e86e,grepping for '!PCI' in arch/x86/ returns nothing now.From all the x86 flavors which didn't need PCI1) There used to be a X86_VOYAGER MCA-based 32-bit arch from NCR whichseems to be gone now2) X86_VISWS "SGI 320/540 (Visual Workstation)" depended on !PCI butdepends on PCI now, so which is it?3) X86_VSMP ("ScaleMP vSMP") used to depend on !PCI but depends on PCInow, [/me puzzled].all seem fine with PCI currently (especially the Voyager :)). So itreally looks like we could enable it by default on x86. Maybe for the.35 merge window and see how much fallout we generate. Or at least putit up for a flamewar on lkml since we like those so much :).> The obvious answer instead is to augment the list of stubs in> <asm/k8.h>. In particular, move num_k8_northbridges into the #ifdef and> just #define num_k8_northbridges 0 in the other clause.Right, it couldn't be simpler, see below. With it, the only warning Iget doing randconfig builds isarch/x86/kernel/cpu/intel_cacheinfo.c:498: warning: ‘cache_disable_0’ defined but not usedarch/x86/kernel/cpu/intel_cacheinfo.c:500: warning: ‘cache_disable_1’ defined but not usedwhich is caused by !CONFIG_SYSFS but this is another senseless case.---From: Borislav Petkov <borislav.petkov@amd.com>Date: Sat, 24 Apr 2010 09:56:53 +0200Subject: [PATCH] x86, k8-nb: Fix build error when K8_NB is disabledK8_NB depends on PCI and when the last is disabled (allnoconfig) we failat the final linking stage due to missing exported num_k8_northbridges.Add a header stub for that.Signed-off-by: Borislav Petkov <borislav.petkov@amd.com>--- arch/x86/include/asm/k8.h | 5 +++++ 1 files changed, 5 insertions(+), 0 deletions(-)diff --git a/arch/x86/include/asm/k8.h b/arch/x86/include/asm/k8.hindex f70e600..af00bd1 100644--- a/arch/x86/include/asm/k8.h+++ b/arch/x86/include/asm/k8.h@@ -16,11 +16,16 @@ extern int k8_numa_init(unsigned long start_pfn, unsigned long end_pfn); extern int k8_scan_nodes(void); #ifdef CONFIG_K8_NB+extern int num_k8_northbridges;+ static inline struct pci_dev *node_to_k8_nb_misc(int node) { return (node < num_k8_northbridges) ? k8_northbridges[node] : NULL; }+ #else+#define num_k8_northbridges 0+ static inline struct pci_dev *node_to_k8_nb_misc(int node) { return NULL;-- 1.6.4.4-- Regards/Gruss,Boris.--Advanced Micro Devices, Inc.Operating Systems Research Center--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
http://lkml.org/lkml/2010/4/24/16
CC-MAIN-2014-10
refinedweb
599
67.35
//************************************** //INCLUDE files for :^!!~File Write~!!^ //************************************** #include <fstream.h> #include <iostream.h> #include <stdlib.h> //************************************** // Name: ^!!~File Write~!!^ // Description:Prompts input and writes it to a file // By: fritz0x00 (from psc cd) // // Side Effects:File Writing //************************************** //by fritz300 of #include <fstream.h> #include <iostream.h> #include <stdlib.h> int main() { //** Declare Varibles, Theres only one char text[80]; //** Declare pointers ifstream fin; ofstream fout; //** Begin; tell user what he/she is about to do cout << "Welcome to Fritzs Text Write program, This program (with source code included) \nwill teach you how to write text to files!\n\n"; //** End; cout << "Type a word:\n"; cin >> text; fout.open("c:/windows/desktop/file.txt"); //** Opens the file to write too. fout << "Fritzs Text Write Program Example:\n\nYou typed:\n\n\t"; fout << text; //** Writes the input to file.txt fout.close(); //** Error handler aka what happens if a error occurs if( !fin || !fout ) { cout<<"Error has occured. Cannot open file.txt\n\n" << endl; } cout<<"\nText was successfully written to C:/windows/desktop/file.txt\n" << endl; cout << "\n\n\tText write program by Zak Farrington alias fritz owner of hAx Studios Ltd. <> development team." << endl; system("PAUSE"); return 0; }.
https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4772&lngWId=3
CC-MAIN-2018-26
refinedweb
199
78.25
This document describes the popular twelve-factor app methodology and how to apply it when you develop apps that run on Google Cloud. If you use this methodology, you can make scalable and resilient apps that can be continuously deployed with maximum agility. This document is intended for developers who are familiar with Google Cloud, version control, continuous integration, and container technology. Introduction Developers are moving apps to the cloud, and in doing so, they become more experienced at designing and deploying cloud-native apps. From that experience, a set of best practices, commonly known as the twelve factors, has emerged. Designing an app with these factors in mind lets you deploy apps to the cloud that are more portable and resilient when compared to apps deployed to on-premises environments where it takes longer to provision new resources. However, designing modern, cloud-native apps requires a change in how you think about software engineering, configuration, and deployment, when compared to designing apps for on-premises environments. This document helps you understand how to apply the twelve factors to your app design. Advantages of twelve-factor apps Twelve-factor design also helps you decouple components of the app, so that each component can be replaced easily, or scaled up or down seamlessly. Because the factors are independent of any programming language or software stack, twelve-factor design can be applied to a wide variety of apps. The twelve factors 1. Codebase You should track code for your app in a version control system such as Git or Mercurial. You work on the app by checking out the code to your local development environment. Storing the code in a version control system enables your team to work together by providing an audit trail of changes to the code, a systematic way of resolving merge conflicts, and the ability to roll back the code to a previous version. It also provides a place from which to do continuous integration (CI) and continuous deployment (CD). While developers might be working on different versions of the code in their development environments, at any given time the source of truth is the code in the version control system. The code in the repository is what gets built, tested, and deployed, and the number of repositories is independent of the number of environments. The code in the repository is used to produce a single build, which is combined with environment-specific configuration to produce an immutable release—a release where no changes can be made, including to the configuration—that can then be deployed to an environment. (Any changes required for the release should result in a new release.) Cloud Source Repositories enables you to collaborate and manage your code in a fully featured, scalable, private Git repository. It comes with code-search functionality across all repositories. You can also connect to other Google Cloud products such as Cloud Build, App Engine, Cloud Logging, and Pub/Sub. 2. Dependencies There are two considerations when it comes to dependencies for twelve-factor apps: dependency declaration and dependency isolation. Twelve-factor apps should never have implicit dependencies. You should declare any dependencies explicitly and check these dependencies into version control. This enables you to get started with the code quickly in a repeatable way and makes it easy to track changes to dependencies. Many programming languages offer a way to explicitly declare dependencies, such as pip for Python and Bundler for Ruby. You should also isolate an app and its dependencies by packaging them into a container. Containers allow you to isolate an app and its dependencies from its environment and ensure that the app works uniformly despite any differences between development and staging environments. Container Registry is a single place for your team to manage container images and perform vulnerability analysis. It also lets you decide who can access what, using fine-grained access control to the container images. Because Container Registry uses a Cloud Storage bucket as the backend for serving container images, you can control who has access to your Container Registry images by adjusting permissions for this Cloud Storage bucket. Existing CI/CD integrations also let you set up fully automated pipelines to get fast feedback. You can push images to their registry, and then pull images using an HTTP endpoint from any machine, whether it's a Compute Engine instance or your own hardware. Container Analysis can then provide vulnerability information for the images in Container Registry. 3. Configuration Every modern app requires some form of configuration. You usually have different configurations for each environment, such as development, test, and production. These configurations usually include service account credentials and resource handles to backing services such as databases. The configurations for each environment should be external to the code and should not be checked into version control. Everyone works on only one version of the code, but you have multiple configurations. The deployment environment determines which configuration to use. This enables one version of the binary to be deployed to each environment, where the only difference is the runtime configuration. An easy way to check whether the configuration has been externalized correctly is to see if the code can be made public without revealing any credentials. One way of externalizing configuration is to create configuration files. However, configuration files are usually specific to a language or development framework. A better approach is to store configuration in environment variables. These are easy to change for each environment at runtime, are not likely to be checked into version control, and are independent of programming language and development framework. In Google Kubernetes Engine (GKE), you can use ConfigMaps. This lets you bind environment variables, port numbers, configuration files, command-line arguments, and other configuration artifacts to your pods' containers and system components at runtime. 4. Backing services Every service that the app consumes as part of its normal operation, such as file systems, databases, caching systems, and message queues, should be accessed as a service and externalized in the configuration. You should think of these backing services as abstractions for the underlying resource. For example, when the app writes data to storage, treating the storage as a backing service allows you to seamlessly change the underlying storage type, because it's decoupled from the app. You can then perform a change such as switching from a local PostgreSQL database to Cloud SQL for PostgreSQL without changing the app code. 5. Build, release, run It's important to separate the software deployment process into three distinct stages: build, release, and run. Each stage should result in an artifact that's uniquely identifiable. Every deployment should be linked to a specific release that's a result of combining an environment's configuration with a build. This allows easy rollbacks and a visible audit trail of the history of every production deployment. You can manually trigger the build stage, but it's usually triggered automatically when you commit code that has passed all of the required tests. The build stage takes the code, fetches the required libraries and assets, and packages these into a self-contained binary or container. The result of the build stage is a build artifact. When the build stage is complete, the release stage combines the build artifact with the configuration of a specific environment. This produces a release. The release can be automatically deployed into the environment by a continuous deployment app. Or you can trigger the release through the same continuous deployment app. Finally, the run stage launches the release and starts it. For example, if you're deploying to GKE, Cloud Build can call the gke-deploy build step to deploy to your GKE cluster. Cloud Build can manage and automate the build, release, and run stages across multiple languages and environments using build configuration files in YAML or JSON format. 6. Processes You run twelve-factor apps in the environment as one or more processes. These processes should be stateless and should not share data with each other. This allows the apps to scale up through replication of their processes. Creating stateless apps also make processes portable across the computing infrastructure. If you're used to the concept of "sticky" sessions, this requires a change in how you think about handling and persisting data. Because processes can go away at any time, you can't rely on the contents of local storage being available, or that any subsequent request will be handled by the same process. Therefore, you must explicitly persist any data that needs to be reused in an external backing service such as a database. If you need to persist data, you can use Memorystore as a backing service to cache the state for your apps, and to share common data between processes to encourage loose coupling. 7. Port binding In non-cloud environments, web apps are often written to run in app containers such as GlassFish, Apache Tomcat, and Apache HTTP Server. In contrast, twelve-factor apps don't rely on external app containers. Instead, they bundle the webserver library as a part of the app itself. It's an architectural best practices for services to expose a port number, specified by the PORT environment variable. Apps that export port binding are able to consume port binding information externally (as environment variables) when using the platform-as-a-service model. In Google Cloud, you can deploy apps on platform services such as Compute Engine, GKE, App Engine, or Cloud Run. In these services, a routing layer routes requests from a public-facing hostname to your port-bound web processes. For example, when you deploy your apps to App Engine, you declare dependencies to add a webserver library to the app, such as Express (for Node.js), Flask and Gunicorn (for Python), or Jetty (for Java). You should not hard-code port numbers in your code. Instead, you should provide the port numbers in the environment, such as in an environment variable. This makes your apps portable when you run them on Google Cloud. Because Kubernetes has built-in service discovery, in Kubernetes you can abstract port bindings by mapping service ports to containers. Service discovery is accomplished using internal DNS names. Instead of hard-coding the port that the webserver listens on, the configuration uses an environment variable. The following code snippet from an App Engine app shows how to accept a port value that's passed in an environment variable. const express = require('express') const request = require('got') const app = express() app.enable('trust proxy') const PORT = process.env.PORT || 8080 app.listen(PORT, () => { console.log('App listening on port ${PORT}') console.log('Press Ctrl+C to quit.') }) 8. Concurrency You should decompose your app into independent processes based on process types such as background, web, and worker processes. This enables your app to scale up and down based on individual workload requirements. Most cloud-native apps let you scale on demand. You should design the app as multiple distributed processes that are able to independently execute blocks of work and scale out by adding more processes. The following sections describe some constructs to make it possible for apps to scale. Apps that are built with the principles of disposability and statelessness at their core are well positioned to gain from these constructs of horizontal scaling. Using App Engine You can host your apps on Google Cloud's managed infrastructure using App Engine. Instances are the computing units that App Engine uses to automatically scale your app. At any given time, your app can be running on one instance or on many instances, with requests being spread across all of them. The App Engine scheduler decides how to serve each new request. The scheduler might use an existing instance (either one that's idle or one that accepts concurrent requests), put the request in a pending request queue, or start a new instance for that request. The decision takes into account the number of available instances, how quickly your app has been serving requests (its latency), and how long it takes to start a new instance. If you use automatic scaling, you can create a balance between performance and cost by setting target CPU utilization, target throughput, and maximum concurrent requests. You can specify the type of scaling in the app.yaml file, which you upload for your service version. Based on this configuration input, the App Engine infrastructure uses dynamic or resident instances. For more information on scaling types, see the App Engine documentation. Using Compute Engine Alternatively, you can deploy and manage your apps on Compute Engine. In that case, you can scale your app to respond to variable loads using managed instance groups (MIG) based on CPU utilization, requests being handled, or other telemetry signals from your app. The following figure illustrates the key features that managed instance groups provide. Using managed instance groups lets your app scale to incoming demand and be highly available. This concept works inherently well for stateless apps such as web front-ends and for batch-based, high-performance workloads. Using Cloud Functions Cloud Functions are stateless, single-purpose functions that run on Google Cloud, where the underlying architecture on which they run is managed for you by Google. Cloud Functions respond to event triggers such as an upload into a Cloud Storage bucket or a Pub/Sub message. Each function invocation responds to a single event or request. Cloud Functions handles incoming requests by assigning them to instances of your function. When inbound request volume exceeds the number of existing instances, Cloud Functions might start new instances to handle requests. This automatic, fully managed scaling behavior allows Cloud Functions to handle many requests in parallel, each using a different instance of your function. Using GKE autoscaling There are some key Kubernetes constructs that apply to scaling processes: Horizontal Pod Autoscaling (HPA). Kubernetes can be configured to scale up or down the number of pods running in the cluster based on standard or custom metrics. This comes in handy when you need to respond to a variable load on your GKE cluster. The following sample HPA YAML file shows how to configure scaling for the deployment by setting up to 10 pods based on the average CPU utilization. apiVersion: autoscaling/v2beta2 kind: HorizontalPodAutoscaler metadata: name: my-sample-web-app-hpa namespace: dev spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: my-sample-web-app minReplicas: 1 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 60 Node autoscaling. In times of increased demand, you might need to scale your cluster to accommodate more pods. With GKE, you can declaratively configure your cluster to scale. With autoscaling enabled, GKE automatically scales nodes when additional pods need to be scheduled and when existing nodes are unable to accommodate them. GKE also scales down nodes when the load on the cluster decreases, according to the thresholds you've configured. Jobs. GKE supports Kubernetes jobs. A job can be broadly defined as a task that needs one or more pods to run in order to execute the task. The job might run one time or on a schedule. The pods in which the job runs are disposed of when the job completes. The YAML file that configures the job specifies details on error handling, parallelism, how restarts are handled, and so on. 9. Disposability For apps that run on cloud infrastructure, you should treat them and the underlying infrastructure as disposable resources. Your apps should be able to handle the temporary loss of underlying infrastructure and should be able to gracefully shut down and restart. Key tenets to consider include the following: - Decouple functionality such as state management and storage of transactional data using backing services. For more information, see Backing services earlier in this document. - Manage environment variables outside of the app so that they can be used at runtime. - Make sure that the startup time is minimal. This means that you must decide how much layering to build into images when you use virtual machines, such as public versus custom images. This decision is specific to each app and should be based on the tasks that startup scripts perform. For example, if you're downloading several packages or binaries and initializing them during startup, a sizeable portion of your start-up time will be dedicated to completing these tasks. - Use native features of Google Cloud to perform infrastructure tasks. For example, you can use rolling updates in GKE and manage your security keys using Cloud Key Management Service (Cloud KMS). Use the SIGTERM signal (when it's available) to initiate a clean shutdown. For example, when App Engine Flex shuts down an instance, it normally sends a STOP (SIGTERM) signal to the app container. Your app can use this signal to perform any clean-up actions before the container shuts down. (Your app does not need to respond to the SIGTERM event.) Under normal conditions, the system waits up to 30 seconds for the app to stop and then sends a KILL (SIGKILL) signal. The following snippet in an App Engine app shows you how you can intercept the SIGTERM signal to close open database connections. const express = require('express') const dbConnection = require('./db') // Other business logic related code app.listen(PORT, () => { console.log('App listening on port ${PORT}') console.log('Press Ctrl+C to quit.') }) process.on('SIGTERM', () => { console.log('App Shutting down') dbConnection.close() // Other closing of database connection }) 10. Environment parity Enterprise apps move across different environments during their development lifecycle. Typically, these environments are development, testing and staging, and production. It's a good practice to keep these environments as similar as possible. Environment parity is a feature that most developers consider a given. Nonetheless, as enterprises grow and their IT ecosystems evolve, environment parity becomes more difficult to maintain. Maintaining environment parity has become easier in the last few years because developers have embraced source control, configuration management, and templated configuration files. This makes it easier to deploy an app to multiple environments consistently. As an example, using Docker and Docker Compose, you can ensure that the app stack retains its shape and instrumentation across environments. The following table lists Google Cloud services and tools that you can use when you design apps to run on Google Cloud. These components serve different purposes and collectively help you build workflows that make your environments more consistent. 11. Logs Logs provide you with awareness of the health of your apps. It's important to decouple the collection, processing, and analysis of logs from the core logic of your apps. Decoupling logging is particularly useful when your apps require dynamic scaling and are running on public clouds, because it eliminates the overhead of managing the storage location for logs and the aggregation from distributed (and often ephemeral) VMs. Google Cloud offers a suite of tools that help with the collection, processing, and structured analysis of logs. It's a good practice to install the Cloud Logging Agent in your Compute Engine VMs. (The agent is preinstalled in App Engine and GKE VM images by default.) The agent monitors a preconfigured set of logging locations. The logs generated by your apps running in the VM are collected and streamed to Cloud Logging. When logging is enabled for a GKE cluster, a logging agent is deployed on every node that's part of the cluster. The agent collects logs, enriches the logs with relevant metadata, and persists them in a data store. These logs are available for review using Cloud Logging. If you need more control over what's logged, you can use Fluentd daemonsets. For more information, see Customizing Logging logs for Google Kubernetes Engine with Fluentd. 12. Admin processes Administrative processes usually consist of one-off tasks or timed, repeatable tasks such as generating reports, executing batch scripts, starting database backups, and migrating schemas. The admin processes factor in the twelve-factor manifesto was written with one-off tasks in mind. For cloud-native apps, this factor becomes more relevant when you're creating repeatable tasks, and the guidance in this section is oriented towards tasks like those. Timed triggers are often built as cron jobs and handled inherently by the apps themselves. This model works, but it introduces logic that's tightly coupled to the app and that requires maintenance and coordination, especially if your apps are distributed across time zones. Therefore, when you design for admin processes, you should decouple the management of these tasks from the app itself. Depending on the tools and infrastructure that your app runs on, use the following suggestions: - For running apps on GKE, start separate containers for admin tasks. You can take advantage of CronJobs in GKE. CronJobs run in ephemeral containers and let you control the timing, execution frequency, and retries if jobs fail or if they take too long to complete. - For hosting apps on App Engine or Compute Engine, you can externalize the triggering mechanism and create an endpoint for the trigger to invoke. This approach helps define a boundary around what the apps are responsible for, in contrast to the single-purpose focus of the endpoint. Cloud Tasks is a fully managed, asynchronous task execution service that you can use to implement this pattern with App Engine. You can also use Cloud Scheduler, an enterprise-grade, fully managed scheduler on Google Cloud, to trigger timed operations. Going beyond the twelve factors The twelve factors described in this document offer guidance for how you should approach building cloud-native apps. These apps are the foundational building blocks of an enterprise. A typical enterprise has many apps like these, often developed by several teams collaboratively to deliver business capability. It's important to establish some additional principles during the app development lifecycle, and not as an afterthought, to address how apps communicate with each other, and how they are secured and access controlled. The following sections outline some of these additional considerations that you should make during app design and development. Think API-first Apps communicate using APIs. When you're building apps, think about how the app will be consumed by your app's ecosystem, and start by designing an API strategy. A good API design makes the API easy to consume by app developers and external stakeholders. It's a good practice to start by documenting the API using the OpenAPI specification before you implement any code. APIs abstract the underlying app functionality. A well-designed API endpoint should isolate and decouple the consuming applications from the app infrastructure that provides the service. This decoupling gives you the ability to change the underlying service and its infrastructure independently, without impacting the app's consumers. It's important to catalog, document, and publish the APIs that you develop so that the consumers of the APIs are able to discover and use the APIs. Ideally, you want the API consumers to serve themselves. You can accomplish this by setting up a developer portal. A developer portal serves as an entry point for all API consumers— internal for the enterprise, or external for consumers such as developers from your partner ecosystem. Apigee, Google's API management product suite, helps you manage the entire lifecycle of your APIs from design, to build, to publish. Security The realm of security is wide, and includes operating systems, networks and firewalls, data and database security, app security, and identity and access management. It's of paramount importance to address all the dimensions of security in an enterprise's ecosystem. From an app's point of view, APIs provide access to the apps in your enterprise ecosystem. You should therefore ensure that these building blocks address security considerations during the app design and build process. Considerations for helping to protect access to your app include the following: - Transport Layer Security (TLS). Use TLS to help protect data in transit. You might want to use mutual TLS for your business apps; this is made easier if you use service meshes like Istio on Google Kubernetes Engine. It's also common for some use cases to create allow lists and deny lists based on IP addresses as an additional layer of security. Transport security also involves protecting your services against DDoS and bot attacks. - App and end-user security. Transport security helps provide security for data in transit and establishes trust. But it's a best practice to add app-level security to control access to your app based on who the consumer of the app is. The consumers can be other apps, employees, partners, or your enterprise's end customers. You can enforce security using API keys (for consuming apps), certification-based authentication and authorization, JSON Web Tokens (JWTs) exchange, or Security Assertion Markup Language (SAML). The security landscape constantly evolves within an enterprise, making it harder for you to code security constructs in your apps. API management products like Apigee help secure APIs at all the layers mentioned in this section. What's next - Review the microservices demo app that employs twelve-factor app principles and is built using Google Cloud products and services. - Review the Google Cloud product suite for logging and monitoring; see the Logging documentation. - Try out other Google Cloud features for yourself. Have a look at our tutorials.
https://cloud.google.com/architecture/twelve-factor-app-development-on-gcp?hl=it
CC-MAIN-2021-21
refinedweb
4,219
53.71
import "go.chromium.org/luci/common/sync/dispatcher/buffer". batch.go buffer.go full_behavior.go heap.go moving_average.go options.go var Defaults = Options{ MaxLeases: 4, BatchSize: 20, BatchDuration:. type Batch struct { // Data is the individual work items pushed into the Buffer. Data []interface{} // (e.g. extending Data doesn't do anything). type BlockNewItems struct { // The maximum number of items that this Buffer is allowed to house (including // both leased and unleased items). // // Default: max(1000, BatchSize) // Required: Must be >= BatchSize MaxItems int } BlockNewItems prevents the Buffer from accepting any new items as long as it it has MaxItems worth of items. This will never drop batches, but will block inserts. func (b *BlockNewItems) Check(opts Options) (err error) Check implements FullBehavior.Check. func (b *BlockNewItems) ComputeState(stats Stats) (okToInsert, dropBatch bool) ComputeState implements FullBehavior.ComputeState. Buffer batches individual data items into Batch objects. All access to the Buffer (as well as invoking ACK/NACK on LeasedBatches) must be synchronized because Buffer is not goroutine-safe. NewBuffer returns a new Buffer configured with the given Options. If there's an issue with the provided Options, this returns an error.. AddNoBlock adds the item to the Buffer. Possibly drops a batch according to FullBehavior. If FullBehavior.ComputeState returns okToInsert=false, AddNoBlock panics. CanAddItem returns true iff the Buffer will accept an item from AddNoBlock without panicing. Flush causes any buffered-but-not-batched data to be immediately cut into a Batch. No-op if there's no such data.. NextSendTime returns the send time for the next-most-available-to-send Batch, or a Zero time.Time if no batches are available to send. NOTE: Because LeaseOne enforces MaxLeases, this time may not guarantee an available lease. Stats returns information about the Buffer's state.Size * MaxLeases) // // Default: max(1000, BatchSize) // Required: Must be >= BatchSize MaxLiveItems int } DropOldestBatch will drop buffered data whenever the number of unleased items plus leased items would grow beyond MaxLiveItems. This will never block inserts, but will drop batches. func (d *DropOldestBatch) Check(opts Options) (err error) Check implements FullBehavior.Check. func (d *DropOldestBatch) ComputeState(stats Stats) (okToInsert, dropBatch bool) ComputeState implements FullBehavior.ComputeState. type FullBehavior interface { // ComputeState evaluates the state of the Buffer (via Stats) and returns: // // * okToInsert - User can add item without blocking. // * dropBatch - Buffer needs to drop the oldest batch if the user does // insert data. ComputeState(Stats) (okToInsert, dropBatch bool) // Check inspects Options to see if it's compatible with this FullBehavior // implementation. // // Called exactly once during Buffer creation. Check(Options) error } FullBehavior allows you to customize the Buffer's behavior when it gets too full. Generally you'll pick one of DropOldestBatch or BlockNewItems. InfiniteGrowth will not drop data or block new items. It just grows until your computer runs out of memory. This will never block inserts, and will not drop batches. func (i InfiniteGrowth) Check(opts Options) (err error) Check implements FullBehavior.Check. func (i InfiniteGrowth) ComputeState(stats Stats) (okToInsert, dropBatch bool) ComputeState implements FullBehavior.ComputeState. based on BatchDuration), or > 0 BatchSize int // [OPTIONAL] The maximum amount of time to wait before queuing a Batch for // transmission. Note that batches are only cut by time when a worker is ready // to process them (i.e. LeaseOne is invoked). // // Requirement: Must be > 0 BatchDurationItemCount int // LeasedItemCount is the total number of items (i.e. objects passed to // AddNoBlock) which are currently owned by the Buffer and are in active // leases. LeasedItemCount int // DroppedLeasedItemCount is the total number of items (i.e. objects passed to // AddNoBlock) which were part of leases, but where those leases have been // dropped (due to FullBehavior policy). DroppedLeasedItemCount int } Stats is a block of information about the Buffer's present state. Empty returns true iff the Buffer is totally empty (has zero user-provided items). Total returns the total number of items currently referenced by the Buffer. Package buffer imports 7 packages (graph) and is imported by 5 packages. Updated 2019-12-05. Refresh now. Tools for package owners.
https://godoc.org/go.chromium.org/luci/common/sync/dispatcher/buffer
CC-MAIN-2019-51
refinedweb
663
50.73
12.6: Pointer Arithmetic - Page ID - 29109.) // C++ program to illustrate Pointer Arithmetic in C++ #include <bits/stdc++.h> using namespace std; int main() { //Declare an integer array int intArr[3] = {10, 100, 200}; //declare an integer pointer variable int *arrPtr; //Assign the address of intArr[0] to arrPtr arrPtr = intArr; for (int count = 0; count < 3; count++) { cout << "Value at arrPtr = " << arrPtr << "\n"; cout << "Value at *arrPtr = " << *arrPtr << "\n"; // Increment pointer ptr by 1 arrPtr++; } return 0; } (Note: Pointer arithmetic is meaningless unless performed on an array.) In the code above we increment the pointer by 1. Look at the output of the addresses below - each address is 4 greater than the previous address!! How is that, we only added one, using the ++ operator, to the pointer variable? Output: Value at arrPtr = 0x7fff9a9e7920 Value at *arrPtr = 10 Value at arrPtr = 0x7fff9a9e7924 Value at *arrPtr = 100 Value at arrPtr = 0x7fff9a9e7928 Value at *arrPtr = 200 C++ knows that the variable - both the array and the pointer - are an integer type, so adding one to that address means we move forward the width of one integer, which is usually 4 bytes. The subscript - that value in the [ ] - says to go a certain number of bytes past that address. So, the first element [0], says to go 0 bytes beyond the address. When we use [1] - C++ says, "okay, this is an integer (in our example), so I will go 1 integer width past the address in intArr. An integer, on this system, is 4 bytes long, so intArr[1] look 4 bytes past the address stored in intArr. Advanced Pointer Notation Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } }; In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)-SA 4.0 "Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY-SA 4.0
https://eng.libretexts.org/Courses/Delta_College/C___Programming_I_(McClanahan)/12%3A_Pointers/12.06%3A_Pointer_Arithmetic
CC-MAIN-2021-17
refinedweb
331
57
Quasar Posted April 7, 2011 I guess it has to be common knowledge by now that the stock gothic2.wad file won't load in any BOOM-derived source port that uses the unmodified W_CoalesceMarkedResource algorithm. My question is why nobody's ever thought about addressing it during all this time. It appears to me that the cause of the issue is an unmatched FF_START demarcator which appears as the last lump in the wad. This rubs out any namespace that gets coalesced after it, leading to, in Eternity, the following error:WadDirectory::GetNumForName: S_START not found!I would suggest that the simplest fix is to ignore demarcator lumps that occur at the very end of a wad directory. EDIT: On closer examination I see it's missing its proper F(F)_START lump at the beginning of its flats entirely. What a mess >_> 0 Share this post Link to post
https://www.doomworld.com/forum/topic/54932-gothic-dm-2s-brokenness-in-boom-based-ports/
CC-MAIN-2019-43
refinedweb
152
61.87
Groovy scripts in your HCI integration flows have the combined class libraries of Groovy and Java available to them. Sometimes, though, you also need to access classes from external Java libraries. Luckily, you can do that. However, this useful feature is only mentioned in passing in the HCI Developer’s Guide, and particularly if you are new to Eclipse, it is not obvious how it works. In this blog I will walk you through the required steps. Before we get started, let me point out that adding external libraries is currently only possible in the Eclipse add-on. I expect the feature to be added to the Web UI sooner or later, though. Step 1: Create the src.main.resources.lib package The JAR files containing your external Java libraries must be imported into the src.main.resources.lib package of your integration project. Since this package is not created automatically in a new project, we need to add it manually. To do so, right-click your project, click New and choose Package. In the New Java Package window, enter src.main.resources.lib in the Name field and click Finish. A freshly created integration project with the package added looks like this: Step 2: Import your JAR file Having created the package, the next step is to import the JAR file containing the external Java library. Right-click the src.main.resources.lib package and choose Import… from the context menu. In the Import window, choose File System in the General category and click Next. Now click Browse and navigate to the directory containing your JAR file and click OK. From the list of files in the chosen directory, check the JAR file to be imported and click Finish: The library has now been imported into the proper package. If you need more than one library, you can go ahead and import multiple JAR files. One restriction to keep in mind: The Java Virtual Machine executing your Groovy code runs Java version 1.7, so for now you cannot use Java 1.8 libraries. As always with cloud software, this can and probably will change in the future. Step 3: Utilise the external classes in your code The classes of the external library are now available in your Groovy code. At this point, you would usually import them at the top of the script, and then reference them by class name in the code. And that is all there is to it 🙂 Bonus: How to determine the Java version How did I determine that HCI’s underlying JVM is version 1.7? The getProperty method of class java.lang.System lets you look at various system properties, including the Java version. At the time of writing, System.getProperty("java.version") returned 1.7.0_121. For a full list of supported properties, check out the method’s documentation. It seems strange that it is using java 1.7. Why not 1.8 so it matches the on prem version on PRO. Hi, I wonder how to upload these libraries so that these scripts can consume them during runtime. Deploying the artifact on tenant does not seems to be uploading these libraries. Thanks..! Hi Sayyad At the moment you need to do it in Eclipse. Some resource editing has been added to the Web UI just recently, however, and I’m sure uploading JAR files will be added as well. Regards, Morten Hey, Thanks for the reply. I did package and upload it via eclipse but somehow groovy scripts are unable to refer them. have raised ticket with SAP.
https://blogs.sap.com/2017/01/23/how-to-use-external-java-libraries-in-hci/
CC-MAIN-2018-17
refinedweb
598
66.23
Abstract: Classes loaded by different ClassLoaders are considered distinct, even when they have the exact same name and bytecode. Welcome to the 18th issue of The Java(tm) Specialists' Newsletter, now sent to 38 countries on all continents of our globe. Please remember to forward the newsletter to others who might be interested. javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge. This week I want to introduce the concepts of having Class objects in the VM with the exact same name, but being completely different. I had the opportunity to question Dr. Jung, who has been using this for a while now, and at long last, my small brain has made "click" and I understand (I think). In two weeks time, he is going to write the newsletter (he wrote the piece on dynamic proxies) and he will demonstrate how you can build up a sibling hierarchy of class loaders which you can use to automatically redeploy classes and find dependencies, etc. I didn't quite follow all of his explanations, so I'm looking forward to read what he has to say about this topic. In the meantime, to prepare us all, I've written a simple example to demonstrate how it works. In JDK 1.2, SUN added a new approach to class loading which allows you to identify classes not only by the class name, but also by the context in which it was loaded. We can set the ClassLoader for a Thread, which we can then use to load classes. By having a different classloader, you are effectively constructing a new instance of Class, which is then completely different from other instances of Class. This was, I think, also possible in JDK 1.1, but it is much easier to make an instance of a ClassLoader in JDK 1.2 as there is now a URLClassLoader which you can point to a directory where it will load the classes from. For example, say we have two directories, a1 and a2. In each of these directories we have a class A: //: a1/A.java public class A { public String toString() { return "This is the first class"; } } //: a2/A.java public class A { public String toString() { return "This is the second class"; } } As you will agree, the two classes are completely different. They can have different method definitions, data members or access control. The normal way of using these two classes is to choose at compile/run time which one you wish to use. For example, we may have a class NormalTest below: //: NormalTest.java public class NormalTest { public static void main(String[] args) { System.out.println(new A()); } } To compile this class, we have to specify the directory where A resides, either a1 or a2. Since the signature is the same, we can compile with one class and run with the other class if we want. javac -classpath .;a1 NormalTest.java java -classpath .;a2 NormalTest would result in "This is the second class" being displayed on the console. What happens if we want to have instances of both A classes in use at the same time? Normally we cannot do that, but if we use ClassLoaders we can. //: Loader.java import java.net.*; public class Loader { public static void main(String[] args) throws Exception { ClassLoader a1 = new URLClassLoader( new URL[] {new URL("file:a1/")}, null); ClassLoader a2 = new URLClassLoader( new URL[] {new URL("file:a2/")}, null); Class c1 = a1.loadClass("A"); Class c2 = a2.loadClass("A"); System.out.println("c1.toString(): " + c1); System.out.println("c2.toString(): " + c2); System.out.println("c1.equals(c2): " + c1.equals(c2)); System.out.println("c1.newInstance(): " + c1.newInstance()); System.out.println("c2.newInstance(): " + c2.newInstance()); } } The two classes, both called "A", are loaded with different ClassLoader objects, and are thus, as far as the VM is concerned, different classes altogether. We can print the names of the classes, compare the two classes (even though their names are the same, the classes are not equal, you should therefore never compare just the class names if you want to compare classes, rather use the Class.equals() method), and make instances of them by calling the newInstance() method. The output if we run Loader is: c1.toString(): class A c2.toString(): class A c1.equals(c2): false c1.newInstance(): This is the first class c2.newInstance(): This is the second class We can also let these two "A" classes have a common superclass. For example, say we have a superclass called Parent.java located in the root directory: //: Parent.java public class Parent { public String toString() { return "Thanks for caring... but what do you want??? "; } } And our A.java classes are now written as: //: a1/A.java public class A extends Parent { public String toString() { return super.toString() + "This is the first class"; } } //: a2/A.java public class A extends Parent { public String toString() { return super.toString() + "This is the second class"; } } We then need to have a common parent ClassLoader which we use to load the Parent.class file. We have to specify the location to start looking for Parent.class, and the locations are searched in a hierarchical fasion. Note that the compile-time Parent class is loaded with a different ClassLoader to the one loaded with the URLClassLoader called "parent" so they refer to a different class altogether, which means we cannot type-cast an instance of "A" to a Parent. Also, if we load the class "Parent" without using the classloader, we will see that it is not equal to the superclass of "c1". //: Loader.java import java.net.*; public class Loader { public static void main(String[] args) throws Exception { ClassLoader parent = new URLClassLoader( new URL[] {new URL("file:./")}, null); ClassLoader a1 = new URLClassLoader( new URL[] {new URL("file:a1/")}, parent); ClassLoader a2 = new URLClassLoader( new URL[] {new URL("file:a2/")}, parent); Class c1 = a1.loadClass("A"); Class c2 = a2.loadClass("A"); System.out.println(c1.newInstance()); System.out.println(c2.newInstance()); System.out.println( c1.getSuperclass().equals(c2.getSuperclass())); System.out.println( Class.forName("Parent").equals(c1.getSuperclass())); try { Parent p = (Parent)c1.newInstance(); } catch(ClassCastException ex) { ex.printStackTrace(); } System.out.println("We expected to get ClassCastException"); } } Thanks for caring... but what do you want??? This is the first class Thanks for caring... but what do you want??? This is the second class true false java.lang.ClassCastException: A at Loader.main(Loader.java:18) We expected to get ClassCastException Note that the super classes of both "A" classes are equal. Where is this all this useful? It is very useful when you have an application server into which you want to deploy business objects written by different people. It is entirely feasible that you have two developers with different versions of classes deploying their applications onto the same server. You don't necessarily want to start a new VM for each deployment, and so with ClassLoaders it is possible to have lots of classes with the same name running in the same memory space but not conflicting with one another. They would also share the common JDK classes with one another, so we would not have to have a java.util.ArrayList class loaded for each of the ClassLoaders. Until next week, and please remember to forward this newsletter in its entirety to as many Java users as you know who would be...
https://www.javaspecialists.eu/archive/Issue018.html
CC-MAIN-2020-05
refinedweb
1,237
57.16
BN: 978-1-25-964387-3 MHID: 1-25-964387-5 The material in this eBook also appears in the print version of this title: ISBN: 978-1- 25-964386-6, MHID: 1-25-964386. Oracle is a registered trademark. Contents at a Glance PART I Introduction to Oracle VM 1 Introduction to Virtualization and Cloud Computing 2 What Is Oracle VM? 3 Oracle VM Architecture 4 Oracle VM Lifecycle Management 5 Planning and Sizing the Enterprise VM Server Farm 6 What’s New in OVM 3.x 7 Disaster Recovery Planning 8 Overview of Oracle Enterprise Manager Cloud Control PART II Installing and Configuring Oracle VM 9 Installing the Oracle VM Server 10 Oracle VM Concepts 11 Installing and Configuring the Oracle VM CLI 12 Configuring the Oracle VM Server Network 13 Configuring the VM Server Storage PART III Managing Oracle VM 14 Swimming in Server Pools 15 Configuring Guest Resources PART IV Installing and Configuring the VM Guest Additions 17 Oracle VM Templates 18 Creating Virtual Machines Using Templates 19 Creating Virtual Machines Manually 20 Managing the VM Environment and Virtual Machines 21 Physical-to-Virtual Migration and Virtual-to-Virtual Migration 22 Virtualization Summary and Best Practices PART V Installing and Configuring Enterprise Manager Cloud Control for IaaS 23 Basic Cloud Control Installation 24 Using Cloud Control 25 Configuring Advanced Cloud Control and User Self-Provisioning PART VI Disaster Recovery, Maintenance, and Troubleshooting 26 Oracle VM Disaster Recovery and Oracle Site Guard 27 Oracle VM Maintenance 28 Oracle VM Troubleshooting Index Contents Acknowledgments Introduction PART I Introduction to Oracle VM 3 Oracle VM Architecture Oracle VM Architecture Servers and Server Pools Oracle VM Manager Xen Architecture Dom0 DomU DomU-to-Dom0 Interaction Networking Hardware Virtual Machine (HVM) vs. Paravirtualized Virtual Machine (PVM) Xen Hypervisor or Virtual Machine Monitor (VMM) Features of Oracle VM Hardware Support for Oracle VM Summary Suspending Cloning, Creating from a Template, and Migrating State Management and Transitions Stopped Running Suspended Summary Summary PART II Installing and Configuring Oracle VM 10 Oracle VM Concepts Hardware and Software Prerequisites for VM Manager Hardware Requirements for the Oracle VM Manager Software Requirements for the Oracle VM Manager Modifying the Firewall Manually (If Necessary) Installing VM Manager Installing and Configuring the OS for the Oracle VM Manager PART III Managing Oracle VM PART IV Installing and Configuring the VM Guest Additions 17 Oracle VM Templates Oracle VM Guest Additions Creating Templates Manually Summary PART V Installing and Configuring Enterprise Manager Cloud Control for IaaS PART VI 27 Oracle VM Maintenance Creating a Repository YUM Repository Server Prerequisites ULN Registration Channel Subscription YUM Server Configuration Patching an Oracle VM Server Configuring Server Update Groups in Oracle VM Manager Updating the Oracle VM Servers Summary 28 Oracle VM Troubleshooting Oracle VM Server Directories and Log Files Command-Line Tools/Networking Multipathing NFS Oracle VM Manager Index Acknowledgments Webook would like to thank Greg King and Simon Hayler for their hard work editing this from a technical perspective. They not only did a great job editing but also offered suggestions along the way. Technical editors can either make or break a book. Greg and Simon put a lot of effort into making this book what it is. Thanks also to Claire Yee, Wendy Rinaldi, and all the staff at Oracle Press/McGraw- Hill Professional for their hard work and professionalism. This publishing company is excellent to work with. —The authors I’d like to thank my wife, Erin, and my son, Ethan, for putting up with all the time I spent working on this book. I’d also like to thank some of the people who have encouraged and supported me professionally over the years: Paul Seifert, Kimberly Borden, Eddie Soles, and all the Oracle Linux and Oracle VM product managers I have had the pleasure of working with, including Honglin Su, John Priest, and Simon Coter. —Erik I would like to thank my parents for inspiring me to be the best that I can be. I’d also like to thank all of the people at Oracle Press who have helped make this book great. —Ed I would like to say thanks for the educational guidance I received from Norman Dria and Lyn Paladino as well as for the never-ending support from my wife of 30 years, Deanna. —Nic Introduction n the last decade, we have seen virtualization evolve from the standard way of doing I business in the data center to a new model called the cloud, where resources are dynamically allocated and managed by the developers, users, and application managers. Cloud technology has changed how data centers are built and managed, as users can now directly provision not only virtual machines but entire applications via a few mouse clicks. The basis of this in an Oracle technology stack is Oracle VM, which is based on the Xen hypervisor. Oracle VM was introduced at the Oracle OpenWorld conference in 2007, and after Oracle purchased Sun Microsystems in 2010, Oracle VM was rebranded as Oracle VM Server for x86, and the Sun Solaris virtualization technologies were renamed Oracle VM Server for SPARC. The latest version of Oracle VM integrates with Oracle Enterprise Manager to provide full technology stack integration. A cloud architecture provides several benefits over the traditional hardware system. Most of the benefits are economic, in that server consolidation, performance improvements, and speed of provisioning all provide value. Here are some of the main reasons companies choose virtualization: This book covers not only the advantages of using virtualization, but also how to install, configure, size, and administer a private cloud virtualized environment using Oracle VM. PART I Introduction to Oracle VM Technet24.ir|||||||||||||||||||||||||||||||||||||||| Technet24.ir|||||||||||||||||||||||||||||||||||||||| CHAPTER 1 Introduction to Virtualization and Cloud Computing loud computing is the term used to describe services provided to your application C either from within your environment or outside of your environment. Anything from storage services to onsite and offsite services is included in cloud computing. The original use of the term referred to providing computer services within a corporation or outside of a corporation in order to deliver additional resources. This in turn started out as virtual computing, or virtualization. Virtualization became the technology that allowed providers to create resources that could then be offered to internal or external clients, including guest systems. This idea expanded and became the basis for cloud computing. In most cases, virtualization is still the key component of cloud computing, but other services such as cloud backup, applications and other technologies as a service have been included in cloud computing. However, virtualization is still the main component of cloud computing. Virtualization has changed the way we look at computing. Instead of using many different computer systems for different tasks, with virtualization we can use a single system to host many applications. Not only has virtualization increased in popularity, but it has also influenced new hardware CPU innovation, including Intel VT-x and AMD-V technologies. Since its introduction, virtualization has become a core technology in every data center. Oracle VM, as one of the virtualization platforms, is based on stable and proven technology. This chapter provides an overview of virtualization technologies, including the various types of virtualization and their typical uses. The reasons why companies choose to use virtualization and how they use it are also discussed. Subsequent chapters discuss the mechanics of installing, configuring, and managing Oracle VM 3.x. What Is Virtualization? Virtualization is the abstraction of computer hardware resources. This definition is very general; however, the broad range of virtualization products, both hardware and software, makes a more specific definition difficult. Virtualization can consist of storage, CPU resources, or a combination of resources. Virtualization can also include virtual tape devices used for backup and recovery. For the sake of this book, virtualization is primarily focused on virtual computer systems (specifically Oracle VM). There are hardware products that allow for virtualization, software products that create virtual systems, and hardware options that assist with software virtualization. All of these products and options perform essentially the same function: they separate the operating system and applications from the underlying hardware. A number of different types of system virtualization are available, including the Technet24.ir|||||||||||||||||||||||||||||||||||||||| following: Hardware virtualization Full software virtualization Paravirtualization Hardware-assisted software virtualization Component or resource virtualization, including storage and backup virtualization As this book progresses, you will learn about these types of virtualization and their attributes. You will also obtain the information you need to decide which type of virtualization to use. Although virtualization allows you to abstract resources away from the hardware layer, there are some limitations. With today’s commercially available technology, virtualization—or at least the most popular types of virtualization—allows you to abstract only like architectures. For example, if you use software virtualization that runs on x86 or x86_64 architecture, you can run only virtual hosts with either an x86 or x86_64 operating system. In other words, you can’t virtualize a SPARC system on an x86 or x86_64 architecture. At this time, several major virtualization products are on the market: VMware was one of the first companies to offer a fully virtualized hardware platform environment, including a range of products with fully virtualized environments. VMware was founded in 1988 and was acquired by EMC in 2003. In addition to hardware virtualization, VMware also offers some paravirtualized drivers. Microsoft Hyper-V was released in 2008. Hyper-V provides both fully virtualized and guest-aware virtualization (if you are running a Windows guest). Hyper-V has been enhanced and now supports Linux as well as Windows clients. Xen Hypervisor is an open-source standard for virtualization and runs on multiple platforms. The first public release of Xen was in 2003, and the company was acquired by Citrix in 2007. Xen currently supports both hardware virtual machine (HVM) and paravirtualized machine (PVM). Xen does not offer any paravirtualized drivers. Oracle VM is a free, next-generation server virtualization and management solution from Oracle that makes enterprise applications easier to deploy, manage, and support. The Oracle VM hypervisor is an open-source Xen project with Oracle enhancements that make it easier, faster, and more efficient. In addition, Oracle VM is currently the only virtualization product supported for the Oracle Relational Database Management System (RDBMS) and other Oracle products. Oracle VM supports both HVM and PV and provides a set of paravirtualized drivers for both Windows and Linux paravirtualized hardware virtual machines (PVHVMs). Cloud computing Server consolidation Server provisioning Functional separation Performance improvement Backup/restore Hosting Training, testing, quality assurance, and practice Cloud Computing Cloud computing has become ubiquitous. Everywhere you look you find cloud computing services and products. Whether you are a cloud provider or a cloud consumer, it is everywhere. As mentioned before, the core of cloud computing is virtualization, and the core of Oracle cloud services is Oracle VM. Cloud computing consists of more than virtual machines; however, for the purpose of this book, virtualization is the primary focus. Cloud computing can also consist of application services, backup services, and other application services. In fact, pretty much every service provided can be called a cloud service, even human resources. Server Consolidation Server consolidation is probably the top reason for virtualizing your environment. To Technet24.ir|||||||||||||||||||||||||||||||||||||||| consolidate servers, you take multiple computer systems and collapse them into (or consolidate them into) one server. Server consolidation is often, though not necessarily, accomplished using virtualization. From an Oracle database perspective, you can consolidate servers in multiple ways. You can consolidate servers by taking databases from several servers and putting them on a single server, each with its own instance. You can take databases from several servers and put them on a single database server within the same Oracle instance, either with or without partitioning. Finally, you can consolidate multiple Oracle databases onto a single server by creating multiple individual virtual machines on a single server and then creating a single Oracle database instance on each virtual machine. Oracle VM is the only platform that allows the Oracle database to be licensed on a vCPU (virtual CPU or core) rather than on the physical cores in the underlying host system. This is true when using hard partitioning in Oracle VM or Trusted Partitions on the Oracle Private Cloud Appliance. load. This option’s downside is that the OS is duplicated, causing more overhead than with the first option. When consolidating an Oracle database, you’ll find both this option and the first option are often good choices. Server Provisioning One of the primary advantages of using virtual machines is the ability to provision servers quickly and efficiently. A virtual environment allows you to keep templates of various types of servers—such as application servers and database servers—and to deploy and put them into production easily in a matter of minutes or hours. The process of provisioning a server typically involves either copying a server or building a new server from a template. Once you have deployed this new server, you run scripts to rename it, change its IP address, and so on, getting it into production quickly. By pre-staging servers and templates, you can quickly, efficiently, and precisely deploy them. By using a pre-staged server, you also avoid mistakes, which makes the provisioning process faster and more exact. You can easily pick what type of server to deploy from your library of templates and pre-staged servers. The Oracle VM architecture allows you to deploy the new server into any system in the server farm that you desire, creating a high-performance, scalable server in a very short period of time. Functional Separation Various applications don’t work well together in an operating system. The reason is primarily due to resource contention in certain subsystems in the OS, such as the memory subsystem, the I/O subsystem, service ports, and the OS scheduler. Often, application servers do not scale (achieve higher performance) when additional resources such as CPUs or memory are added. In these cases, using several smaller servers (two CPUs, 2GB of RAM) is better than using a larger server with many CPUs and lots of RAM. This is especially true of Java, which doesn’t scale very well with large amounts of memory and multiple CPUs. Even when application servers don’t scale well with large numbers of CPUs and lots of RAM, you can still take advantage of the cost effectiveness of these systems by Technet24.ir|||||||||||||||||||||||||||||||||||||||| virtualizing them. Scaling problems typically occur in the application itself and in the OS scheduler, where the system simply can’t keep track of too many processes, or in Java. Java applications typically can’t take advantage of more than 2–3GB of RAM. By virtualizing, you can assign each system a reasonable amount of resources that the application can handle. Because the process tables and application queues exist in the virtual server and not on the host, the virtual environment will continue to scale. Fortunately, the Oracle database server scales very well with CPU and memory resources. In addition, you can use functional separation to split management responsibilities, provide additional security, and reduce contention. By virtualizing and splitting up applications by vendor or group, you can allocate a single application to a single server and still not waste hardware resources. Performance Improvement As mentioned in the previous section, application servers often perform better as several smaller servers rather than one large server. Therefore, virtualizing a large server into multiple smaller ones can often improve application server performance. By splitting up a large host system into multiple, smaller VMs, you can often achieve not only higher performance but also a greater level of scalability. In addition, the virtual environment provides a feature that you can’t find in physical servers: the ability to move the VM to another host. This gives you the flexibility and ability to alter the physical characteristics of the underlying host while the virtual machine is still up and running, giving you the benefits of live load balancing and performance improvements without interrupting service to the VM user. By moving VMs from one host to another while live, you use resources efficiently and you can reuse them when needed. If a host becomes too busy, you can add another to the server pool and move VMs to it as needed. Backup/Restore An often-overlooked feature of virtual machines is the ability to back them up quickly and efficiently because a virtual machine looks essentially like several large files to the host OS. Most performance problems that occur during backups are due to the number of small files in a system. When backing up a small file, the backup software takes more time opening and closing the file and finding all the parts of the file than it actually takes to read the contents and back them up. The amount of data backed up per second drops significantly for small files. When backing up an operating system, the backup software traverses the entire directory structure and opens, copies, and then closes each file. With large files, the software spends more time copying data. With small files, the software takes more time opening and closing files. Because each virtual disk is actually a large file in the OS, backups are very fast. Backups from the VM can be problematic while the VM is running because the state of the files is constantly in flux (a file might only be halfway written when the backup occurs). Memory may also be in flux. Considering that most systems use hard drive files for swap, the backup could become corrupted using this approach. Therefore, you must consider a backup of a virtual machine file to be a “crash consistent backup.” You should back up the virtual server image when the virtual OS is shut down. If you’re running backups from the VM itself in order to back up specific items or to back up the database directly using RMAN, then the advantages you achieve by backing up the entire VM image are not realized. For the same reasons that backing up the entire virtual disk is much faster than backing up each individual file within the virtual disk, restoring is similarly optimized. Restoring one large virtual disk file is much faster than restoring each file individually within the virtual machine. With newer versions of Oracle VM, creating a “hot standby” is now allowed. In fact, an entire standby VM farm can be created. This allows for live standby and quick recovery in the event of the loss of a data center or system. Hosting One of the most common uses of virtualized machines is for hosting environments. Both hosted environments and cloud computing use virtualized machines to provide on- demand computing to their clients. Depending on the underlying hardware, dozens of virtualized systems might be running on the same underlying host server(s). This model allows the hosting vendor to provide virtual systems to its clients using an on-demand model where virtual machines are automatically created as needed. In addition, the hosting vendor can easily size the system to the desired number of CPUs and RAM instantly. Many vendors now offer hosted solutions and cloud computing. Cloud computing defines a type of computer resource that is available over the Internet or internally and is made up of resources that you know little about. These resources, usually in the form of a Linux or Windows cloud computer, are available to be used anywhere, and are provided with a set number of CPUs and a set amount of memory and disk space. Typically the end user doesn’t really know anything about the underlying hardware or software, thus turning computer resources into commodities. NOTE Two types of cloud computing are available: private and public. Private clouds are hosted using internal networks. Cloud computing has become more popular in recent years as many customers have decided to abandon expensive data centers and instead acquire just the resources needed to run their business. Cloud computing is less expensive than traditional computer systems—up to a point. The higher-end cloud computers tend to be a little pricey. Training Training is by far one of the best uses of virtualization. Oracle employs a great deal of virtualization for training purposes. For example, you can reset the VMs for the next week’s training classes by simply removing and replacing them with new copies. You can preconfigure the correct software, class exercises, and configurations and then redeploy whenever necessary. Oracle has an entire library of training classes, including the following: Oracle 11g Oracle 10g Oracle RAC Oracle on Windows Oracle Application Server By storing several classes, you can easily repurpose your training facility to handle any class you need. Because many classroom environments are not CPU intensive, you can create several virtual machines on the same underlying host. Training systems are easy to set up as well as access. By using technology such as Virtual Network Computing (VNC), students can access the systems and run X- Windows programs such as the Oracle Universal Installer (OUI) and the Database Configuration Assistant (DBCA); we will cover VNC in more detail later in this book. You can also create a training system assigned to individual students so they can experience managing an entire OS environment. When the class is finished, or if a student causes irreversible problems with the system, you simply remove and re-create the virtual machine using a preconfigured image complete with a preinstalled operating system and applications. Testing Testing is an important part of every system. Unfortunately, many companies do not have the resources to purchase test systems, thus leading to severe problems and risk to the production environment. I have actually been called in on occasion to assist with recovering from problems that resulted from an upgrade or patch that wasn’t thoroughly tested on a nonproduction server before being put it into production. The reason for not having a test server is usually budgetary. With a virtual environment, you can put a test system into place efficiently and economically simply by making a copy of the original virtual machines. For example, your database administrators (DBAs) can test upgrades, patches, installations, new configurations, and even undertake performance testing without impacting a production business system by using copies of the original virtual machines. Without a proper test system, the DBA might miss some step or important detail of a patch or upgrade that he or she might not otherwise notice. By testing installations, configurations, and deployments, the DBA will be more comfortable with and better at doing these tasks. Test systems are one of the most important resources you can have. And once you’ve finished testing, with one click, you can move the test system into production. By using Oracle VM, you can create multiple test environments and also save these environments at various stages, so you can deploy the next step over and over again, thus testing exactly what you need to test. You can also preconfigure virtual machines with different versions of the OS and various configurations, including Real Application Clusters (RAC). QA Having a set of virtual machines for QA has many advantages. You can keep multiple versions of operating systems, databases, and applications, which allows you to test modifications multiple times using different variations with very little setup time in between attempts. You can also refresh and reset the QA system whenever a new code drop is released, which increases efficiency in redeploying systems for testing and validation. Practice Having a system to practice and test new things on is always a good idea. You can hone your skills and try new things such as backup methods, patching, and upgrades. Through practicing and testing, you improve your skills, leading to professional advancement and self-confidence. Depending on your situation, you might be able to take advantage of one or more of these virtualization types. In this section, we explore each virtualization type, along with its pros and cons. Each type has its own attributes that provide specific benefits. The type of virtualization you choose depends on your needs. Oracle VM supports hardware-assisted software virtualization, paravirtualization, and the hybrid hardware- assisted software virtualization with paravirtualized drivers. environment. The architecture is very flexible because you don’t need a special understanding of the OS or hardware. The OS hardware subsystem discovers the hardware in the normal fashion. It believes the hardware is really hardware. The hardware types and features that it discovers are usually fairly generic and might not be as “full featured” as actual hardware devices, though the system is functional. Another advantage of full software virtualization is that you don’t need to purchase any additional hardware. With hardware-assisted software virtualization, you need to purchase hardware that supports advanced VM technology. Although this technology is included in most systems available today, some older types of hardware do not have this capability. To use this older hardware as a virtual host, you must use either full software virtualization or paravirtualization. NOTE Only hardware-assisted software virtualization requires advanced VM features; full software virtualization does not. VMware ESX works on older hardware that does not have any special CPU features. This type of virtualization is also known as emulation. NOTE Hardware-assisted virtualization is really the long-term virtualization solution. Intel Intel supports virtualization via its VT-x technology. The Intel VT-x technology is now part of many Intel chipsets, including the Pentium, Xeon, and Core processors family. The VT-x extensions support an input/output memory management unit (IOMMU) that allows virtualized systems to access I/O devices directly. Ethernet and graphics devices can now have their DMA and interrupts directly mapped via the hardware. In the latest versions of the Intel VT technology, extended page tables have been added to allow direct translation from guest virtual addresses to physical addresses. AMD AMD supports virtualization via the AMD-V technology. AMD-V includes a rapid virtualization indexing technology to accelerate virtualization. This technology is designed to assist with the virtual-to-physical translation of pages in a virtualized environment. Because this operation is one of the most common, by optimizing this function, you can greatly enhance performance. AMD virtualization products are available on both the Opteron and Athlon processor families. NOTE The virtual machine that uses the hardware-assisted software virtualization model has become known as the hardware virtual machine, or HVM. This terminology will be used throughout the rest of the book and refers to the fully software-virtualized model with hardware assist. Paravirtualization With paravirtualization, the guest OS is aware of and interfaces with the underlying host OS. A paravirtualized kernel in the guest understands the underlying host technology and takes advantage of that fact. This not only helps in runtime but skips many steps in the boot process, resulting in amazingly fast booting. Because the host OS is not running all the device driver code, the number of resources needed for virtualization is greatly reduced. In addition, paravirtualized device drivers for the guest can also interface with the host system, thus reducing overhead. The idea behind paravirtualization is to reduce both the complexity and overhead involved in virtualization. By paravirtualizing both the host and guest operating systems, very expensive functions are offloaded from the guest to the host OS. The guest essentially makes special system calls that then allow these functions to run within the host OS. When using a system such as Oracle VM, the host operating system acts in much the same way as a guest operating system. The hardware device drivers interface with a layer known as the hypervisor. The hypervisor is also known as the virtual machine monitor (VMM). that fact. Since Oracle Enterprise Linux (OEL5), Oracle has provided the ability to create an HVM that uses a few specific paravirtualized device drivers for network and I/O. This hybrid virtualization technology provides the benefits of a paravirtualized virtual machine with the additional hardware accelerations available within the HVM. This technology is still new but might be the future of virtualization. This type of virtual machine is known as a paravirtualized hardware virtual machine, or PVHVM. This virtual machine type has the benefits of both the HVM system and the PV system. from the physical storage. Logical unit numbers (LUNs), or virtual disks, are made up of multiple disk drives, and multiple LUNs can span the same disks. Unfortunately, this means you might not know exactly where your storage is coming from and how many other systems are sharing the same drives with that storage, which can cause unpredictable performance. Because I/O performance is so important to the Oracle database, Oracle Automatic Storage Management (ASM) disks should be made up of LUNs with dedicated drives (that is, no other LUNs sharing the disk drives). In some virtualized storage environments, this is not possible, however. In fact, some storage systems automatically stripe all LUNs across all drives in the system. Depending on the I/O subsystem’s flexibility, different configuration options are available that might let you have more control over storage. In a theoretical environment, the abstraction of logical to physical shouldn’t matter. Unfortunately, in the real world, the speed of the disk drives is finite and therefore must be allocated properly. Backup Virtualization Many sources of cloud backup are available that allow systems to back up directly to storage and/or APIs available in the cloud. Oracle has recently introduced the ability to configure a cloud backup where the cloud backup devices are configured as a tape drive within the Oracle RMAN utility. This provides a valuable resource for backups to be made directly to the cloud. Miscellaneous Other forms of virtualization exist that haven’t been mentioned in this chapter. These virtualization methods typically involve expensive proprietary hardware. Because this book is focused on Oracle VM, which doesn’t use any proprietary hardware, those technologies have been excluded from this chapter. This book will, however, discuss technologies that are similar to and share some of the same ideas as Oracle VM (primarily, VMware ESX Server and Xen). As you will learn in the next chapter, Oracle VM has its roots in Xen technology. The Hypervisor The hypervisor is what makes virtualization possible. The hypervisor is the component that translates the virtual machines into the underlying hardware. There are two types of hypervisors: The type 1 hypervisor runs directly on the host hardware; the type 2 (or hosted) hypervisor runs in software. In addition, some proprietary hardware has a hypervisor built into it. The type of hypervisors we are concerned with, however, are the type 1 and type 2 hypervisors. Type 1 Hypervisor The type 1 (or embedded) hypervisor is a layer that runs directly on the host hardware, interfacing with the CPU, memory, and devices. Oracle VM and VMware ESX Server both use the type 1 hypervisor. The hypervisor treats the host OS in much the same way as a guest OS. The host OS is referred to as Domain 0 (or dom0), and guests are referred to as Domain U (or domU), as shown in Figure 1-1. Here, you can see that all virtual machines must go through the hypervisor to get to the hardware. The dom0 domain is a virtual system just like the domU virtual machines (but it has more capabilities, as discussed later). Currently, the type 1 hypervisor is considered the most efficient and is the most recommended hypervisor. NOTE Even though Oracle VM and VMware both use a type 1 hypervisor, these hypervisors are significantly different. VMware handles device drivers directly in the hypervisor; Xen handles them in dom0 or a driver domain. The dom0 domain does not differ much from the other domains in the virtual environment, except that you access it differently and it is always enabled by default. In addition, dom0 has unlimited rights to hardware, whereas domU only has access through a layer of indirection and only to what the hypervisor grants it. Because the type 1 hypervisor is essentially part of the OS, it must be installed on the hardware itself and support the devices installed on the system. Type 2 Hypervisor The type 2 (or hosted) hypervisor runs as a program and is used for software virtualization. Because the type 2 hypervisor runs as a program, it has neither the same priority as the type 1 hypervisor nor the ability to access the hardware directly. Its main advantage is that you can install it on a variety of host systems without modification. The type 2 hypervisor works with both full software virtualization and hardware- assisted software virtualization. VMware Server is an example of a type 2 hypervisor. Oracle also has another x86 virtualization product called Oracle VM VirtualBox. It is a type 2 hypervisor-based product and is very popular for testing. I know many people who run VirtualBox on their PCs in order to quickly and efficiently spin up a Linux virtual machine. Benefits of Paravirtualization The primary benefit of paravirtualization is performance. Because the guest OS understands that it is actually running in a VM environment, it can bypass some software interpretations of hardware calls and go directly to the underlying host or hypervisor. Both the guest and host must be running the VM kernel so they understand and can communicate with the underlying hypervisor. Drawbacks of Paravirtualization The main drawback of paravirtualization is the restriction on the supported OS. Because the host and guest must both be running a VM kernel, at this time, paravirtual drivers support only Linux, Solaris x86, and Windows. Another drawback of paravirtualization is the lack of hardware support. Currently, paravirtualization does not take advantage of the new VM hooks that hardware vendors are adding to their CPU chips. In the future, this is likely to change. When paravirtualization is accelerated with hardware, performance will increase dramatically. Because the VM kernel must be used, converting a VMware or other image to Oracle VM is difficult. This shortcoming can be resolved, however, but you will find it is a little more difficult than converting a VMware image to a hardware-assisted software virtualization environment. If you are running a Linux guest, paravirtualization is the recommended method of virtualization because of its performance benefits. Upcoming chapters provide information on creating both hardware-assisted software virtualization and paravirtualization guests. Summary This chapter has introduced you to the various types of virtualization. The information provided is intended to be fairly generic because specifics of Oracle VM are provided throughout the book. Both software and paravirtualization were described, as well as the benefits and drawbacks of both technologies. Because hardware support for virtualization is changing so rapidly, some of the information in this chapter may be obsolete by the time you read this book; however, the general principals and methods will remain the same. This chapter compared hardware-assisted software virtualization and paravirtualization. This comparison is based on the technology as it exists today. Soon hardware extensions for virtualization will improve as well as hardware support for paravirtualization. Virtualization is now at the forefront of CPU technology and is leading the new technological revolution. Technet24.ir|||||||||||||||||||||||||||||||||||||||| CHAPTER 2 What Is Oracle VM? Technet24.ir|||||||||||||||||||||||||||||||||||||||| virtualization product that was introduced in 2008. This product appears to be targeted primarily to the Microsoft Windows environment. Another player in the virtualization market is KVM (Kernel Virtual Machine). The built-in virtualization for Linux has moved from Xen to KVM. Although Oracle maintains open-source compatibility with KVM, they have decided to stick with Xen as the basis of Oracle VM rather than moving to KVM. For the time being, Oracle is continuing to use Xen as its preferred virtualization technology. One additional player in the virtualization market is Citrix. Citrix had purchased XenSource, but isn’t pushing it as a dominant virtualization platform, as Citrix tends to focus more on the desktop replacement rather than the virtualization environment. Citrix continues to be a major player in the desktop virtualization market but does not participate in server virtualization. In addition to the major commercial virtualization products, other virtualization products have been created specifically for cloud providers such as the Amazon AWS (Amazon WorkSpaces), which is developed and maintained by Amazon. Other commercial vendors have done the same. Oracle Cloud services are run on Oracle VM or a slightly modified version of Oracle VM. These companies do not represent the entirety of the virtualization market and virtualization products, but they do represent Oracle VM’s main competition. The focus of this book is Oracle VM; although many other virtualization products are available, including hardware virtualization products, they will not be covered here. Virtualization technology is not new to Oracle. Oracle VM is based on the Xen Hypervisor, which is a proven and stable technology. To understand the history of Oracle VM, you must first look at the history of the Xen Hypervisor. History of Xen The Xen virtualization product began around the same time as VMware. It was created at the University of Cambridge Computer Laboratory, and its first version was released in 2003. The leader of the project then went on to found XenSource. Unlike both VMware and Hyper-V, Xen is maintained by the open-source community under the GNU General Public License. In 2007, XenSource was acquired by Citrix Systems. Whereas VMware and Hyper-V only support the x86 architecture, Xen supports x86, x86_64, Itanium, and PowerPC architectures. As mentioned in Chapter 1, the Xen architecture is based on a hypervisor. This hypervisor originally allowed only Linux, NetBSD, and Solaris operating systems to operate in a paravirtualized environment. However, since the introduction of Xen 3.0 and hardware virtualization support in hardware, unmodified OSs can now operate in Xen. Oracle VM 3.4 is based on the Xen 4.4 kernel. In order to fully appreciate where the Xen 4.4 kernel is, let’s look at a brief history of the Xen Hypervisor. The following is a Let’s look at a few of the major releases in more detail. Because Xen is the basis for Oracle VM, understanding where it is coming from and how the various releases have evolved is important. Xen 1.x Xen 1.0 was the first release of the Xen product and included all of the basic pieces needed to support virtualization. Xen 1.0 supported only the Linux operating system, but at the time of its release, the Xen development team was already working to enable Microsoft Windows to run in a virtual environment. The original release of Xen was based on paravirtualization, where the guest operating system is modified so that it’s aware it is actually running in a virtualized environment. This awareness improved performance but did not allow the full range of OSs to run unmodified in a virtualized environment. Xen 1.0 reached its goal of allowing any application that ran on the guest Xen 2.x The Xen 2.0 release again targeted the x86 market and included a number of substantial new features. The most impressive of these new features gave users the ability to perform a “live migration” of a virtual guest from one host to another with no interruption in service. This feature is known as vMotion in VMware and is one of the truly outstanding features of virtualization. Using this feature, users could adjust and manage the load on the underlying hosts without interrupting service to the guest OS. In addition, XenSource improved the manner in which virtual I/O devices were used and configured, especially in the area of networking. Xen 3.x Even though Xen 2.0 and, in some respects, 1.0 had significant features, it wasn’t until Xen 3.0 that Xen was truly ready for the enterprise. The features enabled in this version made Xen viable as an alternative to physical servers and increased its popularity. These features have created the explosion in the virtualization market. In the past few years, the popularity and variety of virtualization have grown tremendously. In this section, we cover the history of Xen 3.x in more detail. Xen 3.0 Xen 3.0 included many features that were required for enterprise computing, including the following: 32P support Xen 3.0 added support for up to 32-way SMP guest operating systems. This support was important for larger applications such as databases. 64-bit Xen 3.0 provided 64-bit support for the x86_64 platform, including Intel and AMD processors. PAE Xen 3.0 added support for the Intel Physical Addressing Extensions (PAE) to support 32-bit servers with more than 4GB physical memory. Although this was not as efficient as 64-bit support, it was better than nothing. Fully virtualized When using Intel VT-x (or AMD’s AMD-V), Xen 3.0 made it possible to run unmodified guest operating systems as hardware virtual machines (HVMs). This feature is sometimes known as hardware-assisted virtualization. It allowed for OSs such as Microsoft Windows and earlier releases of Linux and UNIX to run as unmodified guests. Miscellaneous enhancements Xen 3.0 added other enhancements, including Without 64-bit support, many people found it difficult to migrate their applications to a virtualized environment. This is probably the most significant improvement in the Xen 3.x family. Xen 3.1 The Xen 3.1 release, although not as significant as the 3.0 release, added many valuable new features: XenAPI support Xen 3.1 added support for XenAPI 1.0. This API uses XML configuration files for virtual machines as well as VM lifecycle management operations. Save/restore/migrate Xen 3.1 added the preliminary save/restore/migrate support for HVMs. Dynamic memory Xen 3.1 introduced dynamic memory control for nonparavirtualized machines. 32-bit on 64-bit Xen 3.1 added support for a 32-bit OS (including PAE) to run on a 64-bit host. Raw partitions Xen 3.1 added support for virtual disks on raw partitions. Xen 3.2 Like the 3.1 release, Xen 3.2 was not as significant as the 3.0 release, but it added many valuable new features: Xen 3.3 Like the 3.1 and 3.2 releases, the Xen 3.3 release was not as significant as the 3.0 release, but it probably had the most new features of any of the minor releases: Power management Xen 3.3 added power management for P- and C-states to the hypervisor. In CPU terms, P-states are operational states and C-states are idle states. PVGrub Xen 3.3 added support for booting the PV (paravirtualized) kernels using the actual grub inside the PV domain instead of the host grub. PV performance Xen 3.3 improved paravirtualized performance by removing the domain lock from the pagetable-update paths. Shadow3 Xen 3.3 optimized the shadow pagetable algorithm to improve performance. Hardware assist Xen 3.3 added hardware-assisted paging enhancements, including 2MB page support to improve large memory performance. PVSCSI drivers Xen 3.3 allowed for SCSI access directly into the PV guests rather than through a translation layer through PVSCSI drivers. Device passthrough Xen 3.3 added miscellaneous driver enhancements to allow device passthrough rather than through a translation layer, including multiqueue support on NICs. Full x86 Xen 3.3 added full x86 real-mode emulation for HVM guests on Intel VT, allowing for a wider range of legacy guest OSs. Xen 3.4 Xen 3.4 was the release used by Oracle in Oracle VM 2.2. The Xen 3.4 release did not introduce any major new features but did improve many existing features: Device passthrough Xen 3.4 added more enhancements started in the Xen 3.3 release. Offlining Xen 3.4 added support for CPU and memory offlining, where unused CPUs and memory can be “turned off” to save resources. Power management Xen 3.4 enhanced the power management features introduced in Xen 3.3, including scheduler and timers optimized for peak power savings. Hyper-V Xen 3.4 added support for the Viridian (Hyper-V) enlightenment interface. Xen 4.x As with the other major releases of Xen, the Xen 4.0 had a number of significant and minor features. These features increased the ability of Oracle VM to be an enterprise virtualization platform. The evolution of Xen has increased its ability to participate in the virtualization market as well. This section covers the history of Xen 4.x in more detail. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Xen 4.0 Xen 4.0 added upgrades and features that create a more robust and improved platform. Xen 4.0 included many features that were required for enterprise computing, including the following: Performance and scalability Xen 4.0 added support for 128 CPUs and 1TB of RAM on a physical server. It also added support for up to 128 vCPUs and 512GB of RAM per guest operating system. This support was important for larger applications such as databases. Hardware support Xen 4.0 provided support for improved IOMMU PCI passthrough using hardware-accelerated I/O virtualization techniques for Intel VT-d and AMD IOMMU. Online operations Xen 4.0 provided support for online resizing of guest disks without reboot/shutdown. Hot-plug Xen 4.0 provided RAS (Reliability, Availability, and Serviceability) features such as hot-plug CPU and memory. Xen 4.1 Xen 4.1 added upgrades and features that create a more robust and improved platform. Xen 4.1 is not as significant as Xen 4.0, but is still important. Its features include the following: CPU pools Xen 4.1 added support for CPU pools to allow for hard partitioning. This is very significant for Oracle database licensing. AVX Xen 4.1 provided support for x86 Advanced Vector eXtension (AVX), which allows for more complex CPU instructions. Jumbo frames Support for jumbo frames was fixed in Xen 4.1. Xen 4.2 Xen 4.2 added some scalability and performance improvements: Performance and scalability Xen 4.2 added support for 4095 CPUs and 5TB of RAM on physical servers. It also added support for up to 128 vCPUs and 512GB of RAM per PV guests operating systems, and 256 vCPUs and 1TB of RAM for HVM guests. This support was important for larger applications such as databases. Xen 4.3 Xen 4.3 added some new features, including an experimental feature: that a process was previously run on, so the VM would at least try to run on the CPU where its memory resided. Support for openvswitch Openvswitch is a new networking bridging mechanism. Xen 4.4 Xen 4.4 has added several new features aimed at improving performance and scalability: Solid libvirt support for libxl Xen 4.4 has improved the interface between libvirt and libx. Improved Xen event channel Xen 4.4 has added support for a scalable event channel interface. Hypervisor ABI for ARM support Xen 4.4 has improved the hypervisor ABI for ARM support, but it is still not available for production. Nested virtualization Xen 4.4 has improved nested virtualization so it is now ready for tech review and will soon be available in production. This history of the Xen virtualization monitor shows the dynamic nature of virtualization technology and the care taken to provide the latest and greatest features possible. In addition to the features provided by Xen, Oracle has added a management console designed to assist with the use and management of Xen and Oracle VM. The next section describes the additional features provided by Oracle. NOTE Oracle VM does not immediately integrate new versions of Xen because the value of Oracle VM over the base Xen distribution is rock-solid stability for enterprise use. Oracle fully tests every new Xen feature before using it in Oracle VM. New features can be manually enabled by modifying the vm.cfg file or by using the Xen APIs directly. Oracle, however, does not support this. Oracle VM Features Oracle VM is based on the Xen Hypervisor, but there is more to Oracle VM than just the server software itself. Oracle has taken the Xen Hypervisor and added enhancements and fixes as well as improved the management of the virtualized Technet24.ir|||||||||||||||||||||||||||||||||||||||| environment. Oracle VM is made up of two components: the Oracle VM Server and the Oracle VM Manager. Oracle VM Server The Oracle VM Server has been enhanced to provide better manageability, scalability, and supportability. In addition to modifying the Xen Hypervisor for their own product, Oracle’s engineering team contributes to the development of the mainstream Xen software. High availability You can configure resources to restart guests on another host if the underlying host fails. Live migration You can relocate guests from one host to another with no loss of service. This feature is great for load balancing as well as system maintenance. Oracle VM is the only virtualization technology that performs live migration using an encrypted connection, thus providing an additional layer of security. NOTE The server pool must be created with encryption, which does increase the time it takes to perform the migration. guest startup, thus providing the best overall performance to the VM farm by maximizing resource utilization. Performance Oracle VM is optimized for performance, and the Xen Hypervisor is among the fastest forms of virtualization. Rapid provisioning Through the use of cloning and virtual machine templates, Oracle VM can quickly and efficiently create new guest systems. VM templates Oracle provides a wide range of preconfigured virtual machine templates that can take the guesswork out of configuration. These templates are available from Oracle.com. You can customize downloaded templates, and you can also create completely custom templates based on an Oracle VM guest you create on your own. Fault tolerance Oracle provides a number of features to offer high availability and disaster recovery to both the host servers and the virtual machines. These features are covered in detail in this book. These features and more are covered in detail throughout the remainder of this book. In the next chapter, the Oracle VM/Xen architecture is covered in detail. VM Guest Support Oracle VM 3.x supports a full range of guest operating systems using hardware virtualization, as listed in Table 2-1. Using paravirtualized drivers will improve the performance of the system by avoiding the execution of unnecessary code. TABLE 2-1. Supported Linux and UNIX OSs Using Hardware Virtualization NOTE On 32-bit CPUs, only 32-bit guests are allowed. Oracle VM 3.x also supports a full range of guest operating systems using paravirtualization, as listed in Table 2-2. NOTE No Microsoft operating systems are fully paravirtualized. Although PV drivers are available for Windows XP/2003/Vista/2008, as shown in Table 2-3, having a PV driver is different from having a paravirtualized operating system delivered from Microsoft. Host platforms Oracle VM currently supports Intel and AMD x86 and x86_64 platforms. The minimum CPU is the i686; however, to run HVM fully virtualized guests, you must use CPUs with virtualization acceleration. Intel CPUs indicate virtualization acceleration with the “vmx” flag and the AMD processors with the “svm” flag. NOTE This book covers Oracle VM for the x86 platform. Oracle VM is also available for the SPARC platform as well, but is implemented differently. Memory The amount of memory should be proportional to the size and number of VMs. Currently, Oracle VM Server supports a maximum of 6TB of RAM. Of this 6TB of RAM, you can allocate 500GB to a PVM 64-bit guest, 1TB to an HVM 64-bit guest, 2TB to a PVHVM guest, and 64GB of RAM to a 32-bit guest. CPUs As mentioned previously, having CPUs that support virtualization is advantageous. A minimum of one CPU is required, but this number is not suitable for more than one or two guests. A maximum of 384 CPUs is currently supported. The best practice is to reserve one core for dom0 and use the remaining cores/processors for the domU virtual machines. Disk support Oracle VM currently supports SCSI, SAS, IDE/SATA, NAS, iSCSI, FC, and limited support for Fibre Channel over Ethernet (FCoE) storage. Oracle VM Manager A major feature of Oracle VM is the management console, which is called the Oracle VM Manager. The Oracle VM Manager is a web-based application that you use to monitor and configure the entire VM farm. You install and configure the Oracle VM Manager on a Linux system. This Linux host can be a standalone server or a virtual machine; however, if you choose to install the Oracle VM Manager on an Oracle VM Technet24.ir|||||||||||||||||||||||||||||||||||||||| guest, you will have to manage that VM manually. That is, you cannot start the guest via the console because it is hosting the console. Of course, the VM where Oracle VM Manager is installed can be managed by another Oracle VM server pool or even a VMware or KVM guest. You can download the standalone Oracle VM Manager from the same location as the Oracle VM Server (). Since release 5, Oracle VM Manager has also been incorporated into Oracle Enterprise Manager (OEM) Grid Control with the Oracle VM Management Pack. OEM Grid Control with the VM Management Pack allows for centralized management and monitoring of hosts, databases, applications, and virtual machines. You can see an example of the standalone Oracle VM Manager in Figure 2-1. The VM Manager console is where you perform operations such as creating, starting, stopping, live migrating, and deleting Oracle VM guests. import them into the Oracle VM Manager. Once these templates are imported into the Oracle VM Manager, you can configure new guests from them. We’ll cover how to create guest systems from templates in Chapter 18. Once you have created the virtual machine, it is just a matter of configuring and deploying the guest. The Oracle Template Library is divided into 64-bit and 32-bit templates. You might find it a little surprising, but a lot of software still has not been ported to 64-bit Linux. This includes some Oracle products as well. This section provides a brief overview of the 32-bit and 64-bit templates that are currently available at the writing of this book. Most of the VM templates provided by Oracle are “Just enough OS” (JeOS) installations, based on the Oracle standard of installing just the components needed to perform the task at hand. This not only provides for an efficient OS deployment but also helps to meet security standards as well. Many 64-bit templates are available currently, and more are being added. Oracle has provided an extensive set of preconfigured templates. These templates are built using the JeOS (Just enough OS) Linux software and configuration scripts necessary to deploy the system and the application. Specifics on how to use many of these templates and how to use templates in general are provided in Chapter 18. Summary This chapter continued our introduction to virtualization, and Oracle VM in particular. The chapter began by explaining more about what Oracle VM is. You cannot understand what Oracle VM is without also understanding what Xen and the Xen Hypervisor are. This chapter gave a brief introduction into those concepts and also touched on Oracle’s support for virtualization and the open-source manner in which Xen is developed and supported. The chapter concluded with an overview of the Oracle Template Library. This template library provides a way to download and deploy a complete virtualization environment quickly and easily. These templates are built using the Oracle JeOS Linux distribution. In addition, most of the templates include preinstalled applications that are ready to be configured and deployed. Of course, these templates might need customizing, which will be covered in Chapter 17. The next chapter explores the Oracle VM architecture, including not only the architecture of the VM Server and VM Manager but the Xen Hypervisor architecture as well. By understanding how Xen and Oracle VM work, you will better understand how to configure and tune them. CHAPTER 3 Oracle VM Architecture Technet24.ir|||||||||||||||||||||||||||||||||||||||| iscussing the Oracle VM architecture is difficult without also including the Xen D architecture, the underlying technology. In this chapter, you learn about the different components of both. By understanding how the components work, you can administer, tune, and size the virtual environments within the Oracle VM system more effectively. Oracle VM Architecture Oracle VM is a virtualization system that consists of both industry-standard, open- source components (mainly the Xen Hypervisor) and Oracle enhancements. Oracle does not use the stock Xen Hypervisor. Oracle has performed significant modifications and contributes to the open-source Xen Hypervisor development. In addition to Xen utilities, Oracle provides its own utilities and products to enhance and optimize Oracle VM. Oracle also continues to acquire new companies that provide new technology to improve Oracle VM. As discussed in previous chapters, the Oracle VM system is made up of two components: the Oracle VM Manager, which can be installed on either a standalone server or a virtual machine, and the Oracle VM Server, as shown in Figure 3-1. Oracle VM Server and allocated to a single guest virtual machine. This continues to increase with each new release. NOTE Although it is possible to set up multiple servers in a nonclustered server pool sharing NFS storage, this can lead to issues. The server pool master (OVM 3.3 and earlier) controls the server pool, and the virtual machine server supports virtual machines. The server pool is a collection of systems that are designed to provide virtualization services and that serve specific purposes. A server pool is defined by a single Oracle VM Manager and shares some common resources, such as storage. By sharing storage, the load of running virtual machines (VM guests) can be easily shared among the virtual servers that are members of the server pool. Without a shared disk, a server pool can exist on only one server. presented as iSCSI, then Oracle VM will format it as OCFS2, just like SAN storage. A clustered filesystem is required because of the shared nature of the VM server pool. When using NFS as a repository source, Oracle VM will use the distributed lock manager (DLM) from OCFS2 to handle file locking for cluster server pools. This locking service is called dm-nfs. If you use a single host for the VM Server, you can use local storage. In a single- server environment, there is no need to share the VM guest storage. However, in a single-host environment, neither load balancing nor high availability is possible. By default, the Oracle VM Server installation uses the remainder of the hard drive to create a single, large OCFS2 partition for /OVS, where the virtual machines are stored. NOTE The Oracle VM Manager does not specifically prohibit the creation of a mixed environment. It is possible to create a server pool with mixed architectures. But when the time comes to restart a virtual machine, or to live migrate a virtual machine to a new host, Oracle VM will perform a runtime check and disallow restarting or moving to a different architecture, which is why a mixed environment is not recommended. Although not required, it is a good idea to create a server pool of the same speed and number of processors per system. This setup allows for better load balancing. Mixing various performance levels of VM servers can skew load balancing. Therefore, creating a server pool of similarly configured systems is a good idea. Always consider the requirements of the largest VM. In order for High Availability (HA) to work (or for live migration), you need another server with sufficient resources. If a virtual machine has been granted 32 vCPUs, and only one server in the pool has that many vCPUs, then the virtual machine cannot be restarted or moved. This is not an argument for using larger servers in the pool as much as it is an argument for using horizontal scaling. Databases can use Real Application Clusters (RAC), and middleware can use its own clustering to keep vCPU and RAM requirements per VM reasonable. Oracle VM Server The virtual machine server is the core of the Oracle VM server pool. The virtual machine server is the Oracle VM component that hosts the virtual machines. The Oracle VM Server is responsible for running one or more virtual machines and is installed on bare metal, leaving only a very small layer of software between the hardware and the virtual machines. This is known as the hypervisor. Included with the Oracle VM Server is a small Linux OS, which is used to assist with managing the hypervisor and virtual machines. This special Linux system is called domain 0 or dom0. The terms domain, guest, VM guest, and virtual machine are sometimes used interchangeably, but there are slight differences in meaning. The domain is the set of resources on which the virtual machine runs. These resources were defined when the domain was created and include CPU, memory, and disk. The term guest or VM guest defines the virtual machine that is running inside the domain. A guest can be Linux, Solaris, or Windows and can be fully virtualized or paravirtualized. A virtual machine is the OS and application software that runs within the guest. Visit the Oracle virtualization website at for the most up-to-date support information. Dom0 is a small Linux distribution that contains the Oracle VM Agent. In addition, dom0 is visible to the underlying shared storage that is used for the VMs. Dom0 is also used to manage the network connections and all of the virtual machine and server configuration files. Because it serves a special purpose, you should not modify or use it for purposes other than managing the virtual machines. In addition to the dom0 virtual machine, the VM Server also supports one or more virtual machines or domains. These are known as domU or user domains. The different domains and how they run are covered in more detail in the “Xen Architecture” section of this chapter. The Oracle VM domains are illustrated in Figure 3-2. Oracle VM Agent The Oracle VM Agent is used to manage the VM Servers that are part of the Oracle VM system. The Oracle VM Agent communicates with the Oracle VM Manager and manages the virtual machines that run on the VM Server. The VM Agent consists of two components: the server pool master and the virtual machine server. These two components exist in the Oracle VM Agent but don’t necessarily run on all VM servers. Server Pool Master (OVM 3.3 and Earlier) The server that currently has the server pool master role is responsible for coordinating the actions of the server pool. The server pool master receives requests from the Oracle VM Manager and performs actions such as starting VMs and performing load balancing. The VM Manager communicates with the server pool manager, and the server pool manager then communicates with the virtual machine servers via the VM Agents. As mentioned earlier, you can only have one server pool master in a server pool. In addition, the server pool master has been deprecated in OVM 3.4. Now the OVM Manager communicates with the OVM Agent on all virtual machine servers. Virtual Machine Server The virtual machine server is responsible for controlling the VM Server virtual machines. It performs operations such as starting and stopping the virtual machines. It also collects performance information from the virtual machines and the underlying host operating systems. The virtual machine server controls the virtual machines. Because the virtual machines are actually part of the Oracle-enhanced Xen Hypervisor, this topic is covered in the “Xen Architecture” section, later in this chapter. Oracle VM Manager The Oracle VM Manager is an enhancement that provides a web-based graphical user interface (GUI) where you can configure and manage Oracle VM Servers and virtual machines. The Oracle VM Manager is a standalone application that you can install on a Linux system. In addition, Oracle provides another way to manage virtual machines via an add-on to Oracle Enterprise Manager (OEM) Cloud Control. Both options are covered in this book. The Oracle VM Manager allows you to perform all aspects of managing, creating, and deploying virtual machines with Oracle VM. In addition, the Oracle VM Manager provides the ability to monitor a large number of virtual machines and easily determine the status of those machines. This monitoring is limited to the status of the virtual machines. When using OEM Cloud Control, you have the additional advantage of using the enterprise-wide system-monitoring capabilities of this application as well. Within OEM Cloud Control, not only are you able to manage virtual machines through the VM Manager screens, but also you can add each virtual machine as a host target, as well as any applications that it might be running. In addition, OEM management packs can provide more extensive monitoring and alerting functions. The VM Manager can perform a number of tasks, among which is virtual machine lifecycle management. Lifecycle management refers to the lifecycle of the virtual machine as it changes states. The most simple of these states are creation, power on, power off, and then deletion. Many other states and actions can occur within a virtual machine. The full range of lifecycle management states are covered in Chapter 4. The VM Manager is shown in Figure 3-3. User The user role is granted permission to create and manage virtual Management Methods You have several options for managing Oracle VM Manager, including the Oracle VM Manager GUI tool and the Oracle Enterprise Manager Cloud Control add-in for Oracle VM. You can also use an Oracle VM command-line tool from Oracle. Finally, you can use the Xen tools built into the Oracle VM Server. Which tool is right for you varies based on what you are trying to do. For monitoring the Oracle VM system, a graphical tool is often the most efficient and easiest to use. You can quickly see the state of the system and determine if there are problems. You can sort and group the virtual machines by their server pool and determine the current resource consumption on the underlying hardware easily. In addition, performing tasks such as creating virtual machines is very straightforward with the assistance of wizards. Xen Architecture The core of the Oracle VM system is the software that runs the virtual machines. This software is the Xen virtualization system, which consists of the Xen Hypervisor and support software. Xen is a virtual machine monitor for x86, x86_64, Intel Itanium, and PowerPC architectures (Oracle only supports the x86_64 architecture). At the core of the Xen virtualization system is the Xen Hypervisor. NOTE For the purposes of this book, the terms x86 and x86_64 are interchangeable. With OVM 3.x, only the 64-bit architecture is supported. The terms x86 and x86_64 both refer to the 64-bit architecture. The Xen Hypervisor is the operating system that runs on the bare-metal server. The guest OSs are on top of the Xen Hypervisor. The Xen Hypervisor, after booting, immediately loads one virtual machine, dom0, which is nothing more than a standard virtual machine but with privileges to access and control the physical hardware. Each guest runs its own operating system, independent of the Xen Hypervisor. This OS is not a further layer of a single operating system, but a distinct operating system being executed by the Xen Hypervisor. The guest OSs consist of a single dom0 guest and zero or more domU guests. In Xen terminology, a guest operating system is called a domain. Dom0 The first domain to be started is domain 0, or dom0. This domain has the following special privileges and capabilities: The Oracle VM dom0 is a Just enough OS (JeOS) Oracle Enterprise Linux (OEL) operating system with the utilities and applications necessary to manage the Oracle VM environment. The Oracle VM Server installation media installs dom0, which is a 32-bit OEL system including the Oracle VM Agent. The 32-bit system is installed even on 64- bit hardware. In the small Linux OS, dom0 contains two special drivers, known as backend drivers: the backend network driver and the backend I/O or block driver. You can see both in Figure 3-4. Oracle calls these the netback and netfront drivers and the blkback and blkfront drivers, respectively. The network backend driver (netback) communicates directly with the hardware and takes requests from the domU guests and processes them via one of the network bridges that have been created. The block backend driver (blkback) communicates with the local storage and takes I/O requests from the domU systems and processes them. For this reason, dom0 must be up and running before the guest virtual machines can start. DomU All of the other guest virtual machines are known as domU or user domain guests. If they are paravirtualized guests, they are known as domU PV guests. Hardware virtualized guests are known as domU HVM guests. Access to the I/O and network is handled slightly differently, depending on whether the guest is a paravirtualized or a hardware virtualized system. DomU Read Operation A domU read operation uses the event channel to signal the PV block driver on dom0, which fulfills the I/O operation. Here are the basic steps to perform a read: Technet24.ir|||||||||||||||||||||||||||||||||||||||| Even though this process seems sophisticated, it is an efficient way to perform I/O in a paravirtualized environment. Until the newer hardware virtualization enhancements were introduced, paravirtualization provided the most performance possible in a virtualized environment. DomU Write Operation The domU PV write operation is similar to the PV read operation. A domU write operation uses the event channel to signal the PV block driver on dom0, which then fulfills the I/O operation. Here are the basic steps to perform a write operation: Like the PV read operation, although this operation is somewhat complex, it is also efficient. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Hypervisor Operations The Xen Hypervisor handles other operations that the OS normally performs, such as memory and CPU operations. When an operation such as a memory access is performed in the virtual guest, the hypervisor intercepts it and processes it there. The guest has a pagetable that maps the virtual memory to physical memory. The guest believes that it owns the memory, but it is retranslated to point to the actual physical memory via the hypervisor. Here is where the introduction of new hardware has really made today’s virtualization possible. With the Intel VT and AMD-V architectures, the CPUs have added features to assist with some of the most common instructions, such as the virtual- to-physical translations. This advance allows a virtualized guest to perform at almost the same level as a system installed directly on the underlying hardware. DomU-to-Dom0 Interaction Because of the interaction between domU and dom0, several communication channels are created between the two. In a PV environment, a communication channel is created between dom0 and each domU, and a shared memory channel is created for each domU that is used for the backend drivers. In an HVM environment, the Qemu-DM daemon handles the interception of system calls that are made. Each domU has a Qemu-DM daemon, which allows for the use of network and I/O requests from the virtual machine. Networking With Oracle VM/Xen, each physical network interface card in the underlying server has one bridge called an xenbr that acts like a virtual switch. Within the domain, a virtual interface card connects to the bridge, which then allows connectivity to the outside world. Multiple domains can share the same Xen bridge, and a domain can be connected to multiple bridges. The default is to map one xenbr to each physical interface, but through trunking/bonding, you can and should (it is recommended) take multiple physical NICs and present them as a single xenbr. The bridges and Ethernet cards are visible to the dom0 system and can be modified there if needed. When the guest domain is created, a Xen bridge is selected. You can modify this later and/or add additional bridges to the guest domain. These additional bridges will appear as additional network devices, as shown in Figure 3-7. systems now have an advantage. Many of the traps that required software emulation are now done by the hardware, thus making it more efficient and perhaps more optimal than paravirtualization. Now work is being done to provide hardware assist technology to paravirtualization as well. The next generation of hardware and software might possibly create a fully hardware-assisted paravirtualized environment that is the most optimal. At the current stage of technology, both paravirtualization and hardware-virtualized machine (HVM) are high performing and efficient. Choosing which to use most likely depends on your environment and your preferences. We recommend and run both paravirtualized and HVM (and now PVHVM) guests. Both choices are good ones. NOTE In some documentation, the virtual machine monitor is known as the virtual machine manager. For the purposes of this book, the two terms are synonyms. The hypervisor has two layers. The bottommost layer is the hardware or physical layer. This layer communicates with the CPUs and memory. The top layer is the virtual machine monitor, or VMM. The hypervisor is used to manage the virtual machines by abstracting the CPU and memory resources, but other hardware resources, such as network and I/O, actually use dom0. Type 1 Hypervisors There are two types of hypervisors. The type 1 hypervisor is installed on, and runs directly on, the hardware. This hypervisor is also known as a bare-metal hypervisor. Many of the hypervisors on the market today (including Oracle VM) are type 1 hypervisors. This also includes products such as VMware, Microsoft Hyper-V, and others. The Oracle Sun Logical Domains (now known as Oracle VM Manager for SPARC) is also considered a type 1 hypervisor. Type 2 Hypervisors The type 2 hypervisor is known as a hosted hypervisor. A hosted hypervisor runs on top of an operating system and allows you to create virtual machines within its private environment. To the virtual environment, the virtual machine looks like any other virtual machine, but it is far removed from the hardware and is purely a software product. Type 2 hypervisors include VMware Server and VMware Workstation. The Oracle VM Solaris 10 container is considered a type 2 hypervisor as well. Hypervisor Functionality In a fully virtualized environment, the Xen Hypervisor (or VMM) uses a number of traps to intercept specific instructions that would normally be used to execute instructions on the hardware. The hypervisor traps and translates these instructions into virtualized instructions. The hypervisor looks for these instructions to be executed, and when it discovers them, it emulates the instruction in software. This happens at a very high rate and can cause significant overhead. In a paravirtualized environment, the Xen-aware guest kernel knows it is virtualized and makes modified system calls to the hypervisor directly. This requires many kernel modifications but provides a more efficient way to perform the necessary OS functions. The paravirtualized environment is efficient and high performing. The primary example of this is in memory management. The HVM environment believes that it is a normal OS, so it has its own pagetable and virtual-to-physical translation. In this case, the virtual-to-physical translation refers to virtual memory, not virtualization. The virtualized OS believes it has its own memory and addresses. For example, the virtualized environment might think it has 2GB of physical memory. The pagetable contains the references between the virtualized system’s virtual memory and its (virtualized) physical memory; however, the hypervisor really translates its (virtualized) physical memory into the actual physical memory. Thus, the virtual-to- physical translation call is trapped (intercepted) and run in software by the hypervisor, which translates the memory call into the actual (hardware) memory address. This is probably the most-used system operation. This is also where the hardware assist provides the biggest boost in performance. Now, instead of the operation being trapped by the hypervisor, this operation is trapped by the hardware. Thus, the most commonly used instructions that the hypervisor typically traps are not trapped and run in the hardware, which allows for almost native performance. Features of Oracle VM Oracle VM is a full-featured product. It is a fully functional virtualization environment that comes with an easy-to-use management console as well as a command-line interface. Here are some of the features of Oracle VM: Guest support Oracle VM supports many guests. The number of guests you can support on a single server is limited only by the memory and CPU resources available on that server. Live migration Oracle VM supports the ability to perform live migrations between different hosts in a server pool. This allows for both High Availability and load balancing. Pause/resume The pause/resume function provides the ability to manage resources in the server pool by quickly stopping and restarting virtual machines as needed. Templates The ability to obtain and utilize templates allows administrators to prepackage virtual systems that meet specific needs. The ability to download preinstalled templates from Oracle gives administrators an easy path to provide prepackaged applications. The choice of hardware depends mostly on the type of virtual machines you intend to run as well as the number of machines. This is covered in much more detail later in the book. Summary This chapter provided some insight into the Oracle VM architecture. By understanding the architecture, you will find it is easier to understand the factors that influence performance and functionality. The beginning part of the chapter covered the components of the Oracle VM system—the Oracle VM Server, the Oracle VM Manager, and the Agent, the latter of which is a key component of the system. Because of Oracle VM’s use of the Xen Hypervisor, this chapter also covered the architecture of the Xen virtualization environment and the Xen Hypervisor. The Xen virtualization system is an open-source project that is heavily influenced by Oracle (since Oracle relies on it). This chapter provided an overview of the Xen system and Xen Hypervisor, as well as detailed some of the hardware requirements necessary to run Oracle VM and Xen. Although Xen runs on a number of different platforms, Oracle VM only supports the x86_64 environment at this time. This book is about the Oracle VM products based on Xen technology and does not cover the hardware virtualization products available with the Oracle line of products. The next chapter covers virtual machine lifecycle management. Lifecycle management is the progression of the various states that the virtual machine can exist in —from creation to destruction. Within lifecycle management, you will also study the various states of the lifecycle of virtual machines. CHAPTER 4 Oracle VM Lifecycle Management racle VM lifecycle management describes the change in state of the virtual machine O —from creation to destruction and every state in between. For example, the lifecycle of a virtual machine starts with the machine being built and then continues with it being started, suspended, resumed, stopped, and eventually deleted. Within the lifecycle of a virtual machine are four major states—nonexistent, stopped, running, and suspended—and a virtual machine can transition between these states, as this chapter describes. Also, various tasks take place within these states, and the transitions that can be made vary according to which state the machine is in. There are several ways in which transitions occur between each state of existence, all of which comprises the virtual machine lifecycle, as described in this chapter. Nonexistent This state is the starting and ending point, where the virtual machine does not exist. The virtual machine has no definition or state and uses no system resources. This is the state before the virtual machine is created and after the virtual machine has been removed from the VM Server. From the nonexistent state, you create the virtual machine. Stopped The virtual machine is defined in this state. Both a configuration file and data files exist. In the stopped state, the virtual machine consumes disk space but does not consume memory or CPU resources. From the stopped state, you can start, migrate or move, clone, edit, or delete the virtual machine. Running This is the operational state of the virtual machine from which tasks and processes are performed. When in the running state, the virtual machine consumes not only disk space but also memory and CPU resources. From the running state, you can stop/kill, restart, migrate or move, clone or suspend the virtual machine. Suspended This state preserves the machine’s current settings and application states without releasing system resources, allowing the machine to resume this state with a short load period. In this state, the virtual machine consumes memory and disk resources but very little CPU resources. When in the suspended state, you can resume the virtual machine. Figure 4-1 shows all the states that are possible in Oracle VM and the transitions that are available. NOTE Although a virtual machine can be created through several different menus, each method uses the same command: Create Virtual Machine. This command invokes a wizard to assist you with creating the virtual machine. You can choose to create a virtual machine from an existing template or a virtual machine from a virtual appliance, or you can choose to create a virtual machine manually. Creating a virtual machine from a template is covered in detail in Chapter 18. Creating a virtual machine manually is covered in detail in Chapter 19. Because creating the virtual machine is the first step in the lifecycle, it is a critical step. virtual machine.” From the stopped state (shutdown), the virtual machine can move to the running state. You do this by starting the guest VM. From the running state, you can stop the virtual machine. Depending on the command you use, this might be a hard stop (similar to pulling the power cord) via the kill command or a graceful shutdown using the stop command. Whenever possible, you should shut down the system gracefully rather than perform a hard shutdown. If you perform a hard stop, you might find it takes much longer to restart the virtual machine. For example, stopping a system might cause the database application running on that system to take much longer to restart because it has to perform data recovery. Suspending The suspended state offers the ability to stop the virtual machine in its current operating state and to return the machine to that exact state upon resuming. The difference between the two states is the manner in which the machine’s settings are preserved and how the resources that the virtual machine uses are affected. Putting a virtual machine into the suspended state simply stops the execution of further commands momentarily, much like a Windows desktop enters Sleep mode. In the suspended state, the machine’s applications and settings are simply stopped (that is, they are kept the same as they were when the suspended state was entered). The settings and application states are not saved to files that are then used upon resuming the virtual machine; they are simply stopped and kept as they are. This allows for a fairly short load period upon resuming operation, but the virtual machine also continues to utilize (some of) the Oracle VM server’s resources. If your desire is to simply stop execution of the virtual machine for a short period of time and to restart it quickly, you should choose to suspend the virtual machine. This option provides a fast restart as well as holds system resources. If the VM Server were to fail, the suspended system will be lost and require recovery if applicable. what resources the machine will use. The Template Library is one of Oracle VM’s most significant features. Templates allow you to save a preconfigured system and reuse it over and over again to provision additional virtual machines quickly and efficiently. With a few configuration changes, you can quickly put the new virtual machine into production, allowing you to add more capacity in an efficient manner. In addition to using the Oracle predefined templates, you can create a template of a virtual machine that you have created. This is done via the clone command. When you select the clone option, you will be asked whether to clone to a virtual machine or clone to a template. Cloning your own, already configured virtual machine to a template can be very efficient and useful because all of the software and updates you require are already installed. Migrating a virtual machine involves moving the execution of an existing machine from one Oracle VM server where it’s currently running to another Oracle VM server, server pool, or storage repository, without duplicating the virtual machine. Migration helps you balance resources as well as achieve high availability. With Oracle VM, you can migrate a virtual machine while keeping it in a running state. This way, you can also balance resources while the virtual machine is live. If you need additional CPU resources and/or memory and they are not available on the Oracle VM server the virtual machine is currently running on, you can move it live to a Oracle VM server that has sufficient resources. Once the migration is complete, you can add resources. In addition, if maintenance is required, you can abandon a VM server during the maintenance period and then return to it once the maintenance has been completed. Stopped In the stopped state, the virtual machine exists but is only consuming storage resources. The virtual machine is not running and is nonfunctional. The stopped state offers you the following options: Start From the shutdown state, you can start the virtual machine. This activates the system, taking it to the running state. Once the virtual machine has started, a Power-On Self-Test (POST) process runs and then the OS boots. At an early stage of the start process, the virtual machine console becomes available. Clone Cloning allows you to copy a stopped virtual machine to either the same or a different server pool. A cloned system is identical to the original. During this process, the virtual machine is not available. In this version of OVM, a hot-clone can be created while the source virtual machine is still running, but this process does not create a completely reliable clone and should only be used for backup purposes. It is best practice to create a clone while the source virtual machine is in the stopped state. Clone to a template In order for you to create a template of a virtual machine, it should be in the stopped state. A running virtual machine that you copy will most likely result in a corrupted image. The template process saves the virtual machine images as well as the virtual machine configuration file. The virtual machine configuration file is modified to reflect the template path. This template makes a great starting point for creating virtual machines. Creating a virtual machine, customizing it as needed, and cloning it to a template is an easy way to deploy custom virtual machines. Delete You can remove a virtual machine from the stopped state. You can probably delete the image files of a running virtual machine, but doing so might leave the VM Server in an unknown state. Of course, deleting a running virtual machine causes it to crash. Edit In order for you to edit a virtual machine, it should be in the stopped state. Modifications include adding disks, network adapters, and so on. In this state, you can add additional disks and/or modify the ones you have. You can modify a few options with the virtual machine running, but the underlying OS might not recognize those changes. Because stopped systems are currently not running, they are in the ideal state for the operations mentioned here. Running In the running state, the virtual machine is available for users and can be accessed. In this state, only some changes can be made to the virtual machine configuration. The following state transitions are available from the running state: Stop Stopping the virtual machine moves it from the running state to the stopped state. You can do this either via an orderly shutdown or by killing it (similar to powering it off). An orderly shutdown is preferable, if at all possible. By stopping the system, you might have to perform recovery operations, resulting in performance problems on startup. Restart The restart state is identical to a system reboot in Linux. The system is shut down and then restarted. However, it is important to note that the virtual machine configuration is not reloaded during a restart, so any manual changes to the vm.cfg file will remain unrecognized until the virtual machine is stopped and then started again. Kill The kill state is identical to powering off a system in Linux. The system is immediately aborted. Migrate You can migrate the virtual machine to another VM server without ceasing operation via live migration from the running state. There are many reasons for migrating the virtual machine, such as load balancing, maintenance, and so on. You can also migrate the virtual machine configuration file and any virtual storage to a different storage repository within the same server pool as long as the virtual machine is stopped. Edit You can edit a few things while the system is in the running state, including memory (up to Max Memory Size). Regardless of whether Oracle VM allows the edit to occur while the virtual machine is running and whether the virtual machine recognizes the changes depends on the virtual machine itself. Not all operating systems recognize dynamic configuration changes. Suspended Entering the suspended state preserves the machine’s current settings and processes in memory without releasing system resources, allowing for quick resumption of the virtual machine’s state. The suspended state can return to the running state via a resume transition. The running state is where most of the work gets done and is the most useful state. Suspended Entering the suspended state preserves the machine’s current settings and processes in memory without releasing system resources, allowing for quick resumption of the virtual machine’s state. From the suspended state, the virtual machine can enter the running state or the shutdown state, and the following transitions are possible: Resume Via the resume transition, the virtual machine returns to its previous state and processes at the point where the suspended state was entered after a short load period. Resuming results in the virtual machine entering the running state. Kill In suspended mode, a kill command powers off the virtual machine and moves to the stopped state. This state is only useful for short periods of time. In the event of a virtual machine server failure, the suspended state is lost. Summary The virtual machine lifecycle is defined by the various states in which it exists and operates in. Four basic states exist within the lifecycle, each one allowing for different tasks and configurations. The beginning of the lifecycle is the creation of the virtual machine. The end of the lifecycle is the deletion of the virtual machine. The states in between are known as the lifecycle of the virtual machine. CHAPTER 5 Planning and Sizing the Enterprise VM Server Farm Technet24.ir|||||||||||||||||||||||||||||||||||||||| All the nodes of the cluster must reside on the same shared storage, thus maintaining the cluster. An interesting option is to locate some of the servers in another part of the data center or another building in order to create a stretched pool. As long as storage is accessible from the stretched nodes in the server pool, this will maintain a higher level of HA. Although the stretched pool is not completely supported, it does work and can be implemented. Keep in mind that there might be some performance degradation for the remote nodes. I then entered the model number X5670 on the Intel website and, among other information, obtained the following: This information tells you that the processor on this system is capable of supporting hardware-assisted virtualization. You can find similar information on the AMD website at. Once you’ve resolved hardware compatibility issues, you need to decide whether to create one large server pool or several server pools. NOTE With Oracle VM version 3.4, the idea of the master server has been deprecated. However, this book covers all the 3.x releases, so it is still discussed. The downside of having a single server pool is that several maintenance tasks require the entire server pool to be rebuilt. These maintenance tasks can cause some loss of service to the server pool while the maintenance is being done. If you have multiple server pools, you can maintain one server pool at a time. These tasks include the following: In the next section, you will learn the advantages of multiple server pools. are server pool master, utility server, and virtual machine server. A VM Server can be designated to perform a single server role, two roles, or all three roles. Utility Servers The utility server is a server that is chosen to perform more specific tasks in the VM server farm. This server performs tasks such as pool filesystem operations and updating the cluster configuration as well as importing virtual machine templates and virtual appliances and creating virtual machine templates from virtual appliances. It is also responsible for creating repositories. By default, all servers are utility servers. If a utility server is not available, a VM server will be used. You can set up server pools in the following ways: All-in-One configuration, Two-in- One configuration, and the individual configuration. Which configuration you decide to use depends on the size of your configuration. All-in-One Configuration The All-in-One configuration is the most straightforward configuration. It is made up of the server pool master and virtual machine servers, all residing on the same VM server. This configuration functions well for either a VM farm where there is only a single or a few servers or a configuration where many virtual machines are managed but there are very few changes. The All-in-One configuration can consist of a single server, as shown in Figure 5-1, or of a single server that supports the server pool master, utility server, virtual machine server, and one or more additional virtual machine servers, also shown in Figure 5-1. With Oracle VM 3.4, because there really isn’t the concept of the server pool master, all VM servers use the All-in-One configuration. The advantage of the All-in-One configuration is that configuring and managing it is easy. This configuration does have a disadvantage in that there is a single point of failure if the single Oracle VM Server were to fail (if there is only one). This configuration is becoming more common as hardware is released that is capable of supporting enormous numbers of virtual machines. Because you can easily add additional virtual machine servers to a server pool (assuming the storage used is capable of being shared), you can always start with an All-in-One configuration and add to it as needed. Two-in-One Configuration The Two-in-One configuration involves setting up the server pool master and utility server on the same server. The Two-in-One server configuration is for larger configurations where separating the virtual machine server from the server pool master is necessary. The Two-in-One configuration is shown in Figure 5-2. The Two-in-One configuration makes sense where the VM server farm is moderately sized and you need to separate administrative functions from virtual machine functions. If the separation is for preference rather than load, you can configure the server pool master and utility server system as a smaller server than the virtual machine servers. The type of configuration you choose is partially based on the capacity you need for the VM server farm and partially based on anticipated growth of the farm. Fortunately, if you decide to change things later, this is one area where modifications are easy. This configuration is no longer valid for 3.4 and newer versions of OVM since OVM 3.4 no longer uses the utility server. Perhaps more important than the configuration of the VM server farm is sizing and capacity planning for the farm. If the VM server farm is undersized, performance and capacity will suffer and your system will not run at the desired level of service or capacity. Computer Sizing Sizing is the act of determining the amount of hardware needed for an anticipated workload. Capacity planning is the act of determining the amount of additional hardware necessary to add to an existing system in order to meet future workloads. This is used to determine if the existing VM farm can handle existing workloads and when additional hardware might be needed. Both sizing and capacity planning are as much an art form as a science. They involve mathematics, monitoring and analyzing of existing workloads, and a lot of extrapolation. Probably more so than most activities, with sizing and capacity planning, the better the data input into the exercise, the better the end result. In addition to the traditional variables used for sizing and capacity planning, such as the number of servers, number of CPUs, RAM, storage size, and I/O performance requirements, CPU virtualization acceleration features must now be taken into consideration as well. These new virtualization acceleration technologies allow for more virtual machines to be run more efficiently than ever before on the same hardware. In addition, server features such as Non-Uniform Memory Access (NUMA) technology affect performance. Sizing and capacity planning are among the most challenging tasks you must undertake in planning the VM server farm. As such, they are two of the most important as well. As mentioned earlier, an undersized system will cause performance problems later. In the next sections, both sizing and capacity planning are covered. Sizing Sizing is the act of determining the amount and type of hardware needed for a new installation of an application. Sizing differs from capacity planning in that the hardware will be supporting a new application or a new installation of hardware, rather than an upgrade or addition to the existing hardware in a system. For example, if a computer system will be replaced by another system that has more resources or is faster, sizing is involved. If that same system will have more CPUs or more memory added to it, capacity planning is involved. Typically, the components that end up being the biggest NUMA Systems Non-Uniform Memory Access (NUMA) systems use multiple memory controllers that are each assigned to a CPU or set of CPUs. This is different from a symmetric multiprocessing (SMP) system, where all CPUs share the same memory controller. NUMA allows you to add more CPUs to the system with better performance. Because a memory controller is a finite component, in an SMP environment, the number of CPUs supported is limited by the memory controller. OVM supports NUMA but does not support C-state power-saving features where unused CPUs can be shut down. The steps involved in sizing a new system are data collection, analysis, and design. The better the data collection, the better the design will be. Keep in mind that there will still be a lot of work to do in the analysis stage where you analyze and decompose the data. Data Collection Sizing the new system starts with collecting as much data as you can about the application and the expected workload. If the new system is a replacement for an existing system, much of this data is readily available. You can collect data by monitoring the existing system. If possible, create specific tests or conditions where a single virtual machine is running, so you can analyze a specific workload. A few different types of data are collected. Data collection is used to gather information about the workload that will be run. In addition, data is collected about the number and type of virtual machines that will be deployed. Collect this data in a workbook that you can then use to determine the number and size of systems to include in the design. Workload Data Collection Collecting data about the required workload is typically done using tools available in the OS that is being deployed with whatever systems are available. If this is a completely new system and there are no available reference systems, sizing is more difficult. As mentioned before, the better the data, the better the result. If you’re modeling Linux systems, use tools such as sar, top, iostat, and vmstat. These utilities provide information about the system’s current CPU utilization as well as memory utilization and I/O utilization. Collect data over a fairly long period of time, so you can gather both averages and peaks. Collect a minimum of one month of data, though longer is recommended. If you’re modeling Windows systems, use Performance Monitor (perfmon). Perfmon provides data on CPU, memory, and I/O utilization. You can use this data to help size the new system. Windows perfmon not only is capable of collecting a large variety of data but also is capable of saving it. Its major downside is its inability to export that data in text form. Memory Over-Commit Memory over-commit is when more memory is allocated to virtual machines than is available in the VM server. If more memory than is actually available is used, that memory is paged out, as is done in a normal virtual memory system. With Oracle VM, physical memory is allocated for each virtual machine when the virtual machine is created. normal work hours. Why is this important? If you use the overall average CPU utilization, the value would be skewed lower in most cases due to the lack of off-hours activity. For example, let’s say a system runs at 50 percent utilization between 6:00 AM and 6:00 PM and is idle overnight. This is a daily average of 25 percent. If 25 percent were used to size a system, the system would be dramatically undersized during normal work hours. In addition, not only should the system be sized based on a normal work-hours load, but also it should be sized based on peak load. Configure the system to handle a peak steady-state load with relative ease. Peak load is the highest load seen during the measurement period. The peak load is slightly different from a spike because the peak load is somewhat sustained, whereas a spike is a one-time event. In addition to memory, you need to gather CPU requirements. The number of CPUs required for virtual machines might be determined by business rules or workload analysis. Typically, some business rules require a minimum of two CPUs. If no business requirements are available, you can figure out the number of CPUs by determining the workload that must be supported. The amount of required disk space is usually determined by the group deploying the application(s). In addition to the amount of space, consider the performance capacity of the I/O subsystem. An underpowered I/O subsystem can result in performance problems from both the OS and the application standpoint. Once you’ve gathered both performance data and physical requirements, you can then move on to the analysis stage. At this stage, the requirements and data you’ve collected is translated into physical requirements for each virtual machine. Once you’ve completed the analysis, you can design the sized system. Analysis The analysis stage of the sizing process involves taking the data collected in the previous step and using it to calculate the amount of resources needed to meet the requirements determined during the collection stage. You can split the analysis phase into several phases. The first phase is to take the requirements from both the collected requirements and, if available, the workload collection process. Enter that information in a spreadsheet and adjust it (that is, translate it to a single reference platform) if you used different systems for data collection. Translated Performance The reason to adjust or translate the performance information is to give you a In the second phase, this data is summed over all of the systems identified in the requirements. This provides you with the data necessary to identify the total resources required for the host(s). Remember, hardware improvements allow the load on several slower CPUs to be replaced with fewer faster CPUs. Once you’ve collected the data and calculated the totals, it is time to start thinking about the potential solutions. In the following examples, the process and some ideas are presented to illustrate how to put together an analysis spreadsheet. Example 1 In the example shown in Table 5-1, data has been collected for several older 1-GHz systems and some newer 2-GHz systems. NOTE The CPUs are adjusted to 1 = 100% of a 2-GHz x86_64 CPU = 1.0. Therefore, two CPUs running at 75 percent is equivalent to 150 percent, but adjusted to the reference CPU, this translates back to .75. Using this spreadsheet, you can then begin the design stage. Example 2 In the example shown in Table 5-2, data has been collected for a half dozen very busy systems. This information will be used to analyze how much equipment is needed for the new installation. In this case, there are some holes in the data for new systems that don’t have an equivalent running system to collect data from. NOTE The CPUs are adjusted to 1 = 100% of a 2.2-GHz x86_64 CPU = 1.0. Therefore, two CPUs running at 75 percent is equivalent to 150 percent, or 1.5. Design The design stage is where you choose the hardware for the VM Server system(s) and create a configuration. Sizing systems involves these components: the amount of memory, the number of CPUs, networking components, and the amount of disk space and storage performance required. Sizing Memory Because Oracle VM does not over-allocate memory, sizing memory is probably the easiest part of this exercise. Simply sum the memory required for each of the virtual machines to be supported and add an additional gigabyte for dom0. In the case of the preceding two examples, the required memory is pretty self-explanatory. Sizing CPUs Sizing CPUs is a little bit more challenging than sizing memory. This is mainly because CPUs are a shared resource and are always over-allocated. Over- allocating means it is common that more CPUs are allocated to the virtual machines than actually exist on the VM server system. Fully allocating CPUs to virtual machines is not feasible because they will not be fully utilized. It is possible (and very probable) that virtual machines will utilize all of their allocated CPUs at one time or another, but it is very unlikely that they will run at that load for an extended period of time. This is why over-allocating CPU resources is possible. Because CPU resources are limited, if a one-to-one allocation of CPUs to virtual machines is used, the number of VM server CPUs would be much higher than really needed. The idea is to have as many as you need, but not to buy more than is necessary. Sizing the Network Sizing the network is another important component of sizing the VM server farm. The network is used for virtual machine network traffic as well as potentially for storage traffic (NFS). In addition, the network is used for live migration of virtual machines. The performance of the network is crucial in all of these tasks. The network should be sized for peak utilization as well as for steady state operations. Peak utilization will occur during a live migration. A slow network could cause minutes or hours of additional migration time. Sizing the Disks Disk or I/O sizing has become much more difficult since most storage is virtualized now. That is, a disk or array is no longer allocated for a single purpose. Instead, pieces of the same array are allocated to many different purposes and potentially to different organizations and applications. Storage sizing is broken into two main components: sizing for capacity and sizing for performance. Sizing for capacity is easy. In the example shown in Table 5-1, 68GB of storage is required. In the example in Table 5-2, 480GB of storage is required. That’s the easy part. The more difficult part is identifying the performance characteristics needed and sizing properly for them. If the I/O subsystem is undersized, the entire environment might suffer. Unfortunately, sizing for performance involves extensive monitoring and data collection, which often are very difficult to do. What’s more, various storage subsystems provide additional features, such as caching and acceleration, that enhance performance. Each storage subsystem works differently and requires specific Capacity Planning Capacity planning is the process of planning the capacity of the system in order to meet future requirements for increased workloads or adding more business systems. Capacity planning is different from sizing in that instead of dealing with a new system and a somewhat unknown workload, it directly involves the system currently being used, so more information is available. Capacity planning results in either adding more hardware (upgrading) or replacing the existing hardware with new hardware. Whether you’re upgrading or replacing the hardware, the capacity planning exercise requires the same steps as with sizing: data collection, analysis, and design. Unlike traditional servers, Oracle VM provides a straightforward, almost seamless, upgrade path. If the VM server farm needs additional capacity, add a new VM server to the server pool. With the addition of the new VM server, you can migrate virtual machines to the new VM server seamlessly, thus spreading out the load to a new server. If a specific virtual machine needs additional capacity, you can easily add CPUs and memory (as long as they are available on the VM server). In addition, the Oracle VM Server farm requires capacity planning not only for the VM servers, but also for the virtual machines themselves. Capacity planning for the Oracle VM Server farm involves monitoring both the Oracle VM Server itself and the individual virtual machines. As mentioned earlier in this section, the basic steps involved in capacity planning are similar to those involved in sizing: data collection, analysis, and design. Data Collection In the section on sizing, the focus was geared toward collecting data from individual servers with the goal of sizing a virtualized environment to host them. This section is geared toward collecting data from an already virtualized environment. Data collection from a capacity planning standpoint is a little different from a sizing exercise. Here, you already have existing systems that hopefully have long-term monitoring enabled on them. Oracle Enterprise Manager (OEM) Cloud Control is an excellent product for monitoring virtualized environments for capacity planning purposes because of the ability to save years’ worth of data that you can then analyze. assigned to it, or 128 virtual CPUs for HVM. The memory limit for Oracle VM 3.4 varies based on the type of virtual machine: 32-bit paravirtualized guest: 64GB 64-bit paravirtualized guest: 500GB 64-bit HVM guest: 1,000GB Some of these limitations are likely to change in future releases. The limit for a 32-bit system will always be 64GB due to 32-bit limitations. In addition, tools such as the Xen Top command (xm top) will display resource utilization in an existing environment. An example of xm top is shown in Figure 5-3. If only the memory and number of virtual CPUs for the various domains are desired, you can acquire this with the command xm list, as shown in Figure 5-4. These statistics provide enough information to give you a good idea of how the individual virtual machines are performing and an idea of how things are currently running. Unfortunately, the xm top utility does not provide data in a tabular form that can be saved, unlike other OS utilities, such as sar. Analysis In the capacity planning analysis phase, you have to do more than in the analysis phase of the sizing exercise. When sizing, you design the system for the workload you have analyzed. When doing capacity planning, you analyze trends and determine future workloads. This involves extrapolation of existing data. Oracle Enterprise Manager (OEM) Cloud Control is an excellent tool for gathering long-term trend data for analysis. Because capacity planning involves trend analysis and extrapolation, gathering long- term data is absolutely critical. Plot this data and extrapolate it for future workloads. In addition to gathering performance data, you need to gather business requirements. Business requirements should include any information related to future workloads as well as future applications and user counts, such as new call centers opening, the addition of personnel, and so on. The final area of analysis involves how far into the future to look. Some companies prefer to plan hardware upgrades to handle workloads for the next two years; others want to handle the next three or four years. This is a business decision that must be included in the capacity planning calculations. Design The design stage varies based on whether the capacity planning is for individual virtual machines or for the Oracle VM Server. If the design is for a virtual machine, the modifications could be as simple as adding CPUs and/or more memory from the VM Manager. If the capacity planning activity is for the Oracle VM Server itself, you may be adding hardware, but, probably more likely, more Oracle VM Servers. Virtualization provides much more flexibility than traditional servers. Rather than you having to move applications to new servers and/or shut down the server to add new CPU boards or memory, Oracle VM provides the ability to add a new Oracle VM Server to the server pool and then live migrate virtual machines to that new server seamlessly. This is one of the primary advantages of a virtualization environment. Servers, CPUs, and Cores You have multiple options when adding hardware to a virtualization environment. Adding more servers to a server pool by sharing the storage and joining the pool is an easy matter. Once you have determined that a new Oracle VM Server is needed, you can actually add it to the pool without incurring downtime from the pool. Simply add the server to the pool and configure load balancing and/or HA, and the rest is easy. A less costly approach is to add resources to an existing server. You can often do this by adding CPUs with or without multiple cores. There is now an abundance of CPUs with multiple cores—anywhere from two to eight. Multiple-core systems came about as a result the chipmakers’ ability to add more and more components to a single chip. A core is a CPU within a CPU. As integrated circuit density has increased, we now have the ability to add more compute power to the CPU by essentially creating multiple CPUs within the CPU chip. The local terminology for the CPU chip is a socket, whereas the individual compute engines within the chip are referred to as the cores. The multiple-core CPU is an evolution of CPU technology. In the early days of the PC, the Intel/AMD architecture had a single core and appeared to the OS as a single CPU. PC vendors eventually developed multiprocessor systems that enabled more capacity within the same server. Later technology was known as hyperthreading or hyperthreaded CPU. This appeared to the PC as an additional CPU, but, in reality, hyperthreading was a method of taking advantage of CPU instruction cycles that might otherwise be wasted. Even though the OS thought that the hyperthreaded CPU was an additional CPU, it really only provided an additional 30 to 50 percent more performance. The multiple-core CPU is actually an additional CPU built into the die of the chip. So the chip itself has multiple “CPUs” built in. These CPU chips also include the multiprocessor technology needed to maintain multiple CPUs and manage memory access between the chip and the RAM. Some designs even include a memory controller on the chip. In addition to the multicore features, hardware acceleration for virtualization has been introduced to allow virtual machines to run at near native CPU speed. This has helped make virtualization very economical. Regardless of whether additional CPUs/cores or entire VM servers are added to increase the VM server farm capacity, planning ahead is important. Planning for additional hardware when the system is out of capacity is too late. At that point, users will already be complaining. NUMA Technology Most newer CPU chips use NUMA technology. With NUMA technology, you have multiple memory controllers that service a specific set of CPUs or cores. This differs from an symmetric multiprocessor (SMP) system, which employs only one memory controller. Each CPU sees the same memory, so it is symmetric. Storage Storage is fairly easy to plan for from a capacity standpoint but is often difficult to plan for from a performance standpoint. This is because storage administration is often not done by the same personnel who manage the servers and the virtual environment. In addition, there are many factors to consider, such as I/O subsystem cache, storage channels (such as fiber channel switches), and storage virtualization itself. Storage-size capacity planning is best accomplished by keeping long-term monitoring data about the size and usage of your storage system. It is impossible to perform capacity planning tasks by looking at a single data point. To project future growth, you have to have data regarding past performance. Tools such as OEM Cloud Control can assist with this by monitoring both the space usage of the individual virtual machines and the VM Server itself. Because Oracle VM storage uses OCFS2, obtaining space information is not difficult. If no tools are available, it is easy to create a crontab script to collect space information on a regular basis. This will provide valuable information for future capacity planning. will be much easier. In addition, good performance data will assist with performance tuning as well as capacity planning. Summary A lack of proper planning can often lead to a poorly performing system. Through proper sizing, the right hardware can be allocated for the right job. This chapter provided information on how to perform sizing and capacity planning for the Oracle VM Server farm. Included was some information on how to monitor the performance of the VM server farm. Performance monitoring is covered throughout this book as well. In the next chapter, you will learn how to install the Oracle VM Server. In later chapters, you will learn how to install and configure the Oracle VM Manager and OEM Cloud Control plug-in for Oracle VM. CHAPTER 6 What’s New in OVM 3.x racle VM Server for x86 version 3 is the latest virtualization product from Oracle O. These releases continue to improve and enhance the Oracle VM product. As you will see in this chapter, Oracle VM is much improved from the previous version, OVM 2.x. OVM Manager The OVM Manager is the web-based tool we use in order to administer the Oracle VM environment. This tool is robust and is constantly being updated and improved. The OVM Manager consists of a database repository, a web server, and a user interface. The OVM Manager provides an API that allows other applications, such as the command- line interface (CLI), to communicate with it as well. In OVM 3.x, this API is implemented as a Web Services API that provides a REST interface into the OVM Manager. Updated Dom0 Dom0, or domain 0, is critical to the Oracle VM system and has been updated with the latest Oracle Unbreakable Linux Kernel and device drivers. The role of dom0 is to be the interface between the administrator and the hypervisor. Unlike other domains, dom0 has direct access to the underlying hardware. view the job through the GUI at any time and debug a failed job through the GUI. Event Logging New event logging is essentially a history that allows changes made to the OVM system to be logged and reviewed. Events can also alert you to issues or problems with the OVM jobs. Topology Maps From the VM Manager, select a VM either through server pools or via the VM server itself. Right-click on the VM and select Display VM Hierarchy Viewer in order to see the virtual machine hierarchy and dependencies. This gives you a graphical view of the VM components. OSWatcher OVM 3.4 has enabled the OSWatcher utility to run at boot time on OVM servers. The OSWatcher utility collects valuable OS performance information that can be used to analyze the system. OCFS2 Filesystem Oracle VM 3 supports the updated OCFS2 cluster filesystem. As new releases of OVM are released, the version of OCFS2 is constantly being improved. OCFS2 is used to provide clustering for the High Availability features of Oracle VM. RESTful API The RESTful Web Services provide a way of communicating between programs (REST stands for Representational State Transfer). The RESTful calls can use XML, HTML, JSON, or other defined formats. The RESTful API is implemented in the VM Manager and is available via the OVM Manager port. Virtual Appliances Virtual Appliances are pre-built virtual machine assemblies. Examples of these “appliances” include Oracle VM Virtual Appliances for E-Business Suite 12.1.3 and Oracle Big Data Appliance Lite. A Virtual Appliance is a virtual machine (or a set of virtual machines) that performs a specific function or service for a particular application. NVME Support With Oracle VM 3.4.2, NVM Express (NVMe) devices are supported and detected. NVMe stands for Nonvolatile Memory Express. These are essentially flash hardware devices that can be used to provide high-performance storage in the OVM environment. Oracle VM Limitations Oracle VM limitations vary slightly by version. In order to give you a complete picture of these limitations, they are provided and notated where subsequent releases have improved on them. Summary This chapter has provided basic information about the new features in OVM 3.x. Some of the features highlighted here were introduced in OVM 3.0, and some were introduced in later versions. At the time of this writing, OVM 3.4.2 is the current version of OVM. However, newer versions of OVM could be out, possibly including OVM 4.x, by the time you’ve read this chapter. Regardless, many of these features will continue to be the core features of OVM in the future. CHAPTER 7 Disaster Recovery Planning Technet24.ir|||||||||||||||||||||||||||||||||||||||| isaster recovery (DR), as well as the common United States government term D continuity of operation plan (COOP), refers to a set of policies and processes that enables systems to recovery from a failure of the primary data center. Disaster recovery is often confused with High Availability (HA), which in the most simple terms is the recovery from a failure within a data center. When you’re planning for disaster recovery, two important metrics directly drive the time and cost for implementing the disaster recovery plan: the recovery time objective and the recovery point objective. Defining and testing the disaster recovery plan are also critical steps in the continuing operation of a system once the primary data center is considered no longer operational. When you’re defining the recovery plan, it is important to understand that there will be a period when the system is completely unavailable and that some data may be lost. The first critical metric, the recovery time objective (RTO), defines the acceptable amount of time within which the system must be restored after a disaster. The RTO normally involves the time needed to bring the disaster recovery system online, including recovery, testing, troubleshooting issues, and notifying end users. The time needed for leadership to declare a disaster traditionally is not included in the metric. The RTO metric is attached to the business process for the disaster and should not include the resources required to implement the process. Therefore, the process should be simple so that less senior staff can implement the plan. Short RTOs tend to lead to more expensive solutions, because in order to reduce the downtime, advanced technologies such as storage replication are usually required. In cases with a very short RTO, warm standby sites are required. In cases with a longer RTO, a cold site can be maintained, with systems built at the time of the disaster. This results in a lower cost to implement the plan. Many third-party companies provide cold site service, but numerous organizations are now leveraging the cloud to provide a warm disaster recovery site and simply scale from a small footprint (to maintain the replication) to the resources needed to continue operations when a disaster is declared. NOTE A warm standby is a site that is operational as a base level, usually with just the operating systems online and the database in a replication mode. Cold sites usually have no servers online and are built at the time of disaster recovery. The second critical metric, the recovery point objective (RPO), defines the acceptable amount of data loss for the business, with smaller amounts quickly driving up the expense to implement the plan. As with the RTO, the metric is attached to the business process for the disaster and does not include the time needed by leadership to declare a disaster situation. An RPO is dependent on a data synchronization point, which defines the relationship between system activity and is defined as the point in time at which a set of backups exist that, when restored, can be synchronized to the same point of the business process. A simpler way is to compare the database backup to the application server on an imaging application. For example, if the database backup was completed at 2 P.M ., but the images are not backed up until 4 P.M ., then the restoration of services will include several hours of missing data for the application. This is a common mistake that disaster recovery planners make, because assumptions are often made at a large scale without understanding each application’s needs. It is because of this that application-level disaster recovery plans are highly recommended—a one-size- fits-all approach to all the replication requirements often will not lead to the results expected. As shown in Figure 7-1, the combination of RTO and RPO can mean the difference between a low-cost solution and a high-cost solution. A cold disaster recovery site, with a sample RPO of 48 hours and an RTO of 48 hours, would normally be significantly less expensive to implement and support compared to a solution with an RTO of 30 minutes and an RPO of 5 minutes, which would require a warm disaster recovery site with database replication combined with storage replication of application data not stored in the database. This chapter discusses different options as strategies for disaster recovery, for both the Oracle VM Manager and virtual machines within a VM farm. NOTE Although other options for disaster recovery are discussed, whenever possible, the best solution is to leverage Oracle Site Guard for Oracle VM. This solution integrates with Enterprise Manager Cloud Control and provides the best solution for disaster recovery challenges. NOTE Your disaster recovery site can be in the cloud, which is a great option due to the agility of most cloud solutions, the small footprint needed to enable replication, and the ability to expand that footprint when the system is needed. Other technologies such as Active Data Guard and GoldenGate are also commonly used. Active Data Guard is similar to Data Guard, but it enables the standby database to be mounted as read-only, thus providing the ability to run reports against the standby system or backup jobs. This is used to offload these workloads from the production system. Oracle GoldenGate is another popular addition to this strategy, enabling real- time replication to the target system while the target database is mounted as read-write. GoldenGate can also be used for bidirectional replication, turning the disaster recovery solution from an active-standby solution to an active-active solution. For the application tier, a combination of preinstalled and configure application servers and operating system–level replication is often used. Using this method, the application is installed at the disaster recovery site, with critical database files being replicated from the production site. For Linux systems, rsync is commonly used for synchronizing these files from the production site to the disaster recovery site. The advantage of this solution is the speed in which the disaster recovery site can be brought online. You simply bring the database online and then start the preconfigured application servers. CAUTION Not all applications will work with this method. However, applications such as the Oracle E-Business Suite work well because most of the data is stored in the database tier. approach using Site Guard. Also, Site Guard can orchestrate the guest failover with or without automated application recovery logic, while at the same time integrating with Data Guard failovers at the database tier, thus enabling a controlled failover to the disaster recovery site without a guest failover. Unlike a nonintegrated storage replication-based disaster recovery solution, a Site Guard-based solution supports both a planned failover to the disaster recovery site as well as recovery in the event of a catastrophic failure of the data center; application and system owners will need to ensure applications are also protected with reliable and consistent backups. By leveraging Site Guard for Oracle VM, the process of replicating the storage, bringing the repository online, and importing the virtual machines is automated though a single Enterprise Manager instance, which is ideally itself protected with at least a Level 3 Enterprise Manager MAA setup to guide you to a successful end to this solution path. For more information about the available Enterprise Manager Maximum Availability Architectures, refer to the Enterprise Manager documentation. Site Guard for Oracle VM works by adding a management tier to the technology stack with Enterprise Manager. As shown in Figure 7-5, the Enterprise Manager system communicates to the Oracle VM Manager at the primary site as well as the secondary site. Oracle VM Manager is running at both locations, with Oracle VM Servers running at each. An Oracle ZFS storage array is running, and ZFS replication is used to replicate storage between the sites. Although each location has its own server pool, there is no requirement that they be the same types of servers, as long as the CPU architecture is the same. You cannot mix x86 and SPARC, for example. As with the first few examples in this chapter, storage replication is used, and the user can choose to integrate with a fully supported array like the ZFS Appliance from Oracle or to use custom integration with some shell scripts. Both storage replication and OVM management are controlled from the Enterprise Manager system, which will control the process moving forward. Site Guard for Oracle VM ships with several scripts that automate the transition of Oracle VM systems between sites. It also enables automation of both Oracle and non-Oracle workloads, including database, WebLogic, and third- party applications. In this example, there is a single Enterprise Manager system, but it is highly recommended that you use a redundant Enterprise Manager deployment. For more information on Enterprise Manager deployment methods, see- 155389.html. Chapter 26 covers how to configure Site Guard. Although the Oracle VM and Enterprise Manager infrastructures can be implemented separately, the Oracle VM environment must be complete and validated before you attempt to implement the Site Guard solution. The integration of the two infrastructures is the last step in the entire process and should be done only after the Enterprise Manager system is deployed in its highly operational configuration. Summary This chapter addressed the many different options you have for planning and providing a disaster recovery solution for your virtualized business. The key metrics needed to plan for an appropriate disaster recovery plan, RTO and RPO, were covered. You learned several different approaches to planning for disaster recovery, including the three major approaches: cold standby site, warm standby site, and application-level disaster recovery. The benefits using Site Guard as a tool to automate the disaster recovery process were covered. The next chapter discusses Enterprise Manager Cloud Control and how it can improve your private cloud operations. CHAPTER 8 Overview of Oracle Enterprise Manager Cloud Control ver since computers became practical for business use, the industry has experienced E a consistent trend of reinvention. Generally, once every decade, the industry reinvents itself to provide a better return on investment. Consistent architecture advancements have led to the modern concept of cloud computing, including private clouds, public clouds, and hybrid clouds. These advancements date back to the 1960s with the adoption of the monolithic mainframe as businesses started migrating workloads to computers. In the 1970s, the precursor to the modern public cloud— timeshare computing—saw widespread adoption as multiple organizations shared expensive mainframe time, each using a fraction of the mainframe and paying for the resources used. By the 1980s, client/server architectures became popular, with desktop systems processing the user interface and backend servers performing the compute workload, similar to how web browsers generate the user interface and the backend web and application servers perform the primary compute. In the 1990s, an explosion of IT services created more knowledgeable users as they were introduced to the World Wide Web, and the industry started to explore using systems on the Internet to provide services. In the 2000s, Software as a Service (SaaS) companies started to form, and at the same time mainstream IT organizations started to virtualize their commodity servers. This decade also saw companies such as Joyent and Amazon start providing virtual machines under an Infrastructure as a Service (IaaS) model to clients over the Internet. It was in this decade when the term cloud was adopted by larger Internet companies such as Google and Amazon. In the 2010s, the public cloud started to make a significant impact to niche markets, with SaaS companies such as Taleo and RightNow cementing their market positions. At the same time, the IaaS providers set the standard for automated provisioning and easy self-service. This is also when Oracle released Oracle VM 3 and Enterprise Manager 12c (EM12c) as tools for building and managing private clouds. Private clouds also started to become common in the enterprise, focused primarily on IaaS offerings, though many Oracle customers started down the path for private clouds focused on a database tier managed by EM12c. At the end of 2015, Oracle released Enterprise Manager 13c, which coupled systems management with the database, middleware, and application management capabilities that EM12c provided for the cloud. NOTE In “The NIST Definition of Cloud Computing,” Peter Mell and Tim Grance of the National Institute of Standards (NIST) define cloud computing as “a model for enabling ubiquitous, convenient, on-demand network access to a The cloud architecture itself can be placed into one of three major buckets: private cloud, public cloud, and hybrid cloud. In a private cloud, all the components exist within an organization, including the hardware, software, and applications themselves. In a public cloud, a third party owns all the assets and provides the user a subscription to access the resources, usually over the Internet. A third, emerging model is the hybrid cloud, which consists of a mix of private and public cloud technologies. A common example is backing up a database to the Oracle public cloud, where the database and its supporting technologies exist under the control and ownership of the organization, but the backups for the database are provided by Oracle, with Oracle owning the backup target technologies, including the disks, servers, and related infrastructure software. The three types of clouds are summarized in Figure 8-1. As the industry continues to move through this evolution, IT is starting to move most (if not all) of the enterprise into a cloud, including custom-built applications and systems containing the most sensitive data—whether it is to a public cloud, hosted by a third party, or a private cloud, where the business owns and manages the hardware, software, and applications. This complex technology becomes even more difficult to manage when a mix of public and private clouds are deployed in the enterprise. As private clouds are more widely adopted, a common problem faced by the enterprise is how to achieve efficiencies in this new cloud world without custom- building complex management and provisioning systems. Oracle VM plays a key role in enabling the transition to a private cloud. Simply implementing Oracle VM and placing just a few virtual environments on an existing server can significantly increase the administrative workload for IT staff if there is no automation, as the great efficiencies are achieved though the coupling of Oracle VM with the application technologies (database, operating systems, WebLogic, and so on) and the business processes. Any solution that paves the way to a private cloud needs to integrate directly into the hypervisor as well as with the other components of the application stack. For architecting private clouds based on Oracle VM, three common toolsets can be used to build and, in some cases, manage the private cloud: Enterprise Manager, Puppet, and Open Stack. In this example, you can also see any jobs that were run against the virtual machine, along with the event history. Events can be as simple as a threshold being exceeded or a failure of the target. With Oracle VM Manager, the administrator can look to see the status of any particular virtual machine, but when Oracle VM Manager is combined with Enterprise Manager, the administrator can receive notifications when a virtual machine is offline as well as look at detail metrics, such as the top processes for a host, as shown here. Enterprise Manager not only enables self-service capability for IaaS, but it fully enables the complete lifecycle management for databases, virtual machines, middleware and even the application tier. A feature-rich security model provides access to developers, team leaders, database administrators, application administrators, and even end users, enabling each the access required to complete their task. This allows for a single tool to provision all aspects of the application, from the application itself, down through the middleware and database tiers, past the virtualization layer and into the storage and network layers. The second challenge that the enterprise experiences with building and managing private clouds is monitoring them. Although it’s not obvious, monitoring is a critical component to a successful cloud deployment. Monitoring involves not just reporting on the availability of the cloud, but also tracking how resources are consumed. The end goal for any cloud is end-user self-provisioning, meaning the user can easily subscribe to IT services, fulfilling the needs of the applications with user-directed provisioning for the entire technology stack, including the operating systems, databases, middleware, and even the applications themselves, to provide a highly available, scalable, and secure system. A properly managed cloud must adjust to the capacity needs of the hosted applications, while at the same time hold these applications accountable for the resources they consume. Enterprise Manager enables this behavior through the operating systems, which allow Enterprise Manager targets to be assigned a cost center, with usage attributes based on resources consumed, software expense required to license the systems, and labor effort required to support the applications through their lifecycle. This complex billing model is based on the concept of a service catalog, which is a collection of documents and artifacts that describe the services an IT organization provides, as well as specifies how those services are delivered and managed. By defining specific combinations of service-level agreements (SLAs), software mixes, and capacity sizes, the IT organization is better able to define what is being offered to the users. Once a service is defined, the cost to provide that service can be calculated. Then, based on the user’s subscription of services, a report can be generated that shows what resources have been consumed. This is commonly referred to as chargeback by the industry, a concept that has been used since the days of monolithic mainframes. Using a correctly accounted-for chargeback model, IT not only can monitor and report on resource usage, but can also use the data for internal cross-charge to enable funding of large-scale platforms that can host multiple applications, such as Exadata and the Private Cloud Appliance. Just like the mainframes of old, these new systems allow infrastructure to be shared by multiple applications, reducing the overall expense to the organization. With the ability for users to rapidly deploy new virtual environments in the enterprise, there is a need to map the value of the resources to what the users are consuming, not only for accountability but also for resource planning. Without some form of showback, users will eventually consume all available resources in the cloud, with little-to-no business value. This has happened with large numbers of VMs sitting idle or barely being utilized. NOTE Showback is a new term that emerged in 2010 that focuses on the ability of IT to allocate resource usage to departments and cost centers. Enabling this is both a simple and complex task. The mechanics are very simple. You just need to download and install the plug-in via the Enterprise Manager Extensibility feature using the Plug-in Manager. Once it’s installed, you can set up a basic charge plan and assign it to your targets. This will provide you the basic showback capability. NOTE Configuring IaaS and showback/chargeback in Enterprise Manager is covered in Chapters 23, 24, and 25. The complexity comes in configuring the rates for the charge plan to leverage the chargeback capability. This is where you may want to get some help, because calculating your costs can be a complicated task, as you need to factor in not only the capital expenses for your environment, but also the operational expenses and the impact that your SLAs have on the cost model. A common example of the complexity is the CPU cost for a RAC database server. Not only do you need to factor in the hardware expense and the Oracle license expense, but you also need to calculate the labor expense for the senior admin who built and supports the cluster, as well as the more junior admins who usually provide the daily care of and feeds to the database. Often this also includes the expenses for backups, disaster recovery drills, and processes unique to your organization. CAUTION Missing an expense item can quickly result in inaccurate rates for your charge plan. Having the showback/chargeback functionality not only helps make IT more efficient through feedback, but it also may show consumers of resources how to better understand their technology footprint, and can act as a tool to provide a way to reinforce good behavior. An added benefit of Oracle Enterprise Manager is its ability to help manage a cloud for all the components, from infrastructure components like operating systems, storage and hypervisors, up the technology stack to the database and middleware tiers. Enterprise Manager can even expand into the application itself, with prebuilt plug-ins for many different applications. An administrator can even use Enterprise Manager to move database workloads easily between private clouds and a public cloud. This ability to almost seamlessly migrate workloads is being expanded to other components of the Oracle Red Stack. Enterprise Manager can also be used to monitor resources in both private and public clouds, enabling it to act as the single tool for monitoring all aspects of the enterprise, also known as single pane of glass for all aspects of the enterprise. Swift The object store, where objects and files are written to storage. Swift can replicate the storage between active nodes, thus providing redundancy. Keystone The core identity service, which acts as the central directory for all users and privileges. It is commonly integrated with existing Lightweight Directory Access Protocol (LDAP) systems. Neutron Where the network is managed from. Neutron provides IP addresses, VLANs, and more. Nova The core compute fabric manager for OpenStack. Oracle VM can act as a Nova target providing for hypervisor management for the virtual machines for both the x86 and SPARC architectures. Cinder Without block storage, most applications cannot run. Cinder provides the management framework for block storage. Modern storage arrays such as the ZS4 and FS1-2 are often used as the storage arrays. Glance The repository of system images. Used to manage master copies of the system that can be used to clone to new instances, these are often called golden images. NOTE OpenStack is written in multiple languages. Administrators need to understand Python to debug and troubleshoot most API issues. JavaScript and XML are the second most common languages used in OpenStack, but some more exotic components can use other languages. environments, but it does not offer the rich blend of monitoring and provisioning features offered by Enterprise Manager 13c. With Enterprise Manager, a feature-rich private cloud can be up brought online by a single admin in a few days for managing IaaS, DBaaS, PaaS, and even the application tier. A comparable OpenStack deployment can often take weeks to months, as it is customized and technology conflicts are resolved. NOTE Starting in Oracle VM 3.2, the CLI utilities are installed when Oracle VM Manager is installed. Leveraging the CLI enables the administrator to integrate OVM to other systems. Summary This chapter addressed the management challenges faced when building private clouds. You learned how different tools can be used to provision and manage IaaS offerings while at the same time providing feedback to the users to show how their applications consume IT resources. You learned how Oracle Enterprise Manager, OpenStack, and Puppet can be used to build and manage a private cloud. Also, Oracle Enterprise Manager was explored in more detail. The next chapter covers how to configure Oracle Enterprise Manager 13c to manage an Oracle VM install. Technet24.ir|||||||||||||||||||||||||||||||||||||||| PART II Installing and Configuring Oracle VM CHAPTER 9 Installing the Oracle VM Server Network Requirements As networking becomes more complex, the requirements also require more planning prior to building an Oracle VM Server. OVS requires at least one static IPv4 address that does not change between server reboots. Although you can do static reservations with DHCP, it is recommended that you use static IP addresses. You will also need the network mask and the default gateway information, at a minimum, for installation. Many actions performed within Oracle VM Manager (OVMM) require that OVS hostnames are properly resolved. It is highly recommended that you have at least one DNS server configured on your network and that the hostnames for each OVS can be resolved by all the systems within your Oracle VM environment. If you cannot set up a DNS infrastructure, you need to manually add host entries to the /etc/hosts file on each OVS and the OVMM server after you have finished your installation. Make sure you have your DNS server IPs and domain search information handy before installing the OVS. Accurate time is also an important network function, and it is recommended that you also have a Network Time Protocol (NTP) infrastructure configured before installing any OVS. Using NTP will keep the time on all your hosts synchronized, which will help with troubleshooting and is considered a best practice for operational stability. The number of network ports also can be a challenge. Although it is technically possible to run an OVS with a single network interface, you should plan to use more interfaces (usually at least two physical interfaces) connected to different switches for redundancy. You do not want your environment to stop working if one network interface fails, and a simple way to protect against that failure is to aggregate two interfaces in a bond interface. A bond port, as it is called in Oracle VM, can work in active-backup mode with no changes required on the network switch. Optionally, you can configure the network switch to enable an active-active aggregate, which will increase performance because it doubles the bandwidth. During the installation of each OVS, the management interface is configured. During discovery by OVMM, the server management interfaces are set as the default network for all functions. Because the management network is capable of providing all network functions in Oracle VM, including storage and virtual machine traffic, there is no functional need for additional networks. In a small production environment with basic network redundancy, a pair of interfaces is enough: the management network can be run on a VLAN and additional network connections can be made via VLAN interfaces configured on top of the single physical network interface. In larger environments, though, it is often ideal to physically separate the traffic across additional pairs of network interfaces. The main reasons to opt for having multiple physical network interfaces are security and performance: Installation Methods You have several installation methods to choose from. The Oracle VM Server can be installed from a CD-ROM, hard drive, or network. The network option involves installing from a KickStart system. The CD-ROM option is the most common and perhaps easiest to perform because no additional configuration steps are required. NOTE Because of the large number of screens involved in installing the VM Server, only screenshots where action is required will be shown. Other screens will be described but not shown. The POST screen is controlled by the hardware and performs operations such as testing memory and discovering and enabling devices at the hardware level. POST is an important part of the system boot process. The POST process performs operations that are crucial to the configuration and setup of devices. In addition, depending on the hardware installed, POST provides options for configuring devices by pressing a specific CTRL key series during device initialization. For example, during POST, the Fibre Channel host bus adapter (HBA) card might launch a configuration program when you press CTRL-Z or some other key combination. If necessary, configure any devices that require configuration at this stage. It is better to configure the hardware devices before any software is installed. Once POST has completed, the OS installation process begins by booting the Oracle VM installer. During the startup of the Oracle VM installer, you will see additional device configuration steps. This process ends with the Oracle VM boot screen. When OVS boots the first time, you can select to use the ISO to perform a physical- to-virtual conversion, or you can just install OVS, as shown here. Press ENTER to install OVS. Once the installer boots, you will be prompted to verify the boot media, as shown here. Normally, you will select Skip and proceed to the next step. The ISO will now boot into the OVS installation mode, as shown here, and will present dialog boxes that ask you a few configuration questions, such as language, IP, name, and so on. Next, you should read the OVS license agreement and accept the terms. You cannot continue without accepting Oracle’s terms. After you accept the EULA, the installer will run for a few seconds and probe for storage. If you have drives that are not initialized for OVM, the installer will prompt you to initialize the drives, as shown here. Note that if you select “Re-initialize all,” any data on the drives will be lost. This includes LUNs and virtual drives that might have critical data you may not want destroyed. Once the drive is initialized, it is possible to create a custom partition table for the drive, or you can accept the default layout, as shown next. Technet24.ir|||||||||||||||||||||||||||||||||||||||| For this example, a custom partition is being created. As shown next, we have a 200GB drive available, and we will partition the drive as follows: 50GB for / 1GB for /boot 6GB for swap space 147GB unused It is not required that you create a custom partition table, and the default installation will work well for most installations. Also, it is currently not possible to create a custom partition layout if you are installing in UEFI mode. If a partition is unused, it can later be used as a local repository for storing VM virtual disks, ISO images, templates etc. Once the partitioning is finalized, do not forget to write the changes to disk, after selecting OK. The installer will now create the filesystems and configure the boot loader. In this example, the Master Boot Record is selected. Next is the option to enable a kernel crash dump. Kdump is a feature of the Linux kernel that will create a crash dump in the event of a kernel crash. When triggered, Kdump exports a memory image (also known as vmcore) that can be analyzed by support personnel for the purposes of debugging and determining the cause of the crash. Although helpful, Kdump does consume a little bit of RAM and is not supported on OVS when the server is using Non-Volatile Memory Express (NVME) or Fibre Channel over Ethernet (FCoE). As shown, Kdump will not be enabled in this example. Next is the initial network configuration. In the reference OVS, no VLANs will be used, so eth0 is used as the primary management interface. After installation, VLANs and aggregates can be configured. Once the network interface is selected, the static IP address and netmask will be assigned, as shown here. In newer versions of OVS, the netmask can be expressed in CIDR notation. Installation of the OVS is almost complete. Next, the network settings for DNS and the IP default gateway are set. The next screen allows the DNS domain to be set. This is useful because, once set, the FQDN is not required to correctly resolve names in DNS. Although many sites will use the local time zone, it is not uncommon in larger geographically diverse organizations for GMT to be used instead; this way, the timestamps in all log files will reflect the same time zone. The NTP settings are made via the OVMM interface later. Setting the passwords is an important step that should not be done hastily. In OVS, two passwords are set during installation, the first being the OVM Agent password, as shown here. This is the password that OVMM uses to authenticate to OVS servers. The second password is the root password for the OVS server, which is set in the screen shown here. Next, the OVS system is installed, as shown here. This will take only a few minutes. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Once the installation is complete, the system will reboot. It is important to remove the media from the server before rebooting. If you’re using ILOM, do not forget to “unpresent” the ISO file. If you’re using physical media, be sure to remove the media from the optical drive. Once the system is back up and running, you should see the OVS login screen, shown next. Unlike in older versions of OVS, you will not need to do anything else from the OVS server. All remaining configuration is performed from the OVMM. Summary This chapter provided instructions on how to install the Oracle VM Server. There really isn’t much work to installing the Oracle VM Server. Although you have several ways to do it, the installation process simply formats the disks and adds the software, including the VM Agent. Once the Oracle VM Server has been installed, you need to configure it as a server pool master, utility server, virtual machine server, or all of the above. Configuring the Oracle VM Server is where the real work begins, as discussed in the next few chapters. CHAPTER 10 Oracle VM Concepts NOTE If you are using a minimal installation of Oracle Linux, you will likely not have all the required packages installed. The OVMM runs additional checks for the required software packages. If a required package is missing, the installer might exit with a warning message, and the missing package will need to be installed. To install a missing package, run yum install -y followed by the package name to install it. The following example installs Perl: # yum install -y perl The Oracle VM Manager system can be either a physical server or a virtual machine. A virtual machine is very capable of handling the workload of the Oracle VM Manager. In a fully virtualized environment, it seems like a waste to dedicate a server to just running the Oracle VM Manager. The contrary argument to using a virtual machine to host the Oracle VM Manager application, however, is that one should never monitor a critical system from within that system. This idea applies not only to the VM Manager, but potentially to Oracle Enterprise Manager (OEM) Cloud Control as well. If an OEM Cloud Control system is used to manage the virtual environment, installing OEM Cloud Control on a separate host system that is not part of the Oracle VM environment makes sense. Oracle recommends that Oracle VM Manager never run as a guest operating system from within the Oracle VM environment it is managing. For maximum uptime, install Oracle VM Manager on two separate physical systems, each running Oracle Clusterware. This allows for maximum uptime and reliability. Keep in mind that Oracle VM servers, guests, and High Availability features continue to function whether the Oracle VM Manager is running or not. A common use case is to run Oracle VM Manager on a virtualized Oracle Database Appliance, along with Enterprise Manager 13c, as shown in Figure 10-1. to host the Oracle VM Manager for one server pool in another server pool (hopefully, in a different part of the data center). The final option is to host the Oracle VM Manager in a different building from the VM servers. This option provides the most protection. If absolute uptime is required for the Oracle VM Manager, install it on physical hardware running Oracle Clusterware. This will allow for failover to occur in the event of a system failure, and by not running Oracle VM Manager in a virtual environment, the loss of that environment will not affect it. Although the createOracle.sh script can add the rules, many administrators prefer to manually add them, knowing some of the tools will help troubleshoot issues in the future. On Oracle Linux 6.X, modifying the firewall is accomplished by using the chkconfig and iptables commands. All of these commands should be run as the root user on your OVMM. You can check to see if the firewall is on by looking at the output from the iptables - L command. If iptables is running, there will be several rules displayed. Rules are organized into chains, each representing a specific type of data flow. The INPUT chain represents traffic coming into the server. The OUTPUT chain represents traffic leaving the server. The third chain, FORWARD, is where packets are routed to another interface on a server, commonly used for network address translation (NAT) rules. On a default installation, all INPUT traffic is rejected, other than TCP port 22 (ssh) and ICMP requests (ping). All OUTPUT traffic is allowed, and there are no FORWARD rules. This is seen in the following example: If the firewall is not running, the output will look like this: To disable the firewall, you can stop it using the command service stop iptables: While this stops the firewall, at reboot the firewall will automatically restart. In Linux 6, you can use the command chkconfig $SERVICE_NAME –list to see the run state that each service runs: Technet24.ir|||||||||||||||||||||||||||||||||||||||| In this example, you can see the iptables will run when the server is in run states 2, 3, 4, and 5. To disable a service from starting at boot, you can use the command chkconfig $SERVICE_NAME off. The following commands illustrate how the iptables service is disabled (chkconfig iptables off) and verify that at reboot the service will not start (chkconfig iptables –list): Not all environments will allow the Linux firewall to be disabled. In this case, you will need to add the required ports into the OVMM. This is done using the iptables command to add in new rules that accept requests on specific ports. On a standard installation, you will need to add ports 7002, 123, and 10000. First, let’s add the ports to the existing iptables chain: Once the rules are added, they will not be reenabled on reboot, unless they are saved. This is done by using the service command to save the configuration: Installing VM Manager Installing the Oracle VM Manager is not a difficult process. Once the system has been properly configured for the installation, the installation itself is fairly straightforward. Only when you get to the stage where you are configuring Oracle VM does the complexity begin. Manager Oracle recommends a minimal (default) Linux installation be used for the Oracle VM Manager. Install Oracle Linux (OL) or Red Hat Enterprise Linux with the default packages. In addition, allocate hardware resources as shown earlier in this chapter. If you did not create a /u01 filesystem with your initial installation, you should create that now, allocating at least 20GB. Next, transfer the OVMM ISO file you downloaded from Oracle to the OVMM. In this example, the 3.4.2 build 1384 is being installed from the source ISO file ovmm-3.4.2-installer-OracleLinux-b1384.iso. Although future versions will have a different filename, the core process is the same. You can download the OVMM ISO from the Oracle Technology Network site:. The loop option specifies that is a special loopback mount, and the ro option mounts the ISO as read-only. This method is used for our example: Once the ISO image has been mounted, change directory to the mount point. You will run the installation from here. createOracle.sh. As root, run the command. This command will not stop on minor issues, such as the oracle user already being created or firewall rules already being in place. Although the command sets up an oracle user, you will need to manually set the password for the user. You now have four options: Install, Upgrade, Uninstall, and Help. Select 1 to continue with the installation: The password will enforce some basic security. It must be between 8 and 16 characters, have at least one uppercase letter and one lowercase letter, and contain one numeric or special character. For example, Welcome! will work, but welcome1 will not. Enter 1 to continue the installation. Depending on the speed of your system, it will take anywhere from 10 to 45 minutes to complete the seven steps. This is a good time to save the password you set. This password will be used for all components of the Oracle VM Manager, including the WebLogic admin password. If your installation has any issues, several logs will be available to help you resolve any issues. The first log to check is the Oracle VM Manager installation log file. Usually, this log can be found in /var/log/ovmm/ovm-manager-3-install-date.log. However, if the installer is unable to create this directory and file for some reason, such Using these commands, you can stop, start, restart, and check the status of each service. In order to affect service, pass the option you wish to use—either start, stop, restart, or status. The following example stops and then starts the OVM CLI, followed by checking the status: Because they are part of the Linux services, they are started and stopped automatically with the system. You can control this using the chkconfig command, just as you would with the network service. These parameters control the automatic backups and the Java virtual machine (JVM), as described in Table 10-3. Normally, you will not need to edit this file, unless you are changing the UUID of the installation. When backing up your Oracle VM Manager system, you need to make sure that both configuration files are backed up. To restore the database as the oracle user, use the RestoreDatabase command located in /u01/app/oracle/ovm-manager-3/ovm_tools/bin. Here’s an example: The RestoreDatabase script expects the name of the directory for a particular backup directory, as seen in the /etc/sysconfig/ovmm configuration file. You do not need to specify the full path to the backup directory because this is already specified in the DBBACKUP variable. The RestoreDatabase script performs a version check to ensure that the database version matches the version of the database from which the backup was created. If there is a version mismatch, the script exits with a warning because this action may render Oracle VM Manager unusable. It is possible to override this version check by using the --skipversionchecks option when invoking the script. This option should be used with care, as version mismatches may have undesirable consequences for Oracle VM Manager. Restart the database, the Oracle VM Manager, and the Oracle VM Manager CLI: Because the certificates required to authenticate various components, such as the Oracle VM Manager Web Interface and Oracle VM Manager CLI, are regenerated during the new installation and the mappings for these are overwritten by the database restore, it is necessary to reconfigure the certificates used to authenticate these components. Run the following commands to reconfigure the Oracle WebLogic Server (remember that the weblogic user password is the same password used when performing the initial installation): If you moved Oracle VM Manager to a new host, you must generate a new SSL key, as follows: Restart Oracle VM Manager and then run the client certificate configuration script, as follows: Next, you will need to reconfigure the OVMM WebLogic instance with the correct certificate. This is already scripted with /u01/app/oracle/ovm-manager- 3/bin/configure_client_cert_login.sh. Run the script as follows: Optionally, you can append a path to the certificate. This is helpful when you’ve used a CA other than the default Oracle VM Manager CA to sign the SSL certificate. The script requires that Oracle VM Manager is running, and it prompts you for the administrator username and password that should be used to access Oracle VM Manager. The script makes changes that may require Oracle VM Manager to be restarted: Once Oracle VM Manager is running, you will need to go to the Servers and VMs tab and perform a Refresh All on your existing server pools. This is covered in Chapter 14. Summary This chapter covered the tasks necessary to configure a Linux system to prepare for installing the Oracle VM Manager. This is often the preferred method for installing the Oracle VM Manager. In addition, the chapter covered how to manually stop and start the Manager and its components. This chapter also covered the tasks necessary to perform regular maintenance on the Oracle VM Manager, including how the automatic database backups can be modified and how to restore the Oracle VM Manager. The bulk of the work in setting up the Oracle VM Manager environment is in the configuration of the Oracle VM Manager itself, which is a topic covered in later chapters. CHAPTER 11 Installing and Configuring the Oracle VM CLI Again, you can use either the /sbin/service command or the service command. An example is shown here: Starting and stopping the CLI is done on the OVM Manager itself. As you will see in the next section, running CLI commands can be done from anywhere. If you are performing multiple commands, you can use the SSH keepalive option, as shown here: Alternatively, you can set the keepalive in the ~/.ssh/config file. The ~/.ssh/config file can be useful for many different parameters, including the hostname, port, and user commands. A sample ~/.ssh/config file is shown here: In this file, I have configured the ovmcli entry as an alias for my ovmmanager system and included the port and username for the OVM Manager user. I also included the keepalive. The ~/.ssh/config file is a very useful option. Here is an example of one: In order to enable password-less connectivity to the OVM Manager, you can use SSH keys for connectivity. This creates a connection without using a password, and it takes advantage of the keepalive feature. NOTE Whenever the CLI or Manager is restarted, you must pass in the OVM Manager password again. Therefore, you cannot rely on this for connectivity every time. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Once you have set up the SSH keys correctly, you can make connections without the use of a password: or Once you have connected to the CLI, you can begin running commands. Commands can be included with the ssh command itself. An example of running list vm via the CLI is shown here: In the next sections, you will see how to run basic commands via the CLI and how to script commands to run in the CLI. Basic Commands A number of commands can be used with the CLI that allow you to perform almost all the functions you can do within the OVM Manager—and in some cases, the CLI allows for much more flexibility and functionality. In addition to the functions these commands provide, they also allow you to get help with the CLI. Let’s look at the help functions of the CLI before we discuss the informational commands and functional commands. Help Commands You have a few ways to get help and information about the commands available within the CLI. For example, the help command provides information about the commands themselves: This gives you an idea of the commands available. In order to get detailed information about these commands, you can use the ? command. An example is shown here: Using the ? command, you can get detailed information about the commands listed. For example, to get additional information on the list command, use list ?, as shown next. (Note that because of the number of options, the complete list is not shown.) In the next section, you will see how to use some of these commands to get information about the OVM system. The two most important CLI commands you need to know are help and ?. Informational Commands The informational commands are list and show. The list command is used to display a list of all of the objects of a particular type. The show command provides detailed information on a specific object. For example, list server lists all of the servers: or show server id=<id>, as shown here (note that only the first 25 lines are provided): The list and show commands can be run followed by the ? qualifier in order to see all of the objects they can operate on. These and a few other commands provide information on the state and configuration of Oracle VM. The other commands are used to actually configure Oracle VM. Functional Commands The functional commands let you perform tasks in OVM such as shut down, start up, create, and so on. The basic functional commands include add, create, delete, edit, set and remove. These commands allow you to perform functions on the OVM Manager that affect objects in the OVM server pool. Let’s look at some of these commands. Add The add command is used to add resources to an object. For example, the The difference between add and create is that the add command takes an object that already exists and assigns it to another entity, whereas the create command is used to create an object from scratch. Objects that can be added include the following: For help on these objects, use the command add <item> ?. For further information on the available options, continue to use the commands provided from the previous command using ?. Here’s an example: In addition, you can find very good documentation on the OVM CLI. Create The create command is used to create new objects in OVM. The create command can take a few or many options, depending on what you are trying to create. For example, create vm takes (but is not limited to) the following parameters: NOTE This command should appear all on one line. If you need to use multiple lines, use \ as the line-continuation character. Delete The delete command is used to delete existing objects in OVM. The delete command varies based on the object that is being deleted. Here’s an example: This example deletes the virtual machine created in the previous example. The following are the objects that can be deleted: Edit The edit command is used to modify existing objects in OVM. More objects can be operated on with the edit command than with create or delete. The edit command takes a variety of options, depending on the type of object being edited. Here is an example using edit vm: The edit commands provide many different options for configuring and using OVM. The preceding example shows how to change the memory allocated to the VM. Here’s a list of the objects that can be edited: For help with these objects, use the command edit <object> ?. The remove command provides many different options for configuring and using OVM. Here’s a list of the objects that can be removed: For help with these objects, use the command remove <object> ?. Migrate The migrate command is used to migrate a virtual machine to a new server or server pool. Here is the syntax of the migrate vm command: This command migrates the named virtual machine to the server or server pool you specify. Clone The clone parameter is used to clone a virtual machine. Here is the syntax of the clone vm command: This command clones the named virtual machine to the server or server pool you specify. Scripts enable you to use variables, conditionals, and looping in order to automate repetitive tasks. In order to use a script, it is often best to contain the CLI within a single-line command. This is done by appending the cli command to the end of the connection screen. Here’s an example: NOTE ssh ovmcli uses the definition in the .ssh/config file. It is the equivalent of ssh -l etwhalen ovmmanager with a slightly shorter syntax. You can add onto this by passing the output of the ovmcli command to filters in order to pass this to other commands: You are probably getting the idea now of how to start using the OVM CLI in scripts. NOTE Whitespace and special characters can sometimes be a problem when scripting in bash or shell. The \ character can be used to delimit a special character. Here is an example: With the single quotes, the spaces are maintained and processed as part of the name. NOTE I am using the same shortcut from my .ssh/config file. The ssh ovmcli command is equivalent to ssh etwhalen@ovmmanager -p 10000. SSH keys are used in lieu of passwords. Technet24.ir|||||||||||||||||||||||||||||||||||||||| NOTE I am using the same shortcut from my .ssh/config file. The ssh ovmcli command is equivalent to ssh etwhalen@ovmmanager -p 10000. SSH keys are used in lieu of passwords. The output of the Python script is essentially the same, with some cosmetic differences: Cloning VMs Cloning one or more VMs is easy with the OVM CLI. Simply put the new VM names in a loop, as shown here: Other Scripts In addition to the scripts we have covered thus far, you can create other scripts for stopping, starting, listing, and cloning VMs as well as specific components. You can even write scripts for creating RAC clusters by adding shared disks to newly cloned VMs. What you do with CLI scripting is totally up to your imagination. Summary In this chapter, you have seen how to use the OVM CLI and some basic commands to create scripts that serve useful functions. We looked at examples for scripts written in shell as well as scripts written in more sophisticated languages such as Python. The chapter not only provided examples but also illustrated the power of command-line processing in OVM. CHAPTER 12 Configuring the Oracle VM Server Network he two most important components of the Oracle VM server that are most likely to T be modified on a regular basis are network and storage. The network configuration tends to change as the requirements for network bandwidth and subnets change. Also, within most environments, the need for storage always grows and never shrinks. Network requirements typically change at the virtual machine level, but the Oracle VM Server network does not need to change very often, except as needed to support new virtual LANs (VLANs). The configuration and functionality of the network are important because the network is the foundation for accessing virtual machines. By making sure that network capacity has not been exceeded, you can optimize the performance of the virtual machines. This chapter covers the Oracle VM Server network—how it is configured and how it is managed. Once it is configured and working properly, making significant changes is often unnecessary. The VM Server network configuration requirements are simple to manage once you understand the basics of networking technologies—mainly bonds and VLANs. NOTE The most common addition to an Oracle VM Server network is VLANs. VLANs are used at the hardware switch layer, however, and do not normally affect the physical configuration of the Oracle VM servers. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Oracle VM Networking The networks used by virtual machines are run through Xen bridges or switches. The Xen interface is the connection between the virtual world (virtual machines) and the physical world (your company network). You can configure Xen bridges in a number of different ways, including bridged, NAT, and routed. Although you can configure all these network types and they will work, only a bridged or switched network is supported by Oracle. Routed and NAT networks are usually found in smaller, home network environments, due to most enterprise environments providing these services as dedicated devices such as firewalls and routers. The bridged network is most commonly found in server environments. Because Oracle VM is designed for the data center, bridged networking is typically the network type of choice, with the switched configuration being popular in more security conscious environments. There are four key network concepts to understand: Network Bonding A degree of redundancy at the network level is often desirable. With redundancy, the Oracle VM Server system continues to operate even in the event of a single network failure. Common practice is to use network teaming, or bonding, to provide this extra bit of protection. Network teaming and network bonding are just different terms for the same thing: network redundancy. For the sake of this chapter, the term network bonding is used to describe this function. If you use active switching, you can use network interface controller (NIC) bonding to increase the throughput of a VM network. For instance, if you have many virtual machines, a single 1GbE network connection might not provide enough throughput. By increasing the number of NICs in the bond, you increase the throughput. Although having multiple 1GbE ports sounds like a good idea, each communication path between a VM and another system on the network is still limited to a 1GbE connection, even if the aggregate is more than a single 1GbE pipe. This is one of the reasons why 10GbE networks have become so popular. One advantage with Oracle servers is that almost all models have four built-in 10GbE ports. In addition to the physical interfaces in the network stack, each physical interface can be combined in what is called a bond. When you install an OVS, bond0 is automatically created on it, with the management IP already allocated. As shown in Figure 12-2, you can see the same bond0 on a newly installed server. You can navigate to this page by clicking the Servers and VMs tab and then selecting the physical server. From there, select Bond Ports from the Perspective drop-down. In this example, the server ovs3.m57.local was assigned an IP address of 192.168.200.26. Although a bond with a single port works, adding a second port to the bond will provide several advantages. To understand these advantages, we first have to look at the type of bonds available: management bonds, especially when live migration traffic traverses the same bond. This bond mode does not work at all with Xen bridges that are associated with a VLAN device, so it cannot be used as an interface for NetFront devices on Oracle VM guests. To modify bond0 to a Load Balanced configuration, highlight bond0 from the Bond Ports perspective view and then click the edit icon, as shown in Figure 12-3. Next, you will see a dialog (shown in Figure 12-4) that details how the bond is configured. This dialog includes the following information: To add a port, simply double-click it. In the example shown in Figure 12-5, we see eth1 being added to the ports and Bonding being set to Load Balanced. Additional bonds can be created. In this example, bond1 will be created on two Oracle VM servers, using both Link Aggregation and VLANs. Prior to the bond being configured, the switch was configured and wired to ovs3.m57.local and ovs4.m57.local, with ports net2 and net3 on the switch side being configured into a single bond per pair. In addition, VLANs 200–210 were configured to work on the aggregates. NOTE Although Oracle VM calls this a “bond,” the method can go by a variety of names, including trunk, link aggregation, NIC teaming, and EtherChannel. The end result is basically the same when several physical interfaces are combined into a single logical interface. The next bond device, bond1, will be created on both OVS3 and OVS4, with link aggregation being used for the bond mode, and the VLANs riding on top of the new bond1 device. On both servers, bond1 will be created. You do this by going back into the Bond Ports perspective on both nodes and using the “+” icon to add a bond. Because VLANs will be used, no IP address is added to the bond. When this is completed, the dialog should look like Figure 12-6. After bond1 is added, it should show in the list of bond ports, and if the switch is configured correctly, it should have a status of “up,” as you can see in Figure 12-7. Network VLANs Often, when building large or complex private clouds, the number of networks that virtual machines need access to will exceed the number of physical ports of the Oracle VM Server. In order to support this, the network industry created a standard (IEEE 802.1Q) that allows for multiple virtual local area networks (VLAN) to share the same physical cable. These VLANs also can share a bonded connection, just as created in the previous section. The next step will be to create the initial VLANs. VLANs allow multiple networks to use the same physical connection. This enables efficient use of the network ports. To enable VLANs on the OVS systems, go to the Network tab in OVMM and select the VLAN Interfaces option. Initially, Oracle VM will not create any VLANs, so the system should show empty, as you can see in Figure 12-8. To create the VLANs, select the green “+” symbol, which will start a guided process for creating them. First, we need to identify the ports the VLANs will use. In this example, we select bond1, as shown in Figure 12-9. Next, the VLANs will need to be created. A VLAN is identified with a number between 1 and 4094. The network administrator will know the VLAN numbers and should inform the OVM administrator what numbers to use. In our example, we will create VLANs 200–210 in bulk by entering in the numbers and clicking the Add button. Figure 12-10 shows the dialog after these VLANs have been added. The final part of the process allows each VLAN to have an IP address set for each server, as well as a unique MTU set. Having an IP address on the OVS makes troubleshooting VLAN configurations much simpler, so this is highly recommended. If you are working with a large number of VLANs, it is recommended that you only add a few at a time, because the complexity can quickly become difficult to manage, as seen in Figure 12-11. Once you click Finish, an OVM job will run, adding the VLANs to all the Oracle VM servers that were selected. Depending on the number of VLANs added, this can take several minutes. Once the job completes, the VLAN Interfaces screen will list all the available VLANs, as shown in Figure 12-12. NOTE As mentioned earlier, Oracle VM is designed as an enterprise server virtualization product. Bridged networks (the default network type) and switched networks are the only supported network types in Oracle VM. Other networking types such as NAT and routed are really intended more for the home or personal network. Although NAT and bridged networks can be configured manually in Oracle VM, they are not recommended or supported and therefore will not be covered in this book. systems meant for multiple users, DHCP networking can be difficult to manage. However, if the Oracle VM server uses DHCP for networking, the virtual machines should use DHCP as well. Configuring Networks Once the bonds and VLANs are created, the next task is to assign a role to each virtual network. As shown in Figure 12-13, each network can be used for the following five predefined roles (under “Network Channels”): Server Management This network role is used for management access from the OVMM to the OVS systems. The traffic should be routed (NAT access to this network is not supported). Only a single network can have this functionality on a single OVM server; however, you can have different management networks across different OVM servers. Cluster Heartbeat This network role is used by the OVS systems to communicate via TCP packets. The cluster is sensitive to network stability and should not be shared with roles that can cause spikes in network traffic, such as Live Migrate and Storage. The network with the heartbeat should have some redundancy. Usually this is the same network used for Oracle VM Server management. This cannot be changed once the server pool has been created. Live Migrate The Live Migrate network role is used to migrate virtual machines from one OVS to another in a server pool without a VM outage. In most environments, live migration should not be occurring frequently because it could cause interruption to other services, particularly the cluster heartbeat. As a result, configuring a separate network for this purpose can improve the performance and availability of the VMs and also prevent cluster heartbeat timeouts due to heavy network traffic. Storage Although the storage network role has no specific functionality, it allows the administrator to quickly identify what networks are used to connect to storage. Virtual Machine Network with this functionality allows VMs to have access to it. This is the most commonly used role for networks. Enabling this role on a network will automatically create a Xen bridge for the network. Adding a new network is a straightforward task. Click the green “+” icon from the Networks screen to start the guided process, as shown in Figure 12-14. You have two paths you can take here. The first path is to add a network using physical ports on multiple OVM servers (either physical ports or bonds). The second path is just for single servers. You can enable a local network that allows VMs to communicate between themselves only on that server and no other systems. For our example, we will add a new VLAN, so the default (first) option will be chosen. VLAN 200 will be the name, and it will be configured for VMs and flagged for storage as well. This is shown in Figure 12-15. If physical ports are being used, they can be added in the next screen. In most cases, though, the network team will use VLANs, so this step will remain empty, as shown in Figure 12-16. Next, click the green “+” button and select the physical server that will have access to the VLANs. You must highlight the server to see the VLANs available to it. In the example shown in Figure 12-17, the server ovs3.m57.local is selected and the VLAN200 bond is checked. This single VLAN/server combination will now be added. This same process needs to be repeated for all Oracle VM servers that will be hosting VMs using this network. In the example shown in Figure 12-18, both ovs3.m57.local and ovs4.m57.local have been added. Click Finish. The Network tab will now list network VLAN200, as shown in Figure 12-19, with both storage and virtual machine access. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Here, the range can be edited. Be careful making changes outside of the 00:21:f6 range, because it is possible to accidently create a duplicate MAC address. The most common use case is to reduce the available range within the existing range—usually one subset per each Oracle VM instance in the enterprise (see Figure 12-21). CAUTION Having a duplicate MAC address is very bad and will cause all sorts of difficult-to-resolve issues on a network. Be very careful when randomly selecting a MAC address range. Summary This chapter covered the configuration of the Oracle VM Server network, starting with Xen networking and ending with the configuration of additional virtual network adapters. You do not need to do a lot of work to configure the network, from a general administration standpoint. As mentioned in this chapter, you configure only the first network adapter as part of the initial installation and then configure other adapters after the Oracle VM server is running. During the normal course of operations, changes do not typically need to be made—only if new adapters are added or networks are changed due to business requirements. CHAPTER 13 Configuring the VM Server Storage Technet24.ir|||||||||||||||||||||||||||||||||||||||| lthough data cannot move without the network, there is no data without storage, A which is arguably the heart of a cloud. To support this, Oracle VM has one of the most powerful storage systems available, enabling flexibility in a virtualized environment and performance almost equal to bare metal. The administrator has a choice of many storage options, as shown in Figure 13-1. These range from Network File System (NFS) shares mounted from a Network Attached Storage (NAS) system, to local storage on an OVS, cluster filesystems using block storage logical unit numbers (LUNs) from a Storage Area Network (SAN), and iSCSI and LUNs directly allocated to a virtual machine to bypass the overhead of the filesystem. Each option has its own advantages and disadvantages, but the flexibility of the Oracle VM storage system allows the administrator to use each of the options as best fits the needs of the data. NFS solutions present a filesystem from the Network Attached Storage (NAS) device that allow the NAS to manage the filesystem that the Oracle VM cluster sees. NFS-based solutions are the easiest to configure, yet traditionally have less than optional performance. Block storage, using Internet Small Computer System Interface (iSCSI) or SAN technologies, uses a cluster filesystem that can improve on the performance seen with NFS, but it has some additional complexity due to managing the LUNs. Local storage is simple to use, but it limits the virtual machines to a single host. Finally, directly allocated storage has the best performance, but it increases the complexity of the configuration. As with any resource, often the user will need more allocated—and this most often occurs with disk resources. When the time comes, adding more resources is necessary. This chapter explains the storage options and how to manage them. The administrator will also use storage to configure an Oracle VM server pool by creating a filesystem, usually on shared storage that’s either NFS or block-based storage. This can be done using local storage on an Oracle VM server (OVS); however; if you plan on enabling High Availability (HA) by creating a VM cluster and a shared storage system is not configured, you need to actually migrate to a shared storage solution. This is the reason why most deployments use shared storage, with a mix of NFS and block-based storage. In addition to HA, shared storage using a Storage Area Network (SAN) or Network Attached Storage (NAS) offers additional benefits such as Enterprise Storage Management, which provides the ability to add more storage easily, as well as redundancy, backup/restore features, and other enterprise storage features. When planning the storage for the Enterprise VM farm, carefully consider the additional features available with SAN and NAS storage. comes at a lower price. Both SAN and NAS storage are suitable for Oracle VM and, depending on the brand and model, offer a high level of performance. NAS storage arrays often support two different varieties: iSCSI and NFS. The iSCSI protocol (technically a block technology) provides network storage for the Oracle VM server that looks like a disk drive and must be configured with OCFS2 in order to be clustered. A Network File System (NFS) is inherently shared because the storage is presented to the Oracle VM system with the filesystem being managed at the storage system, not the host. If a shared server pool (cluster) is desired, all storage used for virtual machines must be shared. Without shared storage, a cluster cannot pass the virtual machines between the different nodes. This is crucial for both HA and live migrations. In addition, the Oracle VM servers must be configured as a server pool with shared storage. storage using the OCFS2 filesystem. Local storage can also be created using an unused partition on a local disk drive. When you’re using a NAS with NFS, the filesystem that’s used is determined by the backend storage. To the Oracle VM system, it is considered NFS storage. How the storage is configured at the hardware level does not vary based on whether it is used in a cluster. It does vary, however, when the VM Server configuration layer is in a High Availability cluster, because all of the storage must be visible by all Oracle VM servers. The next sections cover hardware connectivity using multipath storage. Redundant Storage Redundant storage is designed to be highly available because it avoids a single point of failure. It accomplishes this by having at least two of each component, including the path between the storage array and the OVS system. This way, even if a single component fails, access to storage is retained. Redundancy is accomplished in a number of different ways—through multiple paths to storage, Redundant Array of Inexpensive Disks (RAID) disk storage, and multiple power supplies. Most of these components are transparent to the installer; however, creating redundant paths to storage requires intervention by the storage administrator. Multipath storage requires both hardware and software configuration on the VM Server system itself. NOTE In order to support High Availability and live migration, the storage must be visible by all the VM servers in the cluster, which involves both hardware and software configuration, which is detailed in these next sections. Depending on the type of storage, the configuration differs slightly. The various configurations are covered in the next sections. WARNING The NFS root squash parameter must be disabled on each share used by Oracle VM. This is a security feature that will disable root access to the share. Also, verify that each OVS system can ping the NAS device. A simple ping test, ping $NAS, is all that is required, as shown here: Oracle VM does not need to use all the mounts exported from the NFS server. You can also verify what NFS shares are visible from the OVS by using the showmount -e $NAS command, where $NAS is the name of the NAS device: CAUTION If the showmount command does not display the exported filesystems, the NFS mount cannot be used by Oracle VM. With some arrays, iSCSI may need to be used when the array is not capable of displaying exported mounts. Next, you will need to discover a new NAS device (see Figure 13-2). From the Oracle VM manager, access the Storage tab and then highlight the File Servers option. Click the folder icon with the green + sign to add a new NAS. This displays the dialog where you can select the storage plug-in. For NAS devices, use the Oracle Generic Network Filesystem plug-in. For the example shown in Figure 13-3, the array name is Generic NAS and the hostname is nas10g.m57.local. NOTE Although the generic plug-in will work for block storage, using the vendor- supplied plug-in (if available) will provide additional automation and features such as snapshots, LUN creation, cloning, and more. At the time of this writing, plug-ins are available from Oracle for the Oracle ZFS Storage Appliances. Additionally, plug-ins are also available from EMC, Fujitsu, and Hitachi. Contact your storage vendor for assistance obtaining the plug-in for your array. The system will use uniform exports because all OVS systems, regardless of pool membership, will use the same export from the NAS to the OVS. If different server pools will use different NFS exports, then the Uniform Exports box should be unchecked, and access groups will need to be configured after new NFS filesystems are discovered for the first time. This is most often done when a production pool uses a The last step is to select what filesystems from the NAS will be used by Oracle VM (see Figure 13-5). Because not all filesystems from a NAS could be used for virtual machines, you should select only the filesystems to be used by Oracle VM. There is also a handy option for filtering on specific patterns seen in the name of the filesystem. Normally, if all operations are performed via Oracle VM Manager, it is unlikely that this information will become inconsistent; however, manual updates or modifications may result in an inconsistency within Oracle VM Manager. For instance, if files are manually copied into a repository via the filesystem where the repository is located, then Oracle VM Manager is unaware of the changes within the repository and is also unaware of the changes to the amount of available and used space on the filesystem where the repository is located. When the repository is refreshed, Oracle VM will discover the changes made, including any new ISO files, templates, or VMs added manually outside of the normal process. This discovery is also useful when performing disaster recovery operations, because the repository can be replicated and then discovered at the disaster recovery site. Once the NAS filesystem is refreshed, it can be used for a storage location by Oracle VM. This includes use as a valid location for the server pool metadata and for storage repositories. VM, thus bypassing the storage repository. It does add in some additional layers that need to be configured, mainly concerning the concepts of initiators and targets. The initiator is the storage client, whereas the target is the provider of the storage. With Oracle VM, all network interfaces have iSCSI initiators configured by default; it is the role of the Oracle VM admin to make sure that storage network traffic and other network traffic do not conflict. See Chapter 12 for more information on this. NOTE Although, in general, iSCSI performs better than NFS, there is one notable exception using a technology called Direct NFS (dNFS). If you are running a database with a NAS device, using dNFS for your database mounts should perform better than iSCSI. The exception occurs when dNFS is used in combination with Hybrid Columnar Compression (HCC). HCC over NFS or dNFS is only supported with Oracle ZFS storage arrays. The generic iSCSI Oracle VM Storage Connect plug-in allows Oracle VM to use virtually all iSCSI storage providers. As with NFS arrays, the vendor-specific Oracle VM Storage Connect plug-ins exist for several iSCSI-enabled arrays, allowing Oracle VM Manager to manage additional functionality such as creating and deleting LUNs, snapshots, clones, and so on. Check with your storage array vendor if an Oracle VM Storage Connect plug-in is available. The process of discovering a generic iSCSI array is similar to that of an NFS array. From the Oracle VM Manager, access the Storage tab and then highlight the Unmanaged iSCSI Storage Array option. Click the storage icon with the green + sign to add a new array (see Figure 13-7). Next, name the new target device and then select the storage type and plug-in to be used. In the example shown in Figure 13-8, the generic iSCSI storage plug-in will be used for the iSCSI storage. The process for adding a regular unmanaged SAN, or an unmanaged SAN array, is practically identical, with the exception that the iSCSI array requires some access additional information. iSCSI normally uses the Challenge Handshake Authentication Protocol (CHAP) to authenticate initiators to providers. When configuring the storage on the array, you’ll need the CHAP username and password. To add the CHAP access information, select the green + icon shown in Figure 13-9. This will give you the option to set up the access host and port for the iSCSI array. The access host should be the name or IP of the network interface used to access the storage. In the example shown in Figure 13-10, although nas.m57.local is a valid interface, storage is accessed over a 10 gigabit network (10G) using the hostname nas10g.m57.local. The CHAP username and password have also been added. Next, you need to pick the OVS systems that should have admin access to the LUN. Simply move the hosts from the Available Servers list to the Selected Servers list, as shown in Figure 13-11. This is the same role as admin servers for NFS. When new LUNs are added, you’ll need to refresh the array. These admin servers are used to perform the refresh. Next, you need to define what servers will see the LUN. This is done by using an access group. SAN access groups define which storage initiators can be used to access the LUNs on the SAN. This is the same for both iSCSI and Fibre Channel LUNs. SAN access group functionality is defined by the Oracle VM Storage Connect plug-in being used for the array. By default, the generic iSCSI plug-in creates a single group that manages all available storage initiators and is added at the time of discovery. Other plug-ins can provide more specific control and support multiple access groups that limit access to particular LUNs. Select the edit icon while the access group is highlighted, as shown in Figure 13-12. The next part of the process shows the access group in one tab and the storage initiators in a second tab. Select the second tab and then move the host initiators from the Available Storage Initiators list to the Selected Storage Initiators list, as shown in Figure 13-13. The process is almost done. Once you click OK in the Edit Access Group screen, the final screen requires you to click Finish to kick off the job to refresh the array and add the available LUNs to the hosts (see Figure 13-14). The entire process can be followed using the Job Summary window in the Oracle VM Manager (see Figure 13-15). Monitoring the jobs as the work is performed is helpful because a problem can be detected if a job fails. Once the job completes, the new LUN and its array will appear in the Storage tab, under SAN Servers (see Figure 13-16). The initial name of the LUN will consist of the brand of the array and a sequential number. The size of the LUN is also displayed, as are the OVS hosts that see the LUN, the status of the LUN (online, offline), the VMs using the LUN (if it’s directly allocated to a VM), as well as whether the LUN is marked as shareable. A shareable LUN is a LUN that can be bused by multiple VMs at the same time, but this feature should not be used with LUNs that support pool filesystems or storage repositories. Shared LUNs are required for RAC clusters, ASM clustered filesystems (ACFSs), and other clustered storage technologies. WARNING Shared LUNs are a powerful tool, but you need to be careful because not all filesystems and volume managers support them. The Linux lvm volume manager and ext4 filesystems are examples of technologies that do not work well with shared storage. In most cases, the boot disk will not be shared; only data LUNs are shared. To change the LUN name or the Shareable flag, highlight the LUN and select the edit icon, as shown in Figure 13-17. Creating a Repository Disk storage for the virtual environment is referred to as the storage repository. The storage repository is the home for the virtual machines, the ISO images, virtual machine templates, shared virtual disks, and so on. The top-level directory for the storage repository is the storage repository name (see Figure 13-18). ISOs This folder contains ISO files that can be mounted in virtual machines or used to install new virtual machines. VM Files This folder contains the configuration data for virtual machines— specifically the vm.cfg file for each VM. VM Templates This folder contains virtual machine templates, which can be used to clone virtual machines. Virtual Appliances Virtual appliances contain of a set of preconfigured virtual machines that can contain an entire application stack. An example would be a virtual appliance for E-Business, which contains the database tier and application tier in a single deployment. Virtual Disks This folder contains virtual disks, which can be either dedicated to a virtual machine or shared by multiple virtual machines. Virtual disks are different from dedicated LUNS, in that multiple virtual disks can live in a single repository. Whether a single repository or multiple repositories are used, the rule is that if a VM cluster is going to be used, all storage must be shared. In an all-in-one (non-clustered) configuration, either shared or non-shared storage can be used, but in a cluster, all storage must be clustered. This clustered storage can be either NFS or block devices; however, a repository can only use a single LUN, which limits the ability to grow the repository. This makes NFS shares a more popular choice. To create a repository, navigate to the Repositories tab in Oracle VM Manager and select the green + icon, shown next. Next, the repository will need a name. On the following screen, you can select the type of storage. For an NFS repository, click the magnifying glass icon to select the NFS share. A list of unused NFS shares should be displayed, as shown next. Highlight the share that will host this repository. If a LUN-based repository is being created, you will need to select a LUN from a server pool. Select the LUN by clicking the magnifying glass icon. The following shows what a selected LUN will look like. Next, verify the information and make any changes as necessary. If an NFS share is used, as shown in here, the option Share Path allows you to select a subdirectory of the NFS share to use for the repository. Click Next to continue. Next, you need to select which OVSs will have access to the repository. As shown next, you simply move the servers to the Present to Servers list and click Finish. The repository is now created, and the Repositories tab will show the available repositories (see Figure 13-19). Also, storage consumption information will be displayed for each repository. Storage Plug-Ins As previously discussed, the ability to integrate Oracle VM with the storage array is provided using a Storage Connect plug-in specific to the storage array used. The plug-in leverages an API framework that provides for storage management from the Oracle VM Manager. This can include storage discovery, provisioning, and management features. It enables administrators to provision and manage storage platforms through Oracle VM Manager, thus simplifying cloud storage management. The plug-in provides a layer of abstraction, so cloud administrators do not need to know the specific management interface of each storage array used by the cloud built with Oracle VM, and they are able to perform most common operations as a natural part of Oracle VM management. An important note is that the plug-in is written by the storage vendor to take advantage of the features already built into its array. For the following example, the array used is an Oracle ZFS array. To prepare for this, the following tasks need to be completed: 1. Download the Oracle VM Storage Connect plug-in for the Oracle ZFS Storage Appliance. 2. On the ZFS array to be managed, create an admin user for Oracle VM. In the example, the user ovmm is created with the following admin privileges: changeAccessProps changeGeneralProps changeProtocolProps changeSpaceProps changeUserQuota clearLocks clone createProject createShare destroy promote rename rollback rrsource rrtarget scheduleSnap scrub shadowMigration 3. Grant takeSnapCreate target and target group’s privileges: For iSCSI, create an OVM target group and OVM target. Keep note of the OVM target group name because it will be needed during discovery. For Fibre Channel, create an OVM target group. Keep note of the OVM target group name because it will be needed during discovery. Now that the plug-in is installed, the ZFS can be discovered and managed by the OVMM. This is started the same way you would add any SAN storage array, but when you pick the plug-in, you would select Oracle ZFS (see Figure 13-20). When using the ZFS plug-in, you have several new options. The first is the Plug-in Private Data field, which should be the OVM target group that was configured on the array as part of the preparation work. The second is the Admin Host field, which should be the admin IP for the array being used. Next, you need to add the access information, which is identical to what you did when using the Storage Connect plug-in for the generic array, but instead you use the ZFS user for authentication (see Figure 13-21). The remaining steps are the same: you add the admin servers, finish with the validation, and refresh the jobs. Once this discovery is complete, you can add LUNs directly from the OVMM, without the need to create them first on the storage array. Other features, such as replication, snaps, and clones, may be supported, depending on how the vendor wrote the plug-in. Summary, you can further modify and assign storage to virtual machines. This part of the process is done when the virtual machines are created or modified, and will be covered in later chapters in this book. PART III Managing Oracle VM CHAPTER 14 Swimming in Server Pools T he Oracle server pool is truly the first bridge between real-world hardware and the ethereal world of virtualization. The hardware of each Oracle VM server (OVS) is positioned and combined with other Oracle VM servers to form server pools where guest VMs are created and interoperate with each other, oblivious to the dom0 features and functions of the virtual machine server. Within the Oracle VM server pool, an Oracle VM server can operate independently or share the responsibility of providing availability to the guest VMs by participating in a cluster. This cluster management is afforded through the use of the Oracle Cluster File System (OCFS2). In this chapter, we cover the concept of the server pool as well its capacity considerations and performance requirements. Oracle VM servers are organized into pools in order to provide the processor, memory, and storage needed by the guest VMs while maintaining live migration capability. Although there are some limits to live migration, beginning with version 3.4, some of those limits (such as use of VM server local storage) have been overcome. The Create a Server Pool Wizard provides the following key parameters: Server Pool Name This is the unique name used to identify the pool within the VM environment. Virtual IP Address for the Pool This parameter is for backward compatibility and is not required for Oracle VM 3.4; it is only required if all the servers in the server pool are Oracle VM 3.3. VM Start Policy This parameter establishes the default VM server qualifier that will be used to start the guest VMs, and it can be overwritten at the guest VM level. The following options are available: Best Server The VM server used to start guest virtual machines will be determined based on resource policy metrics (distributed resource scheduling and power management). These metrics are set in the Edit Server Pool Wizard and can be seen in the “Policies” perspective. Note that this option may move the Oracle VM guest to a different server from where you attempted to start the virtual machine. Current Server Indicates that the VM server specified in the definition of the guest virtual machine will be used to start the guest VM. Unlike the Best Server option, this choice leaves the Oracle VM guest running on the server that started the virtual machine. Secure VM Migrate Indicates that during a migration, virtual machine configuration information will be encrypted. This choice significantly increases the time it takes for an Oracle VM agent to complete a live migration. Clustered Server Pool Required to support the live migration of guest virtual machines. If selected, this option will create and format the pool file system with OCFS2. This option cannot be changed except by re-creating the server pool. Timeout for Cluster Indicates the amount of time (in seconds) that OCFS2 on each Oracle VM server will wait before fencing itself if it loses access to other Oracle VM servers in the pool over the cluster heartbeat network. An Oracle VM server will reboot itself if this timeout threshold is exceeded. The default is 120 seconds, and the maximum value is 300 seconds. Keep in mind that a two-node server pool will behave in a counterintuitive manner: a pool with an even number of servers will always favor the server with the lowest OCFS2 node number. This means the Oracle VM server with an OCFS2 node number of zero will always remain running even if it is the server that lost network connectivity. Therefore, always design server pools with odd numbers of servers to avoid this peculiar behavior. Storage for Server Pool Indicates the type of storage used for the server pool filesystem. The server pool filesystem only needs to be 12GB in size, and it can be NFS, iSCSI, or Fibre Channel. The pool filesystem will never exceed 12GB, even with the maximum number of pools, servers, and virtual machines allowed by the product, so there is no reason to make this storage any larger than 12GB. NOTE The storage repository is a uniquely separate storage resource and cannot be shared with any other server pool or virtual machine. As with any IT-related task, a modicum of planning and preparation precedes the task of server pool creation. Assuming the Oracle VM Manager has been successfully installed, Oracle VM server pool creation and administration can be successfully achieved entirely within the graphical web interface. Also, using the GUI means any required triage is fully supported—that is, of course, provided an active Oracle CSI (Customer Support Identifier) somewhere has been purchased. To get a perspective on the role of the server pool, begin with the end in mind: the objective is to create a guest Oracle VM. The virtualized host under normal circumstances runs within the resources presented to it by the Oracle VM server. One or more Oracle VM servers run within a server pool. A given environment may have one or more server pools. However, a given VM server is a member of zero or one server pool. In the event that an Oracle VM server is not a member of a server pool, it is known as an unassigned server, in which case it cannot run a guest virtual machine. A server pool therefore is made up of one or more Oracle VM servers, and each Oracle VM server within the server pool provides utility services (migrating virtual machines, copying, virtual machines, and so on) or hosts virtual machines (or both). After the initial installation and configuration of the Oracle VM server is completed (as covered in Chapter 9), the OVS might be discovered and participate in an Oracle server pool and ultimately be a host of guest Oracle VMs. It is automatically designated as a utility server within the server pool and acts as the administrative focal point of utilities (VM migration, VM deletion, and so on); the role as utility server or virtual machine server can be unassigned at any time. More information on VM server roles is provided later in this chapter. The process of adding a candidate OVS to the Oracle VM infrastructure (and ultimately a server pool) is known as discovery. However, although many tasks can be performed using the command-line interface (CLI) in order to maintain a strict sense of support, it is highly recommended that many (if not all) tasks be performed via the Oracle VM Manager, GUI web interface. The discovery process begins by selecting the Servers and VMs tab and clicking the first icon, which will bring up the Discover Servers Wizard (see Figure 14-2). Figure 14-2 shows a password and a list of hostnames or IP addresses. In Figure 14- 2, the process looks for any server in the given subnet whose last octet is 55 through (and including) 60. It should also be noted that the use of a hostname implies resolution to the hostname will be available any time this OVS is to be used in a pool. In other words, when in doubt, use the IP address when adding an OVS to the Oracle VM infrastructure. The password is used to access the agent on each server in order to execute utilities and perform various operations. The password is also required for agent administration. It is a best practice to use the same password for all the agents; otherwise, tasks that are required across multiple servers must be executed separately because different passwords need to be submitted. NOTE The password is stored and associated with each of the servers that are discovered and ultimately added to the unassigned servers list. Although it can be changed later, the password is required when performing operations on a given VM server (for instance, via a Telnet session). pool filesystem. In other words, the storage cannot be shared across server pools. Each server pool requires its own storage, and it can be storage from a NFS fileserver or a physical disk that is a logical unit number (LUN) carved out of SAN-based storage. This storage will never grow beyond the recommended 12GB of space. Figure 14-4 shows the physical disk assignment of the storage that will be used by the new server pool. After specifying the server pool name and defining the storage (the other parameters will be explained in detail later), the next page in the wizard displays any servers that have been discovered but not yet assigned to a server pool. capacity characteristics change over time. The most significant factor to consider is whether or not to enable cluster management at the time the server pool is created. This cannot be changed. Realistically, the thing that will change the most is the VM server participation in the pool and the role a given VM server will be assigned. By default, all the VM servers added to a pool will be designated with both the utility server and VM server roles. NOTE So little overhead is involved in being a utility server that it is not worthwhile to even worry about assigning the utility server role to a VM server. In other words, unless there is a particular alignment of the planets requiring the separation of utility servers, it is okay to keep the default settings of the server being assigned both the utility server and VM server roles. To add an anti-affinity group, navigate to the server pool in the navigation tree on the left side of the VM Manager pane. Figure 14-6 shows the wizard used to maintain guest VM membership in an anti-affinity group. Select the server pool and then choose Anti- Affinity Group from the drop-down perspectives and then click the green plus sign to add an anti-affinity group or click the pencil icon to edit an existing anti-affinity group. The process of establishing an anti-affinity group begins by editing the server pool that contains the guest VMs that must operate separately. Each anti-affinity group is given a name, and then guest virtual machines in the server pool can be selected and added to the given anti-affinity group. Role Management As mentioned earlier, under normal circumstances, the OVS functions as the host to the guest virtual machines running on the server. In this scenario, the OVS is operating with the VM server role. However, in the case where specific management operations are required (such as during live migration of a running guest VM or during a template import operation), the tasks to support the operation are given to one of the OVS machines assigned with the utility server role. The OVS assigned with the utility server role may also be assigned the VM server role, but the OVS with the utility server role may not be the VM server where the guest VM (requiring migration) is running—which is a reason to have many (if not all) OVS machines assigned the utility server role. Figure 14-7 shows the wizard used for server role maintenance. The ability to perform utility services without the VM Manager is another example of Oracle’s unique perspective on and achievement of abstraction; that is, a separate device outside the operation of the VM server and guest VMs is not required to perform utility services. In fact, the VM Manager, while serving as the user interface into the management of the Oracle VM infrastructure, is not even required to be up and running while these operations are taking place. VM server roles can be assigned during server pool creation when VM servers are being added to the pool. Alternatively, they can be assigned later after the server pool has been created and a VM server is being added and its role assigned, or when a VM server is currently assigned to a server pool and its role is to be changed. The guiding principles of role assignment are based on the VM server’s capabilities and some estimation of the load during operations at different points of the VM server lifecycle. During times of heavy load, for example, it may not matter which VM server is assigned the additional role of utility server. However, at times when a given VM server does not have as high a load as the other VM servers in the server pool, it makes sense to assign that particular server (with the lower utilization requirement) the utility server role. This will remount the pool filesystem, and the server pool is back in business. A new LUN/NFS share that has been created without the old filesystem on it will require additional steps, including the recovery of data. In addition to server pool availability, the actual guest VMs may have a High Availability requirement (specified in the definition of the guest VM), but the actual failover and availability features are afforded by the clustering mechanism of the server pool (OCFS2) and the functionality of the OVS agent running on each of the OVS machines in the server pool cluster. NOTE High Availability features are a function of the OVS agent and the pool filesystem, not the Oracle VM Manager. All High Availability features work regardless of whether the Oracle VM Manager is running. VM High Availability A direct correlation exists between High Availability and server pool cluster configuration. There can be no High Availability with single-point-of-failure components. As such, the components that support virtual machine operations (storage, process, and so on) must also be replicated or duplicated to support the continuity of operations with respect to a running virtual machine. Hence, in support of High Availability, the server pool must contain multiple OVS machines and have been created with the Clustered Server Pool option enabled. Ideally, server pools should always contain odd numbers of servers to allow OCFS2 fencing policies to behave in the most expected way. Having an even numbers of servers always forces the servers with node0 to win any battle around fencing/rebooting. In addition, as seen in Figure 14-8, the virtual machine must also be configured with the Enable High Availability option selected. This can be set either at creation or later by editing the guest VM configuration in the Oracle VM Manager. Also, storage High Availability considerations are usually maintained at the storage management layer of the storage provider (that is, RAID configurations and/or data duplication and replication methodologies). With that said, one of the new features as of version 3.4 is the ability to migrate guest machines that are using storage that’s locally attached to the VM server. This was not supported (or even available) in previous versions. In OVM 3.4, the “storage live migration” feature allows for the migration of local-to- local storage between servers in the same pool without needing to stop the VM. This feature is really ideal for non-clustered server pools that have no shared storage! CAUTION Do not be creative when using NFS storage repositories with non-clustered server pools. The lack of dynamic lock management allows the same VM to be started on multiple servers, which means bad things will happen, including duplicate MACs, duplicate IPs, and corrupted virtual systems and boot disks! Summary In this chapter, we discussed creating and managing an Oracle VM server pool. As stated earlier, this is not a full-time job. In fact, the most important decision required before creating a server pool is related to clustering. That particular configuration item cannot be changed and is only specified at the time of creation. If the environment can afford it, best practice dictates that two (or more) server pools—one clustered and one not—are created. The VM servers in the non-clustered pool can be equipped with enough local storage to support the virtual machines using local storage for performance reasons (or for RAC nodes). In addition, Oracle VM server pools provide guest Oracle virtual machine High Availability capabilities through live migration functionality and operational processes to ensure virtual machines are physically separate from each other through anti-affinity groups. Also, through the use of server roles, an Oracle VM server can be assigned the role of utility server through which the Oracle VM agent performs required tasks in the background without Oracle VM guest configuration changes. CHAPTER 15 Configuring Guest Resources This chapter covers managing Oracle VM Server resources. As you learned in the previous chapter, there are three different ways to configure guest resources: via the Oracle VM Manager, the OEM Grid Control, and the Oracle VM CLI. This chapter focuses on using Oracle VM Manager, with subsequent chapters covering Oracle Enterprise Manager 13c and the Oracle VM CLI. Guest Resources The guest resources are key features that give Oracle VM its functionality and ease of use. The guest resources consist of virtual machine templates, virtual appliances, and shared virtual disks. Virtual machine templates are used to install virtual machines. Shared virtual disks are used in clusters, such as Oracle Real Application Clusters, for shared disk usage. Configuring and administering these guest resources using the Oracle VM Manager are covered in this chapter. Templates Virtual machine templates are a core feature of Oracle VM. Virtual machine templates allow you to create virtual machines quickly and efficiently with less chance of making mistakes than if you had to build them from scratch. Here are some of the advantages of using VM templates: Ease of use By using a template, you can quickly and easily deploy virtual machines. Because templates are preconfigured, you can use them to deploy many consistent copies of the same virtual machine, with each one customized for your environment. Consistency Because creating a virtual machine from a template does not require extensive configuration changes, the virtual machines are very consistent. If the VM template is configured ready to install the Oracle Database, then all virtual machines created from this template will be able to install the Oracle Database consistently. If the VM template is configured with the Oracle Database preconfigured, then all virtual machines created from this template will include a consistently installed Oracle Database ready to go. Provisioning efficiency Because templates are preconfigured and can be created or obtained with applications preinstalled, the time it takes to deploy these applications can be greatly reduced. Virtual Appliances Imagine the power of templates expanded to the entire application. Virtual appliances provide this by enabling entire application stacks to be consolidated into a single object. This enables the administrator to deploy complex systems, including multiple virtual machines to support each tier of the application, from the RAC cluster supporting the database to tomcat clusters supporting the middle tier. This technology is very helpful when deploying complex applications like Oracle E-Business Suite and SAP. Virtual appliances can also include virtual machines using third-party formats such as Open Virtualization Format (OVF) from VMware. This makes migration from VMware to OVM as simple as exporting the virtual machine from VMware to an OVF file and then importing it into Oracle VM. As with templates, Oracle VM stores the virtual appliances in the repositories, in a folder named “Virtual Appliances.” Just click a virtual appliance to view what virtual machines are contained within it (see Figure 15- 2). The next sections cover configuring and managing guest resources using the Oracle VM Manager. You can also use the Oracle VM CLI or Oracle Enterprise Manager 13c. Which method you use depends on your individual configuration and needs. The two most common areas to be edited are the network configuration and the core configuration of the template. The core configuration, shown in Figure 15-5, is where the amount of CPU, RAM, and other parameters related to the system performance are set. These are the exact same parameters used when creating a virtual machine. An example of a change you might make after the template is created is adjusting the behavior of future virtual machines when they crash. Administration might not want to have them restart automatically, for example, but instead to stop. More common is changing the network configuration after the template is created (see Figure 15-6). A template could be built in a non-production network segment, but copied to a new template and updated to use the production network. server. Having the Oracle VM Manager also act as the HTTP server for importing templates is fine, but in larger environments, having the Oracle VM Manager server also act as a yum repository for hundreds of Linux servers will likely cause performance issues when you’re managing the Oracle VM environment. NOTE If you find yourself confusing templates and virtual appliances, keep in mind that a virtual appliance should have the extension .OVA, whereas a template will often use .TGZ or .OVF as its extension. If a template fails with the error “No VM configure file found,” try importing it as a virtual appliance. 1. Templates are managed from the repository in which they reside. Navigate to the repository and select the VM Templates folder. From there, you’ll see a list of all templates currently imported. From the VM Templates screen, click the Import button, highlighted in Figure 15-7. 2. Clicking the Import button begins the template import process. On the first screen that appears, you define the source for the template import, as shown in Figure 15- 8. Once you’ve selected the import method, a job will be created that you can track in the Job Summary window in the Oracle VM Manager. Follow these steps to import an existing virtual appliance into the VM Manager: 1. Virtual appliances are managed from the repository in which they reside. Navigate to the repository and select the Virtual Appliances folder. From there, you can see a list of all virtual appliances currently imported. From the Virtual Appliances 2. Clicking the Import button begins the virtual appliance import process. On the first screen that appears, you define the source for the virtual appliance import, as shown in Figure 15-10. Once you’ve selected the import method, a job will be created that you can track in the Job Summary window in the Oracle VM Manager, as shown in Figure 15-11. 1. Templates consist of at least two files—one being vm.cfg, which contains all the configuration data for the VM, and the second being at least one disk .img file. In order to export the template, you will need to locate these two files and then combine them into a compressed .tar file. From the initial Oracle VM Manager screen, click the Resources tab. From the Resources tab, you can import a template by clicking the Import button. 2. To locate the vm.cfg file for the template, navigate to the VM Templates folder in the repository where the template is stored. As shown in Figure 15-12, the location of the vm.cfg file will be shown when the selection is expanded. 3. To identify the location of the disk file for the template, select the Disks tab in the details area for the VM template. This shows each of the disks used by the template (see Figure 15-13). Several columns are visible, but what is needed is the “mounted path” for the disk image, which, for our example, is 4. The last step is actually fairly simple—if there is enough scratch space on one of the OVS systems. A single compressed .tar file will be created that contains both files. Use SSH to access the OVS, and then use tar to create the file. The format is tar -cvfz $TEMPLATE_NAME.tzg $CFG_PATH $DISK_PATH, as seen in the example: The file /var/template.tgz can now be copied to an HTTP server and then imported into a repository. device path for physical disks as well as the NFS server name, mount point, and the filename and location for NFS-based disks. ovm_vmhostd This command collects metrics about the Oracle VM Server host on which a virtual machine is running. vm-dump-metrics This SAP-specific script gathers metrics about the Oracle VM Server host in XML format, which can be imported into an SAP application. Installing the scripts is simple: after downloading the file from Oracle’s Support site, you need to identify the version required, which is based on the version of Oracle VM Manager running in your environment, and then extract the scripts into a folder. The scripts do not need to be extracted or run from the Oracle VM management server. Oracle Support currently provides three ZIP files: To pin cores on a VM, first check the current configuration. In this example, the OVMM server is ovmm.m57.local and the VM being managed is repo. The -c options are setvcpu, getvcpu, and rmvcpu. Once configured, getvcpu will now show the cores that are pinned: Technet24.ir|||||||||||||||||||||||||||||||||||||||| The password is required each time the command is run. It can be set as an environmental variable, which enables scripting and simplifies access to the scripts when they are being used heavily. To set the password, run the command export OVMUTIL_PASS=$PASSWORD, where PASSWORD is the password being used. When the OVMUTIL_PASS environmental variable is set, add the option -E to the scripts, as shown in the following example: The pinned CPUs can be removed using the rmvcpu option, but the VM will need to be shut down before this option can be run against the VM. Once the VM is offline, run the command, as shown here: The ovm_vmdisks script allows you to retrieve information about disks assigned to virtual machines. The script also identifies the name and location of the vm.cfg file. This is the same information required to manually export a template of a VM from one Oracle VM system. In this example, not only is a disk served from NFS (Virtual Disk : 'sol11'), but also a physical LUN is assigned to the VM: The command ovm_vmhostd collects metrics from the OVS and sends them to the VM specified in the options. The OVS will then send metrics about itself to the VM. These metrics can be recovered using the vm-dump-metrics script from the guest VM. The utility will run every 60 seconds until stopped with CTRL-C. While the ovm_vmhostd script is running, on the VM named in the script, run the vm-dump_metrics command to collect the data. The output can be redirected to a text file for use by SAP or to custom-written processing scripts. This will bring up the Edit dialog for the virtual disk. To make the Virtual Disk shareable, simply check the Shareable box (shown in Figure 15-15). The virtual disk can now be allocated to multiple VMs. This will bring up the Edit dialog for the virtual disk. To make the virtual disk shareable, simply check the Shareable box (see Figure 15-17). The virtual disk can now be allocated to multiple VMs. Once you’ve completed these steps, you can use the physical device as a shared device. Summary This chapter covered several server resource management tasks and how to administer them via the Oracle VM Manager and Oracle VM Utilities. Both tools are easy to install and easy to use, and they work together (for example, Oracle VM Utilities requires and uses the OVM CLI installed on the Oracle VM Manager). The VM Utilities can be readily downloaded from Oracle and can be quickly installed and configured. In the next chapter, you will learn how to monitor and tune an Oracle VM server. A poorly tuned or overloaded server will lead to virtual machine performance issues. By monitoring the load on your VM servers, you can often head off problems before they occur. CHAPTER 16 Monitoring and Tuning Oracle VM Servers O nce the virtual machine environment has been configured and deployed, it should be monitored and managed to provide an efficient and well-performing system. An overloaded Oracle VM server and I/O subsystem result in a poorly performing virtual environment, which in turn results in unhappy customers and users. There are two parts to tuning and monitoring the virtual environment: monitoring and tuning Oracle VM servers and monitoring and tuning the virtual machines themselves. This chapter covers monitoring and tuning Oracle VM servers. Performance Monitoring Performance monitoring can be done via Oracle Enterprise Manager Cloud Control and several tools that are available within the Oracle VM Oracle VM server, you must use other utilities. Let’s look at a couple examples. Running top (Display Top Linux Tasks) in dom0 gives you information on the dom0 system only. You can see this in Figure 16-1. In this figure, top shows a system with 12 CPU cores and 3214404k (3GB) of total system memory. The VM server used in this example actually has 120GB of RAM and 12 CPU cores. What Figure 16-1 reveals is the performance and resources that have been allocated to dom0. By using xm top (a Xen command), you can gather information from the hypervisor and display it within dom0. The information from xm top in Figure 16-2 shows five domains: dom0 and four virtual machines. In addition, the summary information at the top of the display gives configuration information for the entire Oracle VM server with 120GB of RAM and 12 CPUs. The xm top command is one of several xm commands that provide performance and configuration information. You can use most of the xm commands to manage the Oracle VM server, but there are several that you can use to monitor the Oracle VM guests, including the following: Examples from some of the commands are provided in the upcoming sections. These commands are useful for monitoring the Oracle VM server and the virtual machines. In addition to these commands, you can also monitor from within the virtual environment, but monitoring within the virtual machine only gives you performance and resource utilization from the perspective of the virtual machine itself and does not provide information on the entire environment. CAUTION Statistics gathered from a virtual machine itself (including dom0) are, by their very nature, not accurate because a virtual machine is only allocating a part of the actual resources. For example, within the virtual machine, it might appear that the CPU is 100 percent busy, but that 100 percent might be physically only 50 percent of the CPU. Therefore, be skeptical of any statistics gathered from within the virtual machine itself. Below the information about the Oracle VM server, you’ll see information on each of the virtual machines, including information on how much activity is happening in that particular domain. Note that this information includes dom0 as one of the domains. The xm top command is very useful for finding out which domains are the busiest and contributing the most to the Oracle VM server’s load. Unfortunately, the domain name is truncated; therefore, all of the virtual machines appear to have the same name. You might be able to correlate by using the NET field and xm list. Also note that although Domain-0 is allocated all of the CPUs, it is only allocated a small amount of memory. The xm list command does not show significant information about system performance, but it does provide a quick way to determine which virtual machines are running and how many resources have been allocated to each. The ID is important when coordinating with other xm commands, because the name may or may not be truncated in those outputs. Also take note of the number of virtual CPUs as well as the amount of memory allocated to the VM. Domain-0 has access to all the CPUs, but as a virtual machine it’s not allocated very much memory. Oracle has carefully given Domain-0 what it needs to do the job optimally. This command does not provide specific performance information, but it can be used to provide significant information about the resources used by the system as well as about the system’s configuration. which can be useful in determining which physical CPUs a virtual CPU is running on. This command will be shown in further detail later on in this chapter in the section “Tuning Virtual Machines.” The xm vcpu-list command is shown here: This command also gives the CPU time accumulated by the virtual machine, not the clock time that the virtual machine has been running. This is an especially important view when considering CPU pinning, also known as hard partitioning. In this example, you can see where the virtual CPUs from each of the VMs share the same physical CPUs in some cases, and in other cases they might be alone on a physical CPU. Note that CPU Affinity shows that the virtual CPUs can run on any physical CPU. If CPU pinning or hard partitioning were used, you would see virtual CPUs locked down to specific CPUs. This is shown later in the chapter. The xm block-list command provides some information but is usually not that helpful to the OVM administrator. Most of these commands provide information only and not performance data; however, some of this information can be useful when tuning the system. You might find more information by using the brctl command, as will become evident in the next sections. As you can see, there are two sockets with six cores each. Note that hyperthreading is not turned on. Here is an example with hyperthreading enabled. Notice that there are two CPUs per core (not all rows are shown). You have a few ways to allocate CPU resources: by using the xm vcpu command, by configuring the vm.cfg file, and by using ovm_vmcontrol (part of the OVM Utilities). Each of these methods is described in this section, but using ovm_vmcontrol is the preferred method. Remember that only the vm.cfg file and ovm_vmcontrol utility methods are permanent. If the Oracle VM server were to restart, all changes made with xm commands will be lost. NOTE Only ovm_vmcontrol is supported for CPU pinning. It is covered here as well as in Chapter 15. Also note that live migration is not supported with hard partitioning unless you are using an Oracle Private Cloud Appliance (PCA). NOTE Any changes made using the xm cpu commands are lost when the virtual machine is restarted. The xm vcpu-list command lists the virtual machines (domains) and their current CPU settings. This command takes the domain ID as an optional qualifier. If the domain or set of domains is not provided, all of the domains on the system will be displayed, as shown here: Optionally, you can provide a domain ID as a qualifier. In this case, the xm vcpu-list command provides only CPU information about the requested domain. This command as well as others can be qualified by either the name or the ID of the virtual machine. Each provides an equivalent output. Notice in this example that the four virtual CPUs allocated to the domain named 4590_pvtest2 are configured to run on any of the physical CPUs in the system. To pin a virtual CPU to a physical CPU, use the xm vcpu-pin command. The syntax is as follows: For example, to pin the four virtual CPUs just shown on physical CPUs 2, 3, 7, 9, and 10, you would use the following commands: NOTE You would want to pin all CPUs, not just a few, as was done in this example. Use the xm vcpu-set command to limit (set) the number of virtual CPUs that a domain can see. The number of VCPUs can be decreased from the limit that’s originally set, but it cannot be increased above that number. You can then re-enable the virtual machine by using the xm vcpu-set command again, but this time with the number of CPUs set to 4: Using CPU affinity can be a good way to prioritize specific virtual machines. Note that it is possible (and likely) to have two virtual CPUs sharing the same physical CPU. In fact, with xm vcpu-pin, you can set all of the VCPUs to the same physical CPU. NOTE The State field in xm vcpu-list can have one of several values: r running b blocked p paused s shutdown c crashed d dying The virtual CPUs must exist in one of these states. In addition to the xm commands. CPUs can be configured in the vm.cfg file as well. A vm.cfg file generated by the VM Manager only has the vcpus parameter specified. Setting the cpu parameter, as shown here, locks the virtual CPUs to physical CPUs 2, 4, 6, and 8. If you want to set a specific order, put it in the cpu variable, as shown here: As mentioned earlier, you can also lock one or more virtual CPUs to the same physical CPUs. The cpu variable will take either a specific set of CPUs that are comma separated or a set of CPUs with a range. The result differs based on the configuration, for example: Specifying a range of CPUs, as in cpu = '1-2', locks the four virtual CPUs to physical CPUs 1 and 2; however, they will be able to move between those CPUs. Specifying a single CPU, as in cpu = '1', locks all four virtual CPUs to the same physical CPU. Specifying a specific list of CPUs that has the same number of CPUs as specified in the vcpus parameter locks each virtual CPU to a physical CPU, as shown previously. CPU affinity is presented in this chapter because it is not just a tool for tuning the virtual machine; it is also a tool for tuning the Oracle VM server as well by specifying the load on the Oracle VM server’s CPUs. NOTE The -E option uses the environment variable OVMUTIL_PASS to store the OVM Manager password so it does not show up in the command. Unlike the xm commands, because this command is going through the OVM Manager, you will use the name that was provided when you created the VM, rather than the OVM-assigned hexadecimal value. To pin CPUs (also known as hard partitioning), use ovm_vmcontrol with the setcpu and cpulist parameters, as shown here: Once you have pinned the CPUs, you must stop and start the virtual machine in order for the change to take effect. A restart is not effective for pinning CPUs, it must be a stop and start. After starting the VM, you can verify by running getvcpu again: The ovm_vmcontrol utility easily allows you to pin and unpin VCPUs. Whether you pin via the xm commands or via ovm_vmcontrol, the outcome is the same: VCPUs will be pinned to physical CPUs. NOTE See the Oracle whitepaper “Oracle VM 3: 10GbE Network Performance Tuning” for more information on tuning the 10GbE network with OVM 3.4 on NUMA systems. This whitepaper is available at- 1900032.pdf. The network can be configured for Jumbo Frames using a 9000-byte maximum transmission unit (MTU). This works well for large payloads, but care must be taken that the MTU for both guests and dom0 are set the same. You can monitor the network using the built-in Linux command sar. In addition, the OVM server comes with the iperf utility, which allows for testing the bandwidth This information is very useful for determining whether a specific network adapter is saturated. However, you cannot take this information at face value. A 1GB adapter can become saturated at less than 1GB of traffic if the packets are small. If you see the receive and transmit packets per second getting close to 80 percent of the limit, it is time to get concerned. In this case, some of the load (some of the virtual machines on that adapter) should be shifted to another adapter. Once the listener is running, run iperf -c <host> to invoke iperf. By default, iperf will run for 10 seconds, but that is configurable via the command-line options. You should see something similar to this on the source system: You will see this on the target system where you are running iperf -s. In order to check for network errors, you can run ifconfig, which will show you all the network controllers and any errors that might have occurred on those network controllers. The iperf utility provides the ability to check the network between any two systems, thus not only testing performance, but checking for errors as well. I/O Performance I/O performance is limited by the performance of the disk drive itself. In disk arrays, more disk drives mean more I/O performance because the performance of the array is the sum of the performance of the individual disk drives. When purchasing an I/O subsystem, make sure you have a sufficient number of disk drives, a large cache, and a high-performing bus. A slow I/O subsystem slows down I/O performance and subsequently the performance of the virtual machines. performance of your I/O subsystem. However, neither dd nor scp is a good tool for measuring I/O performance. Summary This chapter covered the steps and tools necessary to monitor the Oracle VM server itself. Because the Oracle VM Server OS that is visible from a user’s prospective is actually dom0, traditional methods of monitoring, such as using sar, top, and vmstat, don’t work. This chapter covered some of the utilities that can be used to monitor the hypervisor and VM server as a whole, such as the xm tools. Tuning the actual I/O subsystem and network involve what I refer to as “hardware tuning,” which involves PART IV Installing and Configuring the VM Guest Additions CHAPTER 17 Oracle VM Templates O ne of the primary advantages Oracle VM provides is the capability to create templates. Templates are preconfigured appliances that can range from a simple operating system installation to a complex application installation such as Oracle E-Business Suite. Not only can you easily create your own templates, but you can download many preconfigured and working Oracle VM templates from Oracle. These templates range from OS-only templates to entire E-Business Suite environments. The virtual machine templates allow for efficient and quick deployment of virtualized environments in a repeatable, reliable manner. Templates enable rapid provisioning of virtual machines in a private cloud environment, with each virtual machine based on a standard template. This standardization not only provides for a more agile environment, it also helps reduce the time to troubleshoot problems by leveraging a common set of paths and packages for all systems. This chapter covers the primary way of creating a template in Oracle VM 3.x—namely, creating the template manually. NOTE Oracle VM templates are used for deployments in many of the Engineered Systems from Oracle, including the Oracle Database Appliance and the Private Cloud Appliance. 6, Oracle Linux 7, Windows, and Solaris. Guest Additions for Solaris x86 is developed and supported by the Solaris team and does differ from the Linux implementation. For Linux systems, you can access Guest Additions from Oracle’s public Yellowdog Updater Modified (yum) repository. To enable the Guest Additions add-ons, you need to edit the yum configuration file. Under an Oracle Linux 6 server using the public yum repository, this is managed by the file /etc/yum.repos.d/public-yum-ol6.repo. You need to edit the file and enable the [public_ol6_addons] stanza. To do this, edit the file and change enabled=0 to enabled=1, which should look similar to the following: ovmd The Linux daemon that handles communication to and from the Oracle VM Manager, as well as the configuration and reconfiguration events. xenstoreprovider A library that acts as an information storage space, facilitating communications between the guest and dom0. It passes key-clause paired messages to and from ovmd. python-simplejson A simple and fast JSON library for Python. ovm-template-config A collection of Oracle VM scripts used to configure an Oracle VM template during its initial boot. libovmapi An automatically installed library used to communicate to the ovmapi kernel infrastructure. libovmapi-devel An optional package required when creating additional extensions to ovmd. ovmapi kernel module This kernel module provides the ability to communicate messages back and forth between the Oracle VM Server and the VM—and as such, between the Oracle VM Manager and the VM. Since the Unbreakable Enterprise Kernel version 2 (UEK2) (2.6.39), this kernel module has shipped with the kernel. A number of packages support the communication between ovmd and the guest operating system. Each enables a specific family of supported capabilities. For many administrations, installing all the packages is recommended, but in some secure environments, only the needed packages can be installed. NOTE Changes made to the template are performed in the VM and not directly against the OVMM or OVS. First, install the Oracle VM Guest Additions by configuring yum to point to the public_ol6_addons repository hosted by Oracle. Edit the file /etc/yum.repos.d/public- yum-ol6.repo, edit the stanza called [public_ol6_addons], and set the enabled flag to 1. When you’re finished, the stanza should look like this: Next, use yum to install the required packages with the following command: This installs the packages and any missing dependencies. The command and its output should look similar to the following: Once you have installed the required packages, you can begin installing each of the optional packages. Installing all the packages is a simple process, and it gives you the option to leverage each add-on in the future without having to rebuild the template. To install all the add-ons, simply run yum again and use a wildcard to install all the ovm- template-config packages. The command and its results should look similar to the following: Next, enable the ovmd daemon to start at boot. This is done with the chkconfig command, as shown next. If ovmd is not running at boot, the Oracle VM Manager will be unable to communicate with the virtual machine. To verify when the daemon will start, using chkconfig –level. The chkconfig command shows the initial state for any service when the operating system changes to the target level. In this case, the ovmd daemon is set to run at the init states 2, 3, 4, and 5. Next, manually start the daemon and then check to verify that it is running using the command /etc/init.d/ovmd status. Often when new templates are not communicating with the Oracle VM Manager, it is because the ovmd is not set to start at reboot. Once the daemon is running, more information about the VM will be visible in Oracle VM Manager. To verify that the Oracle VM Manager is communicating with a virtual machine, look at the Networks tab in Oracle VM Manager to see the IP address for the VM, as shown in Figure 17-1. If an IP address is not visible, you need to verify that ovmd is running. Before the VM can be cloned to a template, one critical task remains: the VM needs to be cleaned up in preparation for cloning. Because these commands will effectively wipe the network configuration, you must run them from the VM console. CAUTION It is recommended that you run the following commands from the console on the virtual machine. Part of the process will deconfigure the network, disabling remote access to the virtual machine. The first command used, ovmd –s cleanup, will wipe the configuration: The next command enables ovmd to run the initialization scripts on the next boot: reuse. To do this, log into the Oracle VM Manager. Then, under the Servers and VMs tab, drill down to the VM. While the VM is highlighted, click the Clone button to start the wizard, as shown in Figure 17-2. When the wizard starts, several options are available. Not only can you clone a VM to a template, but you can also use the wizard to move the VM from one repository to another. In this case, we’ll simply clone the VM to a template, as shown in Figure 17-3. The same wizard can also be used to move virtual machines to new storage. In this case, it will be used to clone the virtual machines to a template, as shown in Figure 17- 4. Click Next to continue. Make sure you select Clone to a Template. You can also add a descriptive comment for the template. When you’re done, click OK to start the cloning process. The wizard will close, and you should now see a running job in the Job Summary panel, as shown in Figure 17-5. Depending on the speed of your storage, and the size of the VM, the process can take anywhere from a few minutes to almost an hour. You can click the Details button in the Job Summary panel to display the status of the clone event, as shown in Figure 17-6. Once the job is complete, move to the Repositories tab and drill down into the repository where the template was created to see that the template is now available for VMs, as shown in Figure 17-7. NOTE Once the template has been created, you can reuse it as many times as necessary, easily creating hundreds of identical virtual machines in just hours. The only limitation is the speed of the attached storage array. Summary This chapter showed you how to create a template with OVMD, thus enabling automated configuration of the VM when building private clouds. You learned how to prepare the Oracle Linux operating system to be used as a template and how to clone a VM to a template. The process in Oracle VM 3 is a very effective way to create and use templates. Creating virtual machines from templates is the most reliable and recommended method of creating virtual machines. The next chapter covers just that— how to create virtual machines using templates. CHAPTER 18 Creating Virtual Machines Using Templates N ow we come to the crux of cloud computing: the creation of the guest virtual machine. This is the process through which the target host operating system will run using resources that have been defined and presented to the Oracle VM infrastructure and application systems, databases, and any program that would otherwise execute on bare-metal but is now executing in the virtual machine. With rare exception, anything that runs in the bare-metal machine environment can run without modifications in the virtual machine environment. The following sections present the process of creating a virtual machine in the Oracle VM infrastructure. Other sections of this book covered processes where the necessary resources are configured and presented, including network and storage resources. As a prerequisite to creating virtual machines, the network and storage resources must be available and understood. The process of importing templates is slightly different from importing appliances. Most notable are the “undefined networks” imported along with templates. This can be addressed as follows: The “undefined network” needs to be deleted from the Networking section of Oracle VM Manager. With respect to importing and preparing Oracle VM appliances, this is the newer and now preferred construct for using pre-built virtual machines. The process differs slightly from templates because these will not come based on OVM 2 xenbrX bridge names. 1. Import the template into a storage repository (this process is detailed later in this chapter in “Importing a Template”). 2. Present the necessary storage LUN(s) if using physical disks for the virtual machine boot disk. 3. Add one or more networks (the process of creating Oracle VM networks is detailed in the “Network Management” section of this chapter). 4. Create the template clone customizer. The clone customizer is particularly useful to ensure that the storage components associated with the Oracle VM (the ISOs, templates, appliances, vm.cfg, and virtual disks) are kept is the same place, especially since NFS-based repositories can be shared across server pools. 5. Clone the template to a virtual machine. Network Management The Oracle VM network environment supports detailed Layer 2 and Layer 3 switching and routing and advanced configurations, and it’s fully virtualized. This includes VLAN definitions and support as well as other advanced network concepts. Figure 18-1 shows the Networking tab of the Oracle VM Manager GUI and reflects various networks defined for the network channels used by the Oracle VM operations. Note that any detailed network administration tasks will be discussed in a separate section and/or will reference Oracle VM networking documentation. Also, although a single virtual machine network may be defined and assigned to the Oracle VM for virtual machine communications, the best practice recommendation is to dedicate network processes based on the following specific types of traffic (that is, each of the following should be on a physically separate and dedicated network). depending on the level of activity required across the enterprise. If the resources are available, each physical network should be configured to use a bonded interface of two or more network interface cards. Storage Management As with network operations, details of storage management can be found in the Oracle documentation. Here, we discuss the tasks related to guest VMs that are deployed from templates or used as the source to create a template. In general, two types of disks are associated with guest virtual machines and templates: Virtual disks Virtual disks are sparse files that are contained in Oracle VM storage repositories for use by Oracle VM guests. Virtual disks are optional but pretty common; they are created and used by Oracle VM guests to contain the guest operating system or any other data the VM owner requires. Physical disksPhysical disks can be local disks found on each Oracle VM server or LUNs that reside on external storage arrays. LUNs can be presented to the Oracle VM servers using iSCSI or Fibre Channel and then presented to the Oracle VM guests through the Oracle VM servers. LUNs can be presented directly to the Oracle VM guests if iSCSI is used, but not Fibre Channel. NOTE The choice of which type of disk to use and which protocol is best depends entirely on requirements. The “best” storage is what is deemed to be the best fit for your needs; you don’t need to limit yourself to just one storage Repository-Based Storage To be supported in a production capacity, virtual machines must be deployed using physical disk definitions for disks used by database management systems to contain data. Virtual disks used to contain the guest operating system are fully supported in production. With that said, virtual disk definitions provide more rapid deployment of guest virtual machines because the disks do not need to be pre-allocated and can be used from storage assigned to the repository “on the fly.” Naturally, care must be taken to ensure that storage is available for the virtual machine to be deployed from the template, and this can be determined by examining the template storage requirement on the Disk tab of the expanded template or the expanded source guest VM from which the template was created. Figure 18-2 shows the information screen of an Oracle VM repository where the information of available storage for use by virtual disks can be quickly gleaned. Oracle VM Repository The Oracle VM repository is based on storage allocated on a file server or a storage area network (SAN). In either case, repository-based storage is used for housing guest VMs, configuration files, ISO files, templates, and so on. Virtual disk storage is also carved out of the storage allocated to the repository. Processors The number of processors available to guest virtual machines can theoretically exceed the number of processors (or processor cores) available on the VM server. However, if the actual number of processors required by the guest virtual machines is larger than the number of physical processors available on the VM server hosting the virtual machines, there is a risk the virtual machines will cause the VM server to crash or at the very least be evicted (or “fenced”) from the cluster or server pool where the VM server is running. In the event a VM server is fenced, all virtual machines (even the ones that are not currently running) will be migrated to the remaining VM servers. Memory Just like the number of processors available to guest virtual machines, the amount of memory allocated to guest virtual machines can theoretically exceed the amount of memory available on a given VM server. But again, as with processor availability, if the amount of memory required by active guest virtual machines exceeds the physical memory available on a VM server, node eviction/fencing can occur. With processor and memory limits in mind, as a general rule, the number of processors and the amount of memory allocated to the virtual machines should be lower than the actual physical number of processors and the physical amount of memory available. Even though this may seem to be a commonsense statement, it is often misunderstood that virtualization does not magically allow processor or memory requirements to exceed physical availability. VM Server Storage VM server-based storage is a very tricky thing. It can be used for virtual disk or physical disk definitions used by templates, repositories, and/or virtual machines; however, it restricts the associated operations of the virtual machines to be limited to working only on the VM server that owns the storage. In the past, this was a crippling limitation. With the release of OVM 3.4, a very important feature has been included called “live migration.” OVM 3.4 incorporates storage live migration, which allows for the live migration of VMs and their storage from the local disk on one OVM server to the local disk on another OVM server. For the purposes of this chapter, all references to storage allocated to virtual or physical disks will be with respect to shared network- based storage—whether it’s storage area network, network attached storage, network file systems, or file servers—and this shared storage is available to all the VM servers in the server pool where the virtual machines will be operating. Technet24.ir|||||||||||||||||||||||||||||||||||||||| There are two methods for creating a template: you can clone a virtual machine to a template or you can clone a template to another template. In either case, you must complete the previous steps to allocate storage and configure a network for each template. The template customizer is a construct that is used during the cloning process to specify the specific storage and network components that will be incorporated into the template. The customizer is also used when deploying a virtual machine from a template and/or migrating templates, virtual machines, and so on, from one repository to another and the general processes are described here. Importing a Template The following process describes template creation using a .tar file as the source: 1. Place the .tar file in a directory accessible to the HTTP or FTP service. a. Determine the stub or parent directory structure for the HTTP or FTP service. b. Create a dedicated directory where the .tar file will reside (at least one directory name must be specified during the import operation). 2. Verify the target repository has sufficient resources to support the import operation. a. Increase the storage for the repository or create a new repository. b. Present the repository to the administration VM server. c. Designate the refresh VM server. d. Refresh the Oracle VM storage and repository. 3. Begin the import operation using the HTTP or FTP service. The command will look similar to the following (Figure 18-6 shows an example of the dialog used to input this information): where: uname:pwd is the username and password of an account that has access to the .tar file. @192.168.2.61 is the IP address or fully qualified server name where the HTTP or FTP service is running and the file is located. /tplts/OVM_MADB_1of2.tgz is the path to the .tar file that is a directory subordinate to the HTTP or FTP default service directory. (Note that the parent folders /var/http/www and /var/ftp/pub are not specified.) preferred practice. Exporting a Template The following process describes .tar file creation using a VM template as the source. Although this process is not required in order to create a virtual machine from a template, the steps are provided here in support of moving a template from one Oracle VM infrastructure installation to another. 1. Verify that the target file system has sufficient resources to support the .tar file creation operation. a. Identify VM physical disk storage and configuration file size. b. Identify VM virtual disk storage size. 2. Locate the virtual machine directories in the repository file system shared with the VM servers. The location of the virtual machine–related files can be determined based on the repository file system where the virtual machine definition is located. For more information about the file system structure, refer to the Oracle VM Manager Administration Guide. 3. Use the UNIX tar command create the .tar file using compression. The contents of the .tar file will include the following: All virtual machine virtual disks All virtual machine physical disks The virtual machine configuration file Any other files stored in the virtual machine repository directory The file size maximum needed for a file transfer can be determined using one or more of the following criteria: If the virtual machine being exported exceeds the predetermined amount, the exported .tar file may need to be broken up into two or more files. Oracle Corporation recently released additional information regarding the creation of template files. This information is captured in the backup and recovery strategy of an Oracle VM infrastructure. Specifically, the .tar file can be created by using the repository export feature and a shell script that is passed the unique identifier of the VM guest. For more information, refer to the Oracle documentation regarding repository exports. Technet24.ir|||||||||||||||||||||||||||||||||||||||| Note that in the storage management clone customizer screen, after you select the target storage type (virtual or physical disk), the search icon (the magnifying glass) will reveal only available storage objects (that is, predefined storage) available for use. NOTE After you complete the Network Mappings dialog and click the Finish button, the VM Manager will kick off the jobs to create the clone customizer, which includes the processes associated with network and storage mappings and the clone customizer definition being added to the template in the repository. These jobs can be seen executing in the status window at the bottom of the VM Manager GUI. If they are successful, the Manage Clone Customizer window is displayed showing the newly added clone customizer to the list of customizers available for the given template. Oracle VM Assemblies Creating guest virtual machines from a template is performed as a “single result” set of operations (that is, the guest virtual machine is the single result of the overall set of tasks). There are other, more advanced ways to deploy a set of virtual machines, including some specific interoperability configuration items that can be controlled during the deployment of multiple machines that are tightly integrated; this construct is known as an assembly. Deploying an assembly is a one-shot process, which results in multiple virtual machines based on multiple templates. However, deploying a set of templates in a “one-shot” stream of processes requires the use of Oracle Enterprise Manager 12c or 13c. It should be noted that the exact same process can be done without using Enterprise Manager. However, the process is done one virtual machine at a time and is still based on a template for each virtual machine. With the release of Oracle VM 3.4, assemblies are no longer part of the Oracle VM Manager GUI and are, in fact, managed only through Oracle Enterprise Manager. An assembly is a tightly coupled set of virtual machines with complex deployment requirements, which are part of the assembly definition and are managed during the deployment process. One such example is the Oracle eBusiness Suite Oracle VM Assembly, which can be downloaded from the eDelivery site. After successfully importing the assembly into the OEM software library and after deploying the Oracle VMs inside the assembly using the template import and deployment processes described in this chapter, an entire eBusiness suite set of virtual machines will be running. This suite includes a multi-node RAC database, a highly available and load-balanced middle tier, and a fully populated and production-ready vision database with a network-file- system-capable management layer, which is also production ready. All these components make up a single assembly, which is composed of several template or appliance files (close to 30 files). After applying the underlying principles of this chapter, you will have multiple Oracle virtual machines in a tightly integrated configuration, deployed from an assembly that is constructed and subsequently Summary Creating an Oracle guest virtual machine using templates is the most common method and the basic foundation of deploying complex, loosely coupled machines in a virtualized infrastructure. A more advanced method of integrating templates is through the use of an assembly, which is basically a collection of templates with specific deployment characteristics that, when combined with the basic deployment of a guest from a template, can be used to deploy tightly coupled guest virtual machines. For example, Oracle Corporation has made assemblies available that include all the pieces and parts of a complete E-business Suite infrastructure, including the database machines and databases (in RAC and stand-alone configurations) and the middle-tier application servers, including the SOA infrastructure and WebLogic hosts. CHAPTER 19 Creating Virtual Machines Manually T he counterpart to the process of creating a guest VM using a template is the process of creating a guest VM manually. Consider this: the only difference between creating a host machine running a choice-flavored operating system on a bare-metal host versus a guest virtual machine host is the preparation before installing and configuring the host operating system software. If you are creating a host machine on bare metal, your preparation includes installing the CPU, memory, and storage on a motherboard with a power supply, a fan, and a beverage-cooled chassis. By contrast, if creating the host machine in an Oracle VM infrastructure, preparation involves allocating the storage from the SAN and/or file server, choosing the number of processors to assign, and deciding how much memory to use of what’s available. Other than that, the guest VM will be created from an ISO file or from a PXE server (named Tinkerbell) or cloned from another machine (physical or virtual). In short, there literally is no difference between operating system installation steps after the environment has been prepared. Storage Management Prior to starting the new guest VM, allocate and configure the storage for use. The details of storage management are found elsewhere in this book, but for the purposes of this chapter, just know that the storage management process is the same regardless of the guest VM source media. As shown in Figure 19-1, the resources for the target guest virtual machine have been allocated and configured. Beginning with the storage management screen, the target storage in this example has been allocated as a physical disk. Recall that only physical disk-based storage is supported for production virtual machines. Although virtual disks may be carved out of repository-based storage, physical disk definitions are based on LUNs carved out of network-attached storage or a storage area network (SAN) resource. The storage device needs to be refreshed so that the storage can be detected. The naming convention, by default, is cryptic and will be based on the SAN device if a physical disk is used as the system or boot disk. It is a best practice to edit the physical device and change the simple name of the target storage to something appropriate for the guest virtual machine and to include a brief description. Figures 19-2, 19-3, and 19-4 show the process before and after modifying the name and including a brief description. Technet24.ir|||||||||||||||||||||||||||||||||||||||| It is a good idea to include some meaningful information about the guest virtual machine and the storage device for quick reference, especially during triage and performance-tuning exercises. Critical to the process of manually creating a guest VM is staging the media that will be used for creating the guest VM. In this example, a Microsoft Windows Server 2012 guest VM will be created. The source ISO, shown in Figure 19-5, must have been imported to an accessible repository. Details of this process are found throughout this book and include staging the ISO media and using the import facility of the VM Manager repository. FIGURE 19-6. The first screen of the Create Virtual Machine dialog Selecting the Create a New Virtual Machine option displays a general information dialog for the VM (see Figure 19-7). Although some of the information is optional (for example, the operating system type), during the creation process it is extremely helpful to populate these fields with meaningful information. This comes in handy later when scanning multiple virtual machines in the Servers and VMs tab. After entering the needed information and clicking Next, the Set Up Networks dialog is displayed (see Figure 19-8). Choose a network and add the virtual network interface card by clicking the Add button. Multiple network interface cards may be added, or this task can be deferred until a later time. Figure 19-9 shows an example of this screen with a virtual machine network (defined in the Network Channels section of the Oracle VM Manager GUI). After the appropriate networks are added, the Arrange Disks dialog appears. This is where the boot media and installation target storage are added to the target guest VM. Figures 19-10 through 19-13 show the process of adding the boot media as well as the target storage for the operating system. Technet24.ir|||||||||||||||||||||||||||||||||||||||| It should be noted here that choosing the CD-ROM as the first disk is optional. If the target CD-ROM is listed second or later, then by default it will not be selected as the boot device. However, just as with a bare-metal installation, the BIOS may be used to indicate which disk to use as the boot device. There may be an order to the boot device used to start the machine based on the presence of an operating system. In other words, if the physical disk is selected first and the CD-ROM is selected second, then the boot process will look to the physical disk for an operating system. If no OS is found, the boot process will automatically look to the CD-ROM. Hence, it is equally important during the configuration of a target guest VM to indicate the proper boot device order. The order of the disks will determine the boot device if the boot order is not specifically defined in the Boot Options dialog. If this is left blank, the boot device order will be determined by the order of the disks in the Arrange Disks dialog. Regardless of the position of the CD, after the guest VM is installed, the virtualized boot order will behave just like the BIOS on a bare-metal platform. As stated, regardless of the order of the disks, a boot device may be selected. Be Technet24.ir|||||||||||||||||||||||||||||||||||||||| After selecting the virtual machine and launching the terminal console, start the virtual machine by selecting the Start icon, as shown in Figure 19-17. The terminal console view presents a dialog for configuration tasks. The manual interaction process is illustrated in Figure 19-17. After you start the virtual machine for the first time, the boot device will be accessed based on the boot device configuration or the order of the disks in the Arrange Disks dialog. You can also monitoring the OS installation process through the virtual console, as shown in Figure 19-18, and the level of detail and amount of information is dependent on the OS vendor. Just as if you were sitting in front of the terminal connected to a bare-metal machine, the virtual terminal console will display the installation process from the boot installation media. Figure 19-19 shows an example of this interaction. Proceed with the dialog as normal when installing the target guest operating system. Post–Guest VM Creation After you have installed the guest operating system, either the installation media used as the boot device will need to be removed or the boot device (for subsequent machine startup) will need to be specified in the Oracle VM configuration (in case the target operating system was not specified as the first disk). If, however, the first disk was specified as the operating system disk and the boot device screen was left blank, then the new guest virtual machine will boot from the operating system disk. Figures 19-20, 19-21, and 19-22 illustrate the process of editing the guest VM and removing the installation ISO. As can be seen in Figure 19-21, removing the installation media can be accomplished by either removing the CD-ROM drive altogether or by simply ejecting the media but leaving the CD-ROM drive as part of the VM. It is your choice; either operation achieves the desired result. Assuming the installation source media was based on a CD-ROM, and the guest Oracle VM used the ISO via a virtual CD-ROM device, the virtual device may be removed after the Oracle VM has been created. An example of removing the CD-ROM device altogether is shown in Figure 19-22. Summary Creating an Oracle guest virtual machine manually is an extremely forgiving process in that the guest VM structure can be created prior to your allocating any resources. The guest VM creation process is based on a “source,” which may be a template, a pixie server (PXE), or another guest VM. In actual practice, you can create a guest “object” while managing a given object. In other words, while managing a current guest VM, you can request a “clone,” in which case that is simply another entry point into the guest VM manual creation process. CHAPTER 20 Managing the VM Environment and Virtual Machines T hroughout this book, you have seen how to configure the Oracle VM Server farm and Oracle VM guests. This chapter focuses on some of the day-to-day operations that the VM administrator will perform, including state management and configuring options that might change regularly, such as memory, network, and disks. As with most operations, you have several ways to perform these tasks: the Oracle VM Manager, OEM Cloud Control, Oracle VM CLI, and Xen xm commands. Whereas day-to-day one-off operations such as monitoring and viewing the VM farm work great with the Oracle VM Manager and OEM, anything that is repetitious and complicated will benefit from using the Oracle VM CLI. NOTE The OEM Cloud Control 13c method of managing virtual machines is not covered in this chapter because it is covered in detail later in the book in Chapters 23–25. This chapter covers managing virtual machines via OVM Manager, OVM CLI, and xm commands. You can determine the status of the virtual machine in a number of ways, including xm list (on the VM Server), ovm list vm, and, of course, using the GUI tools. Again, you can determine the status of the virtual machine in a number of ways, including xm list (on the VM server), ovm list vm, and, of course, using the GUI tools. Modifying the virtual machines should be done with care because changing the configuration might also require changes within the virtual machines themselves. Cloud Control, or the Oracle VM CLI. Depending on the underlying operating system, a reboot of the virtual machine may or may not be required. NOTE The network on a paravirtualized guest is faster than the network on an HVM guest. If the intent is to use network storage, keep this in mind. The HVM accelerations speed up memory access, so it is a trade-off among I/O, network (paravirtualized), and memory (HVM). made the deploying process obsolete because you can start with an already configured virtual machine. From the Create Virtual Machine window, you can select to create a virtual machine from an Oracle VM template or a Virtual Appliance, or you can create an entirely new VM from scratch using installation media such as Kickstart, Jumpstart, or any other network-installation method supported by the guest OS. If you select to create a new VM, you will see the Create Virtual Machine window shown in Figure 20-2. Here, you have many options for creating the virtual machine, including the number of CPUs, amount of RAM, and using HVM versus paravirtual. Some of the choices such as RAM, Processors, and Priority, can be changed dynamically. Other choices such as the Domain Type and Operating System cannot be changed while the VM is running. NOTE Newer versions of Linux will dynamically pick up some changes while the VM is active. Once you have filled out the main screen, you have several other tabs of options you can configure, including Networks, Disks, Boot Order, and Tags. Once you have filled out all the screens and have appropriately set up an ISO image and boot order, you can start the VM and install from the installation ISO. Once you have chosen all the options you want to use, you can create the VM. Here is a complete example: Once you verify the delete operation, the virtual machine and selected disks will be deleted. If you are deleting more than one VM, the CLI is a great way to do it. You can select to clone to a VM or template. Input the virtual machine name index and number of copies and then select the server pool name from the drop-down list. Once you are satisfied with your selections, click OK to start the cloning process. There is no confirmation screen for this task. Once you have clicked OK, cloning begins and control returns to the Virtual Machines screen, where you can watch the progress of the cloning operation. destName destType serverPool cloneCustomizer targetRepository Once the cloning process has completed, the new systems are ready for use, as shown here: The cloning process addresses the MAC address issue we used to have with creating templates in earlier versions of Oracle VM. When you create a new VM from this template, a new MAC address will be assigned. Summary This chapter covered some of the different options for managing the state of Oracle VM virtual machines, including the starting and stopping of virtual machines, the suspending and resuming of virtual machines, as well as the older deployment process and the cloning process. Managing the state of the virtual machines is really the most important task an administrator has to take on—in addition to making sure everything is properly backed up. Chapter 21 covers physical to virtual migration. CHAPTER 21 Physical-to-Virtual Migration and Virtual- to-Virtual Migration Technet24.ir|||||||||||||||||||||||||||||||||||||||| Intemplates previous chapters, you learned how to create virtual machines by hand and via and assemblies. In addition to these methods, it is also possible to create a virtual machine in Oracle VM from an existing physical machine. This opens up many possibilities for both testing and upgrading without putting your production system at risk. It also provides the ability to quickly move a legacy system on old hardware to a more stable and robust virtual machine. Uses of the physical-to-virtual migration include the following: As you can see, there are multiple reasons why performing a physical-to-virtual (P2V) migration is useful. In addition, if hardware virtualization is being used, there is no reason why this technique cannot be used to migrate from another vendor’s virtualization product to OVM. From here, the system will boot into the OVM installer by booting the Linux operating system (OS). Once it has completed the boot process, you will see the Disk Found screen. Here, you can choose to test the CD-ROM or press TAB to move the focus to Skip and then press ENTER, as shown in Figure 21-2. The installation process will begin to discover the hard disk of the physical system and will eventually end up at the “Select the disks to include in the image” dialog. From here, you should select all the disks you intend to migrate. The sample system in the figures has only one disk associated with it. Highlight all the disks to be included by using the arrow keys and spacebar to select the disks. Once you have selected all the disks you want to include, tab to OK and proceed by pressing enter. This screen is shown in Figure 21-3. FIGURE 21-3. The “Select the disks to include in the image” dialog At this point, you will be prompted to provide some additional information about the virtual machine to be created. The information requested includes the name of the VM, the memory to be allocated, the number of virtual CPUs, and the console password. This is shown in Figure 21-4. When you have filled in all of the blanks, tab to OK and press ENTER. Once you click enter, you will see a message at the bottom of the screen informing you of a web server that has been started. The URL of the web server is the IP address that has been provided here, as shown in Figure 21-5. You will use this URL in the next stage. Open the URL (IP address) in a browser using HTTPS. This will open a web page showing you a list of files that are available for download. This is shown in Figure 21- 6. Take note of the files that have been displayed. You will need the vm.cfg and virtual disk image System-sda.img in the next step. Now that you have the URL of the images, you will import them into OVM via the OVM Manager. In the OVM Manager repositories screen, select the repository to be used and navigate to templates. Once you are in the templates screen, you can select Import Template. Fill in the URL for the virtual disks and vm.cfg file that you noted in the previous screen. The Import VM Templates dialog is shown in Figure 21-7. Once the template has been imported, you will create a virtual machine using the methods described in this book to create a virtual machine from a template. VMware images and convert them directly into an OVM virtual appliance. Fill in the path to the local directory where you want the OVF template to be exported to. This will be a directory on the system from which you are running, not on the Oracle VM server. Once you have completed this, you will see the progress in the Depending on the size of the virtual machine, this could take a while. Once it has completed, you will see the Export Complete dialog (not shown). The next step moves from the VMware vSphere client to the Oracle VM Manager. In order to import an OVA image into Oracle VM, you must use a web server to download the file. However you decide to do this, you must move the OVA file that you just created to a web server that is accessible from OVM. Once you have uploaded the file to a web server, you will be able to import using the Oracle VM Manager. From the Oracle VM Manager, select the repository into which you want to import the OVA image. Select the Virtual Appliances folder within the repository that you want to use and then choose the Import Virtual Appliance icon from the toolbar in the management pane. This will bring up the Import Virtual Appliance dialog, as shown in Figure 21-10. Fill in the URL and click OK in order to import the virtual appliance. Once you have imported the virtual appliance, you are then ready to use it. Select Create Virtual Machine (available from several menus) and select Clone from an Existing Virtual Appliance, as shown in Figure 21-11. Once you have selected to create from a virtual appliance, you will be asked what the repository is, what the virtual appliance is, and which server pool to install it in. This is shown in Figure 21-12. FIGURE 21-12. Select the repository, virtual appliance, and server pool. Once you have clicked Finish, the virtual machine will be created. This will complete the conversion from VMware to Oracle VM. Before starting the virtual machine, you should edit it and make sure the network and disk are set up correctly. Once you have completed this step, you can start the VM. Summary As you can see from this chapter, it isn’t very difficult to create a virtual machine from either a physical system or from a VMware virtual machine. Each process is different, but both are very straightforward and easy to do. Both also require the virtual or physical machine to be down during the process. CHAPTER 22 Virtualization Summary and Best Practices Technet24.ir|||||||||||||||||||||||||||||||||||||||| This chapter summarizes the key concepts and tasks presented in this book relating to the Oracle virtualization platform. This chapter uses two approaches: the minimalist approach (sometimes confused with “least expensive”) and the realist approach, whereby benefits of virtualization are realized using recommended best-practice methods without breaking the bank. For example, although it is true only one virtual machine server is required to deploy guest VMs, and although such a configuration may be deemed acceptable for demonstration or discussion purposes, a single-VM-server configuration cannot realistically meet even the most basic availability and performance requirements. In addition, a single Oracle VM Server configuration is also limited to the scaling capability of just that machine (that is, the number of CPU sockets, memory slots, expansion slots, and so on). Meanwhile, a recommended best practice is to have three or more virtual machine servers. Again, depending on the objective, three, five, seven, or nine OVS machines may be required in the long run, but the initial deployment requirements are satisfied with five servers. Each approach (minimalist or realist) will be followed by a summary of post- deployment, management, and operations best practices. These include the concepts and tasks in support of backup and recovery, monitoring and tuning, and capacity planning, which will primarily focus on storage volume, network traffic, and process performance, including virtualization administrative tasks such as VM migrations and patching. Storage The source of storage from the perspective of the guest VM is either storage presented by the repository, storage presented directly to the guest VM by a SAN or a file server, or storage residing locally on an Oracle VM server. Generally speaking, all storage in an Oracle VM environment is based on SAN storage, file server storage, or storage residing locally on an Oracle VM server. The main difference is whether or not additional maintenance and operations are required when you’re growing the storage used by the guest virtual machine. Regardless of the source (SAN, NFS, or disk attached locally to the Oracle VM server), if the guest VM is using storage presented through a repository, and the repository has available space, then the guest VM storage can grow dynamically without additional SAN, NFS, or VM server local disk administration. If, however, the guest VM is using storage presented directly from the SAN, NFS, or local disk (as opposed to presented through a repository), then additional administration is required to grow the LUN. Repository-Based Storage The storage used by an Oracle VM storage repository is based on SAN storage, file server storage, or storage residing locally on an Oracle VM server. Although there are performance implications between using network-based storage versus locally attached storage, it is more important to understand the maintenance and operational issues when you’re considering using either storage method. Figure 22-1 shows information about physical storage that is locally attached to the Oracle VM server. In this case, the storage is a 44TB array defined as a single LUN. The Oracle VM server detects the storage and lists it as available. This storage can be used when you’re defining the repository. strictly on the VM server where the locally attached storage resides. This limitation is somewhat resolved with the release of Oracle VM 3.4; however, there are still some limitations that have an impact on live migration and are covered in greater detail in the release notes. The key point is that guest VMs using repository-based storage have the flexibility to grow the storage allocated to them dynamically from storage available in the storage repository VM without having to allocate additional storage LUNs from the SAN or grow a file system. Repository-based storage is therefore a general best practice to use as a source of storage for guest VMs. This LUN could have instead been presented directly to a guest VM, but that would have been a 2TB dedication. Because the LUN has been presented to the repository PHYrepo1, the 2TB is available to any VM and the storage can be allocated based on the VM’s need. For example, if an Oracle Linux guest VM (OLVM1) were to be created and needed two disks (for example, 20GB for the root file system and 80GB for everything else), that guest virtual machine (once created) would use a total of 100GB out of the 2TB allocated to the repository, and the repository would still have 1.9TB available for other virtual machines. Meanwhile, if the storage requirements of OLVM1 were to increase, then the disks of that guest virtual machine could be increased to whatever size is necessary (provided it’s less than 1.9TB), and no other administration would be required because the storage is available in the storage repository. If the two discs created in this example were allocated as individual LUNs, then a system administrator would be required to grow each of the LUNs at the operating system before the disks could be grown in the guest virtual machine. There may also be performance benefits between using physical LUNs versus virtual disks out of a storage repository. However, each environment and situation should be tested to determine whether the performance benefits outweigh the additional administration required to manage the shared storage as opposed to using repository- based storage. Networking Generally speaking, there are two primary considerations in the Oracle VM network environment: the physical network components and the virtual network components, also known as network channels. Figure 22-4 shows the Networking tab in the Oracle VM Manager GUI. From the minimalist perspective, there will be one physical network interface card (NIC) per machine, and all Oracle VM network channels use the single NIC. This is an acceptable configuration from the perspective of an operational environment. However, even from a minimalist perspective, in production there should be at least two physical NIC adapters per network path, and these should be bonded to provide at least a minimum sense of availability (in most cases, this provides performance benefits as well). Storage and Virtual Machine network channels These network channels are used to provide the path for the virtual machine virtual network (communications between Oracle VMs and from the Oracle VMs to the Internet and resources on the local network). It is a recommended practice to define VLAN virtual adapters for the storage and network, as well as to manage virtual machine communications. Figure 22-5 shows an example of the VLAN adapter definition screen. In this example, two VLAN interfaces have been defined. They are on two separate bond ports of two Oracle VM servers. In this example, no addressing was chosen for the VLAN interfaces, but they could’ve easily been defined as Static or Dynamic. An IP address and subnet mask would be required if Static were chosen, and DHCP would be expected to provide an IP address if The minimalist approach to memory is simple: pack the Oracle VM server with enough memory to support the guest VMs, plus a little more for the hypervisor. This is not far from reality. Although it is not required to have the same amount of memory on each of the VM servers, it is recommended that all the servers in a given cluster are of the same “family” in terms of CPU, and any given VM server should conceivably be able to handle the load of all guest VMs. Realistically, this should never be expected, especially for some larger implementations. However, there are no rules to the size and speed of memory, save one: more is better. Again, although it is true no given Oracle VM server should be expected to run all Oracle VMs simultaneously, the consideration must be made that in the event of a failure of one or more Oracle VM servers, the remaining Oracle VM servers should be able to sustain the operations of the guest virtual machines currently running. At best, there should be sufficient memory in a single Oracle VM server to run the mission-critical guest VMs. This is the minimalist approach. Realistically, however, a given Oracle VM server or several Oracle VM servers in a cluster should have sufficient memory to support the mission-critical guest virtual machines as well as a few additional servers, for example, servers used for administration and maintenance (Oracle Enterprise Manager RMAN catalog database, etc.) Also keep in mind that the memory resources are not “shared” across the Oracle VM servers (which would really be nice). Finally, the amount of memory on a given VM server needs to be sufficient to run not only the guest VMs, but also to support the requirements of the dom0 hypervisor. Figure 22-6 is an example of a guest VM showing memory and CPU cores. Rule of thumb: add up the memory required by each guest VM and then add another 4 to 8GB. FIGURE 22-6. VM server-based guest VMs showing memory and CPU cores With respect to CPU requirements, as with memory, the number of available CPU cores on a given Oracle VM server should be based on the number of CPU cores required by the virtual machines, plus one or two CPU cores for the hypervisor dom0. For example, if there are 10 guest machines, and each guest VM requires two virtual CPUs, then the VM server should have a minimum of 22 cores available: (two cores per guest VM × 10 guest VMs) + two cores for the hypervisor dom0. Again, this is the minimalist approach. Realistically, because there should be at least three Oracle VM servers, and the load should be spread more or less equally across the VM servers, then each Oracle VM server should have approximately eight CPU cores. Keep in mind this does not mean 12 sockets. In today’s world, a 24-core equipped machine may fit on just three CPU sockets. In short, both the minimalist and realist approaches to CPU and memory are basically the same: more is better (that is, more available physical resources), and ultimately the virtual requirement must be equal to or less than the physical resources available. The difference between the two approaches (minimalist and realist) with respect to CPU and memory resources is a factor of capacity rather than performance; in other words, regardless of the CPU core “speed” (in terms of hertz) or the cores-to-socket ratio, the minimum number of CPUs “to go into the plan” should be equal to or greater than the number of virtual machines. Similarly, for the memory, the total physical memory should be equal to or greater than the maximum that will be allocated (or allowed) to the respective guest virtual machines. Again, a resource’s speed is not the limiting factor. the Oracle VM Manager, Oracle VM server, guest Oracle VM templates, and the requisite Oracle Linux software have been acquired, the concepts and tasks for deploying an Oracle VM installation begin with planning the configuration, with the objective of sustaining some basic guest VMs. The source of the installation and upgrade software should be the Oracle eDelivery site “Oracle Software Delivery Cloud” whenever possible. Although there are many other sources of software, including the Oracle Technology Network, only the eDelivery site is guaranteed to contain production-ready bundles. The URL for this site is, and it contains the Oracle VM software and templates required for most deployments. Figure 22-7 shows a partial Oracle software-delivery site listing of Oracle VM Server software. If the term “template” would have been included in the search, the result would have included 38 products, each of which require further refinement to drill down to the specific required template. Oracle VM Manager Oracle VM Server Oracle Linux template (optional) Oracle Linux server software (optional) Other operating system(s), such as Windows, CentOS, and so on Deploying Oracle VM The deployment of Oracle VM begins with planning. The Oracle VM Manager is the first major component to deploy. As such, the following serves to clarify some points: OVM Manager should not be installed on the same server as Enterprise Manager. The OVM Manager installation cannot use the WebLogic server that is installed with Oracle Enterprise Manager. The OVM Manager installation requires its own technology stack. Oracle VM Manager is an application that is installed on a normal Linux operating system such as Oracle Linux or Redhat Linux 5.8+ (including 6 and 7), and it can be a physical or virtual machine. (However, you should learn the process first before complicating it with virtualizing the virtualization management tools.) The Oracle VM Manager doesn’t need anything special for networking. It just Assuming enough thought and planning have been given to the storage and networking, a typical deployment will have storage served to three or more Oracle VM servers through multiple repositories. It is advisable, if not a best practice, to group the Oracle VM guest virtual machines of a similar type, business system, or role into a given repository or group of repositories, which makes backing up the guest VMs and their associated data much simpler and more logical. In other words, you should create each repository with the intent of putting logically grouped VMs into it. This practice applies not only to repositories, but also to the server pools and network-creation tasks. Figure 22-8 shows an example of logically grouped VM repositories, where there are multiple repositories for guest virtual machines based on physical disks and another repository for guest VMs targeted for cloud deployment. With respect to the planning of the server pools, the most important restriction to remember is that the clustering is only available at creation time. A nonclustered, stand- alone server pool cannot be dynamically “clustered.” It must be re-created as a clustered server pool. The converse is also true: that is, a clustered server pool cannot be made into a nonclustered, stand-alone server pool but rather must be dropped and re- created. The main difference between clustered and nonclustered server pools is the OCFS2 file system used to support the clustered server pool. The crux of the biscuit: it is perfectly acceptable (and is a recommended best practice) to create the server pool as a clustered server pool with only one server and then add servers down the road as the Oracle VM environment grows. The first major task is to install the Oracle VM Manager on a machine. Again, generally speaking, it is this author’s opinion that you should run Oracle products in and around other Oracle products. In other words, it is a recommended best practice to deploy Oracle Fusion middleware, for example, within an Oracle Linux environment, and if you’re virtualizing the environment, to do so with Oracle virtualization products. This may be the most obvious of general best practices, but it is also no doubt the most difficult to address, especially if the given environment is running another flavor of virtualization product. Clustered server pools are defined at the time of server pool creation. A server pool is created using one or more Oracle VM servers; the recommended number of Oracle VM servers is three (or more), but it should also be an odd number of Oracle VM servers (three, five, seven, and so on). In a larger environment, it is also a best practice to logically group the Oracle VM components. Logical groupings include the following: FIGURE 22-9. Networking tab showing multiple channels for storage, virtual machines, and Live Migrate Summary This chapter summarized the most important basic best practices of the Oracle VM environment. Namely, you should logically group guest virtual machines into repositories that can be placed into a backup strategy whereby the repository backups capture the logical grouping of guest VMs, including the guest VM, the configuration, and the data presented through the repository. Additionally, repository-based storage is presented in comparison to storage offered by the SAN or file server directly to the guest VM. With respect to networking, a similar concept prevails as a best practice: to logically group the traffic used by the guest virtual machines into VLANs and furthermore to control the grouping of the traffic (while adding a layer of security) through CIDR addressing schemes. This chapter also showed that some of the best practices allow for a minimalist approach as a proof of concept, while leaving open the opportunity to grow into a more realistic deployment using Oracle VM software for virtualizing the data center in the cloud. PART V Installing and Configuring Enterprise Manager Cloud Control for IaaS CHAPTER 23 Basic Cloud Control Installation Technet24.ir|||||||||||||||||||||||||||||||||||||||| A lthough). This chapter covers how to connect an Enterprise Manager 13c system to Oracle VM Manager, covering steps 1 and 2 of the workflow for setting up a cloud infrastructure (see Figure 23-1). Chapter 25 will cover Steps 3–6 as part of setting up the IaaS self-service portal. 13c environment: Oracle Database Oracle Fusion Middleware Oracle Cloud Framework Additional plug-ins are required to support managing IaaS. The following plug-ins must be installed (in order) prior to your configuring the Enterprise Manager 13c IaaS service: When you are upgrading the plug-ins, use the following order; upgrading them in the incorrect order could potentially cause problems with the system. Each plug-in has several internal dependencies. Save the output from the command because the entire SSL certificate section (in bold in the example) will need to be imported into the Enterprise Manager 13c agent. Note that there are two different keystore files: to and place them into a temporary file. In the example, /tmp/ovmm_ssl.txt is used and will look like this: Next, this SSL key will need to be imported into the Enterprise Manager 13c agent. When prompted for a password, use “welcome” (the default password for the keystore). Once the key is successfully imported into the keystore, the OVMM can be discovered in Enterprise Manager 13c. This will show the Infrastructure Cloud home page, which will be fairly sparse of information until the OVMM is registered. To register the OVMM, select the menu option Register OVM Manager under Infrastructure Cloud, as shown in Figure 23-3. This will start the registration process, where you will input the following information: Technet24.ir|||||||||||||||||||||||||||||||||||||||| Once everything is filled out, click Submit, and an Enterprise Manager 13c job will be submitted to register the OVMM. Once registration is complete, navigate back to the Infrastructure Cloud home page. Initially, there will not be much information, as shown in Figure 23-5. If there are existing VMs in the Oracle VM pool, you can expect to see several new targets in the Target Flux section. Enterprise Manager 13c will report these as new when they are first discovered. Over time, though, the page will show more historical information, as shown in Figure 23-6, including Charge Trend if the Chargeback feature is configured. Target Flux will also show retired VMs, which are VMs that have been deleted. Summary This chapter covered how to prepare the OVMM to be discovered by an Enterprise Manager 13c system. We discussed how to export the SSL key from OVMM and import it into the Enterprise Manager 13c agent. In addition, we covered the discovery process of the OVMM, and you learned how to add the OVMM system to Enterprise Manager 13c. In the next chapter, you will learn how to use Enterprise Manager 13c to perform several common tasks on the OVMM system. CHAPTER 24 Using Cloud Control O nce Enterprise Manager 13c is linked to the Oracle VM Manager, an entirely new set of private cloud features are enabled in Enterprise Manager. Many of these features provide better security and automation for the administrator of Infrastructure as a Service (IaaS) with Oracle VM. Cloud security is enhanced because Enterprise Manager 13c allows granular control of resources in the private cloud. With Oracle VM Manager, only one user is created (admin) and that user has full access to all resources. With the Enterprise Manager 13c security subsystem, administrative access to targets can now be controlled. In addition, administrators can monitor and report on resource consumption, and even assign a cost to each resource with the Chargeback feature. What’s more, most administrative tasks can be performed from Enterprise Manager, including building VMs from templates and destroying VMs. The common administrative tasks are covered in the “Common Tasks Using Cloud Control” section of this chapter. Initially you will see the list of all administrators in Cloud Control. By default, only two users exist: SYSMAN (the superuser) and CLOUD_SWLIB_USER (an internal user for managing the software library). One of two options can be used to create a new user: Create or Create Like. The Create button is used to create a new administrator from scratch, with each role selected manually. For our example, we’ll create a new user called “pellipox” who has full admin privileges on a single VM and read-only access on other VMs. To create this user, click the Create button, as shown in Figure 24-2. NOTE You cannot clone the SYSMAN administrator using the Create Like button, but you can create future administrators this way. In the next screen, shown in Figure 24-3, you set the login name (in the Name field) and the initial password. These are required fields. Optionally, you can set the other fields, including E-mail Address, Location, Department, and Cost Center. You can also require the user to change his or her password upon the initial login by selecting the Expire Password Now checkbox. The next screen, shown in Figure 24-4, sets the administrator’s roles. These roles can be preset by the Enterprise Manager administrator and customized for the specific requirements for your.
https://it.scribd.com/document/371716035/Oracle-VM-3-Cloud-Implementation
CC-MAIN-2020-34
refinedweb
53,363
52.39
Issue: It is undefined how Zope's current (and future) implementation of properties will be mapped into the DOM/XML namespaces. A mapping needs to be defined for both objects and attributes. Notes: As I understand it, Jim is currently working on interface changes to the Property Manager to support namespaces. From this Zope will gain namespace support of attributes. This is only 1/2 of the battle. We will need similar changes to ObjectManager? to allow children to be in different namespaces. In XML both nodes and attributes are allowed to be in namespaces, and they are not neccessarialy the same NS. As the DOM defines it, every node (Elements, Documents, Attributes, etc) each have three components in thier name, a localName (everything left of the :), a prefix (Everything right of the :) and a namespaceURI, what the prefix is in reference too. : -- Mike As a resolution for object namepsaces, I propose adding a new standard attributes to objects, namespace-uri. This will prvide enough information to provide what the DOM API requires. I will defailt the vaule to. If the node name of an element does not contain a prefix, I will default it to zope. --Mike
http://old.zope.org/Members/jim/ZDOM-save/Namespaces/wikipage_view
CC-MAIN-2016-40
refinedweb
198
64.81
Components are the fundamental building blocks of React. In fact, components are the vocabulary of JSX markup. In this section, we'll see how to encapsulate HTML markup within a component. We'll build examples that show you how to nest custom JSX elements and how to namespace your components. The reason that we want to create new JSX elements is so that we can encapsulate larger structures. This means that instead of having to type out complex markup, we just use our custom tag. The React component returns the JSX that replaces the element. Let's look at an example now: // We also need "Component" so that we can // extend it and make a new JSX tag. import React, { Component } from 'react'; import ... No credit card required
https://www.oreilly.com/library/view/react-and-react/9781786465658/ch02s04.html
CC-MAIN-2019-04
refinedweb
128
67.25
Why Use Binary Trees? - Lorin Norton - 2 years ago - Views: Transcription 1 Binary Search Trees 2 Why Use Binary Trees? Searches are an important application. What other searches have we considered? brute force search (with array or linked list) O(N) binarysearch with a pre-sorted array (not a list!) O(log(N)) Binary Search Trees are also O(log(N)) on average. So why use em? Because sometimes a tree is the more natural structure. Because insert and delete are also fast, O(logN). Not true for arrays. 3 So It s a Trade Off Array Lists O(N) insert O(N) delete O(N) search (assuming not pre-sorted) Linked Lists O(1) insert O(1) delete O(N) search Binary Search Tree O(log(N)) insert O(log(N)) delete O(log(N)) search on average, but occasionally (rarely) as bad as O(N). 4 Search Tree Concept Every node stores a value. Every left subtree (i.e., every node below and to the left) has a value less than that node. Every right subtree has a value greater than that node 5 Question: Is This a Binary Search Tree? No. Why not? 6 So S pose We Wanna Search Search for 4 1. start at root move to 3 on left, because 4 < 7 So S pose We Wanna Search Search for 4. (cont.) 3. Now move to right because 4 > Now move to left because 4 < Now move to left because 4 < 5. But nowhere to go! 7 5. So done. Not in tree 8 How Many Steps Did That Take? 7 to 3 to 6 to 5. Three steps (after the root). Will never be worse than the distance from the root to the furthest leaf (height!). On average splits ~twice at each node 9 So Time To Search? So double the number of nodes at each layer. It s like doubling the counter variable each time through a for loop. How long does that take to run? Log(N) 10 Big-O of Search S pose tree bifurcates at every node. (This is an assumption that could be relaxed later). Each time we step down a layer in the tree, the # of nodes we have to search is cut in half. Holds half the remaining nodes. Holds half the remaining nodes. 11 Big-O of Search (cont. 1) For example, first we have to search 15 nodes = then 7 nodes = then 3 nodes = then 1 node = Now, note that tree has ~2 h+1-1 nodes where h = height of the tree. The height is the longest path (number of edges) from the root to the farthest leaf. 12 Big-O Search (cont. 2) So total number of nodes is N = 2 h+1-1 Or 2 h+1 (true for big N) Now how many steps do we have to search? A max of h+1 steps (4 steps in the example above). What is h? Solve for it! log(n) = (h+1) * log(2) h = (logn/log2) - 1 So h = O( log N ). Wow! That s how long it takes to do a search. 13 findmin and findmax Can get minimum of a tree by always taking the left branch. Can get maximum of a tree by always taking right branch. 7 Example min max 5 14 Inserting an Element Onto a Search Tree? Works just like find, but when reach the end of the tree, just insert. If the element is already on the tree, then add a counter to the node that keeps track of how many there are. Do an example with putting the following unordered array onto a binary search tree. {21, 1, 34, 2, 6, -4, -5, 489, 102, 47} 15 Insert Time How long to insert N elements? Each insert costs O(log(N)). There are N inserts. Therefore, O(Nlog(N)) Cool, our first example of something that takes NLogN time. 16 Deleting From Search Tree? Ugh. Hard to really remove. See what happens if erase a node. Not a search tree. Must adjust links There is a recursive approach (logn time), or can just reinsert all the elements in the subtree (NLogN time) Easiest to do lazy deletion. Usually are keeping track of duplicates stored in each node. So just decrement that counter. If goes below 1, then the node is empty. If node is empty, ignore the node when doing find s etc. So delete is O(logN) Tell me why? 17 Humdinger. OK, so on average, insert and delete take O(logN) time. But remember the tree we created with {21, 1, 34, 2, 6, -4, -5, 489, 102, 47}? Let s do the same thing with the array pre-sorted. {-5, -4, 1, 2, 6, 21, 34, 47, 102, 489}? Whoa, talk about unbalanced! -5-4 (Note: there isn t a unique tree for each set of data!) 1 2 6 18 Worst Case Scenario! Remember how everything depended on having an average of two children per node? Well, it ain t happenin here. In this case, the depth is N. So the worst case is that we could have O(N) time for each insert, delete, find. So if insert N elements, took O(N 2 ) time. Ugh. 19 Looking For Balance We want as many right branches as left branches. Whole branch of mathematics dealing with this. (har, har, very punny!) Complicated, but for random data, is usually irrelevant for small trees. Phew, so we are ok (usually). 20 Sample Implementation (Java) public class BinaryNode { public int value; public BinaryNode left; public BinaryNode right; public int numinnode; //optional keeps track of duplicates (and lazy deletion) } /**constructor can be null arguments*/ public BinaryNode(int n, BinaryNode lt, BinaryNode rt) { value = n; left = lt; right = rt; numinnode = 1; deleted = false; } 21 Sample Implementation (C) struct BinaryNode; typedef struct BinaryNode *BinaryNodePtr; struct BinaryNode { int value; BinaryNodePtr left; BinaryNodePtr right; } int numinnode; int deleted; //optional keeps track of duplicates //optional marks whether node is deleted 22 Sample Find (Java) /**Usually start with the root node.*/ public BinaryNode find(int n, BinaryNode node) { if(node == null) return null; if(n < node.value) return find(n, node.left); else if (n > node.value) return find(n, node.right); else return node; //match! } could be null Note: returns the node where n is living. 23 Sample Find (C) /*Usually start with the root node.*/ BinaryNodePtr find(int n, BinaryNodePtr node) { if(node == NULL) return NULL; if(n < node->value) return find(n, node->left); else if (n > node->value) return find(n, node->right); else return node; //match! } 24 Other Trees Many types of search trees Most have modifications for balancing B-Trees (not binary anymore) AVL-trees (restructures itself on inserts/deletes) splay-trees (ditto) etc. 25 So-So Dave Tree Each time insert a node, recreate the whole tree. 1. Keep a separate array list containing the values that are stored on the tree. so memory intensive! Twice the storage. 2. Now add the new value to the end of the array. 3. Make a copy of the array. ooooooh, expensive. O(N). 4. Randomly select an element from the copied array. because randomly ordered, will tend to balance the new tree O(1) 5. Add to new tree and delete from array. oooh, O(logN) insert ughh, O(N) delete 6. Repeat for each N. So what s the total time???? O(N 2 ) for inserts. Why? 26 Can You Do Better? Improve the So-So Dave Tree. p.s. It can be done! p.p.s. Consider storing in something faster like a linked list, stack, or queue You still have to work out details. p.p.p.s. That s the Super Dave Tree. p.p.p.p.s. Bonus karma points if your solution isn t the Super Dave Tree and is something radically different. p.p.p.p.p.s. No karma points if you use a splay tree, AVL tree, or other common approach, but mega-educational points for learning this extra material. From Last Time: Remove (Delete) Operation CSE 32 Lecture : More on Search Trees Today s Topics: Lazy Operations Run Time Analysis of Binary Search Tree Operations Balanced Search Trees AVL Trees and Rotations Covered in Chapter of the text Heaps. CSE 373 Data Structures Binary Heaps CSE Data Structures Readings Chapter Section. Binary Heaps BST implementation of a Priority Queue Worst case (degenerate tree) FindMin, DeleteMin and Insert (k) are all O(n) Best case (completely. Algorithm Performance and Big O Analysis Data Structures Algorithm Performance and Big O Analysis What s an Algorithm? a clearly specified set of instructions to be followed to solve a problem. In essence: A computer program. In detail: Defined Algorithms and Data Structures Written Exam Proposed SOLUTION Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points Search Tree AVL Trees / Slide 1 Balanced Binary Search Tree Worst case height of binary search tree: N-1 Insertion, deletion can be O(N) in the worst case We want a tree with small height Height of a binary tree Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * * Binary Heaps A binary heap is another data structure. It implements a priority queue. Priority Queue has the following operations: isempty add (with priority) remove (highest priority) peek (at highest: 1 2-3 Trees: The Basics CS10: Data Structures and Object-Oriented Design (Fall 2013) November 1, 2013: 2-3 Trees: Inserting and Deleting Scribes: CS 10 Teaching Team Lecture Summary In this class, we investigated 2-3 Trees in Big Data and Scripting. Part 4: Memory Hierarchies 1, Big Data and Scripting Part 4: Memory Hierarchies 2, Model and Definitions memory size: M machine words total storage (on disk) of N elements (N is very large) disk size unlimited (for our considerations) Converting a Number from Decimal to Binary Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive TREE BASIC TERMINOLOGIES TREE Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing hierarchical relationship between the grand father and his children and Ordered Lists and Binary Trees Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0: Analysis of Binary Search algorithm and Selection Sort algorithm Analysis of Binary Search algorithm and Selection Sort algorithm In this section we shall take up two representative problems in computer science, work out the algorithms based on the best strategy to Chapter 14 The Binary Search Tree Chapter 14 The Binary Search Tree In Chapter 5 we discussed the binary search algorithm, which depends on a sorted vector. Although the binary search, being in O(lg(n)), is very efficient, inserting a Symbol Tables. Introduction Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. Algorithms and Data Structures Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2 Data Structure with C Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, algorithm Binary search algorithm Definition Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less Data Structures and Algorithms Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list Binary Search Trees CMPSC 122 Binary Search Trees CMPSC 122 Note: This notes packet has significant overlap with the first set of trees notes I do in CMPSC 360, but goes into much greater depth on turning BSTs into pseudocode than, Persistent Binary Search Trees Persistent Binary Search Trees Datastructures, UvA. May 30, 2008 0440949, Andreas van Cranenburgh Abstract A persistent binary tree allows access to all previous versions of the tree. This paper presents Persistent Data Structures 6.854 Advanced Algorithms Lecture 2: September 9, 2005 Scribes: Sommer Gentry, Eddie Kohler Lecturer: David Karger Persistent Data Structures 2.1 Introduction and motivation So far, we ve seen only ephemer Full and Complete Binary Trees Full and Complete Binary Trees Binary Tree Theorems 1 Here are two important types of binary trees. Note that the definitions, while similar, are logically independent. Definition: a binary tree T is full (BST) Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to node 2. Each node has at most two child nodes (a left and a right child) 3. Nodes are organized by the Binary Search OPTIMAL BINARY SEARCH TREES OPTIMAL BINARY SEARCH TREES 1. PREPARATION BEFORE LAB DATA STRUCTURES An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such that the tree cost is minimum.) Data storage Tree indexes Data storage Tree indexes Rasmus Pagh February 7 lecture 1 Access paths For many database queries and updates, only a small fraction of the data needs to be accessed. Extreme examples are looking or updating An Immediate Approach to Balancing Nodes of Binary Search Trees Chung-Chih Li Dept. of Computer Science, Lamar University Beaumont, Texas,USA Abstract We present an immediate approach in hoping to bridge the gap between the difficulties of learning ordinary binary MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) ----------------------------------------- =============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - Binary Trees and Huffman Encoding Binary Search Trees Binary Trees and Huffman Encoding Binary Search Trees Computer Science E119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 March 17, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure A Comparison of Dictionary Implementations A Comparison of Dictionary Implementations Mark P Neyer April 10, 2009 1 Introduction A common problem in computer science is the representation of a mapping between two sets. A mapping f : A B is a function M-way Trees and B-Trees Carlos Moreno cmoreno @ uwaterloo.ca EIT-4103 Standard reminder to set phones to silent/vibrate mode, please! Once upon a time... in a course that we all like to Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know Binary Search Trees 3/20/14 Binary Search Trees 3/0/4 Presentation for use ith the textbook Data Structures and Algorithms in Java, th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldasser, Wiley, 04 Binary Search Trees 4 Simple Balanced Binary Search Trees Simple Balanced Binary Search Trees Prabhakar Ragde Cheriton School of Computer Science University of Waterloo Waterloo, Ontario, Canada plragde@uwaterloo.ca Efficient implementations of sets and maps - Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time Skip Lists CMSC 420 Linked Lists Benefits & Drawbacks Benefits: - Easy to insert & delete in O(1) time - Don t need to estimate total memory needed Drawbacks: - Hard to search in less than O(n) time (binary Chapter 8: Bags and Sets Chapter 8: Bags and Sets In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which Big O and Limits Abstract Data Types Data Structure Grand Tour.. Big O and Limits Abstract Data Types Data Structure Grand Tour Consider the limit lim n f ( n) g ( n ) What does it) Union-Find Algorithms. network connectivity quick find quick union improvements applications Union-Find Algorithms network connectivity quick find quick union improvements applications 1 Subtext of today s lecture (and this course) Steps to developing a usable algorithm. Define the problem. Find Chapter 8: Binary Trees Chapter 8: Binary Trees Why Use Binary Trees? Tree Terminology An Analogy How Do Binary Search Trees Work Finding a Node Inserting a Node Traversing the Tree Finding Maximum and Minimum Values Deleting
http://docplayer.net/9076306-Why-use-binary-trees.html
CC-MAIN-2018-39
refinedweb
2,884
62.58
How do I make a full-screen button and handle button-down and button-up events? I want to be able to enter data in a Morse-code-like language while my phone is in my pocket by pushing anywhere on the screen. I've examined the UI examples, but I am confused as how to separate button-down events and button-up events in separate handlers. Also, since this will be a full-screen button, I might not need to use a "button" at all. How could this be done? @technoway, subclass ui.View and implement touch_beganand touch_endedmethods. These methods get a ui.Touch object, there's some stuff there if you need more fine control. Thank you mikael and ccc. I am an experience python programmer and I've written a lot of python code that uses Tk, so both your posts helped me immensely. ccc, I do appreciate the code, that saved me a lot of time looking up details. I really appreciated it! This is a great forum. By the way, I used time.perf_counter() to get high resolution times, so I could enter the Morse code at about 20 words-per-minute. I store "up" and "down" intervals in parallel lists, and process them after having at least one "up interval in the "up" list and when the update handler is in the "down" state for at least 2 seconds - so that when I stop entering Morse code, the message is processed roughly 2 seconds later. Thanks again for saving me so much time. Cool!! And you saw ? May be bit easier with scene. import scene class MyScene(scene.Scene): def setup(self): self.name = scene.LabelNode('', position=self.size/2, font=('courier', 60), parent=self) def touch_began(self, touch): self.tap_time = self.t def touch_ended(self, touch): self.name.text += '.' if (self.t - self.tap_time) < .2 else '-' scene.run(MyScene()) import scene class MyScene(scene.Scene): def setup(self): self.name = scene.SpriteNode(color=(1,1,1), position=self.size/2, size=self.size, parent=self) self.name.alpha = 0 A = scene.Action self.dot_action = A.sequence( A.fade_to(1, .2), A.fade_to(0, .2)) self.dash_action = A.sequence( A.fade_to(1, .5), A.fade_to(0, .5)) def touch_began(self, touch): self.tap_time = self.t def touch_ended(self, touch): if (self.t - self.tap_time) < .2: self.name.run_action(self.dot_action) else: self.name.run_action(self.dash_action) scene.run(MyScene()) @ccc - Yes, I saw that post about controlling the light. I saw the part about reading Morse Code. My goal was different. It's to covertly enter information. I really only need to enter a two characters for my application at a time. And, the output is done using text-to-speech,. The output is not what I entered - my input just controls what the spoken text is. While I have successfully entered a sentence, the current decoder is very touchy. I build a histogram of "up" times, and "down" times. The "up" histogram is used to determine the threshold between dots and dashes. That works very well. The "down" histogram has to determine a threshold for regular space between symbols, the space between letters, and the space that separates words. That doesn't work well. The problem is that people drift in their sending speed, so these things really need to be dynamically updated - and my program doesn't do that. I don't think the code would help the guy in the "light" topic, particularly for his application. It messes up word spaces right now. Since I'm just entering two letters, that's not an issue. I'd really like to be able to use a hidden switch that plugs into the iPhone USB port. That could be made smaller than the screen. I'm looking at: However, the application I have now using a full-screen button is sufficient for my needs. I've hidden the title (status?) bar, I found out how to do that in another post here. I saw something about adding an image to a button (or "view" in this case) in another post, but I'm having difficulty finding that now. If I can add a full-screen image, I'll do that. That would just be icing on the cake. I just looked at the "Scene" code above, but I seem to recall just being able to add an image to a regular view. Eventually, I'll post some code here, although probably not this application. Pythonista is awesome. @technoway , my 2 cents worth. Sorry, its not technical help. But it seems to me you are going to great lengths to determine a dash/dot. I would seem to me if you had a self rotating view that had 2 buttons that both consumed 50% of the screen it would be quite easy to learn how to touch each button with a high degree of reliability (100%) for a dot and a dash regardless of how the phone was positioned in your pocket. I cant remember exactly , but I think using objc you can also get tactile feedback (depending on the phone model). So on a long press for example, it maybe could give a vibrate feedback to confirm the orientation you are in. I also could imagine this approach over time would allow for faster input as you are not concerned about delays and could use 2 finger input. Don't mean to waste your time, just sometimes we can try to get too technical. Muscle memory is pretty amazing. I considered two buttons early on, however, that's not necessary. The issue isn't separating dots from dashes. That part works very well - in fact, I don't recall the decoder making an error between a dot and a dash in a very long time. The code even handles when there are only dots, or only dashes now, such as: . . . . which is "se" and: - - - - which is "ot" The issue is the spaces between symbols, letters, and words. Theses are all multiples of the dot-length. If sending a lot of text, and the sending speed changes over time, then the symbol-space, the letter-space, and the word-space, can become ambiguous across the entire message. (Usually, the symbol space is fine, but the letter space and word space can drift close together). There really needs to be a mix of short-term and long-term tracking of space lengths, so if the sending speed drifts, the code adapts in real time. The downside of the poor space tracking that sentences can end up as: "T h e dow nsi deof thep o o r sp ace t ra ckin g th at s en t en ces ca n endup as:" It's not usually that bad though, the typical case is that a few extra spaces, which are due to word separations, are thrown in the middle of the text. Usually all the letters are correct, because the symbol space is the same as a dot, and that's usually about a third of the letter spacing. If sending very fast, even the symbol space can get messed up though, which results in combining letters, sometimes changing a letter, and sometimes producing an invalid character. Invalid characters are currently silently discarded. That could be improved too, by having the code try to parse the combined invalid symbols into one or more valid characters. (I probably will never do this though, as that's compute-intensive, and requires a dictionary and even could require natural language analysis). The space threshold problem can be alleviated by exaggerating the separation between letters and words when sending the text, but this sounds unnatural to someone familiar with Morse code. It also feels very unnatural to change the proper flow of Morse code. Imagine reciting letters, and doing really long pauses between letters and really, really long pauses between spelled words. Also, if I work very hard at having a consistent sending speed, the program does much better. But human beings typically allow their speed to vary, just as they do when speaking, particularly if there are distractions, so that's not a good long-term solution. The human brain has an easy time doing real-time tracking of the spaces between symbols, letters, and words in Morse code, and adjusting based on sending speed and content. I think if I work on it long enough, I can get the space tracking to work much better. I have a number of ideas I think that will improve that. Also, right now, I enter Morse code data on the screen, stop entering data, and then wait two seconds for the system to recognized I've stopped and process all the data. A better system would be real-time decoding as the data flows in, with some buffering to allow estimation of thresholds in real-time. Another competently different idea I want to try is to be able to draw individual characters on the screen, and having those get recognized, i.e. crude OCR of large hand drawn characters. That would be a fun and challenging project. I saw the Sketch.py sample program. That's a good starting point for the input part of that program. For now though, I want to improve the Morse Code decoder. @technoway, ok interesting reading. Unfortunately still I am no help. I did get me thinking though. Eg, is morse code only for translation to English? Eg, hard to imagine you could do a Thai translation using morse code. They rarely use spaces at all. You have to understand the language rules how to be able to discern words in a stream of Thai text. LOL, its not easy. Anyway, these are things I will look up myself. Your answer just prompted me to think of these questions. @technoway, i was listening to this podcast yesterday and thought about this thread. I am not sure it can be helpful, but I have a feeling it could spark some ideas for you. The title of the podcast is “parsing-horrible-things-with-python”. I feel there is an answer lurking somewhere in this podcast for you. Thanks. I do know the proper way to solve this problem already though. My undergraduate degree is electrical engineering and I my graduate work is in a field called Digital Signal Processing. I did not implement a more complicated streaming solution because I don't want to load the iPhone down, this is just to control a program that does something else - and currently I only need to enter two sequential characters for all control options, although I have decoded sentences with my current Morse Code decoder. If I were to implement a full streaming solution, I'd create a separate processing thread to decode the Morse code (or up and down button events with times). The UI would write the up and down events to a thread-safe queue, and the decoder thread would read from that queue. The decode would write characters to a thread-safe output queue, which would be read by the UI thread. This would allow decoding while doing other processing. Perhaps I'll implement that someday. Currently there is no point in doing a dynamic adaptation to sending speed variations when I am only decoding very short blocks - currently only two characters. I did find that podcast interesting and entertaining though. Also, I had purchased the "Natural Language" Python book he mentioned over a year ago. It's a great book. The best part of that book is that it provides sources to various online resources, including a word corpus.
https://forum.omz-software.com/topic/4284/how-do-i-make-a-full-screen-button-and-handle-button-down-and-button-up-events/6
CC-MAIN-2022-27
refinedweb
1,950
73.98
"XML Innovator: Doug Copeland Sites intent on raw visual appeal will continue to use WYSIWIG editors, but XML in combination with XSL is really exciting for larger sites that have a lot of semi-structured information." Name: Doug Copeland Company: Media SemanticsTitle: President Media Semantics, Inc. is a software R&D firm that develops manipulative and agent-based technology for use in software products. They've discovered XML to be useful for creating and organizing complicated structures more efficiently than other technologies. In one current project Media Semantics is working closely with NextBook Corporation, a company that uses an agent-based interface for its multimedia textbooks. What exactly does your company do? "We develop custom ActiveX controls that can be embedded in standalone applications or in a Web page. They are display surfaces that allow us to really push the envelope in terms of the user experience. For example, we are currently working on a project in which a user can manipulate mathematical equations in conjunction with an animated instructor character. How are you using XML? "We use custom XML tagsets to let our client author just about everything, from annotated text and equations, to user task information and agent scripting information. "Our use of XML is a little unorthodox, in that we have chosen to compile the XML at author-time, in much the same way that one compiles a C++ program. We do this for performance -- our runtime needs to handle huge amounts of XML, and ultimately this data has to be translated to compact structures such as C++ objects and predicates. The overhead of parsing an XML file to thousands of running COM objects (one per XML element) is just too great for us to use the browser's built-in parser and Document Object Model. "Compiled binary streams, on the other hand, can be rapidly loaded and acted on by a small and fast runtime. We also do it for authorability. XML seems quite authorable in theory, but it quickly becomes very tedious with needless nesting. The compilation step allows us to do more parsing. For example, our client can write a mathematical equation as "3*X^2 + 2*x-1= 0," rather than 20 lines of nested elements. What made you select XML? "We needed a language in which to efficiently express very complex structure. We knew the language would have to evolve over time. "We knew that XML, because of its extensibility, was bound to become very widely adopted. "Even though we are not overly concerned about interoperability for now, we want to be able to offer support for any useful namespaces and standards that evolve." What programs or applications are you using to implement XML? "We use the standard Microsoft Developer Studio editor, together with our own custom-developed compilers and a linker." What's in the future for XML products? "I would like to see a syntax coloring and background validation for XML in my editor. I look forward to using an XSL processor if for no other reason than as a sophisticated author-time transformation tool. There is nothing worse than changing the schema and having to revisit large quantities of XML!" And the future of XML itself? "I certainly agree with those who evangelize XML as an interchange format, for file formats, EDI-(Electronic Data Interchange) type applications, etc. XML will no doubt be an important part of an emerging type of next-generation distributed 'web-apps.' "Sites intent on raw visual appeal will continue to use WYSIWIG editors, but XML in combination with XSL is really exciting for larger sites that have a lot of semi-structured information. An investment in separating content from presentation will pay for itself by making data easier to author and maintain while allowing the presentation to be independently adapted to by different audiences by designers." Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/projectcool/Article/20049/0/page/4
CC-MAIN-2017-43
refinedweb
672
54.52
It was thus said that the Great Dibyendu Majumdar once stated: > On 28 January 2018 at 16:40, Dibyendu Majumdar <mobile@majumdar.org.uk> wrote: > > > I have always wanted to (but haven't managed to yet) bundle some high > > quality libraries with Ravi in a well tested combination with support > > for Windows, Linux and Mac OSX. Is there a list of the best essential > > libraries for Lua? I want to bundle a small set of high quality > > libraries that I will test with Ravi, rather than a huge set of > > untested libraries of varying quality. > > > > I wanted to ask your views on couple of points: > > 1. Should I force all libraries to have a require string that is of > the format 'supplier.module' ? The problem in enforcing this is that > it makes the distro incompatible with existing code. A better approach > may be to use the require string that the module provides but prohibit > any other use of the same module path. This is easy as I have control > over which libraries go in. What is the concern here? So far, Lua has managed without a conherent namespace for modules. If Ravi is meant to run existing Lua code then you pretty much *can't* enforce a new requirement. The stock Lua interpreter provides a mechanism but no real policy. That allows experimentation, but it also allows conflicting modules to exist. Lua also doesn't care about versions (or version numbers) of modules. The ULua distribution [1] does enforce semantic versioning for any modules it supports, so there are Lua distributions that are opinionated. > 2. Folks that have experience with modules implemented as shared > libraries - what are the gotchas? I found two potential issues > already: > > a) in some cases the shared library needs to be on OS specific > environment PATH (or library PATH), and Have you actually encountered this problem? And if so, which Lua module was it? > b) the path resolution doesn't seem to like it if the build adds a > 'lib' prefix to the library (as it does on Mac OSX). It sounds like you are still unclear on how dynamic linking works on Unix. Lua uses dlopen() (a POSIX function) to load Lua modules written in C. Only in the case when the filename of a shared object does *NOT* contain a '/' does dlopen() check the environment variable LD_LIBRARY_PATH (and only if the program is not setuid or setgid). If not found (or LD_LIBRARY_PATH isn't set) does dlopen() then check system wide locations (under Linux, the paths in /etc/ld.so.conf). The 'lib' prefix is a result of the C toolchain. When you invoke the C compiler like: cc -o myprog *.o -lfoo it's the toolchain that adds the 'lib' to 'foo' and looks for 'libfoo.so' (and if not found, 'libfoo.a'). If you don't specify the '-L' option, then the system defaults are searched for 'libfoo.*'. If a '-L' option *is* given, said directories are searched first. Again, the whole 'lib' prefix is added by the C compiler toolchain. Also, shared objects can reference other shared objects. What problems (errors, etc.) have you actually encounted with this issue? Have you tried writing a Lua module in C? Even a simple one? That might answer most of your questions. -spc [1]
http://lua-users.org/lists/lua-l/2018-02/msg00147.html
CC-MAIN-2020-16
refinedweb
550
73.78
The biggest difference between Pyramid and Pylons is how views are structured, and how they invoke templates and access state variables. This is a large topic because it touches on templates, renderers, request variables, URL generators, and more, and several of these topics have many facets. So we’ll just start somewhere and keep going, and let it organize itself however it falls. First let’s review Pylons’ view handling. In Pylons, a view is called an “action”, and is a method in a controller class. Pylons has specific rules about the controller’s module name, class name, and base class. When Pylons matches a URL to a route, it uses the routes ‘controller’ and ‘action’ variables to look up the controller and action. It instantiates the controller and calls the action. The action may take arguments with the same name as routing variables in the route; Pylons will pass in the current values from the route. The action normally returns a string, usually by calling render(template_name) to render a template. Alternatively, it can return a WebOb Response. The request’s state data is handled by magic global variables which contain the values for the current request. (This includes equest parameters, response attributes, template variables, session variables, URL generator, cache object, and an “application globals” object.) A Pyramid view callable can be a function or a method, and it can be in any location. The most basic form is a function that takes a request and returns a response: from pyramid.response import Response def my_view(request): return Response("Hello, world!") A view method may be in any class. A class containing view methods is conventionally called a “view class” or a “handler”. If a view is a method, the request is passed to the class constructor, and the method is called without arguments. The Pyramid structure has three major benefits. Merely defining a view is not enough to make Pyramid use it. You have to register the view, either by calling config.add_view() or using the @view_config decorator. The most common way to use views is with the @view_config decorator. This both marks the callable as a view and allows you to specify a template. It’s also common to define a base class for common code shared by view classes. The following is borrowed from the Akhet demo. The application’s main function has a config.scan() line, which imports all application modules looking for @view_config decorators. For each one it calls config.add_view(view) with the same keyword arguments. The scanner also recognizes a few other decorators which we’ll see later. If you know that all your views are in a certain module or subpackage, you can scan only that one: config.scan(".views"). The example’s @view_config decorator has two arguments, ‘route_name’ and ‘renderer’. The ‘route_name’ argument is required when using URL dispatch, to tell Pyramid which route should invoke this view. The “renderer” argument names a template to invoke. In this case, the view’s return value is a dict of data variables for the template. (This takes the place of Pylons’ ‘c’ variable, and mimics TurboGears’ usage pattern.) The renderer takes care of creating a Response object for you. The following arguments can be passed to @view_config or config.add_view. If you have certain argument values that are the same for all of the views in a class, you can use @view_defaults on the class to specify them in one place. This list includes only arguments commonly used in Pylons-like applications. The full list is in View Configuration in the Pyramid manual. The arguments have the same predicate/non-predicate distinction as add_route arguments. It’s possible to register multiple views for a route, each with different predicate arguments, to invoke a different view in different circumstances. Some of the arguments are common to add_route and add_view. In the route’s case it determines whether the route will match a URL. In the view’s case it determines whether the view will match the route. route_name [predicate] The route to attach this view to. Required when using URL dispatch. renderer [non-predicate] The name of a renderer or template. Discussed in Renderers below. permission [non-predicate] A string naming a permission that the current user must have in order to invoke the view. http_cache [non-predicate] Affects the ‘Expires’ and ‘Cache-Control’ HTTP headers in the response. This tells the browser whether to cache the response and for how long. The value may be an integer specifying the number of seconds to cache, a datetime.timedelta instance, or zero to prevent caching. This is equivalent to calling request.response.cache_expires(value) within the view code. context [predicate] This view will be chosen only if the context is an instance of this class or implements this interface. This is used with traversal, authorization, and exception views. request_method [predicate] One of the strings “GET”, “POST”, “PUT”, “DELETE’, “HEAD”. The request method must equal this in order for the view to be chosen. REST applications often register multiple views for the same route, each with a different request method. request_param [predicate] This can be a string such as “foo”, indicating that the request must have a query parameter or POST variable named “foo” in order for this view to be chosen. Alternatively, if the string contains “=” such as “foo=1”, the request must both have this parameter and its value must be as specified, or this view won’t be chosen. match_param [predicate] Like request_param but refers to a routing variable in the matchdict. In addition to the “foo” and “foo=1” syntax, you can also pass a dict of key/value pairs: all these routing variables must be present and have the specified values. xhr, accept, header, path_info [predicate] These work like the corresponding arguments to config.add_route. custom_predicates [predicate] The value is a list of functions. Each function should take a context and request argument, and return true or false whether the arguments are acceptable to the view. The view will be chosen only if all functions return true. Note that the function arguments are different than the corresponding option to config.add_route. One view option you will not use with URL dispatch is the “name” argument. This is used only in traversal. A renderer is a post-processor for a view. It converts the view’s return value into a Response. This allows the view to avoid repetitive boilerplate code. Pyramid ships with the following renderers: Mako, Chameleon, String, JSON, and JSONP. The Mako and Chameleon renderers takes a dict, invoke the specified template on it, and return a Response. The String renderer converts any type to a string. The JSON and JSONP renderers convert any type to JSON or JSONP. (They use Python’s json serializer, which accepts a limited variety of types.) The non-template renderers have a constant name: renderer="string", renderer="json", renderer="jsonp". The template renderers are invoked by a template’s filename extension, so renderer="mytemplate.mako" and renderer="mytemplate.mak" go to Mako. Note that you’ll need to specify a Mako search path in the INI file or main function: [app:main] mako.directories = my_app_package:templates Supposedly you can pass an asset spec rather than a relative path for the Mako renderer, and thus avoid defining a Mako search path, but I couldn’t get it to work. Chameleon templates end in .pt and must be specified as an asset spec. You can register third-party renderers for other template engines, and you can also re-register a renderer under a different filename extension. The Akhet demo has an example of making pyramid send templates ending in .html through Mako. You can also invoke a renderer inside view code. If you’re having trouble with a route or view not being chosen when you think it should be, try setting “pyramid.debug_notfound” and/or “pyramid.debug_routematch” to true in development.ini. It will log its reasoning to the console.
http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/pylons/views.html
CC-MAIN-2014-49
refinedweb
1,336
66.94
Migrate from version 4 - the Services library Overview of the tutorial This tutorial covers basic use cases to help you switch our services. For example, switching the Routing API or Search API services from version 4 of the Maps SDK for Web to our new version. We will use code examples to explain the main differences between the SDKs. In the new SDK, services are not part of the map library. We now provide a separate library to only include services. You can check how to migrate map displaying here: Migrate from version 4 - the Maps library To start using the latest version of TomTom Maps SDK for Web you need the following: - The Services libraryThe Maps SDK for Web can be used in three ways: - Downloaded from NPM: - With a CDN:<version>/services/services-web.min.js - NOTE: include the latest version in the URL. - Downloaded from here: Downloads. In this tutorial, we are using a CDN as an example. - API Key - If you don't have an API Key visit the How to get a TomTom API Key site and create one. Add the following to the <head> element of your HTML document: <!-- Replace version in the URL with desired library version --> <script src='<version>/services/services-web.min.js'></script> Maps and services use the same namespace and will automatically attach themselves to the tt object. Services will be accessible using tt.services. Displaying a route/directions Here we have the code to display a route from point A to point B on the map. Version 4 of the Maps SDK for Web tomtom.routing() .key('<your-api-key>') .locations('37.7683909618184,-122.51089453697205:37.769167,-122.478468') .go().then(function(routeJson) { var route = tomtom.L.geoJson(routeJson, { style: {color: '#00d7ff', opacity: 0.6, weight: 6} }).addTo(map); map.fitBounds(route.getBounds(), {padding: [5, 5]}); }); Latest version of the Maps SDK for Web}); }); Performing a fuzzy search Version 4 of the Maps SDK for Web tomtom.fuzzySearch() .key('<your-api-key>') .query('pizza') .go() .then(function(result) { console.log(result); }); Latest version of the Maps SDK for Web tt.services.fuzzySearch({ key: '<your-api-key>', query: 'pizza' }) .then(function(result) { console.log(result); }); Differences in APIs Here is an overview of some of the most important updates within our top-level namespace. Common factory functions renamed Some of the common functions changed. Here are some examples: The following table lists the services from the version 4 of the SDK and their equivalents in the latest one.
https://developer.tomtom.com/maps-sdk-web-js/tutorials-migration/migrate-version-4-services-library
CC-MAIN-2021-31
refinedweb
419
56.76
Suppress print output at bottom of screen in Scene For my animation in Scene,, I would like to use the full screen and not be distracted by the output being directed to the the bottom line. Is is possible to disable this (usually very handy) feature? - lukaskollmer If you're talking about the frames per second number in the bottom right corner, you can pass the show_fpsparameter to the run function to suppress that debug output. Example: run(MyScene(), show_fps=False) I'm talking about the lower left hand corner, showing the latest line of console output, Just don't use print! (i.e, you could redefine print to act as a pass) Also, IIRC SceneView does to do that... Suggested by omz here "There isn't really a supported way to turn this off, but you could do it via ObjC by putting something like this in your setup method:" from objc_util import ObjCInstance ObjCInstance(self.view).statusLabel().alpha = 0
https://forum.omz-software.com/topic/3762/suppress-print-output-at-bottom-of-screen-in-scene/4
CC-MAIN-2019-35
refinedweb
161
54.56
Results 1 to 2 of 2 - Member Since - Aug 01, 2008 - 6 Need help with advanced Objective-C and NSComboBox Hi everyone, I am making a program that converts just about anything, and I am making the part where it converts length as in, Standard Units and Metric Units. I made an NSComboBox in Interface builder, I just need a little step by step on what to do from there. Here is how I need it to work: 1. Choose Dropdown from the Window to choose your selection. (Lets say Inches to Meters) 2. Type the amount you want converted in an NSTextField (Editable) 3. Click Convert I know all the Math you need to do to do this, to turn an inch into a meter you need to Multiply it by 2.54 then multiply the answer by 0.01. This is what I have for "Length.m" Code: #import "Length.h" @implementation Length @synthesize I2M; - (float) inchesToMeters { return (self.I2M * 2.54) * 0.01; } @end - Member Since - Aug 01, 2008 - 6 bump, anyone? Thread Information Users Browsing this Thread There are currently 1 users browsing this thread. (0 members and 1 guests) Similar Threads Objective-C helpBy bikka in forum OS X - Development and DarwinReplies: 22Last Post: 05-27-2014, 03:56 PM Need help in objective CBy prateek.chaubey in forum iOS DevelopmentReplies: 3Last Post: 09-23-2011, 10:12 PM Objective-CBy eddielee in forum OS X - Development and DarwinReplies: 2Last Post: 02-02-2011, 01:27 PM Is Objective For me?By Estanislao in forum OS X - Apps and GamesReplies: 1Last Post: 05-26-2009, 05:13 AM Objective-CBy AstralZenith in forum OS X - Development and DarwinReplies: 13Last Post: 03-09-2003, 11:15 AM
http://www.mac-forums.com/forums/os-x-development-darwin/118184-need-help-advanced-objective-c-nscombobox.html
CC-MAIN-2015-48
refinedweb
291
71.75
Java and security bits Moving on After more than six years at Sun working on the Java SE platform, I have decided to move on. Today was my last day. I still very much believe in all the technologies I was involved in and will leave it to my colleagues to continue the work. Thanks to OpenJDK I may not disappear completely and pop in every once in a while. If you want to follow my future adventurers, see my new blog. Posted at 17:19 Mar 14, 2008 by Andreas Sterbenz in About | Crypto Code and OpenJDK I just got a question about the status of the crypto code in OpenJDK that referred to the limitations mentioned in my blog post from last May. Back then some of the encryption code was not open source as we were working through some build and export control issues. Let me give a quick update on that: Brad spent quite a bit of time on this and eventually those issues were resolved, as announced in a message to the mailing lists. That means all the crypto code is available on OpenJDK now. There are a couple of checks (relating to signed providers) which are present in Sun's binaries but that are not present in OpenJDK, but that is simply because those checks are neither needed nor particularly appropriate for an open source project. Everything else is exactly the same as in Sun's releases. Bottom line is that you can modify and build your own versions of the crypto framework and the crypto providers now. Have at it! Posted at 18:08 Jan 15, 2008 by Andreas Sterbenz in Java | JCP Early Draft of JSR 294 Now Available As you have have already noticed, the JCP Early Draft specification of JSR 294 is now available for download from the JSR page. In short, it consists of two chapters of the Java Language Specification that have been updated to cover Superpackages. There are change bars to highlight everything that has been touched. Then there are draft revisions for the Java Virtual Machine Specification. Finally, updates to the Java core reflection APIs.] Nested Superpackages Restated A few weeks ago I posted an entry that explained what superpackages are about. This is a continuation that deals with nested superpackages. If you have not read the first post, read it before continuing. As a reminder, the short version is: a superpackage is a language construct for information hiding [1]. With that in mind, let us explore what a nested superpackage is: a nested superpackage is a superpackage contained within another superpackage. Since a nested superpackage is still a superpackage, what I said about top level superpackages also applies to nested superpackages. In other words, a nested superpackage is a language construct for information hiding. Let's look at what this definition says about what a nested superpackage is not: it is not a namespace construct. The Java source language does not recognize multiple types of the same fully qualified name today. Adding new access control mechanisms does not change that. Of course, the other things I mentioned which a superpackage is not also still apply: no changes to the type system or to the way you package your applications. That states what nested superpackages are and what they are not, but it does not explain why they are useful. But that is pretty simply: they are an access control mechanism and as such allow you to separate code within one project (i.e. one top level superpackage) and to hide implementation details. A way to visualize it is to imagine a bubble representing your project and floating within it all your classes and interfaces. Often you will want to organize those classes into subsystems - a bubble within the bubble. If a subsystem is too large for a single package, you need something else. That is where nested superpackages come in. One example of a project where this structure will be very useful is the core of the JDK, as I explained in this message to the JSR 294 expert group, but there are certainly many other projects with similar needs. The final thing to say about nested superpackages is that (as described above) they are a way to organize the internals of a component, not a way to aggregate code from multiple components. You would use a deployment module solution such as JSR 277 to do that. The guidance is that if a subsystem is tightly coupled with the rest of a project, it should be a nested superpackage. If it is effectively an independent unit and reusable, it should be its own component as a top level superpackage. Other components can import it using JSR 277. The distinction may seem arbitrary and impossible to make, but it is not much different than deciding whether to organize your code into one, two, or more packages. With a bit of experience, it comes natural to developers. That was quite a bit of text, but the one thing to remember is that a nested superpackage is a superpackage contained within another superpackage. In other words, a nested superpackage is a language construct for information hiding. Really. Nothing more to it than that. [1] If you don't like the term information hiding just replace it with access control in this entry. In this context it is a good approximation as information hiding is the concept and access control the mechanism to implement it. Posted at 11:20 May 30, 2007 by Andreas Sterbenz in Modularity | Security Unit and Regression Tests on OpenJDK One thing I forgot to mention in my earlier entry is that apart from the implementation source code we also have a large number of unit and regression tests available on OpenJDK. For security alone, it is more than 400 separate tests, with each test often checking multiple conditions. In total there are more than 3500 unit and regression tests on OpenJDK today and the number is only growing as we write new tests and work to make more existing tests available. These tests are in the j2se/test directory with a directory hierarchy that (usually) mirrors the source files being tested. That means for security most of the tests are in test/java/security and test/sun/security. You can run them using the jtreg harness, which predates JUnit & co. I don't think I need to explain why tests are important, but I have to quote a sentence I first heard from Bill Moore: If it has not been not tested, it does not work. No ifs, buts, or maybes. Even if something happened to work initially, when there is no test, it will eventually get broken. So make sure to include a test when you decide to contribute code. Posted at 13:43 May 29, 2007 by Andreas Sterbenz in Java |] JavaOne Pen with USB Flash Drive I finally went through the contents of my JavaOne backpack this weekend. Along with the usual promotional materials there was a small case with a pen - as far as I recall this was the speaker gift. I was about to dismiss it as another uninteresting pen when I noticed that you can pull out the top, which is in fact a 1 GB USB flash drive. Not huge, but at least potentially useful. So to all you JavaOne speakers: take a closer look before you throw it out. Here is an image of it: Posted at 12:49 May 20, 2007 by Andreas Sterbenz in Java | Comments[2]] Superpackages Restated There seems to be some confusion about what superpackages are about. My one sentence explanation is: a superpackage is a language construct for information hiding. Let's examine that statement. "Information hiding" is fancy way of saying "keeping implementation details private." In Java, we have access control modifiers to achieve that: private, default (aka package private), protected and public. But sometimes "public is too public". I also said "language construct." That means something that is part of the Java language, defined in the Java Language Specification and enforced by all Java compilers (e.g. javac). It will also be part of the Java Virtual Machine Specification so that it is enforced at runtime by the JVM. Let's look at all the things I did not say: no changes to the type system. No changes to the compile time and runtime access control architecture (just a small extension). No changes to how you must package your apps: if you had organized your application into 6 "components" before, each with its own JAR file, you most likely will do the same thing after migrating to superpackages (see note at the bottom). In other words, a superpackage is a language construct for information hiding. Really. Nothing more to it than that. But if that is still too abstract, how about this version: superpackages define an extension to the Java access control mechanism: a new access level for classes, which is wider than "package private" but narrower than "public". One could call the new access level "superpackage private", but that is potentially confusing so please don't use that term. PS: a runtime infrastructure for component based applications is also desirable, see JSR 277. But that is very much orthogonal to the information hiding objective of superpackages. Posted at 02:13 May 08, 2007 by Andreas Sterbenz in Modularity | Comments[8] JavaOne 2007 JavaOne is upon us once again. Here is a list of the sessions and BOFs related to the work that I am involved in: Tuesday 9pm: BOF-2400: Modularity in the Next-Generation Java Platform, Standard Edition (Java SE): JSR 277 and JSR 294 Tuesday 10pm: BOF-2899: Java Programming Language Features in JDK Release 7 Wednesday 9.35am: TS-2594: Secure Coding Guidelines, Continued: Preventing Attacks and Avoiding Antipatterns Thursday 9.35am: TS-2401: Java Language Modularity with Superpackages Thursday 4.10pm: TS-2318: JSR 277: Java Module System Thursday 8.55pm: BOF-2516: Stump the (Security) Band My main involvement is with the JSR 294 session that I am co-presenting with Alex as well as the JSR 277/294 BOF and the Security BOF, but I plan to attend all the others as well to help out with questions if needed. See you soon! Posted at 00:58 May 07, 2007 by Andreas Sterbenz in Java | Superpackage strawman and the JSR 294 mailing list After a lot of internal discussion, Alex and I recently started the expert group discussion for JSR 294 (Improved Modularity Support in the Java Programming Language). Not an earth shattering event, but what may make this interesting to you is that we decided to make the expert group discussion publicly readable via a web archive and an observer list that anyone can subscribe to. You will not be able to post to the expert group list, but you can read all the discussions from now on. It's all out in the open. Secondly and related to that, we also posted our strawman proposal for superpackages. The concepts will not be news to you if you read my earlier postings. Alex and I think that it is a straightforward way to address limitations in information hiding in the Java language and so far the expert group agrees. Finally, we are presenting a session at JavaOne this May. It is called Java Language Modularity with Superpackages (abstract). Stanley will also present a session JSR 277: Java Module System plus we will all do a joint Modularity BOF that covers both JSR 277 and 294. We hope to see you all there. Posted at 23:53 Apr 05, 2007 by Andreas Sterbenz in Modularity | Comments[9] |] Aboard JSR 294 A short note to let people know that Alex Buckley and myself have assumed responsibility for JSR 294 (Improved Modularity Support in the Java Programming Language) and that we will be serving as co-spec leads. The direction for the JSR has not changed. I had already been working with Gilad on superpackage issues before his recent departure and we will continue on the course that he wisely laid out. You can read more about the concepts in this other posting. I will also continue to be involved in the work on deployment modules being defined by JSR 277 (Java Module System) taking care of some of the core aspects of the implementation and helping out Stanley on a few spec issues as I mentioned earlier. Posted at 15:26 Nov 08, 2006 by Andreas Sterbenz in About |
http://blogs.sun.com/andreas/
crawl-002
refinedweb
2,097
60.24
<< First | < Prev | Next > So far we've seen how to interact with the perl parser to introduce new keywords. We've seen how we can allow that keyword to be enabled or disabled in lexical scopes. But our newly-introduced syntax still doesn't actually do anything yet. Today lets change that, and actually provide some new syntax which really does something. Optrees To understand the operation of any parser plugin (or at least, one that actually does anything), we first have to understand some more internals of how perl works; a little of how the parser interprets source code, and some detail about how the runtime actually works. I won't go into a lot of detail in this post, only as much as needed for this next example. I'll expand a lot more on it in later posts. Every piece of code in a perl program (i.e. the body of every named and anonymous function, and the top-level code in every file) is represented by an optree; a tree-shaped structure of individual nodes called ops. The structure of this optree broadly relates to the syntactic nature of the code it was compiled from - it is the parser's job to take the textual form of the program and generate these trees. Each op in the tree has an overall type which determines its runtime behaviour, and may have additional arguments, flags that alter its behaviour, and child ops that relate to it. The particular fields relating to each op depend on the type of that op. To execute the code in one of these optrees the interpreter walks the tree structure, invoking built-in functions determined by the type of each op in the tree. These functions implement the behaviour of the optree by having side-effects on the interpreter state, which may include global variables, the symbol table, or the state of the temporary value stack. For example, let us consider the following arithmetic expression: (1 + 2) * 3 This expression involves an addition, a multiplication, and three constant values. To express this expression as an optree requires three kinds of ops - a OP_ADD op represents the addition, a OP_MULT the multiplication, and each constant is represented by its own OP_CONST. These are arranged in a tree structure, with the OP_MULT at the toplevel whose children are the OP_ADD and one of the OP_CONSTs, the OP_ADD having the other two OP_CONSTs. The tree structure looks something like: OP_MULT: +-- OP_ADD | +-- OP_CONST (IV=1) | +-- OP_CONST (IV=2) +-- OP_CONST (IV=3) You may recall from the previous post that we implemented a keyword plugin that simply created a new OP_NULL optree; i.e. an optree that doesn't do anything. If we now change this to construct an OP_CONST we can build a keyword that behaves like a symbolic constant; placing it into an expression will yield the value of that constant. This returned op will then be inserted into the optree of the function containing the syntax that invoked our plugin, to be executed at this point in the tree when that function is run. To start with, we'll adjust the main plugin hook function to recognise a new keyword; this time tau: static int MY_keyword_plugin(pTHX_ char *kw, STRLEN kwlen, OP **op_ptr) { HV *hints = GvHV(PL_hintgv); if(kwlen == 3 && strEQ(kw, "tau") && hints && hv_fetchs(hints, "tmp/tau", 0)) return tau_keyword(op_ptr); return (*next_keyword_plugin)(aTHX_ kw, kwlen, op_ptr); } Now we can hook this up to a new keyword implementation function that constructs an optree with a OP_CONST set to the required value, and tells the parser that it behaves like an expression: #include <math.h> static int tau_keyword(OP **op_ptr) { *op_ptr = newSVOP(OP_CONST, 0, newSVnv(2 * M_PI)); return KEYWORD_PLUGIN_EXPR; } We can now use this new keyword in an expression as if it was a regular constant: $ perl -E 'use tmp; say "Tau is ", tau' Tau is 6.28318530717959 Of course, so far we could have done this just as easily with a normal constant, such as one provided by use constant. However, since this is now implemented by a keyword plugin, it can do many exciting things not available to normal perl code. In the next part we'll explore this further. << First | < Prev | Next >
http://leonerds-code.blogspot.com/2016_09_01_archive.html
CC-MAIN-2018-22
refinedweb
710
54.46
A simple Python library to provide an API to implement the Reactive Object Pattern (ROP). Project description AlleyCat - Reactive A part of the AlleyCat project which supports the Reactive Object Pattern. Introduction AlleyCat Reactive is a project to explore the possibility of bridging the gap between the two most widely used programming paradigms, namely, the object-oriented programming (OOP), and functional programming (FP). It aims to achieve its goal by proposing a new design pattern based on the Reactive Extensions (Rx). Even though it is already available on PyPI repository as alleycat-reactive package, the project is currently at a proof-of-concept stage and highly experimental. As such, there can be significant changes in the API at any time in future. Furthermore, the project may even be discontinued in case the idea it is based upon proves to be an infeasible one. So, please use it at your discretion and consider opening an issue if you encounter a problem. Reactive Object Pattern AlleyCat Reactive provides an API to implement what we term as Reactive Object Pattern or ROP for short. Despite its rather pretentious name, it merely means defining class properties which can also serve as an Observable in Rx. But why do we need such a thing? We won't delve into this subject too much since you can learn about the concept from many other websites. In short, it's much better to define data in a declarative manner, or as "data pipelines", especially when it's changing over time. And Rx is all about composing and manipulating such pipelines in a potentially asynchronous context. But what if the data do not come from an asynchronous source, like Tweets or GUI events, but are just properties of an object? Of course, Rx can handle synchronous data as well, but the cost of using it may outweigh the benefits in such a scenario. In a traditional OOP system, properties of an object are mere values which are often mutable, but not observable by default. To observe the change of a property over time, we must use an observer pattern, usually in the form of a separate event. Some implementation of Rx allows converting such an event into an Observable. Still, it can be a tedious task to define an event for every such property, and it requires a lot of boilerplate code to convert them into Rx pipelines. More importantly, the resulting pipelines and their handling code don't have any clear relationship with the original object or its properties from which they got derived. They are just a bunch of statements which you can put anywhere in the project, and that's not how you want to design your business logic in an OOP project. In a well-designed OOP project, classes form a coherent whole by participating in inheritance hierarchies. They may reference, extend, or redefine properties of their parents or associated objects to express the behaviours and traits of the domain concepts they represent. And there is another problem with using Observables in such a manner. Once you build an Rx pipeline, you can't retrieve the value flowing inside unless you write still more boilerplate code to subscribe to the stream and store its value to an outside variable. This practice is usually discouraged as an anti-pattern, and so is the use of Subjects. However, the object is not observing some outside data (e.g. Tweets) but owns it, which is one of the few cases where the use of a Subject can be justified. In such a context, it's perfectly reasonable to assume that an object always has access to a snapshot of all the states it owns. So, what if we can define such state data of an object as Observables which can also behave like ordinary properties? Wouldn't it be nice if we can easily access them as in OOP while still being able to observe and compose them like in Rx? And that is what this project is trying to achieve. Usage To achieve the goal outlined in the previous section, we provide a way to define a property which can also turn into an Observable. And there are two different types of such property classes you can use for that purpose. Reactive Property Firstly, there is a type of property that can manage its state, which is implemented by ReactiveProperty[T] class. To define such a property using an initial value, you can use a helper function from_value as follows: from alleycat.reactive import RP from alleycat.reactive import functions as rv class Toto: # Create an instance of ReactiveProperty[int] with an initial value of '99': value: RP[int] = rv.from_value(99) # You know the song, don't you? Note that RP[T] is just a convenient alias for ReactiveProperty[T] which you can use for type hinting. As with other type annotations in Python, it is not strictly necessary. But it can be particularly useful when you want to lazily initialize the property. You can declare an 'empty' property using new_property and initialize it later as shown below. Because it may be difficult to see what type of data the property expects without an initial value, using an explicit type annotation can make the code more readable: from alleycat.reactive import RP from alleycat.reactive import functions as rv class MyClass: # Declare an empty property first. value: RP[int] = rv.new_property() def __init__(self, init_value: int): # Then assign a value as you would do to an ordinary property. self.value = init_value A ReactiveProperty can be can be read and modified like an ordinary class attribute. And also you can make it a read-only property by setting the read_only argument to True like the following example: from alleycat.reactive import RP from alleycat.reactive import functions as rv class ArcadiaBay: writeable: RP[str] = rv.from_value("life is strange") read_only: RP[str] = rv.from_value("the past", read_only=True) place = ArcadiaBay() print(place.writeable) # "life is strange" print(place.read_only) # "the past" place.writeable = "It's awesome" print(place.writeable) # "It's awesome" place.read_only = "Let me rewind." # Throws an AttributeError # Of course, you can't change the past. But the game is hella cool! But haven't we talked about Rx? Of course, we have! And that's the whole point of the library, after all. To convert a reactive property into an Observable of the same type, you can use observe method like this: from alleycat.reactive import RP from alleycat.reactive import functions as rv class Nena: ballons: RP[int] = rv.from_value(98) nena = Nena() luftballons = [] rv.observe(nena.ballons).subscribe(luftballons.append) # Returns a Disposable. See Rx API. print(luftballons) # Returns [98]. nena.ballons = nena.ballons + 1 print(luftballons) # [98, 99] # Ok, I lied before. It's about Nena. not Toto :P If you are familiar with Rx, you may notice the similarities between ReactiveProperty with BehaviorSubject. In fact, the former is a wrapper around the latter, and observe returns an Observable instance backed by such a subject. To learn about all the exciting things we can do with an Observable, you may want to read the official documentation of Rx. We will introduce a few examples later, but before that, we better learn about the other variant of the reactive value first. Reactive View ReactiveView[T](or RV[T] for short) is another derivative of ReactiveValue, from which ReactiveProperty is also derived (hence, the alias of functions module used above, "rv"). The main difference is that while the latter owns a state value itself, a reactive view reflects it from an outside source specified as an Observable. To create a reactive view from an instance of Observable, you can use from_observable function like this: import rx from alleycat.reactive import RV from alleycat.reactive import functions as rv class Joni: big: RV[str] = rv.from_observable(rx.of("Yellow", "Taxi")) If you are familiar with Rx, you may see it as a wrapper around an Observable, while a reactive property can be seen as one around a Subject. Like its counterpart, you can initialize a reactive view either eagerly or lazily. In order to create a lazy-initializing view, you can use new_view, and later provide an Observable as shown below: import rx from alleycat.reactive import RV from alleycat.reactive import functions as rv class BothSides: love: RV[str] = rv.new_view() def __init__(self): self.love = rx.of("Moons", "Junes", "Ferris wheels") It also accepts read_only option from its constructor (default to True, in contrast to the case with ReactiveProperty) setting of which will make it 'writeable'. It may sound unintuitive since a 'view' usually implies immutability. However, what changes when you set a value of a reactive view is the source Observable that the view monitors, not the data itself, as is the case with a reactive property. Lastly, you can convert a reactive property into a view by calling its as_view method. It's a convenient shortcut to call observe to obtain an Observable of a reactive property so that it can be used to initialize an associated view. The code below shows how you can derive a view from an existing reactive property: from alleycat.reactive import RP, RV from alleycat.reactive import functions as rv class Example: value: RP[str] = rv.from_value("Boring!") # I know. But it's not easy to make it interesting, alright? view: RV[str] = value.as_view() Operators As we know how to create reactive properties and values, now it's time to learn how to transform them. Both variants of ReactiveValue provides map method, with which you can map an arbitrary function or lambda expression over each value in the pipeline: from alleycat.reactive import RP, RV from alleycat.reactive import functions as rv class Counter: word: RP[str] = rv.new_property() count: RV[str] = word.as_view().map(len).map(lambda o, c: f"The word has {c} letter(s)") # The first argument 'o' is the current instance of Counter class. counter = Counter() counter.word = "Supercalifragilisticexpialidocious!" print(counter.count) # Prints "The word has 35 letter(s)". Wait, did you actually count that? You can also use pipe to chain arbitrary Rx operators to build a more complex pipeline like this: from rx import operators as ops from alleycat.reactive import RP, RV from alleycat.reactive import functions as rv class CrowsCounter: animal: RP[str] = rv.new_property() # The first argument 'o' is the current instance of Counter class. crows: RV[str] = animal.as_view().pipe(lambda o: ( ops.map(str.lower), ops.filter(lambda v: v == "crow"), ops.map(lambda _: 1), ops.scan(lambda v1, v2: v1 + v2, 0))) counting = CrowsCounter() counting.animal = "cat" counting.animal = "Crow" counting.animal = "CROW" counting.animal = "dog" print(counting.crows) # Returns 2. There are also convenient counterparts to merge, combine_latest, and zip from Rx API, which you can use to combine two or more reactive values in a more concise manner: from alleycat.reactive import RP, RV from alleycat.reactive import functions as rv class Rectangle: width: RP[int] = rv.from_value(100) height: RP[int] = rv.from_value(200) area: RV[int] = rv.combine_latest(width, height)(lambda v: v[0] * v[1]) rectangle = Rectangle() print(rectangle.area) # Prints 20,000... you do the math! rectangle.width = 150 print(rectangle.area) # Prints 30,000. rectangle.height = 50 print(rectangle.area) # Prints 750. Install The library can be installed using pip as follows: pip install alleycat-reactive License This project is provided under the terms of MIT 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/alleycat-reactive/0.4.7/
CC-MAIN-2021-49
refinedweb
1,944
58.28
01 May 2009 14:54 [Source: ICIS news] By John Richardson ?xml:namespace> It’s hard to say – in fact it’s impossible to really say right now, which is a major concern for producers. Mathematically speaking, you would have thought that the retreat in pricing cannot be as bad as last year because prices are nowhere near their 2008 highs. Ethylene, for example, which reached a 2008 high of $1,625/tonne FOB (free on board) SEA (Southeast Asia) on 11 July, suffered its first big period of correction to $1,040/tonne It then fell to $420/tonne FOB by 12 December, according to ICIS pricing. Prices have subsequently rallied to only $660/tonne It’s the same for most petrochemicals and plastics. High-density polyethylene (HDPE) film grade was, for instance, at $1,120/tonne CFR (cost and freight) What could happen, though, if crude tumbles towards $30/bbl because of panic by traders who have built historically high inventories because they think the economic recovery is just around the corner? Swine flu is yet another threat to the recovery. But petrochemical producers seem to have reacted sensibly to the collapse in demand. Operating rates in US and European producers have made big cutbacks. LyondellBasell, Dow Chemical, BASF and others have idled numerous plants. Japanese C2 operating rates were only around 75% in March, estimated Mitsubishi Chemical. Logistics problems have limited the amount of product flowing from the Some of the polyolefins that might have moved from the West to the East have remained where they are because a lack of container ships in the right place at the right time, he claimed. Exports of finished goods from Asia to the Ship owners are apparently also playing games to try and achieve barely reasonable returns in very weak gas and liquid chemicals markets, he said. “You might book a vessel to, say, leave Rotterdam carrying benzene to Asia on the 5th of May but the ship you need doesn’t show up until the 10th because the owner has taken another extra shipment beforehand.” Insurance premiums have gone up because of the increase in piracy off the coast of A ship owner might not be willing to take the risk of moving a low-level gas carrier making it easy to board) from the West to Cargoes are also taking longer to reach their destination as ships sometimes need to wait for 3-4 day in the This is all positive stuff if you are a producer or buyer wanting a little stability. But if you look at the trade data in isolation, an entirely different feeling begins to take hold. Around 200,000 tonnes of US and European benzene is heading for The surge in toluene shipments from the West to These figures are perhaps only startling if you don’t have a clear view of global production levels (does anyone have such a view? If so, please let us know). Have they gone up since prices began to rally in mid-February, have they remained unchanged – or might they have even gone down? Some producers, and certainly the traders who of course love volatility, appear to have only intuitions as answers. “The But a source with a leading Western polyolefins producer argued: “I can’t see the logic of this as US and European producers are struggling to push through domestic price rises.” The surge in West-East imports might be over as inventory pressures have been relieved. It is too early to tell if this is right as all business for May arrival has been concluded with discussions for June delivery either only just beginning or yet to start. Everybody agrees that it could be a big risk to fix shipments possibly for June arrival – and definitely for July – because of the end of the Asian turnaround season and new capacity in the Middle East and Lower naphtha prices could also contribute to a price retreat – along with, of course, a collapse in crude. What would happen to polyolefins, though, if there are more production problems at PetroRabigh – the Saudi Aramco/Sumitomo Chemical joint-venture project - which came on stream recently? “If PetroRabigh had been on schedule then the increased supply would have stopped the price rally in April,” added the source with the Western producer. The complex includes a 300,000 tonne/year high density PE (HDPE) line, a 250,000 tonne/year easy processing PE (EPPE) unit, a 700,000 tonne/year PP plant and a 350,000 tonne/year linear-low density PE (LLDPE) facility. It gets even more confusing: some producers and traders talk of higher operating rates at Chinese and South Korean crackers since mid-February as a threat to markets. Some of the scheduled second half start-ups in On the positive side again, though, much of the volume from three other big new These are YanSab and Sharq in Saudi Arabia and Ras Laffan Olefins Co in Qatar – all of which had been due to be fully on stream in 2009. PP capacity growth has also been slowed by several delays of propane-dehydrogenation-to-PP units in Reliance Industries’ refinery-linked 900,000 tonne/year PP plant is also substantially behind schedule. If prices suddenly start to soften significantly, it is also quite possible that we will see more shutdowns in the West – perhaps some of them permanent as obsolete plants are scrapped. On the other side of the debate, though, is talk from some traders (perhaps it is in their interests to say this?) of high polyolefin inventories among fellow traders and distributors in But at least two producers say that stock levels are only at medium levels. Switching back to aromatics again, though, toluene inventories are widely reported to be close to 100,000 tonnes in It’s hard work trying to read market direction – but maybe everyone is putting too much sweat and tears into this and over-complicating things. Perhaps what’s needed is a focus on some good old-fashioned big-picture fundamentals. These could apply to all commodities including crude oil, chemicals, iron ore, steel, aluminium and equities. “I learnt long ago as a trader that it’s usually a mistake to ask someone why a market went up or down,” said Paul Hodges, chemicals consultant with the UK-based International eChem. “JP Morgan, when asked about the outlook for the market, said very wisely that it would fluctuate. “If a market wants to go up it will go up because there are more buyers than sellers and vice -versa. “Commentators will then ascribe this to news of something or other, but that doesn’t imply cause and effect. “What is always interesting is to understand why people are buying or selling. “I am pretty sure it’s the ‘seeing through-to- the-recovery’ argument, which makes people think they have to jump on the train before it leaves the station. “ So all you need is to make your mind about is whether the global economic recovery is really imminent. That’s an easy task for the
http://www.icis.com/Articles/2009/05/01/9213030/insight-trying-to-read-market-direction.html
CC-MAIN-2014-52
refinedweb
1,187
53.85
16 August 2011 04:59 [Source: ICIS news] SHANGHAI (ICIS)--?xml:namespace> Its total output for the first seven months of this year was at 120m tonnes, an increase of 3.9% year on year, according to data from China Petroleum and Chemical Industry Federation (CPCIF). Its total processing output from January to July increased by 6.9% year on year to 261m tonnes, the data showed. The country’s domestic natural gas output is growing steadily, while its consumption remains high, resulting in a supply-demand balance, a source from CPCIF said. Its total output from January to July was at 59.76bn cbm, an increase of 7.7% year on year, the data showed. Its ethylene output increased by 11.5% year on year to 1.3m tonnes in July, while its total output for the first seven months was at 9.2m tonnes, an increase of 16.9% year on year. Source: CPC
http://www.icis.com/Articles/2011/08/16/9485336/china-july-energy-petrochemical-outputs-stable-on-new-capacities.html
CC-MAIN-2014-35
refinedweb
156
69.58
I have this strings : "case" and "ro". I need to get every combination between them, where I substitute the single letters from the second string into the first one, but only if the letter is greater than the other one. Ex: in "rose : r>c, o>a. Other Examples are: "cose", "roso", "coso" I tried writing something, using iteration, but it goes on a infinite loop and doesn't generate nothing. If someone can help me figure out a simpler way to do this, it would be great. I am answering on basis of what i have understood from the question. Please check whether the following answer is correct for you.If yes then I can explain the code later. def solve( s1, s2): # prints all combinations of s1 from letters of s2 in a list ans = [s1] if s1=="": return ans tmp = solve( s1[1:],s2 ) ans += [ s1[0]+x for x in tmp ] for c in s2: if c>s1[0]: ans += [ c+x for x in tmp ] return list(set(ans)) print solve("case","ro")
https://codedump.io/share/JICIUbWFsWIf/1/mixing-two-string-recursively
CC-MAIN-2017-09
refinedweb
178
78.48
Dani Arribas-Bel (@darribas) The Modifiable Areal Unit Problem (MAUP) is a well know phenomenon for any researcher interested in spatial issues. In this notebook, we'll get our hands dirty experimenting with different geographical configurations and will see, in a practical way, some of the implications of the MAUP. In doing this, we'll also tour some of the basic functionality in geopandas. To motivate this exercise, let us start from the end and show how, the exact same underlying geography, can generate radically different maps, depending on how we aggregate it: In this case, we have started from a set of points located in a hypothetical geography (left panel). We can think of them as firms located over a regional economy, the distribution of a particular species of trees over space, or any other phenomenon where the main unit of observation can be described as points located somewhere in space. Now, in the central pane, we have overlayed a five by five grid and, for every polygon, which we could think of a regions, we have counted the number of units and assigned a color based on its value. In the right pane, we have done the same, using the same underlying distribution of points, but have overlaid a ten by ten grid of polygons. The gist of the MAUP is that, even though the original distribution is the same, the representation we access by looking at the aggregate can vary dramatically depending on the characteristics of this aggregation. In our example, the units were points and the aggregation were simple polygons in a grid. But the same problem occurs, for example, when we look at income over individuals and aggregate the average in neighborhoods, regions or countries: if the units we use for this aggregation are not meaningful, in other words, if they don't match well the underlying process, there can be substantial distortions. Now we have the conceptual idea clear, let's see how we have arrived to the picture above! Before anything, here are the libraries you'll need to run this notebook: %matplotlib inline import matplotlib.pyplot as plt import geopandas as gpd import pandas as pd import numpy as np from itertools import product from shapely.geometry import Polygon, Point First we need an engine that generates grids of different sides. This will allow us later to easily create many geographies with different characteristics, which will dictate the aggregation process. We can solve this problem with the following method, which generates polygons and collects them into a GeoSeries: def gridder(nr, nc): ''' Return a grid with `nr` by `nc` polygons ... Arguments --------- nr : int Number of rows nc : int Number of columns ''' x_breaks = np.linspace(0, 1, nc+1) y_breaks = np.linspace(0, 1, nr+1) polys = [] for x, y in product(range(nc), range(nr)): poly = [(x_breaks[x], y_breaks[y]), \ (x_breaks[x], y_breaks[y+1]), \ (x_breaks[x+1], y_breaks[y+1]), \ (x_breaks[x+1], y_breaks[y])] polys.append(Polygon(poly)) return gpd.GeoSeries(polys) Once defined, it's easy to generate a grid of, for example, four by three polygons: polys = gridder(3, 4) polys.plot(alpha=0) plt.show() Now we have the "engine" to generate the geography, we need to create observations that we can pinpoint over space. The easiest way is to randomly generate points within the bounding box of the geographies we create, and store them in a different GeoSeries. That's exactly what the following function does: def gen_pts(n): ''' Generate `n` points over space and return them as a GeoSeries ... Arguments --------- n : int Number of points to generate Return ------ pts : GeoSeries Series with the generated points ''' xy = pd.DataFrame(np.random.random((n, 2)), columns=['X', 'Y']) pts = gpd.GeoSeries(xy.apply(Point, axis=1)) return pts This allows us to create, for example, 100 points: # Set the seed to always get the same locations np.random.seed(123) pts = gen_pts(100) pts.head() 0 POINT (0.6964691855978616 0.2861393349503795) 1 POINT (0.2268514535642031 0.5513147690828912) 2 POINT (0.7194689697855631 0.423106460124461) 3 POINT (0.9807641983846155 0.6848297385848633) 4 POINT (0.4809319014843609 0.3921175181941505) dtype: object Since we already have tools to create both the underlying points and a geography in which to aggregate it, let us imagine what this could look like. In fact, stop imagining and simply plot them: Now, to get to a map like those above, we need a way to assign how many points are within each polygon. The following method does exactly that, albeit in a fairly computationally expensive way. There are faster ways to do it in geopandas (spatial join, I'm looking at you), but they require additional dependencies, and are not as intuitive as this one I think. For now, this approach will have to do: def map_pt2poly(pts, polys): ''' Join points to the polygon where they fall into NOTE: computationally inefficient, so slow on large sizes ... Arguments --------- pts : GeoSeries Series with the points polys : GeoSeries Series with the polygons Returns ------- mapa : Series Indexed series where the index is the point ID and the value is the polygon ID. ''' mapa = [] for i, pt in pts.iteritems(): for j, poly in polys.iteritems(): if poly.contains(pt): mapa.append((i, j)) pass mapa = np.array(mapa) mapa = pd.Series(mapa[:, 1], index=mapa[:, 0]) return mapa Check how we can collect the count for each polygon in a GeoDataFrame that also holds their geometries: pt2poly = map_pt2poly(pts, polys) count = pt2poly.groupby(pt2poly).size() db = gpd.GeoDataFrame({'geometry': polys, 'count': count}) db.head() At this point, we have everything we need to make a map of the counts of points per polygon: db.plot(column='count', scheme='quantiles', legend=True, colormap='Blues') <matplotlib.axes._subplots.AxesSubplot at 0x10e55a8d0> Although we have all the pieces, one of the beauties of scripting languages like Python is that they allow you wrap different functionality so that obtaining the final outcome is easier than repeating every step every time you need the final product. In this case, we can ease the process by encapsulating the process above into a single method that takes nr, nc and the points we want to plot and generate a table of counts per polygon: def count_table(nr, nc, pts): ''' Create a table with counts of points in `pts` assigned to a geography of `nr` rows and `nc` columns ... Arguments --------- nr : int Number of rows nc : int Number of columns pts : GeoSeries Series with the generated points Returns ------- tab : GeoDataFrame Table with the geometries of the polygons and the count of points that fall into each of them ''' polys = gridder(nr, nc) walk = map_pt2poly(pts, polys) count = walk.groupby(walk).size().reindex(polys.index).fillna(0) tab = gpd.GeoDataFrame({'geometry': polys, 'count': count}) return tab For example, we can generate the counts for a five by five grid: counts_5x5 = count_table(5, 5, pts) counts_5x5.head() And quickly plot it on quantile map using PySAL under the hood: counts_5x5.plot(column='count', scheme='quantiles', colormap='Blues') <matplotlib.axes._subplots.AxesSubplot at 0x10cec7e10> %%time np.random.seed(123) pts = gen_pts(1000) sizes = [5, 10] f, axs = plt.subplots(1, len(sizes)+1, figsize=(9*len(sizes), 6)) pts.plot(axes=axs[0]) axs[0].set_title('Original point pattern') for size, ax in zip(sizes, axs[1:]): tab = count_table(size, size, pts) tab.plot(column='count', scheme='quantiles', \ colormap='Blues', axes=ax, linewidth=0) ax.set_title("%i by %i grid"%(size, size)) plt.show() CPU times: user 3.43 s, sys: 42.8 ms, total: 3.48 s Wall time: 3.48 s We can also generate a plot for each case in which we compare the points, with the geography, with the final map: def plot_case(nr, nc, pts): ''' Generate an image with the original distribution, the geography, and the resulting map ... Arguments --------- nr : int Number of rows nc : int Number of columns pts : GeoSeries Series with the generated points ''' tab = count_table(nr, nc, pts) f, axs = plt.subplots(1, 3, figsize=(18, 6)) pts.plot(axes=axs[0]) tab.plot(alpha=0, axes=axs[1]) tab.plot(column='count', scheme='quantiles', \ colormap='Blues', axes=axs[2], linewidth=0) plt.show() plot_case(7, 4, pts) And then run if for several cases: np.random.seed(123) pts = gen_pts(500) plot_case(2, 2, pts) plot_case(5, 5, pts) plot_case(10, 10, pts) <span xmlns:The Modifiable Areal Unit Problem, visually, in Python</span> by <a xmlns:Dani Arribas-Bel</a> is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
https://nbviewer.jupyter.org/gist/darribas/8b5a7b93d4085223f1c5/maup.ipynb
CC-MAIN-2018-13
refinedweb
1,422
54.63
I was about to write about Protobuf and GWT but I thought I'd rather start with a more general Protobuf (or Thrift or Avro or…) in the browser. I'll post the Protobuf and GWT thing as a follow up. In a new webapp project at work, our client wants to handle scalability by moving some parts of the app to other machines instead of clustering; i.e. the server is composed of modules that could be distributed on several machines. Back in september I started to look around for protocols and solutions to help us implement it, and found Protocol Buffers and Thrift, among others. As the project now becomes more concrete, I've started revisiting my previous researches. I found out that Thrift now has an official release and that protobuf now has an (experimental) generator plugin mechanism. This last thing, along with parallel reseaches on Comet, which made me think about Wave and remember that it was said to use protobuf, made me wonder whether and how it could be used in the browser. My Comet researches also lead me to Closure Library, which has a goog.proto2 namespace, confirming using protobuf on the browser isn't totally dumb. And finally last week I was reminded of gwt-rpc-plus, which happens to have something about Thrift. The context having been exposed, let's discuss it, in the form of Q&A's. Q: Isn't protobuf about serializing objects to a compact binary format? (which you couldn't read from JavaScript) A: Yes, but not only. Protobuf is 2 things: an IDL with a code generator, and a compact format for object serialization. Q: But then which serialization frmat would you use? A: the most efficient on the browser-side certainly is JSON. That's also what Closure Library uses, in different flavors (an array indexed by the field tags, and object keyed by the field tags or an object keyed by the field names). Q: OK, so if it's not about the binary format, it's about the IDL; but why not go with JSON Schema then? A: JSON Schema sure would be an alternative, but my first goal was to use protobuf (or thrift or…) for server-to-server communications, so I'd rather use the same technology everywhere. Add to this that to my knowledge there's no existing tool to generate Java classes from a JSON Schema (Jackson can generate a JSON Schema from an annotated Java class, but given the client-side will be GWT, i.e. Java, there would be no point generating such a schema). Q: Er, if you're using GWT and server-side Java, then why not just use GWT-RPC? A: GWT-RPC by default tightly couples the client and the server, as it passes around a checksum for each serialized class based on the class name, its parents classes name and all their fields name. This means that as soon as you add or remove a field from a class, you have to redeploy both the client and server side or they will fail to communicate. GWT-RPC also enforces primitive type equivalence between the client and server: if you changed a byte into an int on one side, the other side will error if it receives a value that cannot fit into the expected byte type. Protobuf is all about allowing you to update the messages (to a certain extent) without having to redeploy all involved parties. This is particularly true for high-availability services (such as Google Apps) where you'll upgrade servers in the cluster one at a time and/or upgrading the server while the client is still loaded in clients' browsers and has to be able to communicate with the upgraded server without error or reload. In our case, high availability isn't a high goal, but I think it might help during developments and particularly help focusing on "protocols" (including how much data goes on the wire) rather method calls (particularly true when you start mixing ORM with lazy-loading on the server-side; you don't really think about it on the database communications' side, but have to keep it in mind when it comes to browser-server communications; and it's even worse when you pass JDO/JPA entities in GWT-RPC!) Q: OK, OK, but that's a GWT-RPC issue. You said this post wasn't specifically about GWT but more generally about protobuf in the browser, that you'd use JSON as a serialization, and that Closure Library has goog.proto2 support. But Closure is JavaScript so why isn't it just using JSON (on the client side at least)? A: With plain JSON, you have to handle default values in your code each time you retrieve a property. I suppose there's also a rule within Google to sometimes change the name of a field, such as adding an "OBSOLETE_" prefix when obsoleting a field. This works with protobuf because the binary format only deals with field tags. In JSON though you'd likely use the field name as the key in an object, so you'd have to "break the rule" and not rename fields, or code defensively on client side (looking into both "foo" and OBSOLETE_foo", still fragile though as the developer could have made a typo and named the field OBSOLTE_foo), or serialize using field tags as the keys. In all those cases, either the code is fragile, depending only on some informal rule, or it becomes less readable and harder to maintain. Client-side developers would probably start writing functions to retrieve field values, then eventually wrap the decoded JSON object into a higher-level object so they can turn their functions into methods, etc. Which is exactly what goog.proto2.Message provides, and where a code generator becomes very helpful. (the next step is to find that your JSON object's property names adds bytes to be transmitted on the network and switch to a lighter representation, such as PB-Lite or using field tags as keys, now that you have wrapper objects to access field values.) Q: Let's say you convinced me. Now how about services you can declare in a .proto file? A: Closure Library (the only JavaScript library I know of that deals with protobuf) doesn't seem to provide anything. With GWT I'm expecting to reuse the GWT-RPC APIs or even infrastructure and wire protocol. More in the followup post about Protobuf and GWT…
http://blog.ltgt.net/exploring-using-protobuf-in-the-browser/
CC-MAIN-2021-17
refinedweb
1,095
57.1
Bluemix create container group linking to another container We have a Java application running with MongoDB, each one in a different Bluemix container. Both are SINGLE Bluemix containers. We want to serve the Java app using one of our subdomains:, which is already pointing to Bluemix. How can we do it? OUR APPROACH Because the Java container needs to link to the Mongo container, we created both containers programmatically (we didn’t find in the UI a way to link a container to another container) like this: sudo bluemix ic run --name mongo-container -p 27017 -m 128 registry.eu-gb.bluemix.net/mycompany/mongo sudo bluemix ic run --name java-container --link mongo-container:mongo -p 8080 -m 128 registry.eu-gb.bluemix.net/mycompany/java This works well, but the Java app is only accessible through an ugly Blumix IP, not through as we want. What about using a Bluemix container GROUP (SCALABLE container in the UI)? Again, we don’t know how to link containers from the UI, so it should be something like sudo bluemix ic group-create --auto --name java-scalable -p 8080 -m 128 --hostname subdomain --domain mydomain.com registry.eu-gb.bluemix.net/mycompany/java BUT according to the documentation we cannot link a container group to a container, since there is no --link parameter. Back to the original question. How can we serve the Java app using? 2 Solutions collect form web for “Bluemix create container group linking to another container” The link option basically creates environment variables in one container to reach the other one. You can do the same with your scalable container in Bluemix. Here are the steps I did: 1) Create your MongoDB container: bx ic run --name ads-mongo -p 27017 -m 128 registry.ng.bluemix.net/namespace/mongo 2) Inspect the MongoDB container to find the private IP address: bx ic inspect ads-mongo The private IP will be at end of the output, I am adding just part of the output below for brevity: "Ports": { "27017/tcp": [ { "HostIp": "172.31.0.235", "HostPort": "27017" } ] }, "PublicIpAddress": "" 3) Run your scalable container and include one or more environment variables with your MongoDB credentials. Make sure you change your Java code to get the credentials from the environment variables you are passing to the scalable container: bx ic group-create --name ads-node -e "MONGO_URI=mongodb://172.31.0.235:27017" -p 3000 -m 128 --hostname ads-node --domain mybluemix.net registry.ng.bluemix.net/namespace/ads-nodebx In my test I used a Node.js application and it reads the MONGO_URI environment variable for the MongoDB credentials. You can assign a public IP for your MongoDB container as well if desired, the end result should be similar. The only difference I see is that you can then access your db using mongo command line or other tools to connect to the database. So following the second approach, you may be able to create a MongoDB service before creating the Bluemix Container Group. During Bluemix Container Group creation you have the ability to bind an existing service under the Advanced Options section in the UI: You can also choose to use a custom Domain during Container creation, if you have previously created one: In this case you would have a container with a custom Domain that also includes an existing service. You can find more information about binding an existing service in the Container Integration Documentation. You can learn more about creating a custom domain in Bluemix in the Updating Apps Documentation.
http://dockerdaily.com/bluemix-create-container-group-linking-to-another-container/
CC-MAIN-2018-26
refinedweb
594
51.18
This section describes how to parse well-formed and valid XML documents, and shows the differences between them. In this section, we show how to read a simple XML document, called department.xml, using Xerces. This document represents a set of employee records in a department (see Listing 2.1). The meanings of the tags should be self-explanatory. <?xml version="1.0" encoding="utf-8"?> <department> <employee id="J.D"> <name>John Doe</name> This is a well-formed XML document, and it should be parsed by a non-validating XML processor. The first task of this book is to read and parse the document by using Xerces. We run the sample program, SimpleParse, located in samples\chap02 on the CD-ROM, using the following commands: R:\samples>java chap02.SimpleParse chap02/department.xml R:\samples> This program, as in the previous section, produces no output. However, we know that Xerces did its job, because SimpleParse did the following: Opened the XML document department.xml Parsed it with an XML processor, which is described later Created a corresponding data structure in memory, a structure that can later be referred to or manipulated by application programs such as a Java object The fact that you see no output means that there were no violations of well-formedness (missing end tags, improper nesting, and so on). Listing 2.2 gives the source code of SimpleParse. Although a very short program, it shows the basics of how you can use Xerces. package chap02; /** * SimpleParse.java **/ [5] import org.w3c.dom.Document; [6] import org.apache.xerces.parsers.DOMParser; import org.xml.sax.SAXException; import java.io.IOException; public class SimpleParse { public static void main(String[] argv) { if (argv.length != 1) { System.err.println( "Usage: java chap02.SimpleParse <filename>"); System.exit(1); } try { [18] // Creates a parser object [19] DOMParser parser = new DOMParser(); [20] // Parses an XML Document [21] parser.parse(argv[0]); [22] // Gets a Document object [23] Document doc = parser.getDocument(); [24] // Does something [25] } catch (SAXException se) { [26] System.out.println("Parser error found: " [27] +se.getMessage()); [28] System.exit(1); } catch (IOException ioe) { System.out.println("IO error found: " + ioe.getMessage()); System.exit(1); } } } Now we'll look at the program SimpleParse line by line, referring to the numbers in square brackets on the left side of the program listing. First, this class imports some classes to use with Xerces: In line 5, the Document class, from the org.w3c.dom package, which is the interface that represents the whole XML document In line 6, the DOMParser class, from org.apache.xerces.parsers, which is a DOM-based XML processor Also, two exception classes (SAXException and IOException) are imported. The heart of this program is in lines 19–22. [19] DOMParser parser = new DOMParser(); Line 19 creates a DOM-based processor to parse an XML document. [21] parser.parse(argv[0]); Next, line 21 parses an XML document specified by a command-line argument (argv[0]). In this case, the parse() method takes the filename of the XML document. The method has the following argument patterns (signatures), and you can choose the appropriate one. Document parse (String uri) Document parse (java.io.File f) Document parse (org.xml.sax.InputSource is) Document parse (java.io.InputStream is) Document parse (java.io.InputStream is, String systemId) The third one requires an object of the org.xml.sax.InputSource class, which is useful to wrap various input formats for an XML document to be parsed. Though it is originally from the SAX 1.0 API, it is widely used for a DOM parser as well as a SAX parser. The class has four constructors: InputSource () InputSource (java.io.InputStream byteStream) InputSource (java.io.Reader characterStream) InputSource (java.lang.String systemId) If you want to write a method (say, processWithParse()) that takes an input file name as an argument, processWithParse(InputSource is) is more reusable than processWithParse(File f) or processWithParse(String url). [23] Document doc = parser.getDocument(); Line 23 receives the Document instance. The org.w3c.dom.Document interface is specified by the DOM specification from W3C. The variable doc actually refers to an instance of an implementation class (org.apache.xerces.dom. Document/mpl) provided by Xerces. The instance represents the whole XML document and can contain (1) at most one DocumentType instance that represents a DTD, (2) one Element instance that represents a root element (which is called a document element), and (3) zero or more Comment and ProcessingInstruction instances. The interface provides methods to visit and modify child nodes of the root element. For example, an application can get the root (document) element of an XML document by using the getDocumentElement() method of the Document interface. This sample program is simple, but you can see many other programs in this book. When something goes wrong, the program throws an exception. The program shown in Listing 2.2 catches the following two exceptions: java.io.IOException— Occurs when the XML processor failed to load the XML document (because the file was not found, for example) org.xml.sax.SAXException— Occurs when the input document violates the well-formedness constraints You might think that this program has no practical value because it does not produce any output. However, it is useful as a syntax checker. It can tell you whether the input XML document is well-formed or not. To show you how this works, we give an XML document that is not well-formed, department2.xml, to SimpleParse in Listing 2.3. This document is not well-formed, because the end tag of the first email element is </email1>, not </email>. The result of parsing the document is as follows: R:\samples>java chap02.SimpleParse chap02/department2.xml Parser error found: The element type "email" must be terminated by the matching end-tag "</email>". The XML processor recognizes the mismatch of the start and end tags, and reports it to applications by an exception (SAXException). In Listing 2.2, the exception is caught in lines 25–28. In this section, we parse a valid XML document according to a DTD. An example called department-dtd.xml is shown in Listing 2.4. The DOCTYPE declaration (the second line) tells an XML processor the location of the DTD. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE department SYSTEM "department.dtd"> <department> <employee id="J.D"> <name>John Doe</name> The DTD for the document is shown in Listing 2.5. <!ELEMENT department (employee)*> <!ELEMENT employee (name, (email | url))> <!ATTLIST employee id CDATA #REQUIRED> <!ELEMENT name (#PCDATA)> <!ELEMENT email (#PCDATA)> <!ELEMENT url EMPTY> <!ATTLIST url href CDATA #REQUIRED> As shown in Section 1.4.2, a DTD specifies the structure of an XML document. For example, the first element declaration in Listing 2.5 says a department element must have zero or more employee elements. The second declaration says an employee element must have a name element as the first child element and an email or url element as the second child element. The third one indicates an employee element must have an id attribute. The word #PCDATA means characters, and the url element cannot have any children (it is an empty element). Refer to the XML 1.0 specification for the details. Xerces is a validating processor, but it does not validate by default. So we must tell Xerces to validate an input XML document against the DTD. Listing 2.6 shows a sample program for the validation. package chap02; /** * SimpleParseWithValidation.java **/ import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ErrorHandler; import org.apache.xerces.parsers.DOMParser; import share.util.MyErrorHandler; import java.io.IOException; public class SimpleParseWithValidation { public static void main(String[] argv) { if (argv.length != 1) { System.err.println("Usage: java "+ "chap02.SimpleParseWigthValidation <filename>"); System.exit(1); } try { // Creates parser object DOMParser parser = new DOMParser(); [25] // Sets an ErrorHandler [26] parser.setErrorHandler(new MyErrorHandler()); [27] // Tells the parser to validate documents [28] parser.setFeature( "", true); [31] // Parses an XML Document [32] parser.parse(argv[0]); [33] // Gets a Document object [34] Document doc = parser.getDocument(); // Does something } catch (Exception e) { e.printStackTrace(); } } } Again, let's look at the program in detail. First, a DOMParser object is created. In SimpleParse, shown in Listing 2.2, we caught a SAXException exception when an input XML document was not well-formed. An XML processor provides an error handler to handle errors more flexibly. The error handler recognizes fatal errors that prevent it from continuing a parsing process, errors that are defined in the XML 1.0 Recommendation, and warnings for other problems. Error handlers should implement the org.xml.sax.ErrorHandler interface. To create an error handler, there are two well-known methods. An application itself implements org.xml.sax.ErrorHandler. A separate class implements the interface, and an application call the class. If you can work with a general error handler that can be shared with other applications, the latter approach is good in terms of software reuse. If you want to use an application-specific handler, or you don't want to create a new class for the handler for some reason, the former approach may be better. This book employs the latter approach. MyErrorHandler, shown in Listing 2.7, is a typical implementation of an error handler. package share.util; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class MyErrorHandler implements ErrorHandler { /** Constructor. */ public MyErrorHandler(){ } /**) { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /**(); } } The org.xml.sax.ErrorHandler interface defines fatalError(), error(), and warning(). The MyErrorHandler class implements these methods to show a filename, line and column numbers, and the content of an error. In SimpleParseWithValidation (see Listing 2.6), MyErrorHandler is created in line 26 and set to a parser object. [25] // Sets an ErrorHandler [26] parser.setErrorHandler(new MyErrorHandler()); Next, we tell the XML processor to turn on validation by using the setFeature() method. This is a method of the org.xml.sax.XMLReader interface that is implemented by the DOMParser classes. The method is used to set various features of an XML processor. In this book, we use some of the features (see Section 6.3.1 for more on these features). Refer to for the complete list of features. Note that the default value of the validation feature ("") is false, so SimpleParse in the previous section did not check the validity of the XML document. [27] // Tells the parser to validate documents [28] parser.setFeature("", true); Finally, we start parsing. This is the same process as in SimpleParse. [31] // Parses an XML Document [32] parser.parse(argv[0]); [33] // Gets a Document object [34] Document doc = parser.getDocument(); Now we run this program to parse a valid XML document, department-dtd.xml. R:\samples>java chap02.SimpleParseWithValidation chap02/ department-dtd.xml R:\samples> Because department-dtd.xml shown in Listing 2.4 conforms to department.dtd (see Listing 2.5), it should be parsed without error. The next example is an invalid document, department-dtd2.xml, shown in Listing 2.8. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE department SYSTEM "department.dtd"> <department> <employee> <name>John Doe</name> When we parse the document with SimpleParseWithValidation, we can see an error because the document does not conform to the DTD. R:\samples>java chap02.SimpleParseWithValidation chap02/ department-dtd2.xml [Error] 4:13 Attribute "id" is required and must be specified for element type "employee". As shown in the previous output, the fourth line of department-dtd2.xml has an error. The email element does not have an id attribute, although it is required. Errors and warnings with line numbers make it possible to recognize where and why they occurred. NOTE The difference between an error and a fatal error is defined in the XML 1.0 specification. An error is a violation of the rules of the specification. A conforming XML processor may detect and report an error and may recover from it. That means an application may get the internal structure of parsed XML documents. Violations of validity constraints are errors. On the other hand, the XML processor must detect and report fatal errors to the application. Once a fatal error is detected, the processor must not continue normal processing. Violations of well-formedness constraints are fatal errors. In the previous sections, you learned how to parse well-formed and valid documents. In this section, we discuss which types of documents should be used when you design and develop real Web applications. In other words, what are the pros and cons of validation? This section discusses the design point from several viewpoints. If a document structure is strictly defined by a DTD, an application can skip a checking process for the structure. For example, suppose a DTD specifies a name element as a required element. Applications don't have to check the existence of the element, because if an XML document that conforms to the DTD is parsed by a validating XML processor, the element should appear in the document. If you use XML Schema (discussed in Chapter 9), data type checking is also done by a validating processor. This can prevent applications from stopping by receiving data that has an unexpected data type. That is, validation makes your applications simpler and safer. Validation is an expensive task when very large documents are to be parsed. Even if the documents are not so large, it is time-consuming when many documents must be parsed at the same time in a high-volume Web application. In such cases, we should think carefully if we need validation. When you consider a non-PC platform such as PDA devices, validation might be impossible in the limited-resource environment. It is an important point for design if we really need validation. For example, suppose two companies want to exchange an XML document. If both companies know the structure of the document and the sending company sends a valid document, the receiving company can expect the document to always be valid and thus validation is not needed. As discussed before, parsing with validation makes applications safe. However, if the transaction between the companies is very large, parsing without validation may be a good choice. If the structure of the document is not complex and applications do not require all the information in the document, validation might not be
http://codeidol.com/community/java/basics-of-parsing-documents/12583/
CC-MAIN-2017-17
refinedweb
2,415
52.26
On Thu, 31 Oct 2013 19:22:18 +0100, Oleg Nesterov wrote:> On 10/29, Namhyung Kim wrote:>>>> +static void __user *get_user_vaddr(unsigned long addr, struct trace_uprobe *tu)>> +{>> + unsigned long pgoff = addr >> PAGE_SHIFT;>> + struct vm_area_struct *vma;>> + struct address_space *mapping;>> + unsigned long vaddr = 0;>> +>> + if (tu == NULL) {>> + /* A NULL tu means that we already got the vaddr */>> + return (void __force __user *) addr;>> + }>> +>> + mapping = tu->inode->i_mapping;>> +>> + mutex_lock(&mapping->i_mmap_mutex);>> + vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {>> + if (vma->vm_mm != current->mm)>> + continue;>> + if (!(vma->vm_flags & VM_READ))>> + continue;>> +>> + vaddr = offset_to_vaddr(vma, addr);>> + break;>> + }>> + mutex_unlock(&mapping->i_mmap_mutex);>> +>> + WARN_ON_ONCE(vaddr == 0);>> Hmm. But unless I missed something this "addr" passed as an argument can> be wrong? And if nothing else this or another thread can unmap the vma?You mean WARN_ON_ONCE here is superfluous? I admit that it shouldprotect concurrent vma [un]mappings. Please see my reply in otherthread for a new approach.Thanks,Namhyung
https://lkml.org/lkml/2013/11/4/71
CC-MAIN-2021-25
refinedweb
150
55.13
Share and distribute Open Policy Agent Bundles with OpenFaaS functions One of the features of OpenFaaS is an auto-scaling mechanism. The auto-scaling means is that you can scale up/down your function instances as demand increases. Also, OpenFaaS provides a feature called zero-scale. By enabling this feature, you can scale to zero to recover idle resources is available in OpenFaaS. Using OpenFaaS as an OPA’s Bundle API, you can have all the features by default with less effort. Also, you can’t have to manage to build/push and deploy phases with your Bundle API. What you will learn in this post? In this post we are gonna learn: - What is OPA (Open Policy Agent)? - How can we deploy OPA co-located with our service? - How can OpenFaaS help us with the OPA? - Demo What is OPA (Open Policy Agent)? OPA describes itself as a general-purpose policy engine, for more detail you can look at the official documentation. OPA’s main goal is to decouple policy decision-making from policy enforcement. When your software needs to make policy decisions it queries OPA and supplies structured data (e.g., JSON) as input. OPA accepts arbitrary structured data as input. Credit: How can we deploy OPA co-located with our service? When it comes to deploying OPA, you have more than one option depending on your specific scenario: - As a Go library - As a daemon The recommended way is to run OPA is as a daemon. The reason is that this design increases performance and availability. By default, all of the policy and data that OPA uses to make decisions is kept in-memory for the low-latency and we should colocate OPA and the service to avoid the network latency also. Credit: How can OpenFaaS help us with the OPA? OPA exposes a set of APIs that enable unified, logically centralized policy management which is called “Management API’s”. Think of them as a Control Plane for the OPA instances working as a Data Plane. With the Management API's you can control the OPA instances like enable decision logging, configure the Bundle API, etc. Let’s focus on Bundle API which is one of the Management API for OPA. Bundle API’s purpose is to help OPA to load policies across the stack to the OPA instances.OPA can periodically download bundles of policy and data from remote HTTP servers. The policies and data are loaded on the fly without requiring a restart of OPA. In this demo, we create a serverless function that mimics an OPA’s Bundle API. Simply, this serverless function designed as a plain file server. When OPA’s asks for the policies it basically returns bundles that ready on the filesystem as a response. Demo You can find all the details about this demo in the Github repo. Prerequisites - A Kubernetes cluster (kind, minikube, etc.) - OpenFaaS CLI - Arkade - Kubectl - KinD Setup 1. Setup Tools - Arkade $ curl -sLS | sudo sh - KinD $ arkade get kind - Kubectl $ arkade get kubectl - faas-cli $ arkade get faas-cli 2. Set Up Cluster You can start a Kubernetes cluster with KinD if you don't have one already $ arkade get kind $ kind create cluster 3. Deploy OpenFaaS - Install OpenFaaS using Arkade $ arkade install openfaas - Verify Deployment $ kubectl rollout status -n openfaas deploy/gateway - Enable local access to Gateway $ kubectl port-forward -n openfaas svc/gateway 8080:8080 & 4. Configure faas-cli - Access password that available in the basic-auth secret in openfaas namespace $ PASSWORD=$(kubectl get secret -n openfaas basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode; echo) - Login with using the password to Gateway $ echo -n $PASSWORD | faas-cli login --username admin --password-stdin 5. Deploy Function - Go to the functions directory, pull the right template and deploy the function $ cd functions $ faas-cli template store pull golang-middleware $ faas-cli up -f bundle-api.yml 6. Load Images - Load images from Docker Hub to the KinD $ docker image pull openpolicyagent/opa:latest $ kind load docker-image openpolicyagent/opa:latest $ docker image pull openpolicyagent/demo-restful-api:0.2 $ kind load docker-image openpolicyagent/demo-restful-api:0.27. Deploy the application - Deploy an application with located OPA, detail: deployment.yaml $ cd ../hack/manifests <br> $ kubectl apply -f deployment.yaml - Verify Deployment $ kubectl rollout status deployment demo-restful-api - Enable local access to the application $ kubectl port-forward svc/demo-restful-api 5000:80 & Test Rego is the DSL for the OPA. We can author our policies using the rego. For this tutorial, our desired policy is: - People can see their own salaries (GET /finance/salary/{user} is permitted for {user}) - A manager can see their direct reports’ salaries (GET /finance/salary/{user} is permitted for {user}’s manager) Check that Alice can see her own salary - This command will succeed because Alice wants to see your own salary. $ curl --user alice:password localhost:5000/finance/salary/alice Check that bob CANNOT see charlie’s salary. - bob is not charlie’s manager, so the following command will fail. $ curl --user bob:password localhost:5000/finance/salary/charlie - bob is Alice's manager, so the following command will succeed. $ curl --user bob:password localhost:5000/finance/salary/alice Acknowledgments - Special Thanks to Furkan Türkal Emre Savcı Hüseyin Güner for all the support.
https://batuhan-apaydin-11378.medium.com/distribute-your-policies-with-the-power-of-functions-3a79faf0ed47?source=post_page-----3a79faf0ed47--------------------------------
CC-MAIN-2021-25
refinedweb
888
55.64
. Good article in the online Washington Monthly: How [the] Democrats Could Have Won (the 2002 elections, that is). Congratulations to Sumana on her promotion. For the past week or so I have been occupied with the difficult question of why Computer A refused to respond to ARP queries from Computer B. Today, I finally thought to read the routing table on Computer A closely enough to realize what was wrong. Computer A used to have two IP addresses (long story), and the second one has been recycled for Computer B, but the old annotation saying to route packets for B's address via the loopback interface was still there. The loopback interface, naturally, does not reach Computer B. why am I still awake? ICSI is located in an oldish building with oldish elevators. The emergency phones in these elevators were installed when there was only one Phone Company and it wouldn't sell you anything except phone lines with telephones attached. In other words, they're not intercoms, they're telephones, old-fashioned telephones with rotary dials. And, as I discovered today, it's possible to call these telephones. I was in the elevator when it started ringing. Who was on the other end? A robot, inviting me to participate in a survey. "If you are interested," it said, "press 1 now." On a rotary phone, this would be difficult. I wanted to see if I could somehow get hold of a human and explain to them what place they had reached, but I was holding up the elevator, so I just hung up. This has been there for awhile: Teresa on the vanity-press scam. In the discussion is some very interesting stuff on why self-publishing is such a scam in print fiction — and the only sane way to go in many other genres, like music. The lack of posts for the last few weeks has been entirely caused by my not being in the right mood to write any. This, in turn, is because very little happened which would be of interest to a general audience. I could blather about the endless rounds of test case redaction that have occupied my working hours, or about the joys of changing one's mail client, primary editor, and desktop environment all at once, but really, what would be the point? Unmedia: principled pragmatism. Tomorrow is Election Day in the USA. Both houses of Congress are balanced right on the edge between Republican and Democratic Party control. Quite a few races are also balanced right on the edge — Democrats Abroad has a list for your perusal. I want all my readers who are US citizens to vote tomorrow. You really can make a difference this time, especially if you live in the ambit of one of those close races. I'm not going to tell you which way to jump — but consider carefully. Specifically, consider carefully these articles. And ask yourself: do you want to let people who do things like that run the country? Commentary on the Microsoft antitrust decision by Ben Rosengart. Review of the coherent arguments for war on Iraq (as opposed to the incoherent ones currently being put forth by the USA's leadership) by Joshua Marshall. Teresa Nielsen Hayden on fraud and gormless cover letters. Read the discussion. I just spent about an hour stuffed inside a narrow cylinder with my head immobilized, only able to see a blurry projection screen, instructed to imagine carrying out sentences projected on the screen while a giant magnet induced radio frequency absorption in my brain. Or, in other words, I was asked to be a guinea pig for Shweta's fMRI experiment. The idea is to see which parts of the brain are active when one imagines taking an action, and compare this with the parts of the brain that are active when one actually carries out an action. The theory is that they will be more or less the same. The experience of being MRI-scanned is not terribly pleasant: you can't move, you're in a coffin-sized space, and the machine makes a horrific noise while it's operating, sort of a buzzing chirp, which is so loud that they give you earplugs to prevent hearing damage. However, it was fun to have done it, and theoretically I will get to print out pictures of my brain and stick them on my wall or something. Also, the setup is thoroughly mad-science: it's a giant magnet, full of liquid helium! With a crazy tangle of hoses to carry various coolants, and big fat copper cables to supply current! You have to walk through a metal detector to get into the room, lest you have some iron on your person that might get yanked around by the field! Tonight, the ICSI Movie Committee (of one) screened "Dark City", which is a beautifully disturbing movie about memory and identity. I can't really describe the movie without spoiling it; for this reason I am not linking to any reviews. But go rent it, you won't be disappointed. (It is not a horror movie.) We were invited to come in costume. I had all of ten minutes to put mine together, so I pulled some old clothes out of the back of my closet and went as a 1992 grunge rocker. This costume worked only because of the wonderful hat which my mother made for me this summer: it's all black and brown and blue wool, in a sort of pointy cylinder shape. I don't think any grunge rockers actually wore such a thing, but it is definitely something one can imagine seeing on a grunge rocker. This makes two movies in one week, which is a personal record for the entire year: I see a movie about once every three months, on average. In other news, the British Standards Institute has reissued the original C standard, ISO/IEC 9899:1990 (commonly known as "C89"): a hard copy can be yours for only £30. Just punch "9899" into the search box on that webpage. C89 has been superseded by the newer C99 (ISO/IEC 9899:1999) but it's still good to have it available; backward compatibility will be important for years to come. Just got back from seeing Seven Samurai at the Castro Theatre with friends. It was an amazing movie. I'm not going to try to review it in detail, there's plenty of commentary on it available elsewhere; let's just say it's worth seeing in uncut form, despite the length (more than three hours). Walk into the Castro Theatre and you step right back into the Roaring Twenties. The place is as spectacular as any of Los Angeles' remaining Deco theaters — and none of them have a real live pipe organ which is played before every nightly show. It is apparently the largest fully operational Wurlitzer organ remaining on the West Coast. I got to Castro Street by taking the Muni streetcars from a downtown BART stop. In downtown SF, the streetcars run underground; it reminded me strongly of the New York City subway experience, even to the crowdedness. It is utterly lame how difficult they make it to transfer between BART and Muni. You have to exit through the BART turnstile, cross the station, and enter the Muni turnstile, paying a second time, and woe betide you if you haven't a dollar in coins. At some stations, there are change machines that will break a dollar bill, but none that will break a five... too bad that BART's change machines will only give you fives for larger bills. They're putting in new network wiring here at ICSI. Current practice for this seems to be to run separate cables from the wiring closet to each and every ethernet jack on the floor. I find this bizarre. It's harder to do, it's not at all extensible, it uses far more wire than it should, and it'll have to be done all over again when they want to bump from 100baseT up to whatever replaces it. I would have thought that the appropriate tactic was to put a fiber optic loop all the way around the building, with fanout hubs to each cluster of offices.. Leonard reports the creation of a nifty utility. And I'd like to say that I don't get why people like putting spaces between the parentheses and the argument list, either. My mother points out that I misspelled bain Marie earlier — the first word has an I in it. This is no doubt why I couldn't find Maria the Jewess's history online. She wasn't French at all; she lived in Egypt in the third century BCE, or possibly the first century CE, sources differ. In the "why didn't I think of that?" category, a chap name of Tkil suggests that the way to prevent your car's wheel from turning when you're trying to loosen the lug nuts is not to jack it up until they're already loose. Seth responded to my earlier Let's back up from the technical details and talk about goals. The status quo is that if you've got a computer and a chunk of data in a computer-readable format, you can do whatever you want with the data. In particular, you can make an unlimited number of perfect copies of that chunk of data, and transfer them to other people, without any effect on the original. There are people who would like this not to be the case, and they have designed technological measures such as Palladium which could prevent it in the future. I am perfectly happy with the status quo. In fact, I prefer the status quo to the alternative. However, it is possible that a system similar to Palladium could be designed which I would prefer to the status quo. I'm the customer; the people pushing Palladium and/or other "trusted computing" initiatives have got to convince me to buy new hardware that implements it. (Let me remind you that most corporations can be prevented from doing things by not fucking paying for the product.) So, on the hypothesis that we are going to design a new computer architecture incorporating something similar to Palladium, what functionality should it have, and equally what functionality should it not have, to make me consider it something worth buying? Here are some examples of both categories. Features that would be useful: Features that would be undesirable: Now, can we design devices and primitive operation sets that permit the implementation of the desirable features, while preventing the implementation of the undesirable features? I suspect we can. However, I suspect the result doesn't look much like Palladium; I suspect it's more like a normal computer with a smart-card interface. In this vein, I'd like to point out Richard Stallman's opinion piece on "treacherous" computing (as he styles it), and also his much earlier essay The Right to Read. The organization Transportation for a Livable City has released a roadmap for improving transportation in San Francisco. This open letter encourages the FCC not to bail out failing telecoms companies. Thirty-five questions that haven't been answered, but should be.. The difficulty with the ban Marie, at least the cheapass one I bought specifically for candlemaking, is that it boils over at the slightest provocation. To melt the wax, you want the water in the bottom level just barely below the boiling point. The stove setting that achieves this, once the thing's reached working temperature, is just barely above the point at which the burner goes out. Note that this is not "off." Small amounts of gas continue to leak out of the burner once this happens, which is Not Good. The hardest part of candlemaking is actually cleaning up. Wax sticks to everything and dissolves in nothing. The best approach I've found is to pour gallons of boiling water over all the dirty equipment. Even this doesn't work very well. A number of operations would be easier if I had a heat gun. I wonder how much they cost. I was making candles last night. And I decided to be totally perfectionist about them. I'm not sure why, but possibly the fact that one of the molds had its sealing gook come off, thus spewing molten paraffin all over the stove, twice, had something to do with it. The thing about casting candles is, paraffin shrinks when it cools. Since it cools from the outside in, unless you're careful you'll get a huge air bubble in the middle of the candle, with a narrow channel connecting it to the exterior. Care, in this case, means re-melting the skin on the top of the candle and pouring more wax in at regular intervals. Normally one does this a maximum of twice, with about half an hour in between pours, which makes them come out with dips in the bottom but otherwise fine. I was poking holes in the top and putting in half-tablespoons of wax at ten-minute intervals from about midnight until about 3:30 AM. Of course, this means I had to have a supply of molten wax. It is extremely dangerous to melt wax over an open flame, so one uses instead a ban Marie, which is a fancy name for a double boiler. The water in the lower half acts as a thermal buffer, preventing the wax from getting hot enough to flash over. "Marie", it is said, was the French alchemist and witch who invented this technique; I cannot, unfortunately, find any reference to her history online. I've linked to the Alarm before. The song I quoted is from the album Raw, although it seems to have been written much earlier. The title is The Wind Blows Away My Words. Blows away my reason Blows away my soul Taking my existence Oh the wind blows away my words (repeat from "Blown out of house" to end of chorus) (repeat from "Blown out of house" to end of chorus) Despite the rather grim lyrics, I find this song cheers me up immensely. Late night ... listening to the Alarm, waiting for the candles to stop shrinking. Hoping I've found the right setting on the stove so the burner won't go out and leak gas into the kitchen, nor will the ban Marie boil over. I'm blown out of house, blown out of home Blown down the road On the wind that blows away my words Yesterday I went to the "Heart of the Forest" Renaissance Faire with a bunch of friends. Sights! Sounds! Clothes which have been out of fashion for centuries! ...Five hours in miserable heat with no sunglasses. The site was by no stretch of the imagination in a forest; there were a few big oak trees, but not nearly enough to provide adequate shade to make it pleasant to wear medieval garb (designed for a much cooler climate). However, it was great fun. The high point of the day was probably the various performances, including a demonstration of falconry, an Irish dance (I didn't know they had tapdancing then!) and an authentic Punch and Judy puppet show. The low point of the day was the shop selling a remarkably malicious set of magical charms. Either the shopkeeper doesn't believe that they work, in which case they're a fraud and a charlatan to sell them in the first place, or they do believe that they work, in which case selling e.g. a "charm to break up an existing relationship" with no strictures or conditions on its use is highly unethical. And the whole concept of openly selling magic charms is out of period. If I'd been properly roleplaying the honest merchant type that my costume implied, I should have gone straight to the constabulary and denounced them for witchcraft. This biological taxonomy web site. Two articles in Forbes by John Perry Barlow: The Pursuit of Emptiness and Why Spy?. (While you're reading Barlow, take a gander at his The Economy of Ideas.) An article in the New Yorker about the trouble with being the world's only superpower. And a lengthy rant about the apparent motivations for invading Afghanistan. Last night one of the neighbors knocked on my door. "Hey, did you know your car has a flat tire?" "Uhh... no..." This morning I went downstairs and sure enough, flat tire. So I got to have the fun of taking the wheel off and mounting the spare. It turns out that the hardest piece of this is getting the lug nuts off. Since the flat was on one of the front wheels, the only way to prevent the wheel from turning when I tried to wrench the nuts would have been to put a brick on the brake pedal — and start the engine, so that the brake assist would kick in. This struck me as a bad idea. Instead I wedged a crowbar between the wheel and the ground, which worked well enough. Of course, once I got the spare on, it proved to have gone soft over two years of sitting in the back unused. It worked well enough to drive to the tire dealers, though, and even as I type this a new tire is being installed. There was a big honkin' gash in the sidewall; I must have scraped against something sharp. (It wasn't clean enough to have been done with a knife.) "So you hit a tree and the light changed?" "Yeah. It was fantastic!" From Ftrain: How Google beat Amazon and Ebay to the Semantic Web. I sold all of my Preacher graphic novels, and then went and got the latest two Transmetropolitan bound volumes and an Usagi Yojimbo collection. I can't recommend Transmetropolitan highly enough. It's brilliantly written, and the story one that needs telling; for all its futuristic trappings, it's just as much about right here and now. It is, however, rated R. Usagi Yojimbo ("Rabbit Bodyguard") is just fun. Preacher was a nice concept but did not live up to itself, alas. I find that it looks wrong to write "a <a href=..." even when I know perfectly well that in the rendered version the word after the "a" will begin with a consonant. a <a href= a sticker. I'm pleased to report that the handymen showed up and are repairing the doorframe that got kicked in last night. They haven't gotten to the outer door yet, but I'm guessing that's only a matter of time. Someone just broke into my apartment building. He smashed a pane of glass in the front door to get in, and then came upstairs and tried to kick in one of the apartment doors — not mine. The door frame is wrecked but it didn't actually break open. Then he seems to have just left. Unfortunately, no one got a look at him, so the cops are not too sanguine about being able to catch him. What surprises me is that he didn't do anything else. My bike is still parked in the hall, he didn't try to kick any other doors down, and so on. The people who live in that apartment are shook up but unhurt. Today, I gave the client three hundred megabytes of almost-working source code, and they gave me nine hundred cubic inches of printed manuals. (That's a 1'x9.5"x8" rectangular prism.) I'm not sure which of us got the short end of the stick. I also discovered that if I turn my monitor around so it faces the other way, it has to be degaussed. Not sure why. Couple weeks back I got a notice instructing me to report for jury duty. "Call this number after five PM the day before for instructions." So I call, and the tape recording says we don't need anyone in the morning, call back tomorrow to see if we need you in the afternoon. I call back in the morning — thanks, we don't need you this afternoon either, you're done. Driving home from the grocery store yesterday at twilight, as I pulled into my parking space, I saw a pair of raccoons on top of the adjacent wall. They looked at me for awhile, then startled and ran away when I opened the car door. Invader Zim is a fine work of animated cartoon fiction from the twisted mind of Jhonen Vasquez. It ran for two seasons on the Nickelodeon network, but seems to have been cancelled now. Some of my friends have been raving about it; I just now got to see the first few episodes. I like it — particularly Gaz — however, it disappointingly suffers from History Eraser Syndrome, that is, each episode has no connection whatsoever to the previous. For instance, the "Walk of Doom" episode ends with Zim and Gir lost in the barrio, with no obvious way to get home; the following episode begins with them at home, just fine. Grrr. Another John-Wood-ism, from another post in the same thread that invented nasal demons: ...the C compiler itself MUST issue a diagnostic IF this is the first required diagnostic resulting from your program, and then MAY itself cause demons to fly from your nose (which, by the way, could well BE the documented diagnostic message) ...the C compiler itself MUST issue a diagnostic IF this is the first required diagnostic resulting from your program, and then MAY itself cause demons to fly from your nose (which, by the way, could well BE the documented diagnostic message) concisely and accurately describing the (lack of) specification in the C standard about what constitutes a diagnostic message. I like the mental image of turning over a page in a compiler manual and discovering a sentence like "in the event that the compiler detects a syntactic or semantic error, you will be notified by means of a demon flying out of your nose." It happens about once a year. Some programmer discovers that their code has been "mis-optimized" by GCC, files a bug report, and we point out that it doesn't obey the rules in the above-mentioned section of the C standard. Thus GCC is allowed to do whatever it pleases to their code, up to and including replacing it with an invocation to make demons fly out of your nose (when executed, not at compile time). They come back with "but it's obvious what this code is intended to do, you should get it right anyway!" and the thread degenerates into name-calling and references to the Halting Problem. The 1999 instance of this argument is particularly long, painful, and has Richard Stallman in it; but thankfully I seem to have stayed out of it. Alas, not so this year. The "demons fly out of your nose" quip is due to John Woods, who also invented a line which I had on a button on my backpack for a long time: SCSI is NOT magic. There are fundamental technical reasons why you have to sacrifice a young goat to your SCSI chain every now and then. SCSI is NOT magic. There are fundamental technical reasons why you have to sacrifice a young goat to your SCSI chain every now and then. The button had no attribution. I'd just like to say thank you, John. Because I'm tired and procrastinating... let's have a tinfoil hat joke, from Warehouse 23: you open one of the 1008 boxes on this floor and find.... In the other random thoughts department, a number of new apartment buildings around here have this nifty racked storage system for cars. It's basically two fixed platforms on a hydraulic lift, which can rise or fall to bring either platform to the level of the garage floor. This lets them get twice as many cars into the floorspace. But to do it, they have to dig a pit under the platforms, to give the lift somewhere to go. There's space for another row of cars there, but it can't be used. How would your friendly local mad scientist fit more cars into this space? Consider the humble fifteen puzzle. Any of the tiles can be brought to the lower right-hand corner. Now imagine that you have a parking garage laid out like this. Instead of tiles, you have motorized platforms with cars on them. To get a car out of this garage, you rearrange the platforms until the one you want is adjacent to the entrance, then drive the car away. To put it back, rearrange the platforms until an empty one is at the entrance, then drive the car on. There's no reason to restrict this system to two dimensions; the platforms could easily be stacked to fill whatever space is available. It can store as many cars as could theoretically be crammed into the space, less one for the required empty cell. (Assuming of course that all cars are the same size, but this assumption is shared by the original system I described.) The FSF has released a lengthy FAQ on why, in their opinion, one should speak of "GNU/Linux" instead of just "Linux." I don't wish to address that issue, but I do want to respond to one of their questions: ". I take issue with the description of the Hurd as a working kernel. It's never going to be efficient, nor has adequate attention been paid to security; features have been thrown in for no good reason; all the interesting things that the Hurd claimed to make possible are also possible with the Linux kernel. It is my personal opinion that the Hurd should be scrapped immediately, and the resources currently devoted to its development redirected to work on Linux or EROS. The latter is an interesting experimental kernel, which genuinely does have capabilities (no pun intended) that Linux lacks; further, serious attention has been paid to elegance, efficiency, and security. Very interesting two-part article in the Sierra Times: "Dis-Mything 9-11: Is The USA PATRIOT Act Patriotic?" (part 1, part 2). I smell kookery in both the article and the Sierra Times generally. For instance, Mr. White refers to a "hard money clause" of the Constitution, which he implies made the 1933 Act abolishing the gold standard unconstitutional. There is a sentence in the Constitution which could be described as a hard money clause (in article I, section 10, paragraph 1) but it does not make that Act unconstitutional. It is a restriction on the powers of the individual states, not of Congress; it's clearly intended to ensure that the states do not issue their own currencies (as they did under the Articles of Confederation). A few paragraphs before that, in section 8, Congress is given unrestricted power to "coin money and regulate the value thereof," without any mention of what material the coin must be made of, or what if anything its value must be backed by. There is no justification for an assertion that the Constitution requires a hard currency. However, that's a minor flaw in an otherwise excellent pair of articles. Mr. White is correct to object to legislation passed without due consideration, and to the PATRIOT Act specifically. I would like to encourage all my readers who are resident in the USA to sign the online petition for its repeal. Another good article is in this week's SF Weekly: Matt Smith reports on a professional architect's conclusions about the most effective ways to respond to the destruction of the World Trad Center. Apparently simple and cheap-to-implement changes to the fire codes could ensure that skyscrapers can be evacuated safely in the event of another such disaster. Also in this week's SF Weekly is a review of Das Experiment, a German movie based on the 1971 Stanford prison experiment. It sounds well worth seeing. In last week's SF Weekly there was a feature article on why the Bay Area has stopped producing big-time rock bands. I especially want to call your attention to the segment beginning on page two, "This Band Should Be Your Life," profiling the Pattern. This is a new, happening band that deserves more attention. I've downloaded their MP3s and I like what I hear. They're playing Slim's in San Francisco on October 7th; I think I'll go. I'm walking home today and some guy buttonholes me and asks where he can score some pot. What I wanna know is, where did he get the idea that clean-shaven T-shirt-and-jeans white-boy me knows where to score pot? Maybe it's the ponytail. It's not a good thing when updating your weblog becomes one of the things that you avoid doing because you're already ages behind on it. So I'm just going to throw out a bunch of random things that come to mind and we'll call it caught up, okay? This weekend I bought more stackable CD racks because I was out of space, only to discover that the Crate&Barrel and IKEA brands are incompatible. (I would link to pictures of each, but just try to find a specific product in either store's online catalog.) Duct tape and coat hanger wire to the rescue! I bent a coat hanger into an adapter between the two kinds of stacker tab, and duct-taped all the joints together so it wouldn't fall apart. It does want to tip over, but that's okay, it's up against the wall. The reply brief for the petitioners in the Eldred v. Ashcroft case is well worth reading. Free the Mouse! Speaking of which, BumperActive is a pretty cool thing in its own right. As are Rolling Thunder Down Home Democracy Tour and Junction City. I bet the tour would be right up the SF Mime Troupe's alley; perhaps I'll try to hook them up. As long as I'm on the subject of politics, Anna has a fascinating discourse on Socialism and Peter Maass has a number of interesting comments on the Iraq juggernaut. And I think it's high time I added Avedon Carol to the links on the right. It turns out that Lore Fitzgerald Sjöberg lives in Berkeley and patronizes Cafe Elodie, which is also one of my favorite downtown cafes. He also has a "mysterious letter" of advice for web-log-writers, which is worth reading. I am not sure I measure up. And finally, he proposes the glossing links concept, which is nifty, and I may decide to play with it. The link density on this page is arguably too high. Rael has a new version of Blosxom out. I'm not sure I will upgrade. I've already heavily customized this version, and he seems to be taking it in a different direction from me, anyway. (Can someone explain to me what RSS is for and why I should care, please?) A more interesting possibility: an anonymous correspondent sent me a reference to a comment add-on for Blosxom. This is something I'd really like to have, except that it doesn't seem to work on that guy's site, which means I'd probably have to do a bunch of debugging, which I do not have time for right now. Movable Type's standalone trackback utility is also interesting, although perhaps I should just switch to Movable Type... Utukki is being updated again. Several different places which actually sell car radios have now told me that no, they don't sell adapter cables for Radio Shack radios, and have I tried Radio Shack? We crammed all of Dara's stuff into my car, and she drove off to Stanford. I have to stay here and work. Just now back from Woodminster. You don't normally think of the Continental Congress as a bunch of cranky middle-aged men, but such was the (historically accurate!) depiction. The libretto and the story it told were both excellent. The music and singing were not as good, but acceptable for a low-key production like this one. Bed now. Decided to try to replace the radio in my car, with Dara's help. (The amplifier is kaput.) I've had a replacement sitting in my closet for months. We got the old radio out of the dash with no real trouble. Then we discovered that the cables between the radio and the rest of the car are not standardized. So I spent the past hour chasing around town looking for an appropriate adapter. The replacement was made by Radio Shack and their website claims that they have adapters for most car models, but the local store told me smugly that the chain no longer carries any car-radio-related anything. (I got the replacement at a swap meet.) All other potential sources are either closed because it's Sunday or closed for renovations. Feh. Dara's come back from Los Angeles; I picked her up at the airport. Tonight we're going to go see 1776 (the musical) at Woodminster. Went to see Garmarna at the Freight and Salvage with friends. Garmarna are described as a "Swedish contemporary folk fusion ensemble" in the Freight and Salvage's calendar flyer. I'm not sure what they mean by "fusion," but if you're into Swedish traditional folk tunes done with rock'n'roll stylings on violins, and/or a hurdy gurdy being made to do things more conventionally associated with electric guitars, Garmarna is the band for you. Me, I thought it kicked ass. Why Socialists Don't Believe in Fun, by George Orwell: a look at why utopias aren't usually places one would want to live. Worth reading. Here we are one year after terrorists crashed planes into New York City and Washington DC. There's a lot of sound and fury in the media right now; I won't be looking at any of it. Sound and fury, as the man said, signifies nothing. There are, however, a number of thoughtful, constructive observations that various people are making, which I encourage you all to go read: Now I'm going to get up on my soapbox: I want every one of you who reads this to go out today and create something new. It can be anything; I'm not picky. Pick up that hammer, or that pen, or whatever tool you feel most comfortable with; do it with your bare hands even. Put something into the world that wasn't there before, something bright and beautiful. Do it because you can, do it to show the world that even in the face of such catastrophe you will not be broken. And when you've done it, don't hide it away; show your friends what you have done, and make them create something too. We did. Now it's your turn. Note to self: do not make pancakes with rice flour in future. It's mildly entertaining to read through the lists of bugs I've submitted to Debian. There's still-unfixed (minor) bugs more than four years old in there... Enough Day. A-fucking-men, and right on, and well said, and all that good stuff. There's a nifty interview with Larry Wall on Slashdot today. I'm pleasantly surprised to discover that he is familar with the Liavek stories. When people come to your webpage because it showed up in an Google search listing, the referer URL says what they searched for. Here's some things that people searched for and wound up here: Also, someone is reading this page in Italian. I don't speak that language well enough to guess how good the (machine) translation is, alas. Interestingly, it stops translating about three-quarters of the way down the page. This post by John Trussell is highly amusing. Somewhere in America, a rock band is missing an opportunity, because frozenvermin.com is available. The only question is where to put the umlauts. (My suggestion: over the "o" and the "i".) I dreamed a fairy tale last night. Rather than recount it as I saw it, I think I'll tell the tale the way it would be told in a book: there was a monastery, and in that monastery there was a young monk. Next to the monastery was an apple orchard. In the apple orchard lived a farmer, his wife, and their son. The monk and the son were great friends. But what the monk didn't know was that all three of that family were secretly man-eating giants. One day all the monks were to go on a pilgrimage. Our hero made an error calculating the supplies that would be needed. When the abbot found out, he was furious, and he forbade the monk to come on the pilgrimage with the rest of them. He had to stay behind and copy books in the scriptorium. The apple farmer saw all the monks leave, so he snuck into the monastery to steal a pig (when you're secretly a man-eating giant, you take what you can find). He found the monk asleep on his lectern. He decided to steal the monk and eat him instead. But when he brought the monk home, his son protested: "That's my friend, we can't eat him!" So instead they let him wake up, and traded him some of their magic apple cider for a pig. What the monk did with the magic cider ... is another story.1 Maersk Sealand, a huge shipping conglomerate, has put online all their schedules and rates; you can book yourself a cargo shipment from just about anywhere to anywhere else. Well, you can if you know what you're doing. I tried to get a rate quote out of them and was faced with questions like "Do any Shippers Export Declarations apply? Choose [none] [1] [2] ... [10]" with no explanation of what Shippers Export Declarations 1 through 10 might be, but a strong implication that answering incorrectly could get you in legal trouble. Sending a single 20-foot container from the USA to Hong Kong will run you about $3000. Sending more appears to be an additional $2000 per container, but I could have gotten confused. This is the text of the letter I just sent to the errata-reporting address for Shadowrun:. Today I helped my sister move out of her apartment in San Francisco. We went to Joe's Cable Car Restaurant for lunch, with her boyfriend and one of her flatmates who was also moving out. Joe's could well be the most expensive hamburger joint west of the Mississippi - we spent $15 per person! - but it is also damn good. Came home and installed a shiny new three-prong outlet in the kitchen so that I can plug in my microwave. There was nothing behind the old outlet to attach the grounding screw to... so I didn't attach it to anything. No great loss. The microwave may be marginally less safe than it should be, but if I wanted a safe electrical system I shouldn't be living in this building in the first place. Oh, and in the nifty things department, Patrick Farley is now doing a new weekly comic strip called Barracuda: The Scotty Zaccharine Story. He describes it as "looking back at dot-com San Francisco." Noah Johnson's report on the August 22 protests in Portland. Cory Doctorow's story, 0wnz0red. John Judis and Ruy Teixeira's fascinating article in The New Republic on what they call the emerging progressive-center majority in American politics. (This is a summary of their book, The Emerging Democratic Majority. Courtesy of Talking Points Memo.) Why am I still awake? Oh, right, because I spent the last two hours reading the entire archive of Bob the Angry Flower. Galeon's parallel download widget will only download eight files at once. If you try to queue up a ninth download, the "save as" dialog box only comes up when one of the current eight finishes. If you try to queue even more (figuring that "save as" will appear eventually for all of them) it forgets about all of them except the last one you clicked. This may actually be GTM's fault. Machinae Supremacy: I'm going to call it Swedish techno punk rock, because I have no idea what the official term for it is. Alan Cox calls it excellent hacking music. I concur. Yesterday, I was cleaning the bathroom and discovered that the overflow drain on the sink was blocked, and could not be unblocked by rooting around through the hole with a bent wire. So, of course, I took the sink apart. In short order I discovered that (a) it's not possible to take apart the part of the sink where the blockage is, and (b) when you try to unscrew an old rusty steel pipe in the wrong direction, it tears apart. Oops. Today, I went to the hardware store and got a replacement. The sink works again. But still — keep me away from your plumbing. I can't resist pointing out Teresa's delightful article on lost fandoms, specifically those of the nineteenth century. But I really am going to bed now. I hardly ever make HTML coding errors anymore while writing these entries. It's a little scary; I expect to make errors, but time and time again the W3C's validator gives them a clean bill of health. I suppose this means I am a web monkey now. (Addendum: one disadvantage of rounding times to the nearest five minutes, is you can get collisions. Need to do something about that.) I've plugged Stefan Gagne's work before, but allow me to do so again: both Unreal Estate and Penultima are amazingly nifty. The latter requires Neverwinter Nights, which I do not have, so I have not actually played it, but the text visible when you run strings(1) on the modules is funny enough that I'm sure the games are worth playing just for the jokes. (I am considering purchasing NWN just to play Penultima with, but they get my money only when the Linux version is actually released, not while they're still just making noises about doing one. Yeah, I could install Windows on the disk partition that is waiting to have Windows installed on it, and play that version, but that wouldn't be nearly as convenient, nor would it give Bioware any incentive to finish the Linux port.) Electrolite commented on a post on Poor Man, and in the process registered a complaint about the page style which spawned a whole series of interesting comments and a response from Andrew Northrup. All in all, an interesting excursion from political commentary (standard fare on Poor Man and pretty common on Electrolite) into graphic design. But I would like to register a complaint in this context. The issue Patrick had with the Poor Man template was, in a nutshell, poor choice of background and text colors. Now, if the page author doesn't do something special, HTML leaves the choice of colors up to the reader's browser, which has nice handy controls for setting them to something the reader can read. Same same font, text size, and so forth. But you will notice that almost all web pages that have done anything at all with page layout, have explicit color choices. Is this because it's easy to dink with the colors, and has a nice obvious visual impact? Perhaps. However, there's another problem, which is: if you're doing your web page layout with CSS the way it appears to have been intended to be done — with div and span and all the positioning in the CSS instead of the HTML — and you want even one block somewhere which is a different color, you have basically no choice but to specify the color of every last block element, or you will get hideous smears of color all over the place. div span Or, at least, I have not been able to avoid these smears, and believe me, I have tried. Since I think it's more important to leave font and color choice up to the reader than to write HTML4/CSS2 the way they were intended to be written, I don't do it the "right" way. It's endlessly frustrating, though; CSS seems to go out of its way to make obvious simple things that the author would really like to be able to do, very hard. In other news, Seth Schoen as usual has lots of interesting things to say including some short comments on the EFF benefit at the DNA Lounge which I am now even more disappointed to have missed. But I'm pleased to see that Seth too reads Electrolite. Effects of Sleep Deprivation, in convenient table format for incorporation into your role-playing campaign. (It is system-agnostic, despite the /shadowrun/ in the URL. Well, I suppose the requirement for percentile dice could be taken as a system dependency, but everyone's got a couple of 10-siders lying around, don't they?) /shadowrun/ I think I'm coming down with a cold. Which is frustrating, because I wanted to go to CAFE 2002 tonight. Ten- or eleven-year old girl with the top of her head shaved, down to about ear level; the hair that sprouted below her ears, however, went all the way down her back. but I can't remember what it was. Depressing to discover, via a series of endless threads on debian-legal, that LaTeX and possibly even TeX itself may have to be considered not free software. The LaTeX developers have apparently decided that consistency across installations is more important than freedom. This is the exact same philosophical difference that makes, e.g. qmail not DFSG compliant. The problem is, while there are good alternatives to qmail, there really aren't good alternatives to LaTeX. (All you troff fans can go ahead and flame me now.) I normally don't have much interest in Wired magazine — it plays around far too much with form for the content to be readily accessible. But some of their recent content is indeed worth reading. Here's an article about a real, honest-to-ghu bionic eye; another one on the water crisis in central Asia; one on Europe's GPS clone; and finally, GM rethinking the whole "car" concept. And check this out: a Bayesian spam filter, with solid theoretical reasons to believe it will work and keep working. Me want. (If the first paragraph is unreadable turn CSS off. I tested it, it looks good in Mozilla, but I have this nagging feeling you're not supposed to do kerns like that.) Instructions for setting up my shiny new microwave oven: The plug must be plugged into an outlet that is properly installed and grounded. Plug the three-prong power cord into a properly grounded outlet of standard 115-120 voltage, 60 Hz. Your oven should be the only appliance on this circuit. Considering that there is exactly one circuit for the entire apartment, and that the building was wired back in the days when Real Electricians didn't use three-hole outlets, this is going to be difficult. Oh, also, what's something you don't want to smell on opening up a box containing a food-prep appliance? Model airplane glue! I suspect it's the paint, and I suspect it'll be fine if left to air out for awhile, but still. I went to Bed, Bath, and Beyond in search of a microwave, but the only thing they had was the Sharp "half pint", which is accurately described as super-deformed. (Check out the red and blue models.) Managed to find a full-sized one at Macy's. I got a new toaster. (The old one had had a spring fail, I think, so that it would jam every time it popped up.) It's nice - four big slots, removable crumb tray. However, the instructions clearly state that one should keep it unplugged whenever it's not in use. Where does this come from? I've never seen any such restriction on a toaster before. Sumana links to several versions of a list of reasons books are better than drugs. The list is amusing, but I take exception to one of the entries: 21. Books don't have negative interactions. You never have to worry about what's going to happen if you mix two or more books. Simply not true — negative interactions are common. Read, for instance, Ayn Rand and John Stuart Mill in quick succession. If you are not damn confused at the end of this exercise, you missed at least one author's point. Worse, consider what happens when inappropriate connections are drawn between unrelated authors — social Darwinism, for instance. One thousand eight hundred thirty-six. That's how many email messages were waiting for me at my work account. A rough breakdown: 30 messages addressed to me, seven of them spam. Six more pieces of spam caught by the (much less aggressive) filter on this account. 26 messages to internal CodeSourcery mailing lists. Then, 966 from the various GCC development lists; 446 from the Subversion project list; 322 from the Python development list; and a handful more from lower-traffic lists. In the time it took to download all that mail, read everything but the high-traffic mailing lists, and prepare this summary, another twenty-one messages arrived. Datastarve, they call it in cyberpunk role playing games. An addiction to information, brought on by spending too much time with your brain wired directly into the network. But you don't need to jump forward thirty to sixty years and undergo major surgery, have a high bandwidth "datajack" installed into your head, to suffer datastarve. Most of us already have a high bandwidth channel directly to our brains, came free with the body: our eyes. I just spent five days in Los Angeles with my parents. I had great fun. Swam every day. Went barefoot as much as possible. Saw an exhibit of Hopi tithu dolls (more commonly known as "kachina dolls") at the UCLA Fowler Museum of Cultural History. And I didn't touch a computer the entire time. What did I do the moment I got off BART here in Berkeley? Came over to ICSI, where I am now, to check some of my email and write one of these blog entries. And I've the urge to go straight home, turn the computer back on, pick up the remaining mail (the vast majority, since most of the mailing lists go to the other account) and spend the next, well, however long it takes, catching up on every last one of the information feeds that I normally read daily. Takes an hour or so each morning — I would be done by midnight. But I'm not gonna. I'm going to go eat, and then I'm going to San Francisco to the FSF benefit. While riding AirBART away from the airport: A cab with an ad for Yahoo!jobs on its top, showing a signpost for the intersection of Opportunity and Van Ness Avenues. In the Berkeley BART station, a guy busking — with a didgeridoo. Waiting for me in the primary inbox for this account: 37 messages, of which 7 were wanted, 5 were spam, 12 were mailing list traffic I don't care about anymore, and 13 were copies of whichever Outlook worm is making the rounds this week. In the spamtrap box, on the other hand, were 81 messages, of which 3 were legitimate, 1 was a different Outlook worm, 73 were garden variety spam, and 5 were the Nigerian scam. I like SpamAssassin, yes I do. Went back to the vacuum cleaner place. So I showed him, and he went in the back and got me a new one. Happens all the time, he said. He also showed me how to clean hair out of the bearings before they seize up (after they seize up, you're hosed). The aftermarket beaters have an improved end cap that's supposed to stop the hair from getting into the bearings quite so easily. I haven't yet tried it out though. On the way there, I stopped to watch Fulton Street (alias Oxford Street) being repaved. Asphalt is an interesting substance: it comes in a truck, as a pile of slightly sticky gravel/sand/tar mixture, which can be moved around with a shovel. Heat it up and squash it, and it becomes a solid. That is all the road-paving machine does. The trucks dump a trail-like pile of asphalt down the area to be paved. The paving machine comes along, scoops up the pile, spreads it evenly over the road, heats it up, and squashes it. (I think the middle two things happen in the opposite order. It's hard to tell just from looking at the outside of the machine.) Poof, road. Then they come round with the grader and make it all even, later. Road repair machines always remind me of a short story I read once. It's called Mary Margaret Road-Grader. The full text is online at Strange Horizons. In other news, Bruce Sterling's speech at OSCON 2002 is well worth reading. (Scroll past all the contest entries.) Kasuri Dyeworks turns out to sell only cloth, not finished pillows. Last month he came and bothered Shweta, now he's come for me: the man running a chainsaw under my window at 6 AM. I noticed that my vacuum cleaner was emitting an awful burning smell so I took it apart. There was so much hair wrapped around the rug-beater and into its bearings, that it had stopped turning. The motor axle had been spinning against the stationary drive belt, heating it until it charred. So I took the beater and the belt down to the vacuum cleaner parts place on Berkeley Avenue (just east of Shattuck, north of University) only to find out that on Mondays they are open from 9AM to 1PM. I had gotten there just too late. I'm all for shopkeepers taking half days if they want, but couldn't they be open in the afternoon when I'm awake enough to get there, instead? Oh well, I'll just have to go back tomorrow, which is fine 'cos then I'll have a chance to stop at the Kasuri Dyeworks (which is just plain closed on Mondays) and maybe get some new pillows for the couch. I spent today as a volunteer helper-outer for the San Francisco Mime Troupe's show in Ho Chi Minh Park (aka Willard Park). This was loads of fun. I got to lift heavy objects, eat a free lunch generously provided by one of the actors,canvass the crowd for mailing list subscriptions, watch the show, canvass the crowd again for donations, and lift the heavy objects again. All this with a bunch of really cool people. What more could one ask? There were two guys at the back of the crowd with signs protesting the show, on the grounds that it gave a false impression of small obscure Central Asian countries. This accusation is wholly justified, but I think it also totally misses the point. Obscuristan (the show is titled "Mister Smith Goes to Obscuristan", and takes place largely in that fictional country) is a parody, as is everything else in the show. I mean, does anyone actually think George W. Bush wears a shimmering purple dressing gown all the time, and watches celebrity boxing? Does anyone actually think that a celebrity boxing match has taken place between Henry Kissinger and Noam Chomsky? And the accurate elements are precisely those that are salient in the public meme pool right now, which is just what you want in a parody. (Okay, I would be willing to believe that Mr. Bush does watch celebrity boxing; I am not in possession of evidence either way.) The troupe has a nifty portable stage which they built themselves, made out of aluminum trusses with a wooden floor above that. It has several different ways to change the set, lots of ways to get on and off, and good sight lines for everyone in the audience. It's also really easy to put up and take down. I do the occasional "seen on the street" post where I write about something wacky I saw. inpassing.org, however, is a blog devoted to things that the pseudonymous Eve saw or heard on the street. In Berkeley. I should add that I have no trouble believing that even the wackiest things she writes up did happen. Teresa says so. A day of unpleasant discoveries:. The spiraling shape will make you go insane. (Explanation.) Backdating entries with Blosxom is way too hard. You have to find the relevant entry file in a pile of, er, about 250 others at last count, and use touch to adjust its last-modification datestamp. Putting that together with the sheer size of the pile, which will only get bigger, I think it may be time for a bit of redesign. touch The bathtub is still clogged. It looks like it may take a plumber's snake to unclog it, which means time to call the landlord. They had better get on it today; I'm not going to be happy if I have to shower tomorrow standing calf-deep in yesterday's bath water. (I did not have to use the Dremel to get the plate off; it turns out to be easily unscrewed.) A panhandler type sitting on the sidewalk, back against a wall, intently reading Target: Wastelands. A guy wearing this T-shirt. I'm also pleased to notice that a restaurant is opening in the long-deserted building on the southwest corner of Bancroft and Fulton. The bathtub drain has been threatening to clog up for months; today it finally did. Cue my discovery that I do not own a plunger. Easy enough to go buy one, but it hasn't yet had any effect. I suspect I need to plug the overflow pipe, which will be tricky, because there's an apparently unremovable metal plate in the way. Well, worst case, I cut it off with my Dremel. I was riding around in a Zodiac [warning: unnecessary use of Java] with Nathaniel and Shweta, in a swimming pool. This Zodiac had a bizarrely designed outboard motor: it got fuel pumped to it by an immersion pump in the tank, which you could not turn off; if you did, it would explode and spray fuel oil all over the place. You could only stop the motor by hoisting the pump out of the tank, leaving it running. Unfortunately, someone did turn off the pump, and it did spray fuel oil all over the surface of the water, and I had to clean it up with nothing more than a bucket at the end of a retractable chain on a pole. As I did this, the swimming pool gradually got bigger and bigger until it was a full-size harbor, and no matter how many patches of oil I scooped up, there were still more. Also, there was nothing to do with the oil except dump it on the ground, which is not exactly a good move. Then I woke up. Today I went to Fairfield for a company meeting. (There is no office and we all live scattered around the Bay Area; Fairfield is about equally inconvenient for everyone.) I got to meet Nathan Sidwell, who was visiting the States on account of SIGGRAPH 2002. Among other things, we played miniature golf at Scandia Funland, which is your standard arcade plus minigolf course except it's all Scandinavian themed. We don't know why. Not exactly new. I had an old dirty keyboard in my closet for awhile; I got it out and cleaned it. The keys don't move as smoothly as they could, but the right-hand Shift key works properly. Now I just have to retrain my fingers to use it. Honest to ghod actual email I received today: From: "Hermione Granger" <censored> To: <censored> Subject: Segmentation Fault Date: 29 Jul 2002 06:30:16 +0100 Can someone please tell me what a Segmentation fault is? From: "Hermione Granger" <censored> To: <censored> Subject: Segmentation Fault Date: 29 Jul 2002 06:30:16 +0100 Can someone please tell me what a Segmentation fault is? I guess they're diversifying... I went to the Exploratorium in San Francisco today, with Shweta, Nathaniel, and about fifty of Shweta's students from Cognitive Science 1. I'd been last year too, and a lot of it was familar, but they had enough nifty new exhibits to make it still interesting. For instance, they'd expanded their seeing collection with a demonstration of change blindness, a selective attention demo (watch these people play basketball, count how many times the team in white shirts bounces the ball... okay, now did you see the bear walk across the court?) and a really nifty persistence-of-vision demo. This last was a huge LED scroller display, like the ones they have for instant replay at sports stadiums, except that there were only a few narrow vertical strips actually present, separated by blank wall. If you looked at this the right way you could see what was going by just fine, as if the display had been complete. Turns out that you really are supposed to write & as & in the href= attribute of an <a> tag, and that most browsers really do support this. (See, for instance, this explanation.) And it also turns out to be inappropriate to use %26 for this purpose; the point of %-escape is to make the server not interpret the & as a delimiter. LiveJournal's CGI scripts are just fine. & & href= %26 So I've changed all the back entries to use this convention. If you've got a weird browser that this breaks, file a bug report. I sent in a bug report for the LiveJournal issue mentioned below. We'll see what develops. Seth: All of the Nethack Sokoban levels are solvable without destroying boulders, as long as you're playing 3.3.1 or later. And you don't want to destroy boulders, because you get penalized to the tune of -1 luck for every boulder you smash. Having negative luck is Very Bad. Cleverer people than me have worked out complete instructions for solving Sokoban; they're available from Kate Nepveu's spoilers page. [You can safely load that page without being spoiled about anything.] I find it helps immensely to instruct Nethack (via ITEMS=, or boulder= in 3.4.0) to use digit zero for boulders instead of backquote. This makes it harder to get confused about which square the boulder is in when you're below it. Since zero is normally only used for iron balls, which are rare and (in color mode) drawn in a different color, there's no real risk of confusion with another object. Just make sure your font has readily-distinguishable glyphs for zero and capital O, or that boulder may turn out to be an ogre. ITEMS= Another handy nethack tip, if you feel up to hacking the source, you play in color tty mode, and your tty displays bright-black as a visible color — the x86 Linux console does; to check, execute this shell script with any modern Bourne shell: for a in '' '1;' do for x in 0 1 2 3 4 5 6 7 8 do printf '\033[%s3%sm%s' $a $x $x done echo done printf '\033[0m' ... is to cause Nethack to stop confusing black and blue objects. You can do this by applying this patch to win/tty/termcap.c: Black objects will then appear as dark gray, not dark blue, which makes it (e.g.) possible to tell the difference between a pit and a rust trap, or a black dragon and a blue dragon. Note that this patch only works for systems that define both UNIX and TERMINFO; other systems do color with different code, elsewhere in that file, that I'm not about to try to hack up. UNIX TERMINFO A minor complaint: LiveJournal URLs tend to look like this: Note the ampersand. The W3C HTML validator (correctly) objects to this, but if you substitute & then some browsers mangle the URL, and if you substitute %26 then the LJ CGI scripts don't understand the URL. The latter, at least, damn well ought to work. There is a large road-repair machine parked a couple blocks from my apartment. It rather resembles a dinosaur, perhaps a brontosaurus, except for having four tractor treads where its legs should be, and no tail. More reviews of the TMBG concert: Leonard, Seth (scroll down), Benjy (Tuesday and Wednesday), Adam (metareview). I have to applaud Benjy's dedication in going both days and writing down the complete set list both times. Leonard and Seth both pointed out the excessive volume of the concert. It was loud enough that I worry a little about (gradual, cumulative) damage to the audience members' hearing. Also, even if you don't care about going deaf, some of the songs were totally incomprehensible because of massive distortion. Jamie Zawinski, with his nightclub-owner hat on, has some comments on show volume (down at the bottom: look for the bit that starts "Oh, and we're also giving away free earplugs at coat-check now..."). Leonard: Yes, Nethack does give you okonomiyaki instead of pancakes when you play a samurai; as I understand it, it is the closest that traditional Japanese cuisine comes to pancakes. It is difficult to find web pages on the history of this dish, because of the flood of Ranma ½ fan pages that come up. It seems one of the more popular characters on that show, Ukyō, owns a okonomiyaki restaurant. The best I can offer on the history front is the paragraph near the bottom of the Otafuku Foods corporate webpage.. CALL OUR TOLL FREE NUMBER: 877-655-4557--OPEN 24 HOURS! or WRITE US AT: P. O. BOX 720791, Orlando, Florida, 32872, USA, or IF YOU ARE OUTSIDE USA, CALL US AT 407-207-7971. (1,000,000 SENT IN MEMORY OF ETTA CAYWOOD (1917-2002)). (1,000,000 SENT IN MEMORY OF ETTA CAYWOOD (1917-2002)) I am almost tempted to arrange a postal dropbox and send it to them, just to see what happens. Bought from both Amoeba and Rasputin, this time. They have near-complementary used CD collections. I'm listening to the Big Country album right now; it's good. John Gilmore is suing the government for the right to travel anonymously. Good for him. I wish I could Bank of America has finally developed enough clue to realize that they should offer their online bill payment service for free. This comes just in time for this month's cycle of bills. Here's an interesting Wired article about GM's plans to make hydrogen-powered cars profitable. (From the Daily Illuminator.) Last night I went to see They Might Be Giants at the Fillmore Theater in San Francisco. This is only the second time I've seen a live rock concert in a nightclub (the first being Blue Öyster Cult at the now-defunct club on California Avenue in Palo Alto). It is definitely a different experience from a concert in an auditorium; since I've now seen TMBG in both kinds of venue, I can make a comparison eliminating other variables. The basic difference: In a nightclub, one stands up on a dance floor, fairly close to the performers, who are on a stage elevated about five feet; so you're looking up at them, across other people's heads. In an auditorium, one is assigned a seat which is likely to be above the level of the stage; you're looking down at the performers. Unless you paid an awful lot of money, also, you are far away from the stage. The presence of a seat doesn't make an awful lot of difference; I have never been to a rock concert where anyone bothered sitting down through the entire show. (However, a dance floor is designed with the expectation that people will stand, and even jump up and down, on it; therefore it is more pleasant to stand on than an auditorium floor, which may well be thin carpet over concrete.) Since you are much closer to the performers in a nightclub, the performance is much louder. I neglected to bring earplugs, and regretted it throughout. It was simultaneously easier and harder to see what was going on on stage; the Johns were closer and much more visible, but the sight lines made the backup band (all of whom are named Dan) very hard to see. I spent a lot of time jostling for positions with sight lines unblocked by tall people's heads. At a nightclub, the lights are set up to be played over the audience as well as the band; they usually don't bother doing that at an auditorium. TMBG used this effectively, as part of their usual tactics to make the audience participate in the show. However, I do not like having 1000-watt stage lights shone directly into my eyes, especially when they've just been adapted to seeing the inside of a dark nightclub. The show itself was superb. It took them awhile to click with the audience, which is my only complaint. In particular, I think Birdhouse In Your Soul works much better played as a closing number (which is what they did last time I saw them) than as third in set (this time). But they were not pressured into playing Spider which they don't like anymore, and they clearly did enjoy everything that they did do. Including Fingertips. Bet you didn't know it was possible to do Fingertips live. They repeated the dial-a-drum-solo joke in the middle of She's Actual Size, to good effect (well, the drummer was expecting to be asked to do Animal this time; he got this wonderful deer-in-headlights look last time). One somewhat disappointing thing about going to see TMBG is that they never play all the songs I'm hoping they'll play. This time, it was Spiraling Shape they didn't get to; last time, I Should Be Allowed to Think. But the list of songs I wish they would get to is just endless: Ana Ng, The Bells Are Ringing, Turn Around, Wikkid Little Critta, Dirt Bike, The End of the Tour... So it's not exactly fair for me to complain, especially since they do always play something I wasn't expecting to hear, and it is good. (Robot Parade and How Can I Sing like a Girl, this time.) The opening act was Noe Venable, a local musician playing solo. She was great too; good music, solid stage presence, knew how to work the audience (not quite as well as John Flansburgh, but then friggin' Bono isn't as good at working the audience as John Flansburgh — admittedly, this is not a fair comparison, Bono has to work an audience at least an order of magnitude bigger). I think she's going places. A challenge for the readership: The best answer will be posted. #include <stdio.h> int main(void) { int x, y, k; char *b = " .:,;!/>)|&IH%*#"; float r, i, z, Z, t, c, C; for (y=30; puts(""), C = y*0.1 - 1.5, y--;){ for (x=0; c = x*0.04 - 2, z=0, Z=0, x++ < 75;){ for (r=c, i=C, k=0; t = z*z - Z*Z + r, Z = 2*z*Z + i, z=t, k<112; k++) if (z*z + Z*Z > 10) break; printf ("%c", b[k%16]); } } } According to GnuCash, I should have $32.04 in my wallet. I have only $28.04. What did I spend those four dollars on? I have no idea. Afghanistan risks disintegrating into warring regions. I've added a new link, to Anna Feruglio Dal Dan's weblog. She writes long chewy articles about the politics of Italy, and related things, every now and then. Frank Herbert wrote an awful lot of books besides Dune, which is the only one that anyone remembers him for. One of these other books is The Dosadi Experiment. The premise is simple: a mixed population of two sentient species (Humans and Gowachin) has been isolated on a hostile planet, Dosadi, by parties unknown as an experiment; they've survived, and in fact they've become so dangerous that the experimenters are considering destroying the whole planet rather than let them get out into the more civilized galaxy. The protagonist must attempt to find a better solution. The book unfortunately does not live up to its premise. The whole issue of whether or not the Dosadi are dangerous to the galaxy is sidestepped, in favor of a lot of tangled stuff about body-swapping and the Gowachin legal system. It reads well, though. In fact, the descriptions of the Gowachin legal system are one of the most interesting parts of the book. It's genuinely different from anything we Humans have ever put together, but coherent and does seem to work. Herbert does not paint a very clear picture of the system, or how it is used in ordinary times — the Dosadi situation cannot be described as ordinary. The glimpses we do get are nifty enough to leave me wanting more. Another dream. I was at a party. There were these two people going around trying to kill the other party-goers because, they insisted, they were servants of the Handmaiden of Death. I said something like "Why settle for the handmaiden?" and began a ritual to summon Death. Everyone was trying to stop me, but it worked anyway. Death showed up in the form of one of those Hopi kachina figures, grabbed the two people, and took them away to learn how to be his servants. Then I woke up. The most interesting part of the dream was the bit where I was doing the ritual. It was a song and dance ritual, and when I woke up I could remember all of the words of the song. They were nonsense, but they were all there. (They've faded now.) Random cool thing: a bibliography for Nethack. (Nethack is a really cool computer game which happens to be chock full of references.) Sailor Nothing is a fine work of on-line fiction written by Stefan "Twoflower" Gagne. It's about why being a magical warrior of love and justice is no fun. Y'all should go read it. (Caveats: It's fairly dark; it would probably get an R if it were a movie; if you're not familiar with the "magical girl" anime subgenre you may not get the references.) A lengthy dream in which I was wandering around this insanely expensive hotel suite in a bathrobe. I wanted to take a shower, but someone had put all their clothes in one of those plastic stacking shelves on wheels, and wheeled it into the shower, and I couldn't move it or use the shower while it was there. Then this crazy man broke into the suite and attacked me with a kitchen knife. I said "Ha, I'm crazier than you are" and took the knife away from him (getting some small cuts in the process). It then transpired that the crazy man was trying to steal enough money to buy a plane ticket back to Stanford (he was a college student). I was on the phone with a lawyer, trying to explain this, while simultaneously restraining the guy. It's hard to tie someone up properly when they aren't cooperating and you don't have any help. At this point an older man materialized in the same room claiming to be the crazy man's father. "Okay, whatever, you take him." Then I woke up. Rachel. I would like to make an actual legal argument for why the phrase "under God" should not appear in the Pledge of Allegiance, nor "In God We Trust" on U.S. paper money, nor any other reference to God or gods anywhere in anything officially endorsed by the government of the United States, federal, state, or local. The precise text of the First Amendment relating to religion is Congress shall make no law respecting an establishment of religion, nor prohibiting the free exercise thereof. On its face that is pretty narrow. An "establishment of religion" refers only to the practice of having one organized religion endorsed by a state and supported by its laws, to the detriment of all others. It doesn't say anything about mentioning religion. But permit me to make an analogy to Jewish law, which has mitzvot and gezeirah. The mitzvot are the things which were explicitly prohibited in the Torah; the gezeirah are additional prohibitions added by the rabbis to prevent people from accidentally violating the mitzvot. Gezeirah are written on the principle that one should not do anything which has even the slightest potential to turn into, or look like, a violation of a mitzvah. For instance, the mitzvah against cooking a lamb in its mother's milk is expanded into a requirement that milk and meat be eaten only at separate meals, off separate sets of dishes, with separate sets of utensils, etc. etc. It is this guiding principle that I would like to apply to the First Amendment. The government, then, should avoid anything that might even potentially be, or appear to be, an establishment of religion. Yes, it is a stretch from an officially established church to "In God We Trust" on a dollar bill. But it is also a stretch from not cooking a lamb in its mother's milk to eating milk and meat off separate sets of plates. Just got back from buying a whole bunch of groceries. There will be food tomorrow. Never seen Berkeley Bowl as crowded as today. I'm guessing lots of people are stocking up for parties tomorrow. Overheard by the bike racks: "It was a nice vacation in the meat world." Over at Nerve, there is a hilarious deconstruction of the Abercrombie & Fish catalog. Lore Fitzgerald Sjöberg would be proud. Then again, Abercrombie do a pretty good job of deconstructing themselves with their splash page. [Caveat lector: All of Nerve contains nudity and/or discussion of sex.] Two great books in a row this week: Patricia McKillip's Winter Rose, and Neil Gaiman's Coraline. I read the first, and had the second read to me and ~800 other people by the man himself. Yes, the entire book. It took more than three hours, from 7-11 last night, with a break for refreshments in the middle. It's interesting to compare these two. They are quite different books, told in different styles and with different heroines, but you could make a strong case that they have the same antagonist. I wish I could expound further, but it would be too spoilerful. A couple of observations on style, though. McKillip is wonderful at atmosphere, and it shows in Winter Rose: it is bitterly, bitterly cold inside that book. Just as it should be, given the plot. Gaiman, now, he's better at painting characters. There's a talking cat in Coraline and it's a cat, not a human wearing a cat's body. Sumana points out that it was one in four simulated weapons that got through security. I had it backward. A newspaper headline: "Airport Security Still Ineffective." The subhead said that only one in four simulated weapons was caught by security screening. My thoughts were first "no surprises" and second "I'm glad they're actually testing the system." A truck went by with a modified U.S. flag: instead of the field of stars, it had an Aldermaston (peace sign). Salon interviews John Gilmore about why ICANN should be abolished.: Every gun that is fired,..) A dream: I was helping someone assemble a complex map-of-the-world puzzle, with a nasty twist. All the pieces had the same shape, and if you put one in the wrong place it would melt. There was also some concern about pieces having been used up already — they gave the owner magic powers, rather like the cards in Card Captor Sakura, but only when loose, and using them that way could make them vanish. It was really important that the puzzle get completed. Also there was something about a can of spray paint but I don't remember that bit clearly, I'm playing with Galeon, which is a web browser. The authors basically took Mozilla, peeled off the layers and layers of bloat wrapped around its rendering engine, and put in a nice thin GTK-based user interface instead. Thoughts so far: On the up side: On the down side:. Powell's Books interviews Norton Juster (author of The Phantom Tollbooth). (So has Salon, last year.) It's hot. It's not ever supposed to get hot here, dammit. I cannot cope with temperatures above 70 degrees Fahrenheit. (Half kidding.) I've bought more cinder blocks and boards with an eye to enlarging my bookshelves again. Two more tiers on the shelves on the far wall of the living room, should hold me for another six months or so. Home Depot does not carry the right kind of cinder blocks. I think the pavers I bought instead will work, but they are disturbingly thin. Dave Trowbridge (linked from Electrolite) proposes a solution for the "excruciating dialogue" of Attack of the Clones: set the language on your DVD player to one you don't speak, and pretend it's opera. I have not seen this movie, and after all the bad reviews I don't plan to bother. If you want to see a big-ticket action movie, consider Spider-Man instead: it's well written, believable (as much as a superhero movie ever is) and has three-dimensional, interesting characters. I do have to agree with Roger Ebert (review - mild spoilers) that the movie doesn't portray Spider-Man as well as it does Peter Parker, but I didn't mind that so much as he seems to have. Dammit, I miss New York City. This afternoon, I spent a good hour in the bank putting two years' worth of small change (pennies, nickels, dimes) into rolls so that I could deposit them. It came to $40.22, which is not trivial; however, I'm left somewhat disgusted at the bank. Why on earth don't they have a counting machine? Bank-scale models only cost about two thousand dollars, which is chump change from their point of view, and I'm sure they have plenty of customers who could use it (think small businesses; two grand is not small change to your typical low-margin restaurant). Neglected to mention, yesterday, that while Dara and I were loading the futon onto my car we saw and heard some military jets scream by overhead. I don't know what they were doing, and it didn't make even the local news. It still makes me nervous. On a related note, here's a feature article for the Washington Monthly discussing whether or not the USA should attack Iraq. I picked my sister up at the airport this morning, she was flying back from having spent Memorial Day weekend down in L.A. We visited the SF MoMA; they were showing a bunch of themed selections from their permanent collection, and a retrospective on the work of this photographer whose name I unfortunately cannot remember (and their website is timing out on me so I can't look it up either). He lived in Carmel and took hundreds of photos of, at, and around Point Lobos. After that, we went to pick up a futon she was buying from this guy who was moving out, and deliver it to the apartment she'll be living in this summer. That would have been easier if the frame had come apart all the way. They're supposed to break down into five or six relatively flat pieces that fit into my car's cargo space. This one's fasteners were frozen, so we wound up lashing most of it — still a three-dimensional object — to the roof. Driving up and down San Francisco hills with this thing up there was, well, an experience. But we did arrive with no injuries and nothing broken. Finally, we went to the Cliff House for dinner. We were too tired to visit the camera obscura afterward, which was kind of a shame; I've done that before and it's really nifty. My grandfather has been hospitalized after suffering a heart attack and a whole cascade of complications. He might well recover; the doctors are talking about doing an angioplasty to reopen the blocked artery, and optimistic about the prospects for success. We won't know if it worked for several days though. Shweta's friend Conor Quinn (possibly Connor) was visiting for the past couple of days. He's a linguistics student at Harvard, and was in town on his way to Indonesia, where he's doing a month of field work. He speaks half a dozen languages, most of which I had never heard of, and will happily animadvert on the resemblance of words or names that come up in casual conversation, to words in other languages. We (me, him, Shweta, Nathaniel)went out to lunch at Vik's, which is a really great Indian chaat house down on Fourth and Addison. Then we wandered up and down the Farmer's Market and the Telegraph bookstore row for awhile, and in the evening we went to see Spider-Man (the movie). I ran into Seth on the street, but I don't think he saw me.. Delete file. DELETE FILE. DELETE FILE!!!!! DIE ZOMBIES DIE!!! Forty-four thousand lines of rotten spaghetti code! GONE! MWAHAHAHAHAHHAAHAHAA!!!!1!!!11! Okay, I'll stop now. At about five AM someone started rolling a noisy cart up and down the sidewalk in front of my building. Clatter, clatter, clatter. This continued until around seven. At first I was woken up; after awhile I drifted into a dream in which the exact same thing was happening, only I was staying in a cheap motel somewhere. Monthly Berkeley-area SF kaffeklatsch. Shweta and I went, and I convinced Shweta's friends Conner and Pat to come along too. A good time was had by all. I got to meet Heather Nicoll (aka Darkhawk) which was nice - have read her Usenet posts for some time and thought she might be interesting to talk to in person, and so it proved. For some reason, whenever I do laundry, none of the socks get dry. They are all spread out on my bed now, drying the rest of the way. Everything else gets dry, you understand, just not the socks. Joshua Micah Marshall on the Vice President's opposition to an independent inquiry into intelligence failures pre-Sept. 11: ... To which, the only thing one can say is "Right on." And hope that various members of Congress read his column. I dreamt I was asked to perform a marriage between two of my old college friends. A full-fledged Jewish religious marriage. One is not obliged to be a rabbi to do this; however, the rabbi is less likely to make a total mess of it, which is what I did. (It would have helped if I'd had a prayer book to work with. I had to make up most of the ritual.) For some reason all this was happening on the top of a hill and everyone was wearing beach clothes. Ted Barlow has a lot of good commentary, and links to commentary, about the intelligence failures leading up to Sept. 11 and the current political arguments over same. Go read. Meantime, Electrolite links to a bone-chilling post by Charlie Stross: World War Three ... .... Makes our little political dust-ups seem real insignificant by comparison. Over here on Willamette Week Online, we got four articles about marijuana. One in particular argues that legalizing pot will kill pot culture, and that this would be a Good Thing. I am not convinced of either prong of this assertion, but it's still a fun read. They also have a more serious interview with New Mexico Governor Gary Johnson, who advocates legalization of pot and possibly other recreational drugs on the grounds that prohibition is a failure, and one with horrible side effects:. This is a position I wholeheartedly agree with; it's nice to see a serious politician (and a conservative, no less!) espousing it. (Also from Ted Barlow.) Two of my all time favorite Mozilla bugs, 76431 and 101016, have been fixed. Now if they would just do something about 29838... Groceries have now been bought. Berkeley Bowl is a local non-chain supermarket, which has any number of interesting quirks. For example, it's the only market I've ever seen which has Ready Made and the Utne Reader but not the National Enquirer on its check-out magazine rack. Also, they do not stock any Coca-Cola products. I do not know why, but it's likely to be because the store is run by ex-hippies (they have a complete selection of organic and other good-for-the-environment stuff) and they have some issue with Coca-Cola. However, they stock plenty of other megacorporate products (Kleenex, for instance) so I am not sure. Emacs 20 has an irritating bug in its "customization" code. When you ask the customizer to save your changes, it writes a bunch of Lisp forms at the end of your initialization file (.emacs). If it sees there's already a block of forms that it wrote, it is clever enough to replace them without clobbering what you put in the file by hand. .emacs However, if you have byte-compiled your initialization file, which you might like to do if you have lots of Lisp functions in there, then it goes and writes its stuff at the end of the compiled file. It does not know how to remove the existing byte-compiled version of its stuff from before, which means all the settings get applied twice, and any side effects happen twice. Worse, the next time you modify your personal set of Lisp routines and recompile the file, those settings get clobbered. The Right Thing would be to modify the source file, which will cause Emacs to ignore the out-of-date compiled version, and notify the user that they may want to recompile. (You don't want to recompile every time you tweak something, it's quite expensive.) A user who has a byte-compiled init file can be assumed to know what the program is talking about. For all I know this has been fixed in Emacs 21, but I'm not particulary interested in upgrading (it's likely to break a lot of my complicated custom Lisp...) One is not entirely clear as to where the month went. One also suspects that one has forgotten to move one's car to avoid street sweeping and will now owe the city $26. The computer got a lot quieter after I removed one of the fans, which seems to have a vibration problem. I upgraded to a 2.4 kernel; despite earlier concerns, it seems to work quite well for my purposes, and is noticeably faster in some situations. (It's not obvious which of those are due to better hardware though.) Bonus, the combination of the new machine's video card and the new kernel enables accelerated 3D graphics, which means that if I ever feel like playing elaborate 3D games it'll be possible. Desperately need to buy groceries. Robert Dewar's attitude (exhibits A, B, C) is really starting to grate. I've upgraded from a two-year-old computer to a one-and-a-half-year-old computer. It's faster, has more memory, more disk, and a spiffier sound card. On the other hand, it's got four fans and two noisy hard drives... it's loud. I'll be looking into noise-reduction technology. Sumana had her graduation party yesterday. Lots of people came. There were samosas. Seth captivated everyone with his EFF rants. Today I go watch Shweta get her masters' degree. Turns out there's a ton of Internet resources for car buyers. Of course, it also turns out to be hella complicated and require wheeling and dealing. I hate wheeling and dealing. But I hate getting suckered more. So I'm looking into getting a new car. This is unpleasantly difficult. First off, car salesmen are really big on high-pressure tactics. You would think that if I walk into a dealership and say "I want to buy a car sometime in the next two months, I am looking to spend less than $25,000, whadya got?" this would put the discussion on a somewhat more relaxed footing. But no. They do not take my word that I want to buy a car. They try to convince me anyway. This does not strike me as good customer relations. More seriously, the car companies are all assuming that their customers (a) have a track record of buying cars already, and (b) drive at least a thousand miles a month. Thus, for instance, the warranty on the drivetrain on a Toyota runs five years or 60,000 miles. In five years, assuming no major lifestyle changes, I will drive less than 20,000 miles. (Perhaps this is an unsafe assumption.) Accordingly, all of the helpful calculate-your-payments webpages that the auto manufacturers have ask me multiple-choice questions to which the correct answer is invariably "none of the above" and I'm left not having any clue how much money will be involved. Well, the sticker price gives a ballpark figure, but 9% interest for however many years does add up. There's a whole village of spiders living in the window frame of my bathroom. I saw three this morning while showering. As I've said previously, I like spiders. And anything that stops flies getting in that window (which is open most of the time for ventilation) is good by me. However, I am getting a little concerned. They don't seem to understand that it is not safe for them to come onto the inner windowsill, because they'll fall into the bathtub and be drowned. I would rather not have to worry about this every time I take a shower. Also, guests that need to use the shower may not be as egalitarian as me about sharing the apartment with spiders. (Insects, mind, are not welcome.) A week in deep hack mode means another sink full of dirty dishes. Once again I have to do two loads because there isn't enough space in the dishrack. I wonder how expensive those portable dishwashers that latch onto the sink spout are, and how difficult it would be to get one up the stairs. Trying to get back to a reasonable frequency of bloggery... let's start with some One honest-to-gosh anxiety nightmare that left me not wanting to go back to sleep, in which my parents were being disappointed that I'd failed them by washing out of graduate school. One surreal situation in which I was trying to play a complicated card game to which I did not know the rules, on a table piled high with kipple much of which was part of the card game. And impress a girl at the same time. And another surreal situation in which all the GCC developers had gathered at someone's house to celebrate the release of 3.1 but I was having to talk someone down who was upset that his patches hadn't been included. Here is the final paper I wrote for CS 260, and the presentation I gave. There was a minor earthquake (more details) a few hours ago. The USGS reports it as magnitude 5.2 at the epicenter, which is getting up there. But it was quite a ways south, near Gilroy. In Berkeley, the building rattled a bit and that was all. Still a creepy feeling... I haven't been in an earthquake since the big 6.7 in Northridge back in 1994. For a moment I was expecting it to keep shaking and get worse. The paper's done. I go to bed now, and do the presentation in the morning (which will be a simple matter of cloning text out of the paper and turning it into bullet points). That was one bloody awful week, followed by a kick-ass weekend, and if I can just finish the paper that's due tomorrow, I'll be done with coursework, which will give this week a chance to be kick-ass too. But I have to finish the paper first. I just want to show you my evil rock star made of Legos: Done with the Mini-Mizer. Sumana points out that Eric Raymond is giving a talk, er, right now, at Soda Hall. I have seen him talk before, so I'm not particularly interested in going (besides, that would involve getting up and dragging my ass all the way back across campus). In fact, I am singularly unimpressed with the stuff he's been writing recently. The issues he presents are all either so obvious as to be not worth saying, or a lot more controversial than he makes them sound. It occurs to me that I'm singularly unimpressed with an awful lot of free software advocates—and developers too, come to that. The movement, like any other movement with a political component to it, attracts political kooks. Some political kookery can be necessary and even useful—there probably wouldn't be any free operating systems today if not for the Free Software Foundation's efforts, and the FSF was started by a kook of the first water. (Disclaimer: I hack GCC, which is an FSF project). But compare this article with this letter. The fundamental message is the same, but one was written by a kook, the other by a professional politician and his staff. It's pretty clear which brand of advocacy is more effective, I think. (To be fair, the politician has a distinct advantage here: he is responding to a specific letter which is written with so little understanding of the thing it attacks, that it might as well be a straw man. Except it isn't. Please note that the link above is a translation from Spanish; the grammar issues are not the fault of the original author, but I think it's safe to say the content issues are.) There was a fire in an apartment building down on Shattuck, not so far from where I live. I went by there on the way to the grocery store, and there were three fire trucks on the block and policemen directing traffic. Wonder what happened. It'll probably be in the local newspaper tomorrow. I got my notebook back! Apparently I left it at the Other Change of Hobbit (local bookstore). The staff were kind enough to hold it for me. Now I don't have an excuse not to finish the Minicon report. My art project is done: twenty-four obsidian (I think) pebbles with symbols carved into them: ᚠᚢᚦᚫᚱᚲ ᚷᚹᚺᚾᛁᛃ ᛇᛈᛉᛋᛏᛒ ᛖᛗᛚᛜᛟᛞ —that is, the Elder Futhark, also known as the runic alphabet. If you transliterate all the symbols into the Latin alphabet it comes out "FUThARKGWHNIJYPZSTBEMLNgOD", and now perhaps you see where "futhark" comes from: it's the first six letters glommed together, as if we were to call our alphabet the abcdef. Which, if you think about it, we do, only in Greek. There are a lot of "extended" futharkim: all the cultures that borrowed the original set from the Norse added letters so they could have all their phonemes represented. This one doesn't do so badly for English; the only letters missing, compared to the conventional orthography, are CQVX, and in exchange you get single letters for "th" and "ng" which would come in handy. In fact, in older books (we're talking Old and Middle English here), "the" was occasionally written þe. This was misread by medieval monks as "ye", and now you know where that alternate spelling came from. I think it's interesting that the correct plural for "futhark" uses the Hebraic "-im" suffix. Ain't English fun? Hyperfocus is a phenomenon observed mostly in people with ADD. Most of the time ADD individuals cannot concentrate on much of anything. However, they often have the ability to concentrate on one thing to the exclusion of anything else, for hours on end, if they really want to. I can do this sometimes; for me it's more like "if I really need to". I did it on Monday, putting in about eight hours straight to complete the big merge I mentioned then. The problem is it leaves me utterly wiped out for up to a day afterward. I now know more about Emacs Lisp than I ever planned to learn, Emacs' 3-way merge utility works almost the way I'd like, and the big merge is done. Later merges will hopefully be smaller. (fx: collapses in a heap) Also, today I finished rereading The Dispossessed. I like it just as much as I did as a twelve-year-old, but for completely different reasons. The twelve-year-old me liked it mostly because Shevek (protagonist) gets to invent new physics theories. I wanted to do that. The idea of a culture with no law but basic decency to one's fellows was appealing, but I didn't really grok it at the time. The current me likes the book because Le Guin manages to make her anarchist society genuinely believable. The people of Anarres are real people, with their flaws and virtues both. She understood what troubles it would have, why Shevek might decide to leave in hope of reopening communication with the outside universe, and what he would not understand about the more conventional culture he travels to. The idea of inventing new physics is still appealing, especially physics that could let us leave our little blue dot and see the wide universe. Do you ever look at the stars and want to go visiting? I sure do. It turns out that Emacs has two three-way merge facilities, and the one I didn't try is a lot better in terms of showing you what the situation is. Unfortunately it's got a totally brain-dead user interface: it matters which pane is active when you type commands. Fixing this would appear to take considerable hacking. Grrr. To use it, I'd also have to figure out the undocumented "gnuserv" interface (for getting a running Emacs instance to do stuff) well enough to make the merge facility play nice with Perforce, which may be a serious pain. But it might well be worth it. How much do I feel like hacking Emacs Lisp? Cringe-inducing filkage. Series of bizarre dreams, the only one of which I remember involved me trying to read a book which was done entirely in embroidery, words and all. There seemed to be a picture on each page. The content of the book was rather similar to the Dictionary of the Khazars (which I never did manage to finish...) Unsurprisingly, Emacs does indeed have a three-way merge facility, but it lacks many of xxdiff's abilities; in particular it is not nearly as good at showing me enough context to figure out what needs to be done. I must resist the temptation to hack it up and make it better. The Postal Service gave me two slips of paper with tracking numbers on them when I mailed my tax returns. They have a web form where you can enter the number and be told where the item is. The Federal return came up as "delivered" within forty-eight hours. But for about a week, punching in the number for the state return gave me "We've never heard of that". Then it changed to this: Your item was accepted at 1:37 pm on April 15, 2002 in BERKELEY, CA 94704. Status is updated every evening. Please check again later. and it still says that today, nearly two weeks later. I doubt it's gotten lost; much more likely that whoever delivered it neglected to scan the bar code, or that their database is still out of date. But it doesn't fill me with confidence, either. Sounds like something that might be illegal in Georgia, but it isn't. It's the process of combining changes made by Alice with different changes made by Bob to the same program. It tends to take days and be extremely tedious. There is good software to help out, but not quite good enough for my tastes: in particular, the best program I've found (xxdiff) does not have a facility to edit the merged file as I go along. This means I have to write down all the edits I need to make, finish the merge, then launch an editor. Slow, error-prone. Yuck. The author says he doesn't want to turn xxdiff into an editor, but I think that's a lame excuse. It just now occurred to me to wonder if Emacs has a three-way merge facility. That would solve that problem... An exercise: How long can you keep from thinking any words? It's not easy. Seems to be easier while walking, for me anyway. Back from the Mac OS X talk. It's really technically spiffy, but I don't see it as serious competition for Windows. This only because they, as a company, still don't have a clue how to position themselves to be competition. Case in point: If they were willing to consider giving up just a smidge more control, by porting the operating system to stock PC hardware, they would suddenly have a much bigger market. They insist that it isn't worth it, because they can offer a user experience that's just so much better by controlling the hardware platform, but I don't buy it. Users would be content with better than what they already have. The drivers don't have to be perfect, nor the mobility, nor whatever. Perhaps they have some slick long-term strategy which requires them to not look like serious competition for Microsoft right now. But that just smells like conspiracy theory to me. There's an old guy with a beard, in dirty overalls, doing something with a plumber's snake on the roof of the building next door. (One would assume he is a plumber.) I've redone the layout again, mainly so that I can put a mug shot in the upper right-hand corner. (If it's not there, your browser doesn't support CSS. Have you considered upgrading to Mozilla?) The original photo was taken by David Dyer-Bennet at Minicon 37. The observant will note that I gave up on doing all the layout in CSS and am using tables again. This is because it's impossible to specify the layout I want in CSS. Or at any rate I have not been able to manage it. If you know how to make the right column be exactly as wide as it needs to be, the left column stretch to take up the entire rest of the page, and the yellow background not smear across part of the left column, please contact me. Now off to see a talk on Mac OS X. Random linkage: Book-A-Minute. Hilarious but only if you've read the books, or attempted to, first. Panix has a system administrator who does nothing (as far as I know) but install and upgrade software packages. This makes me feel somewhat less pathetic for having nearly killed myself doing the same thing way back in 1996 except on top of a full load of college courses. Bad precedent. Spent most of yesterday sorting through my finances. I was expecting this to be a drag, but keeping accurate records (using gnucash) turns out to be kind of fun. And it should prevent next year's taxes from being another exercise in digging through file folders to find old credit card bills to attempt to reconstruct how much I spent on what. Or, for that matter, an exercise in wondering what the hell "Yang's" is and why I spent fifty bucks there. It is a bit sobering to discover that I'm $3K in the hole this year. Gnucash's save files are much too big, because they're dumping out extremely verbose XML; they compress down about ten-fold. I wonder how hard it would be to wire zlib into the program so they got automatically compressed. I also read a whole bunch of investment advice over at The Motley Fool. Again, I expected this to be a drag, but it wasn't; they're really good at laying out your options in clear, witty language, and at making the subject interesting. Annoyingly, Fidelity's website has regions which don't work with Mozilla—not the actual "invest online" forms, but the bits where they explain the details of each mutual fund. Which is important to know before one goes off and buys them. From Slashdot: Havoc Pennington (one of the core GNOME hackers) has written an essay on free software and user interfaces. Very interesting read. If you hit some of the hyperlinks you eventually run into a bunch of people making the assertion that graphical user interfaces are always and intrinsically better than command line interfaces. These days, every time I run into this I want to confront the person making the assertion with Jo Walton, who is emphatically not a "power user" (whatever that means) and yet is much happier at the command line than in a GUI, simply because iconography doesn't work on her. Period. She cannot, for instance, read comic books, because they don't make any sense: in the same way that a text in Hebrew makes no sense to someone unfamiliar with the language. It seems unlikely to me that she is unique in this. I agree with Havoc that excessive customizability is a bad thing in one user interface, overall. But I claim something else, which is that a computer ought to have completely different user interfaces which offer roughly equivalent functionality. Some people like the GUI, others the CLI, and yet a third group want to use each for the tasks it's good at. For evidence, I point at Mac OS X, which has got hard-core Mac junkies poking at the Unix layer and liking it, and hard-core Unix junkies poking at the friendly GUI and liking it. So as I'm getting out of the shower this morning, a big spider falls off the window ledge into the tub. I do not freak. I rather like spiders, come to that. It kept trying to climb back up and failing because everything was slippery and wet, so I did the only sensible thing: I laid strips of toilet paper down the wall and side of the tub to make a path with some traction. It caught on real fast, and is now happily back at its web in the window frame. It only now occurs to me that I could have just taken a towel and dried off the wall and the side of the bathtub. Oh well, next time. Brenda Clough's novella May Be Some Time is available online from Analog. It's about what might have happened to Titus Oates, who was on the ill-fated Scott expedition to the South Pole, and whose body was never found. There's a spoilerful review at Infinity Plus. Blue poster-stickum works better than candle-mold putty for holding little obsidian pebbles down so I can grind designs into them. Now I just have to figure out what I'm doing wrong that causes the diamond grit to wear off the grinding bits. Not enough water, probably. Or it might be that a cheap $10 set of grinding bits is, well, a cheap $10 set of grinding bits (but you'd think they'd sell the good ones at a jeweler's supply...) Tonight and for the next few weeks, all five planets visible to the naked eye are in conjunction. Shweta, Nathaniel, and I climbed up on the roof of my apartment building and looked for them; we found Mercury, Venus, Mars, and Jupiter with no difficulty, but couldn't agree on which of several candidates was Saturn. According to the article, Saturn is lower in the sky than Jupiter, so Shweta's candidate was probably right. Makes me want to go buy some binoculars or a mini telescope just to be able to check them for discs. If you want to look tomorrow night, start immediately after the sun goes down; Mercury sets only about an hour after the sun does. They'll all be in the western half of the sky, between the Moon and where the sun set, in a diagonal line. Venus and Jupiter are the brightest two points in the sky. Mars looks like a moderately bright star, tinged red. Saturn and Mercury are faint, and Mercury will be very close to the horizon. I had a dream in which I was expected to eat live albino snails. Except the snails might eat me first. They were the normal snail size, but secreted a paralytic toxin. One of them began eating my left hand and I couldn't get it off. There was also a scene in which I was trying to load stuff onto a truck with the assistance of a bunch of anthropomorphic lizards. The lizards kept trying to steal stuff while my back was turned; they had sabotaged the lock on the truck's cargo door. This was culturally expected and I had to keep complimenting them on their cleverness while stopping them. This website documents experiments in making computers available to minimally educated children. They call it "minimally invasive education." We get to throw away dozens of old obsolete GCC target configurations. I was expecting opposition, but people seem positively enthusiastic about suggesting dead targets. a29k-*-* alpha*-*-osf[123]* arm-*-riscix* c*-convex-* elxsi-*-* i?86-*-aix* i?86-*-bsd* i?86-*-chorusos* i?86-*-dgux* i?86-*-freebsd1.* i?86-*-isc* i?86-*-linux*oldld* i?86-*-osf1* i?86-*-osfrose* i?86-*-rtemscoff* i?86-*-sunos* i?86-go32-rtems* i?86-next-* i?86-sequent-bsd* i?86-sequent-ptx[12]* i?86-sequent-sysv3* m68[k0]*-*-lynxos* m68[k0]*-*-rtemscoff* m68[k0]*-*-sysv3* m68[k0]*-altos-* m68[k0]*-apollo-* m68[k0]*-apple-* m68[k0]*-bull-* m68[k0]*-convergent-* m68[k0]*-isi-* m68[k0]*-next-* m68[k0]*-sony-* m88k-*-coff* m88k-*-luna* m88k-*-sysv3* m88k-dg-* m88k-dolphin-* m88k-tektronix-* ns32k-encore-* ns32k-merlin-* ns32k-pc532-* ns32k-sequent-* ns32k-tek6[12]00-* sparc-*-rtemsaout* And more coming. Wheee! Off to mail in my tax returns and bills. I'd be happier if I could find my credit-card bill, but I'm sure it'll turn up (probably right next to the Minicon notebook). For some peculiar reason Fidelity does not let me transfer money from my money-market account to my IRA through their website. I had to call a broker and do it that way. At one point, while waiting for the computer to do something, the broker chatted with me about the weather here in California versus there in Texas. Okay, fine, except the whole time there's this little voice in the back of my head going "This is normal social lubricant. Do not freak." Which makes me wonder if other people get that, too. I have lost the notebook with all my Minicon notes in it. This is singularly frustrating; I can't work on my con report. I'm doing an art project which involves cutting symbols into lots of small obsidian pebbles. You do this with diamond grinding bits, which can be had from a jeweler's supply store for about ten bucks. Diamond bits have to be kept wet, or they overheat and melt. The jeweler's supply will sell you an expensive carving drill which runs a constant stream of lubricant onto the bit, but I'm a cheapskate so I'm just using a Dremel. It works almost as well to put the stone in a basin full of water, with a couple of catches. First, having the stone underwater means it's hard to see what you're doing. It is essential to change the water often; it will rapidly become cloudy with suspended obsidian dust. Most of the bits are shapes that don't disturb the water much; unfortunately, some of the more useful ones will send it splashing all over the place. There's usually a critical water depth at which they don't do this. Trial and error is about the only way to figure it out. It's also essential to have strong light directly on the piece being worked; I've been holding a flashlight in my other hand, since I don't have a proper work lamp. Second, you need some way of holding the stone at the bottom of the basin. This is actually the hardest part of the project. I've been using the sticky putty that came with a candle mold. It doesn't work very well: it is not much interested in sticking to the smooth glaze at the bottom of the bowl I'm using. The stone therefore tends to come loose halfway through a cut. The putty does stick to the stones, a bit too well; it's difficult to get off again once I'm done. And, worst of all, the stuff is positively eager to stick to my fingers. I know I have some of that blue poster-stickum around here somewhere; that might work better, if I can find it. At least it would come off my fingers without rubbing alcohol. My 2001 income tax return comes to twelve (single-sided) pages of forms, including the somewhat exotic Form 2210 whose purpose is to explain to the IRS that I did not, in fact, underpay estimated taxes. The state tax return adds another five; they want a complete copy of the federal return plus some extras. I had an interesting conversation with Shweta about why it is I don't use electronic filing. The most important reason, to me anyway, is that paper filing means that I can look over the forms and know exactly what's going into the envelope to be sent to the IRS. With electronic filing I would have to trust the tax program to do it right. (I already trust the tax program to fill out all the forms correctly, but it is much more likely that that part has been properly debugged. Also, I can do spot checks of the printout to make sure it's accurate.) From: It is our policy to send copies of all notices of alleged infringement to third parties who will make them available to the public. ... and to put a link to the notice at the bottom of any censored search result. And the notice has to include the URLs that were censored. Nice end-run. Well, Windows, at least, is not currently my friend. I sat down last night to do my taxes. However, I didn't ever get to run the program, because Windows decided it was Not Happy about various hardware upgrades being perpetrated behind its back (the last time I booted that partition was to do last year's taxes). So it refused to talk to the network until I reinstalled it. Which, as you know, takes hours; the more so since I stubbornly tried several other things first, refusing to believe that it had to be reinstalled. I did finally get the thing working, and about halfway through the taxes, but I'm too tired to finish. And they're due Monday. Bleah. (What does the network have to do with taxes? Mainly, that one of the upgrades was the video card, so I needed the right driver or I was going to be stuck working in 800x600 16-color VGA mode, which is No Fun. Also, it tends to be necessary to download a batch of updates to the tax program.) Stayed up all night reading Kushiel's Dart. It's a alternate-Renaissance fantasy which gets major points for not using any Extruded Fantasy Product tropes. The distorted mirror of Europe that she's using occasionally becomes obnoxious (choice of words to render in French .vs. English, for instance) but the story takes hold and doesn't let go. Unfortunately it's 900 pages long, which is awkward when you start reading at midnight. Now I'm working my way through Little, Big, which is another very long book but one that I can only read in small doses. I'm not sure what I think of it yet. I found the C library bug. Someone converted a chunk of the RPC code to thread-safety without thinking it through, and the obvious change was wrong. (Hence recompiling the aforementioned tiny file outside the library, and therefore with thread safety turned off, made the bug vanish.) -> ld < test.o value = 134765376 = 0x8085b40 -> test hello world 2+2 = 7 value = 0 = 0x0 (Two and two are seven? See Trurl's Machine in The Cyberiad, by Stanislaw Lem.) The last bug, incidentally, was that the system has no concept of a machine with two network interfaces, only one of which can talk to the embedded board. This happens to be how I arranged the local network. Recompiling and LD_PRELOAD-ing one tiny chunk of the C library causes the bug to mysteriously vanish. I love this sort of thing. Hopefully a coherent C-library bug report can be extracted from it. Now I have a new bug to fix, or two bugs: T O R N A D O Development System Host Based Shell Version 2.2 Cannot start the asynchronous event notification -> -> Segmentation fault One hopes that the first bug will be easy to find and that fixing it will make the second bug go away, but I'm not exactly sanguine. Time to kick it in the head for tonight, though, I think. Still can't get my "target server" to attach to the board. The bug is firmly in This Can't Possibly Be Happening territory; something is going wrong deep in the guts of the C library, for apparently correct input data and operation sequences. I can't run the program under the debugger to find out what's wrong, because it uses threads, and GDB does not like threads. (When "break main" doesn't work, you know you're in trouble.) Question for the audience: Should one timestamp blog entries with the time that one starts writing them, or the time one finishes? (I suspect most blog-automation winds up using the finish time; I've been writing these by hand and using the start time. It's getting tedious to update the boilerplate, so that might change soon.) Nope, I still find Mozilla's page editor unusable. There's been an argument on rec.arts.sf.composition about the appropriate words to describe organic farming and related issues. One side takes the position that it's inaccurate to describe crops grown without benefit of synthetic pesticides or fertilizers as "organic"—all food is organic, in the chemical sense. The other side says that words mean what their speakers want them to mean, as long as their hearers comprehend, what's the problem? rec.arts.sf.composition As an argument over semantics of a word it's really not that interesting. However, both sides appear to have major hidden agendas. Word choice is being used as a proxy for the real argument, which is whether organic farming is an appropriate thing to do. And in this service, the "it's inaccurate" side is using rhetorical tactics which are toxic to discussion. If someone comes to the table with the axiom that organic farming is the province of hippie nuts, well, it's not possible to have a productive debate with them over whether or not it's a good idea. This despite the same people claiming that they do see the problems with antibiotic resistance, algae blooms, etc. associated with "conventional" farming. People will come away from the discussion remembering the hippie nuts. I find this thoroughly disappointing. These people are writers (mostly); they understand rhetoric and discourse; they are none of them kooks. Therefore, I can only conclude that they want to poison the discussion. And no good ever comes of a poisoned discussion. Jeff Gerhardt and Doc Searls have announced their intent to form a political action (i.e. lobbying) committee with an agenda directly supporting free software and opposing antiinovative legislation like the infamous DMCA. See the draft position statement. It's a shame that this is necessary, but since it is, bully for them. I'll wait a bit for them to finalize their agenda, and then send them some money. I'm lucky enough to have friends who can tell, when they call me on the phone, that I'm messed up because I haven't eaten all day, and will then drag me out to eat. I feel much better now than I did this morning. In fact, I might feel better than James Brown. While engaging in the quintessential act of navel-contemplation known as "rereading old Usenet posts via DejaNews Google", I found a post about what it's like to come home and discover someone who's overdosed on speed sitting in your living room. Yes, it's a true story (although I seem to remember it was a bit more convoluted than that... oh well, these things always get simplified down in the telling). I can't say it any better than the judges did: The Supreme Court [of the State of Colorado] recognizes that both the United States and Colorado Constitutions protect the rights of the general public to purchase books anonymously, without government interference. ... and therefore that the government may not demand purchasing records from a bookstore. Well, it's not as absolute as that. ..) As reported on Slashdot. Apropos of Avram Grumer's speculations about theories of what makes a "liberal", or a "conservative", and Gary Farber's observation that people self-identifying as either simply do not understand how the other group's arguments can be rational, let alone right: I'm told that it is instructive to get one's hands on a copy of George Lakoff's Moral Politics, which taps the Gordian knot at an angle you may not have thought even existed and sees it neatly fall into two pieces. I say this not having read the book, so cum grano salis as Teresa says. Joel Rosenberg, who knows far more about these things than me (being a person who actually owns and shoots guns) confirms my suspicion that it would be trivial to get a gun through airport security, if one were determined enough. Bizarre dreams, involving plastic bags full of human blood, trying to find a microscope in a derelict physics laboratory, and trying to sew together a gift T-shirt for someone on very short notice. Also there was something about extremely expensive Magic Markers. As I said long ago, my dreams don't tend to make any sense. The Flash Girls' Banshee is playing on the music shuffler just now, and I'm reminded of the trouble I had falling asleep last night. Not because I expect the Cwn Annwn to howl for me anytime soon... see, Banshee is a love song (sort of). And I have come to despair of finding love, or even lust, again; it's been years now since there was anything but missed connections. I don't let it bother me in the daytime, but in the dark it's harder. (The music shuffler put Mysterious Ways immediately after Banshee. I see it's decided to be unhelpful this morning.) Blogs like Electrolite and Pigs and Fishes make me wonder why I'm in this game at all. They give you political commentary, humor, and interesting newsbits. I whine about my life. What's the point? Is anyone actually reading? I'm rereading The Dispossessed by Ursula LeGuin. I should have done this years ago; I last read it when I was about twelve years old, and missed about two-thirds of the story, never mind the point (it's definitely a book with a point, or several). Also recommended: Making Book, a collection of essays by Teresa Nielsen Hayden. You would perhaps not expect a set of guidelines for copy editors to be amusing, nor to illustrate so many useful principles for writing as well; yet that is exactly what the On Copyediting essay does. And The Pastafazool Cycle ought to be required reading for eighth graders learning how to do library research. Wonders never cease—the landlord sent someone around to vacuum the carpet in the common hallway. It is a great improvement. (Alas, they didn't do the stairs.) And the laundry room no longer has slime on the floor, although in other respects it is still rather grungy. Slashdot has a link to a paper called Single Points of 0wnership which discusses how the distributed computing client bundled with KaZaa has created a serious security risk: if the distributed-computing servers were compromised, they could distribute trojan horses to all the KaZaa clients out there, potentially rendering millions of computers into zombies (sense 2). This seems an opportune moment to do the airport security rant I promised last week, but it turns out that Bruce Schneier has beaten me to it by several months. All I can add is that to anyone with half a brain it's bloody obvious that the security checks are appearance without substance. Who do they think they're fooling? Oh, also, you know which security regulation was being most carefully enforced? The photo-ID requirement, of course. Which, as Bruce points out, adds no security at all (fake IDs are trivial to obtain, and even if you can reliably detect them (which you can't) you still don't know whether or not the person you have reliably identified, is a hijacker). Its real purpose? Read his rant. A collection of obfuscated programs that are also ASCII art. I particularly like the l33tsp34k generator shaped like Piro's head. (Yes, I am websurfing to keep myself awake. Why do you ask?) The Fellowship of the Rings, as a text adventure for the original Atari 2600. Things you can get away with at two AM: backing up through an intersection in order to reach a parking space on the other side, which would otherwise require going around the block since the street is one-way in the wrong direction. Have now gotten through approximately 1,000 messages waiting for me at the work address (of which 900+ were mailing list traffic), and most of the Usenet backlog. Also, my suitcase has been returned to me by the airline, undamaged. Shouldn't still be awake, but I got playing with valgrind, which is a nifty program for finding memory-access bugs. Back from Minicon. Watch this space for a conrep, in the next couple of days, after I get a chance to compare notes with Shweta. There will also be a rant about airport security and general airline incompetence, after I calm down enough to be coherent; for now let's just say that my suitcase is currently somewhere between Phoenix, Arizona and here, and contains several of my favorite books (which I schlepped to the con to get them signed), not to mention most of my clothes. Of 49 pieces of mail waiting for me at this address, 47 were spam.. I'm exhausted. I keep waking at 7 AM no matter how late I went to bed the night before, and I've not been to bed before 1 AM since, ugh, last week. Bad sun, stop coming up so early. (I like the long afternoons we're getting now, but not the early mornings.) Today was the checkpoint presentation for my CS260 project. You can read the outline and slides if you're interested. (Please offer suggestions on the open questions.) -traditional is dead, and no one spoke so much as a word against its passing. I dance on its grave. -traditional I have a new video card, which can drive this monitor at 1600x1200x24. Now I can have two full columns of text side by side, and 78 rows deep. The only downside is that Powermanga is now unplayably slow. Oh well, time to find a new game. Maybe I'll go back to Nethack. Sent in a patch to kill off support for pre-standard C in GCC. Let's see how many people scream. Off to grab some munchies, then to San Francisco to see Jeana dance. Seth was kind enough to try his hand at designing a algorithm I need for my flip viewer. I shall describe the problem briefly. Suppose that each column of this table represents a version of a text file. a a * * * % % @ b * c c a * * # c c d d c a 0 * d d e d c d 0 e d e d e e The challenge is to slide the columns up and down and insert gaps so that each (notional) individual line has its own row. It comes out looking something like this: % % @ a a # b * * * * * * * a a 0 0 c c c c c c d d d d d d d d e e e e e Unfortunately, Seth's algorithm has cubic time complexity, which makes it useless for anything much bigger than the above example, and I don't see an easy way to get it down. Another nail in the coffin of the hoped-for working prototype by Thursday. It is definitely time to use the Wizard of Oz technique. In the department of things that are obvious once you've thought of them, I realized today that the way to get a coating of wax off a spoon is to pour boiling water over it. Had fun at Amira's - great dancing, so-so food, but I wasn't really paying attention to the food. Jeana stole the show. Come home and discover that the build I kicked off just before leaving had died 11 minutes in due to an unrelated buggy patch that someone else committed. Grrr. Spent all day attempting to hack together the "flip viewer" that I've had a picture of inside my head for about a month, using Python's GTK wrapper. (This is the same thing that generated 27MB of HTML when I tried to do it that way.) I have to say, they sure make it difficult to do simple stuff. Maybe it's just that the PyGTK documentation is crap, but you would think it would be straightforward to, oh, make a text widget scale itself according to what the text inside needs... nope. No way. Appears to be totally impossible. Oddly enough, I remember having exactly the same complaint about CSS not so long ago. I'm gonna wash dishes and go to bed; and in the morning I'm gonna resort to drawing pictures of this thing with a sketch program, because there's no way I'm going to get a working prototype in time for the presentations on Thursday. Borrowed a huge (21") monitor from work to replace the 17" one I've been using. This thing can theoretically handle 1800x1440 resolution at 76Hz refresh. My video card is not even remotely up to that; I get a choice between 1600x1200 with 8-bit color or 1280x1024 with 15-bit. Right now I'm trying the former, but thinking the latter might be better; color depth helps lots of stuff, and the fonts are kinda small right now. On the other hand, I can't get two side-by-side xterms in 1280x1024. Maybe it's time to get a beefier video card. It's quite frustrating that XFree86 can't handle changing the color depth on the fly, the way it can the screen resolution., though. I had to go to the dentist today to get a cavity filled. Most people, including me, expect this to be a lengthy and painful procedure which leaves you unable to talk properly for several hours. Not so: it was a 20-minute, nearly painless visit. Apparently the latest thing in dentistry is vaporizing decayed tooth with a laser instead of drilling it out. This is faster, more reliable, and less invasive. Oh, and far less painful, to the point where it isn't necessary to get shot up with local anaesthetic (hence no numb puffy jaw for the rest of the day.) After the dentist got done with the laser, he filled the hole with some sort of epoxy and set it with a small ultraviolet lamp; again, faster and less painful than the old mercury amalgam (and no risk of chronic mercury poisoning, either). I really like this guy. If you're in Berkeley or Oakland and need a good dentist, check him out; he's got a somewhat silly-looking website with contact info. Another month, another trip to Amoeba—the one on Telegraph Avenue, this time. Sadly, they did not have any Luther Wright and the Wrongs albums. I bought: You will note that I bought a real AC/DC album this time. Factory Showroom contains the wonderfully disturbing tracks Spiralling Shape and The Bells Are Ringing. It's worth buying just for those two (the rest is also good, or the part I've listened to, anyway). Aside: Why on earth is <U> a deprecated HTML tag when <I> and <B> aren't?! prosewitch complains about being shy and feeling guilty about being shy, etc. etc. and I read the whole thing thinking "gee, is she secretly me?" because I have all the same problems (except for the talking to professors bit). For instance, here I am feeling like I'd like some company and to get away from work; and I know I could pick up the phone and call any of several people, and hang out; but I probably won't, because that would be, y'know, extroverted. Bunny-puppy, yes, I know. Wrote some more Shadowrun spells: static and dynamic magnetic fields, more sleep magic, and more Oliver Sacks-inspired illusions. It's been raining off and on for the past week; today it seems to have settled down to rain in earnest. I like a good gentle rainy day. The soft gray light makes everything seem friendlier, somehow. The mist brings the horizon closer. Things nearer than the mist somehow seem sharper, probably by contrast. Noises are muffled. I walked through Sproul Plaza on the way back from class and saw that someone had decided to dump bubble bath liquid in the fountain for a joke. It wasn't real impressive, though. It occurred to me earlier today that the forms and procedures of a criminal trial have interesting resemblances to magical ritual. Two things in particular come to mind: the goal being to determine an absolute Truth (who is guilty of a crime) by inquiring of witnesses, and the unusual powers given to the judge as representative of the state. (Under normal circumstances, ordering that someone be locked up for the rest of their life is itself a criminal act.) This is not surprising when you consider that most modern criminal procedure is based on protocols developed in solidly religious—mostly solidly Christian—cultures and times. Most religions do include the concept of absolute truth, and the spectrum from religion to magic is well understood in anthropology. With my speculative-fiction hat on, there are two ways one could run with this observation. One, let's call it the "Ken MacLeod direction", would be to explore the nature of a legal system that didn't have any basis in magic or religion. Instead, it might take an approach similar to scientific method, with experiments done to probe the scene of a crime for what happened. More emphasis would be placed on preventing crime than punishing it. Punishments would focus on compensating the victim, probably with money (weregild, anyone?) The other possibility, the "Jo Walton direction", would be to explore a legal system overtly and explicitly based on magic principles. Here, you'd investigate a crime with rituals intended to extract truth from suspects and witnesses, and punishments might have a direct effect on the state of the criminal's soul. The power went out. When I turned the breaker back on, it buzzed at me and flipped off again. Wasted some time trying to figure out where the load was. It turns out that the two master breakers control the front and back halves of the building, not the top and bottom floors like I'd thought, so I bothered the wrong person. Then I gave up and turned the power back on a second time; this time it seems to be staying on (knock wood). We had a rash of this last month, which I'd figured was due to everyone running electric heaters, but now it's warmer and people aren't doing that. Maybe something else is wrong. So I'm walking down the street and I see that it is street-sweeping day. Of course not everyone has moved their cars out of the way of the sweeping truck, so the guy driving has had to avoid them and miss long chunks of curb. All these people will come back to find they've been slapped with tickets. This is a lose any way you slice it. People have trouble remembering which day of the month the sweeping happens, they resent paying the tickets, and the streets aren't even clean. How would your friendly local mad scientist solve this problem? Perhaps with a sweeping truck that could move cars that were in its way. Here are three designs: Chop up everything except the eggs. The potato, onion, olives, and garlic cloves should be cut fairly small. The mushrooms and tomato should be cut large, because they shrink when fried. Cut the cheese to whatever size suits your fancy. Break the eggs into a bowl and beat them smooth. Heat a pan and grease it with olive oil. Fry the vegetables, adding them in this order: potato, onion, mushrooms, olives, green onions, garlic, tomato. When the tomato is cooked, throw in the cheese and stir until it begins to melt. Then pour the eggs over the entire mess, stir a bit so that it is evenly distributed, and put a lid on the pan. Reduce the heat and allow everything to steam for a couple of minutes; then remove the lid and scramble everything up until the eggs are thoroughly cooked. Serves one. To scale up, keep the proportion of tomato, potato, and onion constant, and add about two-thirds the number of mushrooms, olives, eggs, etc. per additional person. Go right now and find a copy of the Riddlemaster of Hed omnibus, and read it. No, you don't have anything better to do today.. Well, in this case, the best thing about standards is they often have completely brain dead mandated semantics. Take the humble #line directive. Its purpose is to let a programmer adjust the apparent file and line of the code being compiled. It takes a filename parameter. You would think that it would use the same syntax as the other directive that does that, #include. But no, the C standard mandates they have different syntax. Well, maybe. As is common with the C standard, the text can be interpreted multiple different ways; and if you ask the committee informally, two different members respond with contradictory answers, both with solid arguments. #line #include Meantime, there's code out there that assumes that #line works like #include, and no one has shown me code that assumes that they don't. So I'm making GCC treat them the same way. It turns out that this requires major surgery; not because it's intrinsically hard to do, but because you'll never notice the difference unless you use filenames or #line directives containing nasty characters (like newline), and other bugs pop up if you do that. So I can't validate my fix without fixing all the other bugs as well. (That is, on Unix you'll never notice the difference. On Windows, you definitely will, because Windows uses backslash (\) for its directory separator, and most C programs treat backslash as meaning "the next character in this string is special.") \ Emergency laundry is done. Now to take a shower and run off to the NTL meeting. I hope we're having edible food this week.. Shifted January to the archives, only two weeks later than I should have. Today in class, we were invited to critique user-interface toolkits we have used—as in, have written software using. Most of the code I've written has been batch-mode command line applications, so I don't have a huge amount of experience here. (Which isn't to say that user interface design for a batch-mode command line program is either unnecessary or trivial, of course.) However, I do have a criticism to level, which is: A GUI toolkit should make it easy to say what you mean. For instance, consider the overall page layout of this blog. The specification, expressed in English, would read something like this: ...Below the title and subtitle, there shall be two columns. The left column is to have a yellow background, and small sans-serif text. It shall be only as wide as the text inside requires, plus some padding on all sides. The right column shall take up the remainder of the horizontal width of the page, stretching to fit. It is to have no special background or font selection. I have still not figured out how to express that in HTML and CSS. The sticking point is the "only as wide" bit. You can say "N pixels no more no less" or "X percent the width of the page", but as far as I can tell you can't say "size this according to what's inside with no stretch." After class I went to the engineering library and printed out five papers which seem to be relevant to my project. I could have kept going; those five came from the first two keyword searches I ran. I think five is enough for one batch, though. The library has cute software for tracking how much printing you do and charging it to your copier card. It's named after the world's first known lighthouse, Pharos. I'm not sure why. Remember the lightsaber spell? I've now got a revised version, along with nine more, on a grimoire page. Share and Enjoy. I think I'm going to do more of my reading assignments in cafes from now on. I'm done with all the reading for next week already. The past few weeks I've been stuck doing it the night before the class, or even the morning of. Now I just have to write up my presentation for Thursday, which should be easy. I was hoping to have some more progress on the User Interfaces project, but although I've had a bunch of ideas none of them have made it out of my brain and onto a hard disk yet. Maybe tomorrow. When I make pasta, a disturbing amount of the cheese winds up stuck to various plates, bowls, pots, etc. rather than being eaten. A pity. Oops, I left out the href on one of the hyperlinks in the last entry. href Friday was unmemorable. Work, mostly. I found a bug in half an hour after someone else had been stuck on it for three days. I hope this maintains my reputation as a miracle worker in the face of the bug that I've been stuck on for three weeks now. Saturday, went to the Alternative Press Expo at Fort Mason in San Francisco, with Shweta and Nathaniel and Patrick Farley. That was fun. One barn full of genuine artists, as opposed to the ComicCon experience of a couple football fields worth of The Man with a few genuine artists scattered around the edges. Here's some nifty things found in the barn: Peko Peko, Last Kiss, Shades of Green, K.O. Comix, XXXlivenudegirls. (This last is not what you might think! It's self-described as "a scrapbook of bad choices." Extremely sharp broken glass edges, proceed with caution.) Patrick was on a panel called "Online Comics: Telling stories on the web" with Tristan Farnon, Scott McCloud, Justine Shaw, and Derek Kirk. The panel itself was nothing to write home about, but go check out all the above hyperlinks. APE goes on today, but I have too much work to go again. Well, I dreamed that I was sitting in a bar, listening to Bono explain in great detail how neither he nor any of the other members of the band could stand any of the tunes on Achtung Baby anymore, and this was why they never played them in concert. Waking up, I wonder if that's true. Unfortunately I cannot remember if they really didn't play anything off AB when I saw them back in October, and the official band webpage, which should have set lists, is a shining example of category 3 bad web design so I can't find them. (Why are rock bands' web sites so often like that?) So I needed to write a script to walk back in time through the GCC source repository until it started miscompiling this test case I've got, but I didn't want to start now, I wanted to start back in 2000 sometime. How do you do that? The CVS client won't take anything convenient like a simple count of days since 1970... ... but it turns out that you can write -D "4 days ago 2000-06-24" and the "4 days ago" bit will modify the "2000-06-24" bit. That's good enough. The script is now grinding merrily away. It takes longer to update the working copy than it does to compile the result, but it's going to run overnight anyway, so I can live with that. -D "4 days ago 2000-06-24" Off to bed. Today I got up, looked out the window, saw the threatening clouds, and thought "There have been threatening clouds all week, and every day they've burned off by two PM; I don't need waterproof clothing today." So, of course, today it rained. I did have a relatively waterproof jacket, but my shoes are soaked through. Interestingly, this morning there was a thread in rec.arts.sf.fandom about fiction that does and does not have "creationist" assumptions embedded in it, with the works of Ken Macleod suggested as a prime example of the second category. (They are also uniformly excellent books. -ed) rec.arts.sf.fandom What's this got to do with the weather? Well, my first two paragraphs up there have got a creationist assumption embedded in them, by the terms of the thread—the idea that it rained today because I didn't wear my rain boots finds causality where there is none, and (by implication) ascribes consciously malevolent humor to the weather, which is not alive. From there, it's not much of a leap to an actively participating trickster god, and from there to a creative one. Consider Ifni from David Brin's Uplift series, who is a consciously worshipped deity of the perversity of the cosmos, and in some contexts described as the chief servitor of God Almighty. (She's said to determine the course of luck by rolling dice, which I bet is a deliberate nod to role-playing games.) Now personally I don't mind leaving a few gods in my universe, but it's always good to examine assumptions, eh? And different assumptions make for new, different stories, and there can never be too many new stories. I am now $620 poorer and officially enrolled in CS 260. The Dean of the College of Engineering looked at my form and asked me when I'd graduated from Columbia; turns out he went there too, just barely before I was born. There were some kids ahead of me in line at the UC Extension office who were trying to get the cashier to let them pay the exorbitant fees next week after their "refund checks" (tax refunds this early?) came in. The cashier was not sympathetic. They bailed out of the line and stood around griping at each other. I suggested post-dated checks to one of them, but didn't stick around to see what the cashier thought of that idea. Stayed up until 4 AM talking about our Shadowrun campaign with Shweta. It was loads of fun; unfortunately, now I'm gonna be tired all day. I've edited the lightsaber spell a bit, it was too wimpy and too draining. Sumana comments on a previous entry: I realized upon the third reading that he did not mean to speak directly to a person named "Furrfu." Well, of course I didn't! That was what the link on the word was for, to explain the meaning of the word...).
http://www.panix.com/~zackw/exbib/2002/
CC-MAIN-2014-15
refinedweb
25,999
71.04
One of the strengths of the Django framework is its emphasis on the Don't Repeat Yourself philosophy. From Wikipedia: "The philosophy emphasizes that information should not be duplicated, because duplication increases the difficulty of change, may decrease clarity, and leads to opportunities for inconsistency." This approach has many advantages in web development, avoiding a great deal of the redundant and tedious HTML editing that often must be done on static sites. One way that Django truly shines in facilitating the implementation of DRY is in its URL handling. In traditional static HTML authoring, the URL is defined by the filesystem. If a directory changes for any reason, every HTML file that contains a link to that resource must be edited with the new URL. Even in small sites, this can quickly eat up a developer's time and generate a lot of frustration. It's easy to fall into the trap of handling Django sites the same way, hardcoding links to views in templates and models. After creating URLs in your urls.py file, it's tempting to simply add links in your template to "/my/url/" and absolute URL methods in your models.py that look like return '/%s/%s/' % (self.attribute, self.other_attribute). If you ever want to change the URL, however, the pain begins. You must go through each template and model to hand-change all of the links you included in your code. Say hello to hours of mindless manual labor! Permalinks Luckily for us, Django provides some excellent tools to completely avoid that kind of tedious nightmare and make our URLs DRY compliant throughout our applications. The first and most commonly used of these tools is the @models.permalink decorator that can be used in your models.py files. This is covered in Django's excellent documentation site here. This works very well in conjuction with named URL patterns, which is how I will be using it in the examples below. The @models.permalink decorator allows you to reference a view as the target for a link generation method (such as get_absolute_url) in your models. Django automatically determines the URL to the view based on your current urls.py, and if your URL patterns change the link generated by this method changes with them. Examples are often the best way to describe a concept, so I'm going to jump into a demonstration of this in a quiz application I recently worked on. My URL to a view of a quiz model looked like this: url(r'^(?P<category>[w-]+)/(?P<date>[d-]+)/$', 'quiz', name='quiz'), In my quiz model, I have the following method to generate an absolute URL to the quiz: @models.permalink def get_absolute_url(self): return ('quiz', [str(self.category.slug), self.created.strftime('%m-%d-%Y')]) In this example, self.category is a ForeignKey pointing to a category object. I passed positional parameters in this example, but if you'd like you can pass keyword parameters as well. Details are in the aforementioned documentation entry. Once you've created your permalink, you can take advantage of it in your templates whenever you need to link to the standard view of a quiz item. You can simply call the item's method in your template like this: <a href="{{ quiz.get_absolute_url }}">{{ quiz.title }}</a> You can handle other scenarios with multiple permalinks in your model. For example, in the same application I also created a permalink to the results view for a quiz. @models.permalink def get_results_url(self): return ('results_quiz', [str(self.category.slug), self.created.strftime('%m-%d-%Y')]) I call this in the template the same way. <a href="{{ quiz.get_results_url }}">{{ quiz.title }}</a> The URL Template Tag Permalinks should be able to handle the majority of the links in your site. There are cases, however, where this will not meet your needs. This is most commonly encountered in your site navigational menus. Often you will want to have a link that simply goes to the index view for a particular app. In many cases, there won't be a way to accomplish this through model permalinks. Django comes to the rescue here with a template tag for generating absolute URLs based on views, documented here. In my main navigation for the site housing the quiz app, I have a link that looks like this: <a href="{% url quiz_index %}">Quizzes</a> This generates a link to the desired view, using the URL pattern named 'quiz_index'. This tag has some limitations however, which Jeff Croft illustrated in a post here. It's definitely a good idea to carefully consider each usage of this tag, and only utilize it when necessary. The reverse() Utility Function If you need functionality similar to the URL template tag in your views, you can use the reverse() function, documented here. I've not had the opportunity to use this function much so I don't have an example here, but it is another tool that Django provides to make dynamic URL schemes possible. Hopefully this overview has been helpful in learning how to put the DRY philosophy to work for you using Django. If you have suggestions or questions, please feel free to leave a comment below.
http://konkle.us/20081121djangos-dynamic-urls/
CC-MAIN-2017-17
refinedweb
872
54.93
, Trying to tune alignment of xtick labels. I have the following for my lables === import matlplotlib.pyplot as plt x_dat = [1,2,3,4] x_label = ['$\mathrm{nn}$' , '${}^2\mathrm{H}$', '${}^4\mathrm{He}$', '${}^4_{\Lambda\Lambda}\mathrm{He}$'] plt.xticks(x_dat,x_label) === you can see I have both superscripts and subscripts (and sometimes none) on these labels. Try as I might, I can not figure out how to get these to align how I want (I have tried all the options from verticalalignment=option in the plt.xticks() command. If LaTeX were rendering such fonts (in a TeX document), it would align the bottom of the characters, and then place the super and sub scripts accordingly. It seems that matplotlib is creating a bounding box around each label, and then aligning according to the top, bottom or center of the corresponding bounding boxes. Is there a way to get the alignment to work according to my above description (the LaTeX way)? If it involves fine tuning the position of each label - could someone demonstrate a simple example of how to set the positions individually? I am using the mathtext (there are issues I have had trying to get latex to work with my current set up, which I am still working on, but aren't sorted out yet). Thanks, Andre > From: Andre' Walker-Loud [mailto:walksloud@...] > Sent: Thursday, June 21, 2012 22:19 > > Hi All, > > Trying to tune alignment of xtick labels. [...] > Try as I might, I can not figure out how to get these to > align how I want (I have tried all the options from > verticalalignment=option in the plt.xticks() command. [...] Does the following do what you want? plt.xticks(x_dat, x_label, va='baseline') plt.gca().xaxis.set_tick_params(pad=16)
https://sourceforge.net/p/matplotlib/mailman/message/29441496/
CC-MAIN-2018-17
refinedweb
293
62.27
This is the first post in a series to take you through my learning experience to using the Windows Azure service bus. The Service Bus is a concrete implementation of the service bus pattern designed to operate at Internet scope within highly-scalable Microsoft data centers as a constituent of the Windows Azure platform. The Service Bus provides a federated identity and access control mechanism through Access Control, a federated naming system, a dynamic service registry, and a robust messaging fabric capable of overcoming the internet and distributed services connectivity. The internet challenges that any distributed service platform face are summarized in the below diagram. The way that the service bus overcomes these challenges is by implementing a relay service pattern as below.. A central component of the Service Bus messaging fabric is a centralized (but highly load-balanced) relay service that supports a variety of different transport protocols and Web services standards, including SOAP, WS-*, and even REST. The relay service provides a variety of different relay connectivity options and can even help negotiate direct peer-to-peer connections when possible. So in this article I will show you how to develop your first hello service hosted on the service bus. The major steps can be summarized as below. Step 1: Create a new service bus namespace on the Azure service bus. Step 2: Implement the service and client. Step 3: Configure the service and client to use the required relay binding configuration. So as you can see it is as easy as 1, 2, and 3. Or is it?! J Step1: Create a new service bus namespace So you need to go to the URL: that will request you either to login using a live ID that has already an active Azure subscription or to sign up. If you already have an account then just logon, or if not you can click sign up. That would lead you to the purchase screen of subscription options, study your options well and pick whatever type you want or (even better) click on the FREE trial. Then you will be asked to login using an existing live ID then you will need to go through three steps as below: Then in the third step you would need to enter a credit card just as a form of verification and voila you have a three month trial subscription on Azure. Next logon to your management portal using you live ID on the URL: it should look something like this. Now to create a new namespace do the following steps. · Click on “Service Bus, Access Control & Caching” from the bottom left. · Then click on “Service Bus” · Enter the namespace name and the portal will check if it is available or not for you and select the needed details as below: · Click “Create” and the namespace would be ready to use. · Now we will need three details to get started, the service hosting URL, the secret issuer name and issuer secret. The service hosting URL would be dependent on the namespace you already created so for the shown above example the URL would be:. · To get the secret details click on the created namespace. · Then scroll the right action pan all the way down and click on “View” for the “Default Key”. · It will then give you the option to copy both the issuer name and the issuer secret to the clipboard. Do this one by one and keep this information were you can use it later. Step 2: Implement the service and client This is a straight forward step. Just create two console applications, one for the service host and another for the client and create a service definition as below. [ServiceContract] public interface IHelloServiceBus { [OperationContract] string SayHello(string name); } Listing 1: Service Contract public class HelloServiceBus : IHelloServiceBus { public string SayHello(string name) { string greeting = string.Format("Hello {0}!", name); Console.WriteLine("Returning: {0}", greeting); return greeting; } } Listing 2: Service Implementation static void Main(string[] args) { Console.WriteLine("**** Service ****"); ServiceHost host = new ServiceHost(typeof(HelloServiceBus)); host.Open(); Console.WriteLine("Press [Enter] to exit"); Console.ReadLine(); host.Close(); } Listing 3: Host Implementation static void Main(string[] args) { Console.WriteLine("**** Client ****"); Console.WriteLine("Press <Enter> to run client."); Console.ReadLine(); Console.WriteLine("Starting."); ChannelFactory<IHelloServiceBus> channelFactory = new ChannelFactory<IHelloServiceBus>("webRelay"); IHelloServiceBus channel = channelFactory.CreateChannel(); for (int i = 0; i < 10; i++) { string response = channel.SayHello("Service Bus"); Console.WriteLine(response); } channelFactory.Close(); } Listing 4: Client Implementation Now we need to configure both the client and service to use the service bus bindings. Step 3: Configure the service and client to use the required relay binding configuration All you need to do is to put the proper Azure service bus configuration. But before you do that how would the service and client implementation know where to get the binding implementation from? You did not add any custom references, right?! So here is how. · Make sure both the client and service is using the .NET 4 profile (not the client profile). · The go in Visual Studio to tools and then extension manager: · Click on line gallery and search for “NuGet” · Click download and hence install the NuGet Package Manager. · Close the extension manager. · Right click on the references node for the service project and click “Manage NuGet Packages”. · Click online. · Search for “Azure” and select the “Windows Azure Service Bus” and click “Install”. · Install the same NuGet package to the client project. · Now that you have the Azure assemblies in place you can change the service and client configurations as below. <system.serviceModel> <services> <service name="Service.HelloServiceBus"> <endpoint address="" behaviorConfiguration="sharedSecretClientCredentials" binding="ws2007HttpRelayBinding" contract="Service.IHelloServiceBus"/> </service> </services> 5: Service Configuration <system.serviceModel> <client> <endpoint address="" behaviorConfiguration="sharedSecretClientCredentials" binding="ws2007HttpRelayBinding" contract="Service.IHelloServiceBus" name="webRelay"/> </client> 6: Client Configuration Now you are ready to start the service and (wait for it to properly start, as it take some time – couple of minutes or so) the client and watch them communicate through the Azure service bus. Final Notes During this exercise I tried many bindings and I must say that the most reliable one I used was the “ws2007HttpRelayBinding” (I mean reliable from the perspective of being able to start hosting the service with no problems). Hosting a service behind a proxy (specially a proxy that requires authentication) is not supported and does not workL. Check this URL:. Do we need to have seperate service for this? that is like a third project? It’s nice travel service. Farebucket provides great discounts for">online bus ticket booking, we have professionals who have the inside knowledge of the destinations on Online Bus Ticket Booking.
https://blogs.technet.microsoft.com/meamcs/2011/12/23/my-hello-azure-service-bus-wcf-servicestep-by-step-guide/
CC-MAIN-2019-04
refinedweb
1,106
55.03