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
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. XlsXcessive - XLSX Generation Library Introduction XlsXcessive provides a Python API for writing Excel/OOXML compatible .xlsx spreadsheets. It generates the XML so you don't have to and uses the openpack library by YouGov to wrap it up into an OOXML compatible ZIP file. Creating a Workbook The starting point for generating an .xlsx file is a workbook: from xlsxcessive.xlsx import Workbook workbook = Workbook() Adding Worksheets The workbook alone isn't very useful. Multiple worksheets can be added to the workbook and contain the cells with data, formulas, etc. Worksheets are created from the workbook and require a name: sheet1 = workbook.new_sheet('Sheet 1') Working With Cells Once you have a worksheet you can add some cells to it.: sheet1.cell('A1', value='Hello, world') sheet1.cell('B1', value=7) sheet1.cell('C1', value=3.14) sheet1.cell('D1', value=decimal.Decimal("19.99")) Strings, integers, floats and decimals are supported. You can also add cells via row index and column index.: sheet1.cell(coords=(0, 4), value="Added via row/col index") This is useful when iterating over data structures to populate a sheet with cells. Calculations With Formulas Cells can also contain formulas. Formulas are created with a string representing the formula code. You can optionally supply a precalcuated value and a shared boolean flag if you wish to share the formula across a number of cells. The first cell to reference a shared formula as its value is the master cell for the formula. Other cells may also reference the formula.: formula = sheet1.formula('B1 + C1', shared=True) sheet1.cell('C2', formula) # master sheet1.cell('D2', formula) # shared, references the master formula Cells With Style The library contains basic support for styling cells. The first thing you do is create a style format. Style formats are shared on a stylesheet on the workbook.: bigfont = workbook.stylesheet.new_format() bigfont.font(size=24, bold=True) Once you have a style format you can apply it to cells.: sheet1.cell('A2', 'HI', format=bigfont) Other supported style transformations include cell alignment and borders.: col_header = workbook.stylesheet.new_format() col_header.align('center') col_header.border(bottom='medium') Adjusting Column Width It is possible to adjust column widths on a sheet. The column width is specified by either number or index.: # these are the same column sheet1.col(index=0, width=10) sheet1.col(number=1, width=10) TODO: Referencing columns by letters. Merging Cells Cells can be merged together. The left-most cell in the merge range should contain the data.: from xlsxcessive.worksheet import Cell a3 = sheet1.cell('A3', 'This is a lot of text to fit in a tiny cell') a3.merge(Cell('D3')) It's Time To Save Your Work You can save the generated OOXML data to a local file or to an output file stream.: # local file save(workbook, 'financials.xlsx') # stream save(workbook, 'financials.xlsx', stream=sys.stdout) Future This is certainly a work in progress. The focus is going to be on improving the features that can be written out in the .xlsx file. That means more data types, styles, metadata, etc. I also want to improve the validation of data before it is written in an incorrect manner and Excel complains about it. I don't think this library will ever be crafted to read .xlsx files. That's a job for another library that can hate its life.
https://bitbucket.org/chmullig/xlsxcessive
CC-MAIN-2018-17
refinedweb
588
59.9
August 2011 By Darryl Gove "The nicest thing about standards is that there are so many of them to choose from." Computer Networks, 2nd edition, page 254, Andrew S. Tannenbaum System header files define many functions that a program can make use of. The functions that are available, and the way that these functions are declared, depends on the standards that are in force at the time of compilation. It is possible to get compile time errors if the source code relies on a function that is either unavailable under a given specification or has a different declaration. This paper discusses how developers should write and compile programs that depend on functions defined by the many standards supported by Oracle Solaris. The program shown in Listing 1 will compile using the C compiler but not with the C++ compiler.Listing 1: Example Program The C++ compiler reports the error message shown in Listing 2.Listing 2: C++ Error Message The error message complains that a void* pointer is being passed to a function that is expecting a char* parameter. In C, a void* pointer is compatible with a char* pointer, so the C compiler compiles the code without complaint. If the function func() prototype had specified the variable addr as being int*, the C compiler would also have emitted a warning. The definition from the man page is shown in Listing 3. This matches the way it is used in the code from Listing 1.Listing 3: Man Page for mmap The source code matches the man page and is, therefore, correct. So the problem is somewhere else. The answer is in how mmap() is defined in the header files. This is shown in Figure 1. Figure 1: Definition of mmap() We can see in the header files that the definition of mmap() is protected by a couple of #define statements. We get the definition that matches the man page if _XPG4_2 is defined or if _POSIX_C_SOURCE > 2 is true. But we don't get the matching definition by default. Oracle Solaris documents its support for standards under standards(5). The supported standards are shown with the "feature test macros" in Table 1.Table 1: Supported Oracle Solaris Standards The feature test macros should defined in by the developer to indicate which standard the source code conforms to. The POSIX and X/OPEN standards require that the developer specify the standard that the source code adheres to. This is the reason that the code shown in Listing 1 gets an error message from C++. The default standard for Oracle Solaris 10 is the System V Interface Definition v3 (SVID3), so the definition of mmap() from the header files uses caddr_t rather than void*. The POSIX standard states that a strictly conforming application "for the C programming language, shall define _POSIX_C_SOURCE to be 200112L before any header is included." The other observation to make is that all the standards specify a C compiler, not a C++ compiler. The C++ compiler is not mentioned in the POSIX standards, and the POSIX standards are not mentioned in the C++ standards. Where this can become complex is in the use of the C++ Standard Library, which might be built assuming a particular POSIX standard. The consequence of this is that it is possible for there to be a conflict between the requirements of the application and the requirements of the Standard Library. However, these conflicts are typically resolvable, and the resolution would be in the function prototypes and the availability of certain functions. Table 1 shows the feature test macros that need to be defined in order to conform to the interfaces defined in the various standards supported by Oracle Solaris. Selection of a particular standard causes the header files to provide only the interfaces defined in that standard. As an example of the problems that this might cause, the program in Listing 4 relies on the availability of the function gethrtime(). This code will not compile if either the POSIX or X/Open feature test macros are defined. This is because the gethrtime() function is not defined by either standard and, therefore, it is considered an extension to the standards. The failed compilation is illustrated in Listing 5 where the code is compiled with _POSIX_C_SOURCE, indicating adherence or conformance to the POSIX.1-1990 standard. gethrtime()Is Not Available when Compiled to POSIX.1-1990 Standard To compile code that uses extensions to the standards it is also necessary to define __EXTENSIONS__, as shown in Listing 6. Be aware that defining __EXTENSIONS__ includes prototypes for all extensions not defined by the standards. One useful compiler option is the flag -H. This tells the compiler to report the header files that are included in a compilation. An example is shown in Listing 7. -Hto Output a List of Included Header Files The C++ standard defines a number of header files that are equivalent to the C header files. For example, the C++ header file <cmath> is equivalent to the C header file <math.h>. The principal difference between the two header files is that the C++ standard specifies that the functions declared in the header files should be placed into the std namespace. Listing 8 shows an example program that calls the sin() and cos() functions. The code in Listing 8 can be compiled with both the C and C++ compilers. However, when the C <math.h> header is replaced with the C++ standard header <cmath>, the code no longer compiles with the Oracle Solaris Studio C++ compiler, as shown in Listing 9. <cmath> The errors occur because the functions sin() and cos() are placed in the namespace std. This means that they are inaccessible without additional declarations. There are three ways to fix the problem: std::to every use of the functions, to indicate that they will be found in namespace std. For example, sin()becomes std::sin(). The explicit qualifier std::ensures that no other function called sinwill be used for this reference. sin()can be explicitly placed into the global namespace by declaring using std::sin;after including the header. Using this, the standard function becomes visible by normal name look-up. using namespace std;can be added at global scope to tell the compiler to search namespace stdfor names. This is not a good solution for real applications because it places every declaration in namespace stdinto the global namespace, which might introduce conflicting definitions. Note that the original code might compile without error when built using other compilers. This is because not all compilers follow the rule in the C++ standard that the <cyyy> headers place names from <yyy.h> only into the namespace std. Oracle Solaris supports a large variety of standards. If an application requires a particular implementation of the POSIX standard, that requirement needs to be indicated by the definition of the appropriate feature test macros before the header files are included. In the absence of these definitions, the compiler assumes that the code adheres to the interfaces defined in SVID3. If an application is coded to a particular standard, but it also uses interfaces that are extensions to that standard, the feature test macro __EXTENSIONS__ also needs to be defined. I am grateful for the help of Steve Clamage, Alan Coopersmith, and Lee Damico, who provided comments and corrections.
http://www.oracle.com/technetwork/articles/servers-storage-dev/standardheaderfiles-453865.html
CC-MAIN-2014-52
refinedweb
1,223
62.07
Hi Eric, [...] >>What do you thing of adopting the "lexical rule" terminology already >>used by Flex, instead of "single lexical analyzer"? Here is an >>excerpt of what the Flex manual says: > > > Using that terminology is probably a good idea. > > >>To enforce adoption of the "lexical rule" terminology we could rename >>these macros like this: >> >>define-lex-analyzer -> define-lex-rule >>define-lex-regex-analyzer -> define-lex-regex-rule > > [ ... ] > >>Any opinion? > > > Good Idea. I updated the NEWS file to include your updates and use the new "lexical rule" terminology. You will find a new patch at end. I will work on renaming macros as soon as I can, and post a patch ;-) > As you delve deeper in lexical rule and analyzer construction, do you > think it may be time to create a semantic lex input file? I am not convinced it is a good idea to separate lexer/parser input files. I like to have all that in a single file, it is simpler to handle. There are already a lot of files to take into account when adding support for a new language! [...] > Perhaps mention %keyword in the above 2 paragraphs also? Good point! Done. [...] >>+ %token statements, a simple "%type <type>" declaration should >>+ generally suffice to auto-generate a suitable single analyzer. > > > Is that true? I thought the correct patterns were provided by the > syntax table, and the %token statements just specified a subset of > matched entities. If you provided the right syntax tables, you just have to use a "%type <type>" declaration to generate the lexical rule. For example, to generate a lexical rule to handle symbols, based on regexp match, this suffice: %type <symbol> However you also need to define the lexical token which are <symbol>. The simple case is: %token <symbol> symbol The lexical rule will return (symbol start . end) tokens for each input that matches a symbol syntax. A more advanced case is: %token <symbol> ID %token <symbol> DOLLARVAR "\\`[$]" In that case the lexical rule will return (DOLLARVAR start . end) tokens for symbols that start with a dollar, and (ID start . end) tokens for all other symbols. The <symbol> syntax is defaulted in the `syntax' property of the <symbol> type. Using regexp to match symbols is also defaulted in the `matchdatatype' property of the <symbol> type. [...] > Excellent new news. After you rename things and update this, it will > probably also get a home as the intro for writing lexical analyers. Good idea! Thanks for your help. David Index: NEWS =================================================================== RCS file: /cvsroot/cedet/cedet/semantic/NEWS,v retrieving revision 1.15 diff -c -r1.15 NEWS *** NEWS 9 Jan 2004 03:08:18 -0000 1.15 --- NEWS 21 Jan 2004 15:14:39 -0000 *************** *** 69,86 **** ***' --- 69,95 ---- *** Macros to easily build custom lexers. `define-lex' ! Define a new lexer as a set of lexical rules. `define-lex-analyzer' ! Base macro to create a lexical rule. ! ! A lexical rule associates a PATTERN to an ACTION. ! ! A PATTERN describes how to match data in the input stream, with a ! combination of regular expressions and strings. ! ! An ACTION is a set of arbitrary Emacs Lisp statements executed when ! the input stream matches the corresponding PATTERN, typically to push ! a new token on the lexical stream. `define-lex-regex-analyzer' and `define-lex-simple-regex-analyzer' ! Create lexical rules that match a regexp. `define-lex-block-analyzer' ! Create a lexical rule for paired delimiters blocks. ! *** A set of useful lexical rules is predefined. `semantic-lex-beginning-of-line' `semantic-lex-newline' *************** *** 265,270 **** --- 274,299 ---- Language specific human written code must call the automatically generated setup function. + *** Auto-generation of lexical rules + + The new %type statement combined with the use of %token and %keyword + statements permits the declaration of a lexical type and associates it + with patterns that define how to match lexical tokens of that type. + + The grammar construction process can benefit from the %type, %keyword + and %token declarations to automatically generate the definition of a + lexical rule for each explicitly declared lexical type. + + Default values are provided for well known types like <keyword>, + <symbol>, <string>, <number>, <punctuation>, and <block>. Those types + assume that the correct patterns are provided by %keyword and %token + statements, a simple "%type <type>" declaration should generally + suffice to auto-generate a suitable lexical rule. + + It is then easy to put predefined and auto-generated lexical rules + together to build ad-hoc lexical analyzers. Examples are available + among the grammars included in the distribution. + *** Bovine grammar A file FOO.by will create the file FOO-by.el, and FOO-by.elc
http://sourceforge.net/p/cedet/mailman/message/6645131/
CC-MAIN-2014-15
refinedweb
757
57.57
- SUSv3 reference headers - automatic C indenting - byte to integer - switching on strings in standard C - struct pointer to a 2D array - what is regular expression - problem z prostym prgramikiem ;p - Eigenvector routine.... - lint - Earthquake Forecasting Program July 11, 2005 - Playing Music - x rated news room - memory alignment - LFS for Windows apps - Coping with underscore decoration conventions - gcc: pointer to array - mutable data structures - What is Expresiveness in a Computer Language? - C, C++ and C# Forums - Error handling - How would you write it? - First statement always evaluated first? - Is an address change possible by "deconstify/const_cast"? - malloc and memory leaks - Is this the correct?! - a question about multilist in c - HTTP header parsing library - Linking a C++ library to a C program. - Two's complement integer divided by Powers of 2 question - Bizarre experience at the abortion clinic. - Memory Allocating problem - Need some explanation - Checking pointers - UCN and Unicode - How does strtok works? - representation of an escape sequence - qualified and unqualified types - Trigraph sequences - storage for argv - why function like macro doesn't work here? - why function like macro doesn't work here? - Problem with character string loop and strlen() - Clarify atol statment - Are foo[bar] = "" (at declaration) and memset (foo, '\0', bar) the same? - mmap parsing... - Is it the same? - Software Patents - SGI: Need Something like 1 Mutual Exclusion Semaphore for Multible Programs - ISO C jpeg/png/etc lib - Optimized code for finding string length - advanced c programming - Running time calculation - multilist data stracture sample code - Give some ideas for c Optimzation - overloading in c - Time command - Certificate for C Programmer - Using a union to get different representation - Implicit addition of const qualifiers - In a timeline pinch (Suspense: 25Jul05) pleading for assistance - Q1 - How to check file exist using c language - Hardware Programming - Historical variable place - abt time functions - how to compare - about char pointer - Need help with SHA1 - Palm programming in C using GCC - Help w/ "incomplete type" error - Running time of program - Interacting to Internal Modem - How to set a ms access password? - char * and int * - Byte Alignment of Character to 2 byte - Can anyone tell me where to find OCR? - Funny old trick - Implementing Unicode - strto[u]l and ERANGE - setting MAX characters emitted in printf() functions? - accuracy of mathematical functions - Read n bytes from file - float algorithm is slow - evaluate this - How to verify username and password in Visual C - Initializing enum with strings - Modify it ! - Server listening on 2 differents ports - programming style: while(TRUE), for(;;), ...? - sizes of bit fields - Multi says "incomplete type is not allowed" - ON Linux Platform: How can we build binaries for another architecture from 0x86 architecture - If forget to fclose() after fopen(), is there any testing tool who can detect it automatically? - simple c/c++ programming question about encryption - C Primitive Data Type Sizes - Help needed in solving this problem - Preprocessor Directives - will the memory allocated by malloc get released when program exits? - EOF in C - C/C++ DataType for DB2 DECIMAL(18,3) - Makefile question - multi-type - System/ Compiler specific macros - Linked list - Linked list - Access to data into an array causes seg-fault - Code Effect - anybody have star wars: revenge of the sith of War of the Worlds - testing whether a double is a whole number - case label does not reduce to an integer constant - Permutations on binary strings - again some incr/decrement question - some very simple increment/decremant operator question - C Program [ Turbo-C ] , to extract only-Printable-characters from a file ( any type of file) and display them ( i.e equivalent to "strings" command in UNIX) - C Program [ Turbo-C ] , to extract only-Printable-characters from a file ( any type of file) and display them ( i.e equivalent to "strings" command in UNIX) - pointer to pointer question - Hiding that string in the compiled code - [Help] Program crashes/seg-faults on strcpy(). - Multiline strings - coloured text... - pix - Why C++ Questions on a C List - Inverse Functions in Math - == operator on struct - String appending - Linked list in C - Reading from file into struct array / memory layout - How to check for already running program? - printf("%#04x\n", 0); print 0000 not 0x00 - Need to write putchar for embedded system - How To Make Your Own Variable Type? - How to make binary data portable? - why use -> (not .) with pointers? - #defines and strings - reading a line through scanf - Object persistence in C - casting to unsigned char for is*() and to*() functions - Programming Contest: Fit pictures on a page - Reading Lines with Fgets and a bit of C++ {Novice Programmer} - C directives - Floatin point issues - conditional statements - what's wrong with atof() and casting? - lint - Aliasing/Torek's strtod() experience - Aliasing/Torek's strtod() experience - fast multiple file access - openssl and DES - bizarre malloc problem - Array subscripting overflow behaviour - Libraries, function names and link - gcc iso90 and long long - Array name and address of the first element - graphics in Linux... - Is an empty translation unit valid? - ANSI C Compilation linking problem - reading from a file, some times values in file may not be filled - memory delete problem - test - sharing data from DLL - bits comparison - Interface - parameters or stdin - C and Tk - why do I have "file size exceed" problem? - fscanf problem - Tool to trace function calls - Differences between Functio & Macro in C - About c++ - "basic" pointer question - XML serialization of structures - Standard way of dealing with directories - hiding structure members - endof - padding granularity - Finding Repeated and Missing Numbers - Internal representation of char == unsigned small int? - Default arguments - Functions with variable arguments - read 32 bit value into 64 bit variable? - Microsoft Visual C++ 6.0 - New File - how to ask gcc to link with older library ? - constructing own error functions vs something like fprinf() - What about a C compiler with structured data management INSIDE ? - Implementing my own memcpy - Data Structure - nested while - how to go to the beginning of the first while? - A biiiig break ? - realloc, copy and VM - printf() with too many args -- legal? - compiler unable to find defn. of sin() - static function declaration in header file - Convert hex string to struct - URL+JPEG+MPEG+P2P blocking - Memset Optimizing - C preprocessor - Using macros as function_names (for compiling different function_names with one C-Code via a compile flag) - Hmmm, It's Curious - The C execution character set - C software achitecture - how to let gcc warn me when I use = in conditions - GNU MP (gmp) implementation documentation - What does it mean ? - code not working properly - Trimming whitespaces - Reason for the Format - Origin of size_t? Curious. - how come such code can compile? - the usage of void argument - Question - How to calculate the inverse of normal distribution using "C" ? - Endianness - Return type of main() - Writable strings - malloc_consolidate - Does wrong format specifier leads to memory corruption? - smallest positive double number - Regardng algo book - A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... - string comparison - C code for converting IBM/370 floating point to IEEE 754? - seeking in binary files - program artichecture extractor tool - passing pointers - Enlarge the stack size in gcc ? - C calling conventions - Portability - Getting path of a shared object from inside it - formatting output in the form of table - Char difference between C90 and C99 - How does malloc align pointer - How to parse ? - Printing offset of a member of structure - Enumatrators And Macros - Problem while transferring mail ids from MS-outlook to the application - Socket programming problem: can't generate output in server socket - How to convert from Ticks to date&time? - large program data structure - reading Java floats from C - Issue related to system() call and file handles. - How to convert from Ticks to date&time? - Undefined behaviour when modifying the result of an assignment operator - malloc(0) - Why it is not an lvalue ? - uchar -> void* -> uchar - references/addrresses in imperative languages - hi - Removing dead code and unused functions - simple question regarding 5.5 of Ritchie & Kernighan - Hundreds of cases in a switch, optimization? - void *malloc(size_t num_bytes); - perror question - Proper use of scanf - Multiple declarations in differents files - problem with macro - Doubt In Bytes Allocated - Missing file - Heap maintenance and wordsize - quick way to determine the array is irdered? - How to copy a chuck of memory? - typedef help - array questions - conversion of signed integer to unsigned integer - How to deal with time in C ? - Array of bitfields - variables scope - weird function output value problem - Open a file at runtime - Question converting unsigned char [] to int - Implement set for generate data type? - multiple definitions.... - Is this possible? - Cycle with C - cast to volatile - link list question - advantage of C proramming under C - Questions about qsort( ) to sort pointer to struct. - server client question - creating an image file from an ASCII text - Methods to handle filename extensions? - Interpreting CDROM_GET_CAPABILITIES ioctl - Help on warning: non-static const member in class without a constructor - Arithmetic shift operation in C - Converting Little Endian to big endian for a union - Difficulty in understanding the MACRO. - Parse HTML to store it in ROM - padding mechanism in structures - pow(2, 1/2) != pow(2, 0.5) problem - simple tree data struct implementation (beginner) - Function pointer - Printing a NULL pointer - Address on x- byte boundary - C/C++ linkage issues - reg va_next - allocation of local variables on stack - OS/2 Vio* calls in Windows - strsep() function problem, please help - Find C support for NNTP - illegal character - Info about Errors ,warnings..! - Information on Double pointers - how to reset all structure fields to 0 or NULL - Where does fatal() come from? - variable arguments, odd results - Is Both Statement Are Same - libnet - memory allocation and freeing memory - Doubts on C - warning: no newline at end of file - how to define the array of strings - Why does this not work? - 2 dimensional array algorithm question - Unsigned and signed char types - Passing more than value using pointer - struct struct - Plotting the Results - Having problem on printing a string using printf? - Portable way to printf() a size_t instance - database connectivity through C program - sorting 2d arrays using qsort - Why Segmentation fault in malloc( ) after calling several realloc( )? - The 1st Annual Underhanded C Contest - Need recommendation of C library reference book . - difftime problem - Difficulties with passing multi-dimensional arrays - Bloodshed C or Miracle C? - what's the different - Is this valid? - diffrence ?? - struct and typedef problems - question related to sizeof operator - convert dec number to HEX and oct and bin without c library function - Union Issue - Memories - puzzle - fgets() question - XML creation in C - sizeof() style question - adding in ascending order in double linked list - The status of C - define a string - sscanf() question? - efficeincy ( Am I correct ?) - reading first line of a txt file with c - macros - overloaded functions in C - HELP! - time function problem?? - printf justification of printed values - What Happened to bioskey? - C style casting - Is there a better way for scanf? - a value change, why - Array problem - [Mysql Api] Problem with tables listing - transfer from ASCII to int - Pointer - trouble in freeing memory using realloc - What's the best algorithm for it in C - Global Variables in DLLs - double linked list delete problem - nebie : what is the problem with this one? - C program to automatically press F6 every few seconds - Comma operator - table of function calls: need sample code - The strange speed of a program! - read writte to file - Book about data structures in C - Automatic generation of function's uses and dependences (graph representation) - bsearch/qsort problem for effective_dated search non-exact - Easier way to determine if a string is an alphanumeric number? - Hi.. Need immediate help - ANCI C? What is that - a NASA invention? - pure functions - pure functions - help me in port programming - WIRELESS C programming in LINUX question - How to read a part of a string - a make file question - Computation slow with float than double. - Copy by value symantics - Checking endianess in compile time - How to parse the line - How to read data from an excel file by C? - Is it that bad to initialize global variables at outside? - Dynamic char* allocation, malloc and free. - i want to learn c language - Links of C code puzzles - is variant-length array declaration standard compatible? - what's this mean .count = ATOMIC_INIT(n), ? - Calling function name - pointer conversion - how can i get the address of buf which defined as char buf[] = "abcde"; - SIZE_MAX under c89 - Underflow and floating-point math - Pass pointer to double array as func. parameter - Round Number - String concatenation function, request for comments. - What declarations of main exist in the c standard? - Bcc & C - Any quick reference for the difference between C and C++ - selecting the next language - Typedef'ing a function - Typedef'ing a function - Typedef'ing a function - How to test whether strstr() returns a null pointer or not? - Robustify code dealing with input - Function arguments and their size - Why compiler not generating any warning ? - How to store a variable value for more than one executions - why debug step by step, it s ok - New to C - Returning pointer to array problem II - question for char point. - HELP PLEASE - How to convert string to byte array - Why can't you add pointers in c? - What can't you add pointers in c? - I think the question I just posted got lost. - C99 to C89 translator - typedef a matrix - Use disks as large read-write buffer? - overriding functions - enum members namespace clash - C to NASM - lnkflat problem - Problems parsing a flat text file with pointers.. sort of named.conf layout.. - problem with sscanf. - Returning pointer to array problem - rand() related ?? - pointer arithmatic - How to define a common interface between C and JAVA modules - double pointers - When I call malloc() to get some space, I get Segmentation fault - sscanf not working , why? - count of file descriptors - how to make linux makefile work in visual c++? - Help! function declare. - Dynamic library and passing relative pathnames - * * * Please Read And/Or Print This! * * * Press [Ctrl][P] Keys On Your Keyboard To Print >> June 1, 2004 8:23:43 pm >> << * * * * * * * * * - question - One SQL and C question - C string functions - Test - Open source embedded C ; appropiate group? - "comma delimited" numeric output from printf()??? - Bit twiddling - merging list problem - addr2line help required - How to realloc( ) for M[m][n] - File Read help reqd - masks - Criticise my code please. - What's the meaning of this variable definition? - pointers and integers - what's meaning of "warning: initializer element is not computable at load time" - when fflush call is needed? - how to write a makefile? - Swig errors and warnings - Why do I have a core dump ? - mySQL and C question - undefined reference uuid_parse - POPL 2006 Call for Papers - max size for printf() format conversion? - message buffering for logs, sprintf, etc... - Help needed in dereferencing a union - How to interact with Oracle, MS-SQL and Sybase databases using C Language - Some pointer quiestions again - compiling a simple program - multidimensional arrays and pointers - Clear doubts regarding the C++ Runtime - hashtable...squid - typeless data [structures] - Is there a way to write append rewrite a XML Multilingual file - a question about ftell function - read multiple lines of a file - Memory management strategy - Function calls using variables - structure - size of pointer variables - sizeof... - why? - sprintf on MVS - clustering in C - Difference between '\0' and 0 - move bits stream through an array - Formatted IO; %d or %i? - generate a 'call tree' - plz help to solve some problem - plz help to solve some problem - Turbo C(/C++) runtime library source code - How to check file exists. - how to define a function pointer variable witout typdef? - creating child process - Undefined reference to '...' error under gcc - abt variable storage like global static,auto .... - libs and constants - How to pass a pointer to an unknown-size array? - Pointer Question - Getting Excel worksheet names with ODBC - sscanf and int64 in Win32 and Unix - different results? - please check macro - Help for creating a mini OS - string function - How to read .xls sheet from C program? - (void) printf vs printf - using "purify" to check memory leaks - Pointer memory allocation - mixing types promotion etc.. - 1st World Congress on the Power of Language: - Port code from C++ to C? - Querry (Newbe) - String comparison in preprocessor commands - Doubt in Socket Program - howto init 2d structure to zero ? - Function-like macro - how to use scanf()? - fgetc dropping chars - standard operations about string operation - Why wouldn't this line of give give the address of the pointer? - How to determine the local port? - negative array index - Read pixels from a PGM/PPM Image - Using clock() to measure run time - I've forgotten my C: passing 2-D matrices - Get integer bytes order in a compile time - What are OOP's Jargons and Complexities? - Return array of ponters? - Fork question. - Does sizeof(char) always equal to 1? - string generation - Problems with sprintf, need help on this one - getting BCC55 to run - Getting Started in Programming & Scripting - what dose "const char const* var" mean? - question about 'static' definitions - Can't match char 0x10. - Is this a guaranteed signed/unsigned conversion? - find name problem - use of select() - fprintf formatting question??? - realloc() implicit free() ? - WAV file question - structure padding - How to know the number of elements in an static array. - Double precision numbers. - inline functions - union field length mismatch - Telnet client in C - How two check struct size at compile time - DJB hash function - useful tips on how to write your C codes more efficiently - snippet review please - Good C Compiler for Windows..
https://bytes.com/sitemap/f-308-p-99.html
CC-MAIN-2020-45
refinedweb
2,866
51.99
OOPS -- I wasn't supposed to attach that file to that post. I'll try again. :-) Hi guys, We're starting a web site running on mod_python, and we've run into import problems, specifically using from DIR import FILE apache.import_modulewhere DIR is a directory (not a module or package) and file is a FILE.py file. It works with standard Python importing, but now that we have multiple virtual servers, we need to use, but we can't quite. Here's the long gory story: --------------------- Up till now we've just been using the standard import statement, and it's worked fine. But now we're running two copies of our Python code-base on two virtual servers. So there are two files called " code.py" and suchlike in two different directories, and the imports get confused if the two are out of sync. All as the docs explain ... because of how sys.modules is stored without full paths. So I've just been trying to use the new apache.import_module(), but I'm running into various problems because we have multiple directories in our code structure, which looks something like this: code/ code/code.py # main file for mod_python usage, imports everything code/cli.py # command line "test harness" loader code/logic/dbase.py code/logic/errors.py code/handlers/home.py code/handlers/users.py ... # and heaps more files in each of the subdirs "logic" and "handlers" aren't actual packages, so we thought we'd be okay using apache.import_module() on code.py, and all the import statements scattered throughout the code would just work (am I correct in this? if the top-level import uses import_module, the rest will automatically?). code.pyis actually run by modpython_gateway.py, a WSGI wrapper for mod_python that we modified to use import_module instead of __import__. But the problem is that it bombs out on statements like: from logic import errors with "ImportError: No module named logic" I guess this is because logic isn't a file/module, it's a directory. Is this correct? (In .htaccess, I have PythonOption mod_python.importer.path "['c:/www/mpledge/code']" so it definitely knows where to go, but the import statement fallback probably doesn't. It won't help if we set sys.path, because then we're back to the old import problems.) In short, we're wondering the best way forward using mod_python. The options we see are: 1) Only ever run one code base. Non-ideal. 2) Override __builtin__.__import__ with our own one that checks if it's a directory and calls your import_module on the result, e.g., import_module('logic/errors'). Would this work? 3) Write a patch to modpython's import_module that adds that functionality. But I'm guessing there's some good reason it doesn't support this -- is that correct? 4) Change all our import statements to import_module calls. We have a lot of them in different forms, so this would be messy. Particularly because we want it to work in test/command-line mode too. And at the moment with import statements it works just as well from Apache with code.py and from the command line with "python -i cli.py". So we'd have to do if/else conditions around all the imports, for whether it's in cli/test mode or not. 5) Look into FastCGI or something ... but we're not sure we want to go there at this stage. Oh, and one more thing, we're also using Cheetah, so I guess we'll have to change its __import__s to import_module calls too... What do you think is the best way? Thanks for your time! -Ben P. S. Feel free to check out the "early page" for our website (). Hopefully we won't be upgrading mod_python or something when you look. :-) -- Ben Hoyt, +64 21 331 841 -------------- next part -------------- An HTML attachment was scrubbed... URL:
http://modpython.org/pipermail/mod_python/2007-May/023754.html
CC-MAIN-2018-09
refinedweb
657
67.86
Unit Testing code that touches the system Unit Tests should be fast and simple and they should not touch the system. What we mean by touching the system is any code that actually changes the file system or registry of the build system that runs the Unit Tests. Also any code that touches a remote system such as a database or a web server as these remote system should not have to exist during a Unit Test. Unit Test Presentation (using Open Office Impress) Question: So if your code accesses the system, how do you test this code? Answer: You use Interface-based design and a library that can mock that interface. Well, it is not exactly simple. Question: What if you are using some one elses code, such as standard C# libraries in the System or Microsoft namespaces? Answer: Imagine you need to unit test code that touches the registry. You must do the following steps: - Create an interface for accessing the registry that matches Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (and you may have to create an interfaces for each object they need as well). - Create a wrapper that wraps the Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey (again, you have to create a wrapper for each objects they need as well). - Change your production code to use the interfaces and the wrappers instead of using the system code. For example, if dealing with the Registry this involves Microsoft.Win32.Registry and Microsoft.Win32.RegistryKey directly.Don’t use these objects directly, instead you use these objects: SystemInterface.Microsoft.Win32.IRegistry SystemInterface.Microsoft.Win32.IRegistryKey SystemWrapper.Microsoft.Win32.RegistryWrap SystemWrapper.Microsoft.Win32.RegistryKeyWrap - Provide a method in your production code for replacing anywhere you use IRegistry or IRegistryKey with any object that implements the interface. - In your Unit Test, mock any neededIRegistry and IRegistryKey objects. The best solution, long-term, is that Microsoft adds interfaces to the standard .NET libraries and exposes these interfaces so a wrapper isn’t needed. If you agree, vote for this enhancement here: Implement interfaces for your objects so we don’t have use SystemWrapper.codeplex.com However, since Microsoft hasn’t done this, you have to do it yourself. But all of this probably takes more time than your project will allow you to take, so I am going to try to get you there faster. Step 1 and Step 2 are done for you, all you have to do is download the dll or source from here: Step 3 and 4 are not done for you but there are examples in the SystemWrapper project. Step 5 can be done extremely quickly with a free (BSD Licensed) tool called RhinoMocks. So the new steps become these: Step 1 – Download SystemWrapper - Go to and download the latest dll or the latest source. - Copy the SystemInterface.dll and SystemWrapper.dll into your project (perhaps you already have a libs directory). - Add references to these two dlls in your release code. - Add a reference only to SystemInterface.dll in your Unit Test project. Step 2 – Change your code to use Interfaces and Wrappers - Find any place in your code where it touches the system. For example, if you touch the registry, find any place you call Registry or RegistryKey objects or reference Microsoft.Win32. Hint: Use the search feature in your IDE. - Replace the reference with a reference to SystemWrapper and SystemInterfaces. For example, if replacingrRegistry code, SystemInterface.Microsoft.Win32 SystemWrapper.Microsoft.Win32 - For any object that touches the system, change that object to be instantiated using the interface. For example, replace RegistryKey objects with IRegistryKey objects. Step 3 – Allow for replacing the Interface-based objects Create a property or function that allows you to replace the object you are mocking so you can pass in an object that is mocked. Here is an example of how to do this when mocking a RegistryKey object using IRegistryKey. - Implement the IAccessTheRegistry interface from the SystemInterface.Microsoft.Win32 namespace. Here is a sample implementation that uses lazy property injection: #region IAccessTheRegistry Members public IRegistryKey BaseKey { get { return _BaseKey ?? (_BaseKey = new RegistryWrap().LocalMachine); } internal set { _BaseKey value; } } private IRegistryKey _BaseKey; #endregion Notice that the setter is internal. This is because unit tests can usually access an internal method with InternalsVisibleTo. The internal set is hidden for code not in the same assembly and not included in InternalsVisibleTo. Note: You may want to look into the “Factory” design pattern. Step 4 – Download and Reference RhinoMocks in your Unit Test In this step you need to download RhinoMocks and reference it with your Unit Test project. Your release project won’t need it. - Go to and download RhinoMocks. - Add RhinoMocks.dll Step 5 – Mock IRegistryKey in your Unit Test For this, you have to understand and know how to use RhinoMocks and this takes some learning. Instead of trying to explain this here, let’s go straight into the examples. Examples Forthcoming… - Unit Testing Registry access with RhinoMocks and SystemWrapper - Unit Testing File IO with RhinoMocks and SystemWrapper Return to C# Unit Test Tutorial But these situation never(extremely rarely) occurs as we can trust registries and all. Are you trying to be funny?
https://www.rhyous.com/2011/11/04/unit-testing-code-that-touches-the-system/
CC-MAIN-2020-16
refinedweb
865
65.42
this is a similar example to what i have. it's simplified but it still get's the same error. i need to be able to use << operator to print out all information from class A. i have no idea how to do that. i tried casting it as an A object but then it starts telling me that i can do that with virtual functions. is there any way to go around this? #include <iostream> #include <string> using namespace std; class A { public: string name; A(string sName) { name = sName; } virtual void mission(); string getName() { return name; } friend ostream& operator << (ostream& out, A& oA) { out << oA.getName() << endl; return out; } }; class B : public A { public: B() : A("bob") { name = "bob"; } }; int main() { B DUDE; cout << DUDE; // this doesnt work either cout << (A)DUDE; return 0; }
https://www.daniweb.com/programming/software-development/threads/160229/virtual-class-with-friend-functions
CC-MAIN-2017-34
refinedweb
136
80.31
tag:blogger.com,1999:blog-73612237270377115522017-10-15T06:42:42.118-07:00The Oz MixOz Fritz friend Phoebe asked me to write on this topic for research into her next album project.<br /><br />The subject of "home" has always been one close to my heart, there are multiple ways to see it. The old saying, "home is where the heart is," rings true for me. I have a nomadic nature - wherever I go, there I am, so home for me is wherever I'm currently residing; in bardo terms, whatever Chamber currently being passed through. At the moment, I'm on tour - home for me, as I wrote this, is room 47 in the Banfield Motel in Portland, Oregon, but only for another hour. I'm about to upscale to a better hotel downtown, my home is packed and ready to move. <br /><br />At the same time, I see home as a permanent sanctuary space that I have a vague cellular or memetic memory of having once known but can't consciously recall ever having been there. Perhaps this partially explains the nomadic tendencies, a journey through a lifetime to return home, wherever that is. This image evokes the archetypal journey of the Odyssey in Greek mythology, Odysseus's long, perilous journey home after the Trojan war; also the protracted wandering of the Israelites in the wilderness before reaching the Promised Land. Dylan's paradoxical koan-like lyrics: "... no direction home, a complete unknown, like a rolling stone," speak to this feeling as do the lyrics to the Crowley-inspired Led Zeppelin song, <i>Rock-n-Roll</i>. <br /><br /.<br /><br />The passage that first turned me on to Deleuze and Guattari nicely articulates the relationship between music and home. It's the beginning of the 11th chapter in <i>A Thousand Plateaus</i>:<br /><br /><span style="color: cyan; font-family: "timesnewromanpsmt"; font-size: large;">.</span><br /><div class="page" title="Page 333"><div class="layoutArea"><div class="column"><span style="font-size: large;"><span style="font-family: "timesnewromanpsmt";"><span style="color: cyan;"><br /></span></span> </span></div><span style="font-family: "timesnewromanpsmt";"><span style="color: cyan; font-size: large;">II. Now we are at home.But home does not preexist:it was necessary to draw a circle around that uncertain and fragile center, to organize a limited space...."</span></span><br /><span style="font-family: "timesnewromanpsmt"; font-size: 11.000000pt;"><span style="color: cyan;"><br /></span></span></div></div>It seems an interesting paradox that home doesn't pre-exist, but the sense of it does. Most of us have an idea of how to create a home for ourselves; there usually seems an instinctive direction for going home. <br /><br />Drawing a circle around an uncertain and fragile center is also a prime instruction in ritual magick. In ritual magick you learn to create an inner space, a particular mood, of your choosing. This space can be the home space. With ritual magick you learn how to go home by creating a home. It is where? "Ritual is to the inner sciences what experiment is to the outer sciences." ( Robert Anton Wilson from <span style="color: #444444;">a </span>1986 internet chat recently posted by Rawilluination.net). Building a home, going home appears an endeavor of multiple and prolonged experimentation with perhaps many restarts. The fragile and uncertain center can get wiped out like a sand castle on the beach when the tide rolls in, but there's always lots of sand to construct another; memory, the collection of data through personal experimentation, makes it easier and stronger next time around. <br /><br />Hospitality, so important to Sufis, is the art of making the guest feel at home. <br /><br />I hear the communication in the video below coming more from the guitar playing than the lyrics.<br /><br /><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><img src="" height="1" width="1" alt=""/>Oz Fritz Corsaro - High Fidelity Sound Engineer<div style="text-align: center;"><span style="color: cyan;">A Poet makes himself a visionary through a long, boundless, and systematized disorganization of all the senses. All forms of love, of suffering, of madness; he searches himself, he exhausts within himself all poisons and preserves their quintessence's. Unspeakable torment, where he will need the greatest faith, a superhuman strength, where he becomes among all men the great invalid, the great criminal, the great accursed--and the Supreme Scientist!</span></div><div style="text-align: right;">- Arthur Rimbaud</div><br />The Starlight Lounge, that plane of existence where the best musicians and comedians hang out après-vie, finally got their recording and mix engineer of equal calibre. Jason Corsaro left his planetary body two weeks ago at the criminally young age of 58, and he is sorely missed. Jason was to the recording studio what Hendrix was to the guitar, or what Coltrane, Coleman and Davis were to the horn, an innovator of the instrument. In Jason's case, he used the recording studio to produce and invent new means of musical expression. This may sound like hyperbole, but it's not, you can check other testimonials around the web where he's getting similar acclaim (" best engineer ever," says one). The honorific, High Fidelity, doesn't refer to its conventional sense. Jason created his own fidelity, that of an extremely original, high musical aesthetic that evolved and sometimes devolved, but was always different. He had a unique sound that always changed.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><br /><br />Jason was larger than life. Whenever he entered a room, life expanded to accommodate his presence. That was the first thing I learned from him when we met. Jason had the natural, unassuming aura of a star. I didn't spend all that much time with him during a short apprenticeship, but I came away from it loving him like a brother. The longer projects we worked together on, each about a week to ten days, included: The Swans, The Ramones, Ginger Baker, Ronald Shannon Jackson and Stevie Salas. There were some one-offs: a song by L.A. Guns that never saw the light of day, and a few songs by the French group FFF. For FFF, he mixed the most important tracks and I took over the rest. The torch was finally passed on that project and it did very well for the band in France. I also had the great fortune to assist him recording Tony Williams and a group of jazz luminaries.that included Elvin Jones, Sonny Sharrock, Pharoah Saunders and Charnette Moffat. Each and every of these brief tenures is at the top of my list of most intense life experiences.<br /><br />In a beautiful tribute to his friend and former collaborator, Nile Rodgers writes to Jason: "In some way you changed the world." Yes he did. For instance, it was Jason's mixing skills that temporarily promoted drummer Tony Thompson to a job with Led Zeppelin.<br /><br />Mixing live sound for bar bands in the early and mid 1980s, every drummer, without exception, would ask me to make the drums sound like Led Zeppelin's John Bonham's kit. Until, one day in late 1985, the drummer for the bar band Blade Runner requested that his drums sound like the Corsaro engineered Power Station record. This became my first encounter with Jason's influence and ability to change the music industry. With Bonham, you could hang one mic in a stairwell (<i>When the Levee Breaks</i>) and get a huge, powerful, drum sound. The drum sound on the Power Station album started with a powerful hitting drummer but was reached through studio manipulation with Corsaro reportedly punching in and out every reverb move on the drums. After Bonham died, Zeppelin hired Tony Thompson for their Live Aid reunion. You can get a good idea of Jason's drum sound on Robert Palmer's hit <i>Addicted to Love</i>, another Thompson/Corsaro sonic collaboration:<br /><br /><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><br /> Thompson on that recording experience:<br /><br /><span style="color: cyan;">The engineer, Jason Corsaro, took a tube the size of my bass drum and built this tunnel from my bass drum all the way out into the hall and up the stairs. It was this weird thing he hooked up. And it worked. </span><br /><br />Another major contribution Jason made towards changing the world, for better or for worse depending upon your perspective, was recording and mixing Madonna's <i>Like A Virgin</i> album, the record that made her a star. He never once mentioned that to me. <br /><br />My second encounter with Jason was also virtual occurring when Bill Laswell played <i>Cold Metal</i>, the first track off of Iggy Pop's <i>Instinct</i> album, in Platinum Island's Studio East control room. Half of this Laswell produced record was mixed by Corsaro at the Power Station while the other half was mixed by Robert Musso at Platinum Island with yours truly assisting. <i>F</i>rom the opening chord the mix of <i>Cold Metal </i>jumped out of the speakers with its energy, intensity, and excitement and made Musso visibly nervous about reaching that standard. After Bill and company left, as Bob and I began working on the song <i>Easy Rider</i>, Musso lamented that the Power Station studio had beautiful sounding live chambers, how could he match that? I pointed out that we could set up the recording room in our studio as a live chamber and proceeded to do so. A live chamber is any acoustic space configured with amplified speakers fed by an auxiliary send from the mixing desk. This space is miced, often with the mics in a cardiod pattern aimed away from the speakers. These microphones are routed to return channels on the board to make for a natural reverberation chamber that sounds significantly better than even the most expensive digital reverb devices.<br /><br />This was the first time Platinum Island's studio was utilized in this way and the room sounded great as a live chamber. I continue to use this mixing technique to this day. In fact, first on the agenda today when I start mixing the MaMuse record in a couple of hours, is to set up and process tracks through the live chamber at Prairie Sun known as the Waits Room, named for its discoverer as a recording space. It makes for one of the best small live chambers in the world. This room is another studio on the property that's booked up beginning tomorrow so I'll go through all the songs to send the tracks I want processed through the chamber and record them back into the Pro Tools session. I inadvertently rediscovered this "old school" method in response to Musso's concern over matching the intensity of Jason's Iggy Pop's mixes. When Jason started mixing at Platinum Island he used that live chamber all the time.<br /><br />Bob Musso rose to the occasion and produced comparably powerful mixes <i>on </i>his half of <i>Instinct</i>. Corsaro's work motivated Musso to reach a higher level in a similar way that Hendrix's guitar virtuosity spurred Noel Redding and Mitch Mitchell to play beyond their capacity in the early Jimi Hendrix Experience. <br /><br />Jason didn't seem particularly keen about sharing his engineering techniques with anyone outside of the sessions yet, as others have also observed, he was very generous about passing on his knowledge and taking proteges under his wing. The last day of the first project we worked together, The Swans - <i>The Burning World</i>, Jason turned me loose to mix the two alternate acoustic tracks giving a short mixing lesson in the process. I feel it's historically important to the recording community to share some of his techniques and approaches to sound engineering in the same way as it is examining the methodology of any great musician. No one can take his place and achieve the same results, you would have to be Jason to do that, however, his mixing style can inspire creative, outside-the-box sonic artistry.<br /><br />Here's a few things I learned from him. In retrospect, some of these appear quite obvious, but they were revelations to me at the time, and in this day and age where a high percentage of musicians are also amateur engineers, I expect these tips will be useful.<br /><br />1. Remember who you are and what you can do. Bring your full presence of attention and confidence in your ability into the space. Radiate this confidence like a star. If you don't feel confident, fake it.<br /><br />2. Process effects. Most, nearly all, engineers I assisted prior to Jason would return their reverbs, delays etc. straight back into the board. On a regular basis, Corsaro would EQ, compress, gate and route effects into other effects sometimes daisy chaining four or five different processors together to come up with something previously unheard of in this space/time continuum; detune the live drum chamber, add a dash of chorus, flange or phase shifting to a reverb, etc. Something as simple as low passing a reverb return (i.e. rolling off the high frequencies) can make a big difference. Darker reverbs sound more natural. I wish I had saved all the recall notes for Jason's sessions to give specific examples.<br /><br />3. Be fully present in the moment. The moment that the mix is being printed is when the invocation is landing into a corporeal form; when it assumes a morphology taking a material shape. As much as possible, Jason would make the creation of the mix a live event. After getting all the sounds and setting up a balance of the tracks, he would assign all the major food groups (drums, bass, keys guitars, vocals etc.) to the eight subgroup faders in the middle of the SSL console. Then he'd mix the song in one pass as a live performance. He might do a few or several passes, like a guitar player trying to nail the perfect solo, but, in my experience with him, it was always the whole song in one go. He wasn't the type of mixer to work on tweaking a section one fader at a time before moving to the next section. Not to say that he wouldn't embellish and tweak this first basic pass, but the idea was to do the whole thing at once, to create a live mix performance in the studio.<br /><br /><div style="text-align: left;">A great example to hear that is the aforementioned Iggy Pop song, <i>Cold Metal</i>. Jason told me that just when that track was going to print, the SSL computer automation broke down and wouldn't work. All the sounds were set, everything was routed to the central subgroup faders so Jason mixed it live to the two track mixdown recorder. When working in this fashion, you are mixing from the heart and soul - intuitively and on the fly. There isn't time to mentally think about getting everything in its "proper" place. Any great artistic creation bypasses the rational mind and its worries, concerns and editorial censorship. The guitar solo in <i>Cold Metal</i> is slightly inside the track, a little lower in volume level than where you'd commonly place a solo, but the energy and excitement of the track is undeniable. It's the only song from <i>Instinct</i> that made it onto an Iggy Pop Greatest Hits compilation. Contrast that with the guitar solo level in another Corsaro mixed song from <i>Instinct</i>, <i>Strong Girl</i> which sounds a little louder than your average solo. There's a couple of syncrhonicities going on here. First of all, the album is called <i>Instinct; </i>Jason mixed from instinct and intuition - heart and soul, not from his rational mind. The first line in <i>Cold Metal</i> is: "I play tag in the auto graveyard..." - the SSL computer automation was in the graveyard when Jason materialized that mix into the world.</div><div style="text-align: left;"><br /></div><div style="text-align: left;">4. Mix as if it's life or death. This seems the difference between an artist attempting to create something that's never been seen or heard before and a craftsperson producing a socially and culturally accepted artifact according to a standard formula. Quoting from a <a href="" target="_blank"><span style="color: magenta;">much earlier post</span></a>: "One ground-breaking music, such as the Ginger Baker album, <span style="font-style: italic;">Middle Passage</span>, more powerfully than ever before; to strike a Universal Chord, create a vibrational pattern that could and would, perhaps, resonate throughout the planet. At times it would seem that Jason would mix as if the fate of the World hung in the balance. He intensely loved what he was doing which probably contributed significantly to the success his work enjoyed."</div><br />Suggested listening: I haven't had the chance to listen Jason's to entire oeuvre, but I do intend to catch up with some of his classic mixes as points of study. Here is a selection of tracks that I know about with a few comments:<br /><br />1. Public Image Limited, <a href="" target="_blank"><span style="color: magenta;">the entire generic <i>Album</i></span></a>. Jason once relayed a story of recording Ginger Baker's drums for this album. One Sunday at the Power Station recording studio, when most of the staff wasn't around, he somehow managed to stop the elevator, place a sheet of thick plywood for a platform on top of the elevator and set up the drums in the elevator shaft. Later on he got in a lot of trouble from the Power Station management. If anyone got hurt, insurance wouldn't have covered it and they would have been liable for any potential lawsuits.<br /><br />2. Swans - <i>The Burning World</i>. In particular, the tracks <i>The River That Runs with Love Won't Run Dry, Let It Come Down, Can't Find My Way Home,(She's A) Universal Emptiness</i>, and <i>Saved</i>. From the earlier post:<br /><br />"For the first two sessions (of this project) I did the standard assistant's job of patching, keeping notes, etc while also hanging back, staying out of Jason's way and not saying much, which was the politically correct way of working as an assistant - not offering any input or opinion unless asked or if something drastically wrong was occurring.<br /><br />At the end of the second night, Corsaro had, a 'let's get real' talk with me that was kind of a kick in the ass. I don't remember exactly what he said, but something to the effect that I could either continue working as any other stay-in-the-lines assistant engineer jerk or I could seriously help him mix the record as a co-pilot. From then on I was right beside him at the board watching his every move like a hawk, making suggestions when appropriate, even helping with automation moves when his hands were full."<br /><br />From another post about this recording:<br /><br />"One example of how strong the mood became for me was during the mix of the Swans cover of <span style="font-style: italic;">Can't Find My Way Home</span> written by Steve Winwood and originally performed by Blind Faith, the 'super-group' with Winwood, Eric Clapton, Ginger Baker and Ric Grech.<br /><br /><span style="color: #cc33cc;">Come down off your throne and leave your body alone</span> <span style="color: #cc33cc;"><br />Somebody must change</span> <span style="color: #cc33cc;"><br />You are the reason I've been waiting so long</span> <span style="color: #cc33cc;"><br />Somebody holds the key</span> <span style="color: #cc33cc;"><br />Well I'm near the end and I just ain't got the time</span> <span style="color: #cc33cc;"><br />And I'm wasted and I can't find my way home...</span><br /><br /."<br /><br />3. Ginger Baker - <i>Middle Passage</i>. This remains one of the most sonically powerful recording expressions I've ever been a part of. Quoting about the drum solo:<br /><br />"The peak of watching Jason work occurred during the mix of the 5th track, <span style="font-style: italic;">Basil</span>,. Both Bill Laswell and I were sitting with Jason at the SSL while he made multiple passes to get the automation just right. I had the feeling that Bill was equally aware that we were watching a master at the top of his game. It's a memory that I'll never forget. I highly recommend checking out <span style="font-style: italic;">Basil</span>, it's some of the most powerful drumming you'll ever hear. It's about the only drum recording I know of that musically and sonically compares with John Bonham's <span style="font-style: italic;">Moby Dick</span> for a powerfully melodic drum composition, brought to the forefront through Jason's mix."<br /><br />I do remember one of the effects he used for it - a triggered flanged autopan program from the Eventide H3000 SE which he ran the tom toms through.<br /><br />Bill Laswell and Yoko Yamabe put this together to honor his memory:<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><br /><br /><div style="text-align: center;"><br /><br /><br /><div style="text-align: left;">To the being of Jason Corsaro: bon voyage, mon ami, you changed my life. Your work and legacy live on.</div></div><img src="" height="1" width="1" alt=""/>Oz Fritz Language, Sumer, and the Plane of Immanence, (Slight Return)<a href="" target="_blank"><span style="color: magenta;"><i>Butterfly Language</i> </span></a>is an excellent blog that readers of the <i>Oz Mix</i> will likely want to check out on a regular basis. It's written, constructed and published by <span class="s1">Valerie D’Orazio frequently. It came across my radar when<a href="" target="_blank"> <span style="color: magenta;">RawIllumination.net</span> </a>posted a link to the first installment in a series about Jack Parsons, one of Aleister Crowley's magical sons and the inventor of solid rocket fuel, titled: <a href="" target="_blank"><span style="color: magenta;"><i>An Alternate History of Jack Parsons, Part I: Warrior Lord of the Forties</i></span></a>. Ms. D'Orazio uses a technique called Imaginative Cognition (IC), she learned writer </span><span class="s1">Walter Stein, to intuitively embellish the narrative and offer insights. The writing is entertaining, engaging, and thought provoking. I'm reminded of one the more enjoyable Crowley biographies: <i>Magician of the Golden Dawn: the story of Aleister Crowley</i>, by Susan Roberts which took great liberties imagining the Magus' interior states, thoughts and emotions. D'Orazio is more transparent about her process and that honesty makes for a stronger invocation.</span><span class="s1"> Another interesting and novel feature are the links to popular culture images and tropes to illustrate this alternate history. I would like to see more writing like this in Thelemic literature because it seems a creative and valid way to effectively explore, expand and communicate the 93 current. After all, I suspect much of Crowley's artistic output could accurately be described as Imaginative Cognition.</span><br /><br /><br /><div style="text-align: center;"><span style="font-size: x-large;">* * * * * *</span></div><div style="text-align: center;"><span style="font-size: large;"><span style="color: cyan;">Well, I stand up next to a mountain, chop it down with the edge of my hand.</span></span></div><div style="text-align: center;"><br /></div><div style="text-align: right;"> - Jimmi Hendrix, <i>Voodoo Child (Slight Return)</i> </div><br /><a href="" target="_blank"><span style="color: magenta;">Earlier</span></a> we spoke of the plane of immanence as an open-ended environment, a framework where concepts arise, live and proliferate; meet up, connect, and give birth to experimental offspring; <i>mutatis mutandis</i> Every major thinker posits their own plane of immanence for ideas and thought experiments to flourish and find means of expression. The introductory linguistics of Crowley's and Gurdjieff's systems were presented as examples. Deleuze conceives of a plane of immanence of the age. We will observe what that looks like from here: the plane of immanence as it encompasses systems of Initiation; the transformation into the all-worlds sympathetic, post-human condition.<br /><br />Some Deleuzian commentators make note that the French word <i>plan</i> means both plane - as in a geometrical plane, and plan - forming a strategy, and suggest that Deleuze intends the pun. We see Deleuze's pun and raise him a gravity defying vehicle, to wit: the plane of immanence = an airplane for traveling through the macrodimensions of the labyrinth, the hidden recesses of the soul, the parts of the brain we don't use because they are mostly dormant, however, they appear immanent, always there, if unseen and unnoticed. This reads like what they say about bardo spaces - we are always there, always in the bardo, in a between-lives state moving from one relative point of stability to another; like being on a subway train or an airplane flying over the ocean. We acknowledge at least 3 meanings of the phrase "plane of immanence:" 1) the abstract geometrical plane where concepts are born, grow up and procreate, 2) a plan, a strategy for evoking and invoking the limitless possibilities of our future becomings, 3) an airplane of immanence, a vehicle for traveling anywhere and everywhere the mind can conceive and beyond. " A vehicle for Deleuze's " lines of flight." <span style="color: cyan;">I had a dream, crazy dream ... anything I wanted to know, any place I needed to go."</span> (Led Zeppelin, <i>The Song Remains the Same,</i> a musical expression of the plane of immanence) We note the magical pun with the element Air = intellect; the airplane of immanence = a linguistic plane- we get there with language.<br /><br />What follows is a quick sketch, albeit a very incomplete fragment, of the plane of immanence as it regards Initiation, from this biased reporter. In modern times, this plane begins to assume its current reach with the emergence of works by Friedrich Nietzsche and Arthur Rimbaud in the latter half of the Nineteenth Century.<br /><br />As I attempt to thumbnail on paper this plane of initiatory immanence, a young women walks into the coffee shop sporting a large hawk with outspread wings tattooed across her upper back and shoulders. The hawk being a foremost iconic symbol of Thelema:<span style="color: cyan;"> "I am the Hawk-Headed Lord of Silence & of Strength; my nemyss shrouds the night-blue sky." </span><i>Liber Al 3:70</i>.<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><br /><div style="text-align: center;">Synchronicity as affirmation. </div><br />Nietzsche conceived a new form of humanity, perhaps a life beyond the human. He suggested that a vast gulf, or abyss exists between what we are now and what we can become. He also suggested a revaluation of all values. Contemporaneously, Arthur Rimbaud, steeped with knowledge of the Hermetic Arts, poetically fleshes out and describes this abyss in <i>A Season in Hell</i> with glimpses and snapshots of the life beyond in <i>Illuminations</i>. Rimbaud recognized the power of linguistics: <span style="color: cyan;">"Rimbaud had outlined his fantastic self-ordained mission to 'change life itself' by means of a totally new kind of language, by means of magic."</span> (Bertrand Mathieu). Bob Dylan and Patti Smith are two contemporary artists profoundly influenced by Rimbaud and his mission.<br /><br />Crowley made "Crossing the Abyss" the second and final attainment in his magical system of making the immanent actual. This follows upon the "Knowledge and Conversation of the Holy Guardian Angel", magickspeak for learning how to communicate with a highly intelligent, non-human guide. Scientific materialists might call it learning to active different parts of the brain or unlocking hidden strands in the DNA code, and they could be right.<br /><br />Apart from Crowley, this abyss has been explored in literature by Robert Anton Wilson, Thomas Pynchon, Phillip K. Dick, Kenneth Patchen, James Joyce, Kenneth Grant, Flann O'Brien and probably others that I'm leaving out.<br /><br />Ni<span style="font-family: inherit;">etzsche also referred to t</span>he revaluation of values as transvaluation because they are values that go far beyond the current ones. Crowley made the transvaluation of values a primary theme in his <i>Book of Lies</i>. Looking for that quote, I became startled with another hawk synch:<br /><br /><div style="text-align: left;"><span style="color: cyan;">Zoroaster describes God as having the head of the Hawk, and a spiral force. It will be difficult to understand this chapter without some experience in the transvaluation of values, which occur throughout the whole of this book, in nearly every other sentence. Transvaluation of values is only the moral aspect of the method </span></div><br /><div style="text-align: right;">- <i>Book of Lies</i>, commentary on chapter 42</div><br />Slight return to the plane of immanence timeline: Madame Blavatsky formed the Theosophical Society in 1875, the same year Aleister Crowley was born. This began the process of making the spiritual path more democratic and self-reliant; advocating an eclectic approach to esoteric practices and strategies for the genesis of the post human animal condition. Crowley first published his system in the <i>Equinox </i>beginning in in 1909. In it, right near the beginning in <i>Postcards To Probationers,</i> he claimed to be able to produce "Christs" (Leary's C6) with his methods. If you entertain the notion that this is possible, then you're open to the plane of immanence.<br /><br />Right around the same time, or shortly after, G.I. Gurdjieff emerged upon the scene in St. Petersburg and Moscow, introduced to the intelligentsia by P.D. Ouspensky. Both men absorbed Nietzsche. Using and expanding upon many of the philosopher's ideas, Gurdjieff takes up the production and development of a new kind of human in a completely different, but complementary fashion than Crowley. Cross-referencing the two radically different systems can prove very useful to understanding both of them. Once, in a monastery, I saw a drawing of the Enneagram superimposed upon the Tree of Life.<br /><b><br /></b><br /><div style="text-align: center;"><b><span style="font-size: large;">Lady of Largest Heart</span></b></div><br />The slight return of the plane of immanence refers to the fact that both Crowley and Gurdjieff said that they were presenting a revival of an ancient tradition. Both these teachers crossed paths with the Yezidi, an extremely ancient culture that archeologists have dated back to at least 12,000 B.C. Crowley was very specific about the ancient influence: <span style="color: cyan;"><span class="_4n-j _fbReactionComponent__eventDetailsContentTags fsl" data-"Aiwaz is not (as I had supposed) a mere formula like many angelic names, but it is the true most ancient name of the God of the Yezidis, and thus returns to the highest Antiquity. Our work is therefore historically authentic, the rediscovery of the Sumerian Tradition."</span></span> Aiwaz or Aiwass was the name of the non-human entity that dictated the <i>Book of the Law</i> to Crowley. He referred to this entity as his Holy Guardian Angel.<br /><br /><i>Lady of Largest Heart</i> is the name of second oldest known poem in the world. It was composed by Enheduanna, a High Priestess of Sumer and daughter of the first ruler in that land, Sargon, in homage to the Goddess, Inanna. I recently discovered this in a wonderful book called: <i>Inanna, Lady of Largest Heart: Poems of the Sumerian High Priestess Enheduanna </i>by Betty De Shong Meador. Enheduanna was passionately devoted to Inanna her whole life and was responsible for elevating her to the position of supreme deity. The first poem ever recorded, also by Enheduanna, <i>Inanna and Ebih</i>, tells how Inanna put down an uppity male god challenging her domain who manifested as a mountain. The Hendrix quote above encapsulates what Inanna does in the poem. I am fascinated by the coincidence that the first verse of <i>Voodoo Child (Slight Return) </i>channels the world's oldest poem. The poem was translated well after his death so he couldn't possibly have been consciously influenced by it.<br /><br />The first lines that Meador quotes from Enheduanna greatly resembles Crowley's image of Babalon as she appears in the Thoth Tarot XI called Lust or Strength:<br /><br /><span style="color: cyan;">Inanna</span><br /><span style="color: cyan;">child of the Moon God</span><br /><span style="color: cyan;">a soft bud swelling</span><br /><span style="color: cyan;">her queen's robe cloaks the slender stem</span><br /><br /><span style="color: cyan;"> * * *</span><br /><br /><span style="color: cyan;"> steps, yes she steps her narrow foot</span><br /><span style="color: cyan;">on the furred back </span><br /><span style="color: cyan;">of a wild lapis lazuli bull</span><br /><br /><span style="color: cyan;">and she goes out</span><br /><span style="color: cyan;">white-sparked, radiant</span><br /><span style="color: cyan;">in the dark vault of evening's sky</span><br /><span style="color: cyan;">star-steps in the street</span><br /><span style="color: cyan;">through the Gate of Wonder </span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><br /><br />In her poems and hymns, Enheduanna reveals Inanna as a complex goddess with multiple natures. Describing how Inanna was understood by the Sumerians, Meador writes:<br /><br /><span style="color: cyan;"> is her reality may seem, it is the<i> Real </i>every living being must encounter."</span><br /><br /><i>Cosmic Trigger</i>, the book where I first encountered the dynamic duo, Crowley and Gurdjieff, begins with parables from traditions that strongly influenced author Robert Anton Wilson. The first anecdote comes from the Sufis. The second story tells of the goddess Ishtar's descent into the Underworld. Ishtar is the Babylonian version of Inanna.<br /><br />On page 156 of Betty Meador's book, she traces the Tree of Life to the second poem, <i>Lady of Largest Heart</i>:<br /><br /><span style="color: cyan;">Inanna in this poem 'spans the tree of heaven / trunk to crown.' Likewise the central symbol of the Assyrian Ishtar is the tree that Parpola says 'contained the secret key to the psychic structure of the perfect man and thus to eternal life.' The tree appears in medieval Judaism as the Tree of Life of Kabbalah, a primary symbol of Jewish mysticism.</span><br /><br /><i>Inanna, Lady of Largest Heart </i>is a must read for anyone interested in studying the roots of Thelema or for anyone interested in seeing how the power of the active feminine can change the world. <span style="color: cyan;"> "Well I stand up next to a mountain, chop it down with the edge of my hand. Pick up all the pieces and make an island, might even raise a little sand."</span><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz Qabalah Proof<div style="text-align: center;"><span style="color: yellow; font-size: large;">We must learn anew in order that at last, perhaps very late in the day,</span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;"> we may be able to do something more: feel anew. </span></div><div style="text-align: right;"><span style="color: yellow; font-size: large;"><span style="font-size: small;">- Friedrich Nietzsche, <i>The Dawn of Day</i></span></span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;"><br /></span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;">Slept all night in a cedar grove, </span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;">I was born to ramble, born to roll.</span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;">Some men are searching for the Holy Grail, </span></div><div style="text-align: center;"><span style="color: yellow; font-size: large;">but there ain't nothing sweeter than riding the rail</span></div><div style="text-align: right;"><span style="color: yellow; font-size: small;">- Tom Waits<i>, Cold Water</i></span></div><div style="text-align: center;"><br /></div><div style="text-align: left;">Writers who employ qabalistic and other literary devices to transmit multi-layered meanings of imagery and information will sometimes dangle blatant clues encouraging the code-breaking reader to look in that direction. They start with basic and obvious correspondences to draw attention' then increase the complexity of the associations. Decoding this multi-level writing encourages the reader to develop puzzle solving skills and to eventually become maze-bright. Learning to negotiate and solve puzzles and mazes of any kind helps develop the skill set for solving more difficult mazes.... such as life ... and death.<br /><br />Qabalistic subtext, among other things, involves the transposition of letters into numbers. Each number carries a variety of different avenues of interpretation, different meanings, conrespondences and connections as listed in the standard qabalistic dictionary, <i>777 and other Qabalistic Writings of Aleister Crowley.</i> This essay presents the argument that Gilles Delueze, at times, communicates qabalistically, a discovery I first made in <i>The Logic of Sense</i>. Qabalah actually serves as a logic of sense, but by no means the only one.<br /><br />The experimental nature of Deleuze's masterpiece, <i>The Logic of Sense,</i> becomes immediately apparent upon seeing the <i>Table of Contents</i> where the sections get structured as numbered sets of Series rather than Chapters. This transposition from Chapters to Series befits both the nonlinear and dynamic nature of the subject material. Any given subject doesn't necessarily begin with its designated Series, nor does it conclude at the chapter's end. Each Series comprises a discrete block of subject material, a line of thought, that overlaps, interconnects and runs parallel to all the other series. We envision an analogy with electronics - the two basic electrical circuits being series and parallel.<br /><br />The first number/letter correlation that caught my attention and tipped me off to the code was the <i>Twenty-Sixth Series of Language</i>. There are 26 letters in both the English and French alphabets. That's what I mean by a blatantly obvious correspondence between number and subject. Anyone remotely literate in either of these languages knows they have 26 letters in their alphabetr, you don't have to be a certified qabalist to see that. There seems a reason that Deleuze made language the subject of the 26th series. I suggest this widely known, simple correspondence, to be a hint to look for more complex relations. The next rung on the ladder comes right away: <i>Twenty-Seventh Series of Orality</i> plugs in directly to the qabalistic grid.<br /><br />The framework for this grid is known as the Tree of Life. It contains 10 Sephiroth (spheres of influence) and 22 paths connecting these spheres. They get arrayed on three vertical pillars, The Pillar of Mercy, the Middle Pillar, and the Pillar of Severity. Each path gets assigned a Hebrew letter. Also, each path and each Sephiroth has a key number, 1 to 10 for the Sephiroth and 11 - 32 for the paths. I'm giving this very basic outline for the beginning qabalist to demonstrate the significance of 27 and orality. In the spirit of increasing complexity, more info on this esoteric language will be given in due course. Each letter of the Hebrew alphabet is given a name that suggests a "pictorial glyph suggested by the shape of the letter." For example, the first letter Aleph "means an <i>Ox,</i> principally because the shape of the letter suggests the shape of a yoke." The 27th key corresponds to the Hebrew letter, <big><span style="font-size: x-large;"><span class="script-hebrew" dir="rtl" style="font-family: "alef" , "sbl biblit" , "sbl hebrew" , "david clm" , "frenk ruehl clm" , "hadasim clm" , "cardo" , "shofar" , "david" , "ezra sil" , "ezra sil sr" , "noto sans hebrew" , "freeserif" , "times new roman" , "freesans" , "arial";">פּ</span></span><span style="font-size: x-large;"></span>, - <span style="font-size: small;">Pe (pronounced "pay') - "a Mouth, is explained by the shape of the letter. The Yod represents the tongue." (quotes from 777 ). The <i>Twenty-Seventh Series of Orality</i> presents an explicit association with Qabalah.</span></big><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><div style="text-align: center;"><span style="font-size: x-small;">The Tree of Life</span></div><br />Key 27 is the exact place to start if one considers Deleuze a philosophical beacon for Thelema. This key corresponds with the tarot trump The Tower also called War. "The picture shows the destruction of the existing material by fire." (<i>The Book of Thoth</i>). Relate that to Deleuze taking up and continuing Nietzsche's project of overturning Platonism, his criticism and rejection of Hegel's dialectic or of Descarte's cogito (i.e "I think therefore, I am"). Deleuze has been at war with and sought to destroy conventional assumptions in mainstream philosophy right from the start of his career. One of his key concepts for breaking with past convention of any kind is the War Machine which he developed and wrote about with Guattari in <i>A Thousand Plateaus</i>. More on the War Machine and Magick <a href="" target="_blank"><span style="color: magenta;">here</span></a>.<br /><br />Crowley's Tower card has a large eye at the top which he implies is the opening of the Eye of Horus - the gnostic, experiential introduction of Thelemic cosmology. The popular introduction to Thelema masked as one of the best Science Fiction books ever, Robert Heinlein's <i>Stranger in a Strange Land</i> contains much symbolism of the path of Pe. This may be the best path to introduce Thelema because it is the first path that crosses the vertical pillars to connect the Sephira Hod on the Pillar of Mercy with Netzach on the Pillar of Severity - the intellect (Hod) with ordinary emotions (Netzach). It also connects the element Water (Hod) with Fire (Netzach). More on that later. The balance and uniting of the three lower centrums, the physical, emotional, and intellectual in a common direction produces real Will, according to Gurdjieff.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-</a></div><div style="text-align: center;"><span style="font-size: x-small;">The Tower Thoth Tarot card</span></div><br />Immediately north of the path of Pe on the Tree is what's called the Veil of Paroketh. <i>The Book of the Law </i>indicates three grades in Thelema: the Hermit, the Lover, and the man of Earth. Coming just below Tiphareth and above Pe, the Veil of Paroketh separates the grade of the man of Earth from the Lover. The man of Earth begins the process 'know thyself" - self-observation, self-study etc. and begins formulating their True Will. The Lover grade gets attained when passing through the Veil of Paroketh to reach the solar emanation Tiphareth. The veil represents the obstacles to that. This veil is symbolized in Biblical scripture in Mark 15:38: "And the veil of the temple was rent in twain from the top to the bottom." This occurs at the moment of JC's death on the cross, or as they say, when he "gave up his ghost." This death/rebirth motif appears a basic tool in the Thelemic war machine of Initiation and represents a major apsect of the symbolism of the path of Pe.</div><br />Back to <i>The</i> <i>Logic of Sense</i>: the series/parallel nature of the book already becomes apparent with the increasing numerological complexity between Series 26 and 27. They follow each other in the <i>Table of Contents</i> in serial fashion while the occult series of qabalistic subtext runs parallel to the literal text.<br /><br />The next series demonstrating increasing qabalistic subtlety to this eye is: the<i> Fourteenth Series of Double Causality.</i> Key 14 signifies the path of Daleth and connects the sephira of Chokmah with Binah, the archetypal Father with the archetypal Mother - double causality. This represents the third and topmost crosspath on the Tree of Life. It also connects the root of Fire (Chokmah) with the root of Water (Binah). Series 27 and 14, the lower and higher crosspaths in the Tree of Life, appear the only two that show an obvious qabalistic link between its number and title.<br /><br />That it happens to be these two paths so indicated has much personal significance for me because I got an instruction very early, as a student of this Art, to examine the relationship between these two paths. I thus associate these two paths with beginning studies of this kind, so find it synchronistic that Deleuze also begins here.<br /><br />Still with the <i>Table of Contents</i>: other Series titles have no obvious correlation with Qabalah in its universal form, however, every unorthodox practitioner of the Art devises their own lexicon based on personal experience and individual associations. For moi, the Sixth Series on Serialization indicates an advanced look at Tiphareth (key 6). The first sentence in this Series: "The paradox of indefinite regress is the one from which all the other paradoxes are derived." strongly resonates with the function of Tiphareth along with the prime directive that to go anywhere in the macrodimensions one must first pass through the heart of the Labyrinth. (Labyrinth terminology originates from Nietzsche: "If we had to venture upon an architecture after the style of our own souls, a labyrinth would have to be our model. That music which is peculiar to us, and which really expresses us, lets this be clearly seen." - <i>The Dawn of Day</i>).<br /><br />As mentioned, <i>The Logic of Sense</i> comprises a collection of Series. The Sixth Series on Serialization beginning as it does with "indefinite (not infinite) regress" suggests that the whole book embraces an indefinite solar invocation. An indefinite regress seems far more experientially accurate than an infinite regress in the multiplicities of experimental solar invocation. Every Series starts its title with a number followed by the word "of;" for example, <i>First Series of Paradoxes of Pure Becoming</i> etc., except the Sixth and Twentieth Series which has the Series number followed by the word "on." Long time readers of this blog, as well as adepts with Crowley's linguistics, will recognize the word "on" as one of Crowley's magical formulas. I suggest that Deleuze was aware of this; this formula relates to Tiphareth, one could say that it's solar powered. <i>The Twentieth Series on the Moral Problem In Stoic Philosophy</i> concludes its synopsis in the Table of Contents with: "To understand, to will, and to represent the event;" a phrase that speaks as equally well to the ON formula. <br /><br />The <i>Twenty-Third Series of the Aion</i> has a synchronistic association for me. 23 will be forever connected with Robert Anton Wilson who wrote about the 23 Conspiracy in <i>Cosmic Trigger Volume I</i>. Readers who followed Wilson down that particular rabbit hole report experiencing many unusual coincidences with that number which has been my experience as well. Wilson wrote that it was 23 which cracked the Cabalistic (as he spells it) DNA code for him. It was also an entry point for me. The <i>Twenty-Third Series</i> is about time. It begins: "From the start, we have seen how two readings of time - time as Chronos and time as Aion - were opposed." Wilson reports in <i>Cosmic Trigger</i> that his Holy Guardian Angel communicated mostly through synchronicities and that a lot of the messages had to do with the paradoxes of time. During the period of July 1973 to October 1974 he says that he was frequently in contact with a nonhuman entity or entities unknown:"But the entity always intently urged that I should try to understand <i>time</i> better." (italics in the original). Timothy Leary's story and work also feature prominently in<i> Cosmic Trigger</i> and he wrote the <i>Forewards. </i>He also had great interest in the paradoxes of time. The<i> Forewords </i>end with: "We thank-you, Robert Anton Wilson, for this timely and time-full treasure." Timely sounds like Chronos as Deleuze describes it, while time-full accurately describes Aion.<br /><br /><div style="text-align: center;"><div style="text-align: center;"><span style="color: yellow; font-size: large;">Let it roll, roll, roll, let it fill my soul, all right ... </span></div><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="color: yellow; font-size: large;"><span style="color: yellow;">Let it roll baby roll, let it roll baby roll,</span></span> </div></div><div style="text-align: center;"><span style="color: yellow; font-size: large;">Let it roll,..... all night long. </span></div><div style="text-align: center;"><div style="text-align: center;"><span style="color: yellow;"><big><big><span style="color: yellow;"><big><span style="font-size: small;"><span style="font-size: large;"> <span style="font-size: small;"> - The Doors/<i>Roadhouse Blues</i></span></span></span></big></span></big></big></span></div></div><br /><div style="text-align: center;"><span style="color: yellow;"><big><big><span style="font-size: small;"><span style="color: yellow;"><big><span style="font-size: small;"><br /></span></big></span></span></big></big></span></div><span style="color: yellow;"></span>We finally arrive at the<i> Preface</i>. Deleuze lets on his qabalistic intent by hiding it right out in the open like Edgar Allen Poe's, <i>The Purloined Letter</i>, which Deleuze specifically references elsewhere in his oeuvre. The first sentence of <i>LoS</i> reads:<span style="color: yellow;"> "The work of Lewis Carroll has everything required to please the modern reader: children's books, or rather books for little girls; splendidly bizarre and esoteric words; grids; codes and decodings; drawings and photographs; a profound psychoanalytic content; and an exemplary logical and linguistic formalism."</span> Aleister Crowley includes Carroll's <i>Alice in Wonderland</i>, <i>Alice Through the Looking Glass</i>, and <i>The Hunting of the Snark</i> on his reading list with an identical comment for each piece: "Valuable for those who understand the Qabalah." Even as he lists this recommendation, Crowley simultaneously communicates qabalistically ... for those who understand the Qabalah, - a lot easier than people imagine. <br /><br /> A frequent metaphor given to a student entering an esoteric school is that of going down the rabbit hole to the topsy turvey world of Wonderland. This was illustratrated on the big screen in <i>The Matrix</i> which borrowed heavily from various esoteric school sources. Neo literally gets told to follow the rabbit, and he does, leading him completely underground and out of the computer simulated world illusion he's accustom to living in. We find <i>The Matrix </i>one of the best contemporary qabalistic allegories for the genesis of the Ubermensch right from the first scene, which literally spells out its beginning from the Heart of the Labyrinth; hidden right out in the open like <i>The Purloined Letter. </i>Another excellent genesis film is Mel Brook's <i>Young Frankenstein</i>. The genesis allegory in <i>Young Frankenstein</i> was used to great effect in the recent documentary series <i>Long Strange Trip</i> about the Grateful Dead. <br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><div style="text-align: left;">Along with the just mentioned Labyrinth clue in this two minute scene, we see a quick graphic representation of the Veil of Paroketh (or any bardo space, for that matter) at the end of the numerical display. There's also a possible oblique reference to <i>Alice in Wonderland</i> if we can imagine that the writers read the opening words from <i>LoS</i> posted above.</div><br />Deleuze began his studies of nonverbal communication systems at least as early as his 1964 book <i>Proust and Signs</i> in which he creates a taxonomy of symbolic communication, i.e. signs, based on the magnum opus <i>In Search of Lost Time</i>. As one description puts it:<span style="color: cyan;"> "Deleuze reads Marcel Proust's work as a narrative of an apprenticeship of a man of letters. Considering the search to be one directed by an experience of signs, in which the protagonist learns to interpret and decode the kinds and types of symbols that surround him." </span> This, of course, perfectly describes the qabalistic method. It shouldn't be surprising that after classifying Proust's use of signs, Deleuze plants coded linguistics into his own works.<br /><br />Another fairly straightforward clue that Deleuze utilizes Qabalah for the basis of some of his coding comes when he examines the linguistic process of schizophrenic writer Louis Wolfson. Wolfson had a pathological aversion to his native language, English, so he invented a process of immediately translating every English word into a foreign word with a similar sound and sense.<br /><br />Deleuze begins this section with a solar invocation (i.e. reference to Tiphareth) which could simply seem coincidental until we dig a little deeper. He starts: "... let us examine another text whose beauty and density remain clinical." (beauty = Tiphareth). He then provides some analysis before choosing a word to examine Wolfson's process, that word being: <span style="color: cyan;">"'Tree," for example, is converted as a result of the R which recurs in the French word "arbre," and again as a result of the T which recurs in the Hebrew term; ..."</span> (<i>LoS</i> p. 85) In this one sentence fragment we get the clues "Tree," "R" (= Resh = The Sun) and Hebrew (Qabalah is based on the Hebrew alphabet).<br /><br />This could still be a circumstantial coincidence until we get an even more definitive link to Qabalah a few pages later. Deleuze returns to examining the permutations of "tree:"<span style="color: cyan;"> "With respect to the Russian word "<i>derevo</i>" ("tree") the student of language is overjoyed at the existence of a plural form <i>derev'ya</i> whose internal apostrophe seems to assure the fusion of consonants (the linguist's soft sign)."</span> In a footnote he writes further about the effect of the apostrophe upon the consonants; <span style="color: cyan;">"... or as if fused by a yod."</span> Crowley writes about the importance of yod in the esoteric alphabet: <span style="color: cyan;">"The letter Yod is the foundation of all the other letters in the Hebrew alphabet, which are merely combinations of it in various ways"</span> (<i>The Book of Thoth</i><i>)</i> - Crowley continues with more relevant Yod symbolism). Bringing up a foreign word that's a plural form of "tree" as being "fused with a yod," makes for a blatant Qabalistic indicator; a sure sign.<br /><br />Now that it's been shown that Deleuze uses Qabalah, at least some of the time in his communication, we will examine and decode more complex messages presented through this Art in a subsequent post. <img src="" height="1" width="1" alt=""/>Oz Fritz, Linguistics and the Plane of ImmanenceThe title suggests, "the airplane of immanence," or in Deleuze/Guattarian terms: "lines of flight;" Magick = lines of flight.<br /><br />This is the fifth post in the Deleuze/Crowley series with various other of the Usual Suspects (conceptual persona?) showing up from time to time to pitch in. To honor the Discordian Law of Fives we are going to preface this post with a big I DON'T KNOW! This formulation of model agonsticism was inspired by a quote from D&G's <i>What Is Philosophy</i> (<i>WIP,</i> p.128):<br /><br /><span style="color: cyan; font-size: large;">"But on both sides, philosophy and science (like art itself with its third side) include an <i>I do not know</i> that has become positive and creative, the condition of creation itself, and that consists in determining by what one does not know ..."</span><br /><br />This resonates with a subject title Robert Anton Wilson presented in the Crowley 101 course: <i>A Gnostic Approach to Agnosticism</i>. The 'I do not know' of model agonsticism defines a starting point for experimentation and the search for knowledge, not an ending point of resignation to the unknowable unknown. Agonstics have received criticism for being indecisive and wishy-washy for not choosing a theism or atheism. They get accused of hiding behind 'I do not know' as a form of spiritual and intellectual laziness. That may accurately describe some agonstics, those who don't take the gnostic approach or make 'I do not know' "the condition of creation itself." Gnosis proceeds through experimentation whether in science, art, philosophy or in some synthetic mixture of the three. For instance, Magick, which calls itself the Art and Science of causing change to occur in conformaty with Will, and has a philosophical basis.<br /><br />Gnosis likes to communicate after its been received though it's not always easily translated. Robert Anton Wilson was a prolific writer who also regularly toured North America and Europe giving lectures and workshops. He had a desire to communicate. I recall once in an online course: he corrected something I wrote by saying, "magick IS communication" Both Wilson and Timothy Leary described themselves at different times as stand-up philosophers.<br /><br />Timothy Leary once compared his success rate as a philosopher with a baseball player's batting average pointing out that a player who hits one third of the pitches thrown his way for a batting average of .333 is considered very successful, at the top of the game. If at least one third of his postulates/hypotheses/theories proved accurate and/or useful, he was a success and that, to him, vindicated the 2/3rds he might get wrong. I don't know if Deleuze would agree with that metric.<br /><br />This return to the subject of Skepticism should have been included in an earlier post of this series if I wasn't making it up as I go. This particlular magick/philosophy flow is closer to a musical improvisation, expressing and changing direction on the spot -than a well-rehearsed symphony playing off a musical score. You constantly make up a lot of songs then one day <i>Like A Rolling Stone</i> (Dylan) comes through, and it changes people's lives. You experiment frequently with classical modes of music and opera in contemporary electronic form - so-called "Art Rock," and get <i>The Lamb Lies Down On Broadway</i> (Genesis). All of these folks, Leary, Deleuze, Dylan, the members of Genesis, Crowley, and Robert Anton Wilson, who put out acknowledged masterpieces, were extremely prolific. What they also all have in common is the affinity with, and healthy application of skepticism. Skepticism doesn't have to slow down extreme and prolific experimentation. It's ok to get it wrong sometimes. <br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="font-size: large;">The Plane of Immanence</span></div><div style="text-align: center;"><br /></div><div style="text-align: left;"><span style="color: cyan;">The plane of immanence is not a concept that is or can be thought but rather the image of thought, the image thought gives itself of what it means to think, to make use of thought, to find one's bearings in thought. (<i>WIP</i> p.37)</span><br /><br />D&G devote a whole chapter in <i>What Is Philosophy</i> to describing the plane of immanence. It seems, to oversimplify, like a philosophical tool for framing a set of related concepts or ideas. They answer the question that the book poses by saying that philosophy is the creation of concepts. These concepts reside on the plane of immanence. Every school of philosophy creates their own plane of immanence which may include elements borrowed or appropriated from earlier philosophers. Following the plane of immanence, D&G introduce the notion of conceptual personae - anthropomorphic fabulations used by the philosopher to introduce and demonstrate their concepts. <br /><br />The rejection of signified transcendentals such as Plato's archetypal Ideas or the Judeo-Christian God as ultimate causes of things does not diminish the importance of transcendence itself. Deleuze talks about transcendental empiricism, which appears cognate, if not identical with, gnosis. From one point of view, perhaps an ethical one, his whole philosophy could be described as transcending fascist, reactive programming to a place of freedom to create and serve what thou wilt within the immanent world. It requires immanence to make it possible and transcendence to actually get you there. Without any kind of transcendental empiricism or gnosis, it's easy to reject the idea that extraordinary capabilities are possible or that magick works.<br /><br />Deleuze and Guattari define the plane of immanence in terms of movement and chaos:<br /><span style="color: cyan;"><br /></span><span style="color: cyan;">"The image of thought retains only what thought can claim by right. Thought demands "only" movement that can be carried to infinity. What thought claims by right, what it selects, is infinite movement or the movement of the infinite. It is this that constitutes the image of thought." (<i>WIP </i>p. 37)</span><br /><br /><span style="color: cyan;">"The plane of immanence is like a section of chaos and acts like a sieve. In fact, chaos is characterized less by the absence of determination than by the infinite speed by which they take shape and vanish." (<i>WIP</i> p. 42)</span><br /><br />The authors provide a warning that could apply just as easy to magick:<br /><span style="color: cyan;"><br /></span><span style="color: cyan;">"Thinking provokes general indifference. It is a dangerous exercise nevertheless. Indeed it is only when the dangers become obvious that indifference ceases, but they remain hidden and barely perceptible, inherent in the enterprise. Precisely because the plane of immanence is prephilosophical and does not immediately take effect with concepts, it implies." (<i>WIP</i> p. 41)</span><br /><br />The warning continues with words that mirror Crowley's fate:<br /><br /><span style="color: cyan;">But then "danger" takes on another meaning: it becomes a case of obvious consequences when pure immanence provokes a strong, instinctive disapproval in public opinion, and the nature of the created concepts strengthens this disapproval.</span><br /><br />Later, they warn about and discuss the "negative of thought:" ignorance, superstition, delusion, delirium, illusion, etc. <br /><br />The plane of immanence can be seen as an experiment in linguistics. - the notion that words, propositions, concepts, and literature in general, though metaphysical in nature, can change material bodies and states of affairs. Language, in conjunction with the physical universe, creates reality as we know and experience it. Deleuze explores this duality between language and physical things extensively in <i>Logic of Sense</i>. Sense, he says, is what connects language with physical objects. He could definitely be described as a linguistic philosopher, albeit an unusual one.<br /><br /><div style="text-align: center;"><b><span style="font-size: large;">Aleister Crowley's Plane of Immanence</span></b></div><br />The special use of words to alter reality partially describes the method of ritual, or any other kind, of magick. In a lecture titled, <i>Life of Aleister Crowley</i>, Robert Anton Wilson says that one book, <i>Portable Darkness,</i> a compendium of Crowley pieces put together by Scott Michaelsen, "interprets Alesiter Crowley as a linguistic philosopher with everything else subordinate to that. A linguistic philosopher in the vein of Wittgenstein only further."<br /><i><br /></i><i>Magick in Theory and Practice</i> begins with establishing a plane of immanence in <i>Chapter 0 The Magical Theory of the Universe</i>. Crowley advises the student, in the first paragraph, to study the history of philosophy. Yes, magick has philosophy as its base, a unique philosophy that Crowley proceeds to unfurl in this chapter. In the second paragraph, regarding theories of philosophy:<br /><br /><span style="color: yellow;"> "<b>All are reconciled and unified in the theory which we shall now set forth</b>. The basis of this Harmony is given in Crowley's <i>Berashith</i> - to which reference should be made." (emphasis in the original). </span><br /><br /> Berashith is the first Hebrew word in <i>The Book of Genesis</i>. Crowley writes of the genesis of his plane of immanence, his new image of thought, thought that can get creatively used to change the world; genesis of a new world. <i>Berashith</i> represents Crowley's plane of immanence prior to the reception of <i>The Book of the Law</i> (<i>Liber Al</i>) dictated to him by his Holy Guardian Angel. The third paragraph updates his plane of immanence to include the cosmology and understanding he arrived at through Liber Al:<br /><br /><span style="color: yellow;">Infinite space is called the goddess NUIT, while the infinitely small is called HADIT. These are unmanifest. One conjunction of these infinites is called RA-HOOR-KHUIT, a Unity which both includes and heads all things.</span> <br /><br />He goes on to say in the third paragraph that this theory is based on experience, but then suggests that these ideas can be reached by a particular application of reason. The last sentence advises the reader to consult a couple of his previous works, the first one being <i>The Soldier and the Hunchback</i>, an essay on Skepticism. It's almost as if he's telling the reader, don't believe me, find out for yourself.<br /><br />Another point of interest about these opening statements is that Crowley alludes to Tiphareth twice: "The basis of this Harmony..." (AC's capitalization) in the 2nd paragraph and "... a Unity which includes and heads all things." Harmony = Tiphareth and head = the Sun = Tiphareth. I refer to these as solar invocations and note that similar solar invocations or references to Tiphareth occur at the start of <i>Illuminatus!</i>, <i>Schrodinger's Cat</i>, <i>Masks of the Illuminati</i>, and <i>Email to the Universe</i> by Robert Anton Wilson, and in both volumes of <i>Capitalism and Schizophrenia</i>, <i>Anti-Oedipus</i> and <i>A Thousand Plateaus</i> by Deleuze and Guattari. The cover of <i>The Book of Lies </i>shows an illustration of the sun and nothing else. Gurdjieff begins his magnum opus, <i>Bellezebub Tales to his Grandson</i>, with a direct invocation of both Kether, Tiphareth and the omniscient divine spirit with the traditionally Christian, "In the name of the Father, and of the Son, and of the Holy Ghost. Amen." He calls it an invocation but makes it more universal saying that " (it) has been formulated in different ways, in different epochs." When you begin reading <i>Beelzeub</i> you enter a Church. The difference with Gurdjieff's Church is that he's an extremely funny writer. Apparently he used to do stand-up comedy during the war. Groucho Marx apparently inspired his famous mustache. On the second page, the fifth paragraph in the book, Gurdjieff makes a direct solar invocation:<br /><br /><span style="color: yellow;">First and foremost, I shall place my hand, moreover the right one - although at the moment it is slightly injured due to an accident that recently befell me - is nevertheless really my own, and has never once failed me in all my life, on my heart, of course also my own - but on the constancy or inconstancy of this part of my whole I see no need to expatiate here - and frankly confess that I myself have not the slightest wish to write, but am constrained by circumstances quite independent of me, though whether these circumstances arose accidentally or were created intentionally by extraneous forces I do not yet know.</span><br /><br />As if to confirm, the second chapter in Beelzebub is: "<i>Why Beelzebub Was In Our Solar System</i>" which he calls the Prologue. All of these solar invocations that begin some of the most magically powerful books of the last century indicate a very basic bardo instruction: before traveling anywhere in the Macrodimensions of the Labyrinth, one must first pass through the Heart of the Labyrinth. This form of linguistic expression derives from a plane of immanence given by E. J. Gold. <br /><br />Crowley continues presenting his plane of immanence, his new image of thought, throughout this first chapter mostly talking about qabala while also referring the student to other articles he's written. He includes a few other key statements to further diagram this plane, for example:<br /><br /><span style="color: yellow;">The Microcosm is an exact image of the Macrocosm; the Great Work is the raising of the whole (wo)man in perfect balance to the power of Infinity.</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">The <i>apologia</i> for this System is that our purest conceptions are symbolized in Mathematics. "God is the Great Arithmetician." God is the Grand Geometer." It is best, therefore to prepare to apprehend Him by formulating our minds according to these measures.</span><br /><br />Deleuze and Guattari introduce the notion of conceptual personae in the third chapter of <i>What Is Philosophy?</i><span style="color: yellow;"> " ...conceptual persona carry out the movements that describe the author's plane of immanence, and they play a part in the very creation of the author's concepts."</span><br /><br />Crowley borrowed heavily from Egyptian mythology to populate and express his plane of immanence, appropriating those gods for his own purposes, making them into conceptual personae. Perhaps more than any other modern philosopher, Crowley went to great lengths to present his plane of immanence as a revealed religion. In other words, he ascribes the authority of Thelema, his "new image of thought" to an entity far beyond himself and human life in general. He maintains that it was divine revelation; his account of the circumstances surrounding the reception of Liber Al has never been conclusively refuted, nor has it been conclusively proved. Crowley's diaries around that time are suspiciously vague or missing. His account of how Liber Al went down seems to have been written some years after the event. He claims to have rejected the significance of it for about five years having allegedly lost the original manuscript. I'm not saying it was a hoax, I remain agonstic on the subject, however I do know that much praxis with Crowley's techniques - including advances made by his next generation: Robert Anton Wilson, Kenneth Grant, Lon Milo Duquette , Christopher Hyatt etc. - and his brother, George, will render contact experiences of equal intensity such that the way Crowley received his mission appears a real possibility. My opinion is that indeed Liber Al is a communication from an exterior Intelligence far beyond the human though I suspect Crowley of somewhat altering and/or creatively enhancing the narrative to play better for the masses.<br /><br /><i> Chapter O</i> introduces another crucial point immediately after Crowley introduces the Thelemic triad of conceptual persona:<span style="color: yellow;"> "This profoundly mystical conception is based upon actual spiritual experience, but the trained reason can reach a reflection of this idea by the method of logical contradiction which ends in reasoning transcending itself."</span> Crowley demonstrates this by beginning <i>The Magical Theory of the Universe</i> with a hidden logical contradiction. A German phrase is quoted right below the chapter title "Nur Nicht ist," which translates as Only Nothing is and is attributed to a Frenchman - Compte de Chevallerie. Compte = count - what is there to count if only nothing is? The editor's footnote says that no such Compte de Chevallierie can be found in their philosophical reference books, but that the phrase is also in an earlier work by Crowley, <i>Clouds Without Water</i>, p.93: "This is our truth, that only Nothing is and Nothing is an universe of Bliss. Later, in the same book, Crowley calls this "metaphysical nonsense culled from German atheistic philosophy. You have the introduction of nonsense, paradox and logical contradiction with the opening quote. A French noble quoting a German reminds me of Deleuze quoting Nietzsche.<br /><br />The chapter finishes off emphasizing the importance of Qabalah: <span style="color: yellow;">"The whole basis of our theory is the Qabalah which corresponds to the truths of mathematics and geometry. The method of operation in Magick is based on this, in very much the same way that the laws of mechanics are based on mathematics."</span> Some knowledge and recognition of Qabala seems invaluable to any contemporary system or presentation, across the board, of the science of transformation whether it be Magick, the Fourth Way, Deleuze and Guattari, E. J. Gold, Robert Anton Wilson, Thomas Pynchon, James Joyce, Artrhur Rimbaud etc. etc. etc. It becomes especially useful in Magick because that is how the knowledge and communication with the Holy Guardian Angel begins and gets established. The Holy Guardian Angel represents the heart's intelligence, or solar intelligence externalized as a Guide. There is no greater guide. Contact with the guide increases with use, prompting one of the great hermetic truths: use it or lose it. Qabalah serves as the laws of mechanics on Magick's plane of immanence. Crowley closes with a directive followed by a joke: <span style="color: yellow;">Every Magician, therefore, should study the Holy Qabalah. Once she has mastered the main principles, she will find her work grow easy. <b><i>Solivtur ambulando</i></b>: which does not mean "Call the Ambulance!"</span> (translation modified). The editor's footnotes gives the Latin translation: "it is solved by walking," i.e. practice.<br /><br />Time for a related entertainment break. Join Jimi Hendrix for a short bardo voyage:<br /><br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><div style="text-align: center;"> </div><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="font-size: large;"><b> Gurdjieff's Plane of Immanence</b></span></div><br />The first chapter of Gurdjieff's magnum opus, <i>Beelzebub's Tales To His Grandson</i> is titled <i>The Arousal of Thought</i>. This is the arousal of a new image of thought, a plane of immanence, the beginning of Gurdjieff's unique presentation of esoteric development and transformation. Unlike his evil twin brother, Aleister Crowley, Gurdjieff doesn't attempt to diagram his whole system in the first chapter, almost just the opposite. He begins from ground zero by stating up front that he's not a writer and wondering what language he should write in. By realizing his own nothingness as a writer, he's able to make apparent very basic linguistic functions and applications. For instance, he out and out tells the reader that he's going to use puns:<br /><br /><span style="color: yellow;">"I decided to make use of one of the oddities of that freshly baked fashionable language called English and each time the occasion requires it, to swear by my "English soul."</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">The point is that in this fashionable language the word for "soul" and the word for the bottom of the foot, also "sole," are pronounced and written almost alike."</span><br /><br />He goes on to lament the similarity of these two words for the highest and the lowest in a way that echoes the qabalistic statement: Kether is in Malkuth and Malkuth in Kether. A few pages later, p. 17 - 19, Gurdjieff tells a story that, to me, clearly suggest a qabalistic basis to his writing:<br /><br /><span style="color: yellow;">"I have already decided to make the "salt" or, as contemporary pure-blooded Jewish businessmen would say, the "tzmmies" (a traditional Jewish sweet stew) of this story one of the basic principles of that new literary form which I intend to use for attaining the aim I am now pursuing in this new profession of mine." (i.e. as a writer)</span><br /><br />The story begins with a certain Transcaucasion Kurd going to a market and being impressed with the display of fruit, in particular, one fruit "very beautiful in both color and form." He buys a pound of that fruit, which turn out to be red peppers, for 6 coppers. The story goes on in Gurdjieff''s inimitable roundabout fashion to describe the tribulations of this Kurd when he eats the fruit and finds it makes his innards on fire. He encounters another fellow from his village who sees his distress and tells him quite bluntly to stop eating the peppers: <br /><br /><span style="color: yellow;">"But our Kurd replied: Not for nothing on Earth will I stop. Didn't I pay my last six coppers for them? Even if my soul departs from my body, I will go on eating." </span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">Whereupon our resolute Kurd - it must of course be assumed that he was of such - did not stop, but went on eating the red peppers."</span><br /><br />On page 11 Gurdjieff states his intent: " ... to express the so to say niceties of philosophical questions, which I intend to touch upon in my writings rather fully." As with Magick, his system appears one of applied philosophy. In the very next paragraph, he mentions becoming deeply absorbed by "philological questions" at a young age. This seems to me a tip of the hat to Friedrich Nietzsche, whose day job was as a Professor of Philology before he became a full time philosopher, as well as an acknowledgment of linguistics in formulating his new image of thought, Nietzsche profoundly influenced both Gurdjieff and Crowley. They also both dissected and used language for purposes.of service to their mission.<br /><br /></div><div style="text-align: left;"><br /></div><img src="" height="1" width="1" alt=""/>Oz Fritz and The Resistance: The SIMRIT Tour<span style="color: yellow;"> The fingers paused at a page of ideographs that evoked shapes of distant galaxies. Austin Spare had delineated the architecture of cosmic dimensions in the picture I had found in the attic, and the wizard Crowley had left marginal indications in one of his writings concerning sonic notations which acted as keys to other spaces.</span> - Kenneth Grant, <i>Against the Light</i>, p. 84<br /><br />Grant tricks the reader with the title of the book, <i>Against the Light</i>, playing on assumptions, when he reveals its source from<i> Finnegans Wake</i>:<br /><br /><span style="color: yellow;">Yet on holding the verso against a lit</span><br /><span style="color: yellow;">rush this new book of Morses responded</span><br /><span style="color: yellow;">most remarkably to the silent query of</span><br /><span style="color: yellow;">our world's oldest light</span> - James Joyce<br /><br />Taking a break from the Crowley/Deleuze series for an update on the current situation as seen by this traveling reporter. Pragmatic philosophy aims to bring about social change. The practical application of philosophy changes the world we live in. Intelligent social activism becomes a significant application of philosophy and magick. Music seems an ideal vehicle for that kind of activism. <br /><br />I'm Oz Fritz and this is The Resistance. I stand solidly with <a href="" target="_blank"><span style="color: magenta;">Keith Olbermann</span></a>, Rachel Maddow, Chris Hayes and other investigative journalists, brothers and sisters in arms, who form the social memory complex called The Resistance as a response against the destructive anti-humanitarian policies and sociopathic, schizophrenic behavior of the current political administration. The deception and corruption appears so obvious that I get completely bewildered why it's taking so long for the safeguards of the political system to root it out and shut it down. Unless, heaven help us, the political system itself has corrupt elements, or doesn't remember that denial is not a river in Egypt. The process proceeds at a ridiculously slow pace. Impeachment proceedings should begin now for the Russian collusion that helped get Trump elected. We include in The Resistance the insightful comic observations of Seth Myers, Stephen Colbert, John Oliver, and Trevor Noah who point out and document the absurdities, inconsistencies, and contradictions of the situation. Oliver's strategy is particularly noteworthy - buying ad time in the morning Fox news shows as a way to communicate his incisive comic points to the Television-Viewer-In-Chief. We leave the politicians to their political games and hope that the corruption has not completely taken over. In the philosophy/magick game we play music as a method of defiance.<br /><br />Music wears down and removes barriers, sometimes temporarily, sometimes permanently, that prevent empathic connections from being made. Music works to break down what Wilhelm Reich called character armor - obstacles and blockages of energetic flows to and from the properly, therefore powerfully, functioning emotional centrum. In <i>The Mass Psychology of Fascism</i>, Reich attributes the rise of fascism to sexual repression. Fascism is very much on the rise again, to a dangerous degree. We stand by the notion that sexual energy and spiritual energy represent different ways of measuring and/or applying the same energy. Sexual repression = spiritual repression. Music lifts the spirits. In other, very simple words, music tries to enlighten people by making them feel better.<br /><br />I was fortunate to join a musical assemblage known as SIMRIT for part of their <i>Songs of Resilience, Global Unity Tour</i>. <span><span>The band is based around singer/songwriter Simrit Kaur whose music evolved out of a multiplicity of diverse influences starting at an early age with the dark, heavy, mystical chanting of the Greek Orthodox Byzantine church choir she joined. Strong contemporary influences include reggae and the music of Led Zeppelin, both of which include dark, heavy, and mystical attributes. Her long time studies and experimentation with Kundalini Yoga exposed Simrit to the culture of yoga mantra chanting which became another influence. These and other music lineages get blended into an eclectic mix to encompass the broad genre of World Music.</span></span> Her singing contains the devotional, sacred, bhakti aspect of cyclic chanting transplanting it into a framework that includes the sounds, beats and melodies of World Music. A visit to her<a href="" target="_blank"><span style="color: cyan;"> website</span></a> reveals outstanding endorsements from her peers both in the music business and the mantra singing culture. I first met Simrit about three years ago to discuss a possible recording project. It soon became clear that we both were interested in producing music of a healing and transformative nature; music that reached deep into the listener's soul. That project didn't happen, the circumstances weren't right, but a musical connection had been made that apparently planted the seed for this future collaboration. In retrospect, looking back, as we sat in a metal box traveling 600 plus mph some 30,000 feet in the air, our divergent paths from three years ago until now resulted in connections being made crucial to making the band SIMRIT what it is today. The web of synchronicity and Angelic, or Bardo guidance became very strong on this tour as you will soon read.<br /><br />SIMRIT consists of percussion, bass/background vocal, kora, electrified cello/acoustic guitar and Simrit plays harmonium as well as singing. I knew Salif, the kora player, the longest, though I hadn't really heard him play that much until this tour. We spent time together as part of a recording crew in Mali, West Africa for Aja Salvatore's KSK Records. Salif was also in Mali to study with his kora teacher, Mamadou Diabate, and plug into his long lineage, dating back centuries, of kora playing. <br /><br />I met Jared May, the bass player, when a mutual friend, Isaac James, brought him to a studio I work at to record improvised music with E.J. Gold. We must have recorded two or three hours of material straight off without looking back. I was very impressed with his sound and musicianship. Frankly, being a New York bred elitist snob, I was surprised that someone of his caliber was around and about these here country parts. I recently had the pleasure of recording Jared again for Sarah Nutting's (MaMuse) recently released solo outing, <i>Wild Belonging</i>. He played a crucial role in that project. <br /><br />I met Tripp Dudley, our percussionist, and Shannon Hayden, mademoiselle cellist, when we assembled in Miami for the first rehearsal. Hayden is an extremely creative solo artist in her own right. She would open the concerts with a 15 - 20 minute solo set of classically inspired songs combined with loops, samples and her whispery ambient singing. She had a "looper," a pedal that repeats sound cycles, allowing her to create multiple symphonic layers. Shannon knew she wanted to be a cellist from the age of three. It took a few more years for her parents to realize it wasn't just a phase she was going through before they set her up with the instrument. Her post-secondary education included studying with two of the top cello teachers in the country, who, incidentally, had radically different styles and approaches to the instrument.. This may partly explain her ability for improvisation, rare in classically trained musicians, and her ease with crossing over into the world of electronics, sampling and looping.<br /><br />Tripp was the most technically-minded amongst the musicians regarding issues of sound reinforcement which helped considerably as I was definitely an old dog learning new tricks. On our first day, he gave me a wi-fi receiver to plug into Soundcraft Impact digital desk with an ethernet cable. This enabled him, or anyone on stage, to remotely control their monitor mixes with an e-tablet. I was fine with that, you can't really mix the stage monitors from the Front of House mixing position except to do what the musicians request. If the musicians themselves can remotely control their own mixes, then that's one less thing I have to lose hair over. I was only mildly concerned that Russian hackers would interfere with the monitor mixes to subvert our aesthetic subversion. Tripp and I had a few other things in common - a knowledge and love for New York City - he lives in Brooklyn; we are both one-eighth Irish and both our surnames end with the suffix: III - "the third," as it's pronounced. Most importantly, he was stalwart at keeping time, driving the band when they were revving up and keeping a steady thread of metrical consciousness during the slower, ecstatic trance pieces; he set the foundation. Everyone in SIMRIT is a master of their craft, and as masters they are dedicated, life-long apprentices. Even more critical than individual skill is the fact that their collective chemistry - a term used in attempt to describe the unknown and unpredictable synergies within the assemblage - is undeniable. Their whole is substantially greater than the sum of its parts.<br /><br />We were joined in this enterprise by Matt Hagan (the Pagan) who administered the front of house ticket and merchandise sales as well as helping with the set-up and load-out. Matt is an accomplished musician also and seemed well-experienced with road life, battle-hardened, as it were. He became an indispensable part of the team helping me out numerous times in small and large ways. I poetically visualized his role for the concerts as the "strong force" in subatomic physics, responsible for binding together the quarks and gluons to become protons and neutrons in the atomic nucleus. He philosophically endeared me when I overheard him pun Matt with Maat, the ancient Egyption Goddess of Truth, and then correctly ascribe its attribution on The Tree of Life.<br /><br /><div style="text-align: center;"><span style="font-size: large;"><b>The Voyage Begins</b> </span><br /><br /><div style="text-align: left;"><span style="font-size: normal;">With a lyric from a Beatles' song: "there's a fog upon LA..." delaying our flight and causing a missed connection that resulted in getting rerouted through Dallas, Texas. Salif and I traveled together. The rest of the lyrics from <i>Blue Jay Way</i>, could have aptly applied to our multiple departure delays in Dallas. When your intention is to use music to resist the law of the jungle, there's bound to be push-back. As I see it, the forces of political chaos stuck out their tongue at us and laughed when we saw the bizarre sight of former Republican candidate Ted Cruz walking around the Dallas airport by himself! This sounds like I'm making it up, but I have Salif for a corroborating witness. He was the one who first spotted Cruz, dressed casually in jeans and a sports coat. I had my back turned when Cruz first strolled by, Ted responded to Salif's look of recognition with a look of his own which seemed to say, "Yep, it's me." We pulled up a photo of Cruz from the internet ... yep, that was him. He passed by a few minutes later, still by himself, going the opposite direction and I caught a glimpse of this infamous politician whom I'm told is slightly to the right of Mussolini. Other travelers began recognizing him and having him pose for "selfies." This occurred only a couple of days after he'd had dinner with Trump. Maybe he need to boost his self-esteem with some "spontaneous" public recognition? </span></div></div><div style="text-align: left;"><br /></div>The wait in Dallas began to play out like a bardo sequence especially when they switched our gate at 10 pm to one on the other side of this Texan-sized airport because they changed our plane for one considered mechanically fit to fly - quite decent of them, I thought! We got to our Miami air bnb house at about 2:30 am. The house had very little furniture apart from beds, a kitchen table and a washer/dryer. The house was all completely white, all the walls and the bedding, no paintings or wall hangings to splash a dash of color. It reminded me of John and Yoko Lennon's famous "white room" they had at the Dakota building minus the white grand piano. I also became cognizant of the poetic congruence that this was a Southern White House which is what Donald Trump calls his Mar-a-Lago resort located a mere 69 miles north of Miami. Proximity does have a stronger effect when employing the affective qualities of music to good cause. Our white house and DT's White House are maybe only a casual coincidence, yet one that lends itself to sympathetic magic through resonance. After the rehearsals and into the night, Tripp and Salif would stay up until early in the morning improvising music with kora and tabla. It reminded me of being back in Africa.<br /><br /><div style="text-align: center;"><span style="font-size: large;"><span style="font-size: small;"><b><span style="font-size: large;">The First Concert</span></b> </span></span></div><div style="text-align: left;"><br /></div><div style="text-align: left;">We had two rehearsal days followed by the first concert in a new age center called the Sacred Space located in the Wynwood Arts district of Miami. It was an unusual venue. On the first day there, we entered a large, completely empty, L-shaped room, with, again, all white walls. There was no stage or seats. It had a very expensive oak floor recently installed which meant maintaining a cool temperature in the room (slightly above a meat freezer) to keep out the humidity. To help keep the floor from getting dinged or nicked, I tried slightly levitating when moving about by telling lots of jokes. This rectangular, paralleled-walled, parallel ceiling and floor space was very reverberant; somewhere between a church and a gymnasium. I got a pleasant surprise the day of the concert when entering the space to immediately hear the acoustics being less echoey. John, their audio/visual technician, had installed sound diffusors along the length of the walls which were hard to detect as they had the same creamy white shade of the walls. He had also taped down our ethernet snake cable that ran from the FOH mix postion to the stage area with white gaffer tape.<br /><br />I began by learning to program and use the Soundcraft Impact digital mixing desk and getting to know the QSC PA and stage monitor systems before dialing in the sound of the band with a nice, lengthy soundcheck. At that point, the music was largely unknown to me. In a recent article in the <i>New York Times Style Magazine</i>, Tom Waits discusses songwriting: "If you want to catch songs, you gotta start thinking like one and making yourself an interesting place for them to land like birds or insects." That guided my approach to invocationally connecting with SIMRIT before I heard their music.</div><div style="text-align: left;"><br /></div><div style="text-align: left;">The first concert was a success on every level, and I mean every level; we were off and running. I inferred its success on the metaphysical/spiritual level by the fact that Coincidence Control significantly entered the picture after that concert. It first came to my attention the following morning when I read the story of Brian Jones going to Morocco and recording The Master Musicians of Jajouka in <i>The Sun &The Moon, & The Rolling Stones</i> by Rich Cohen. I had just told Simrit the same story, with a little more detail, the day before. Though not knowing so at the time, the story was told before the concert, it became apparent afterwards that The Master Musicians of Jajouka and SIMRIT, though differing radically in sound and content, had a similar intensity for reaching into the unknown and bringing something useful back; they both use music to cast a wide butterfly net through the intensity of ecstatic trance-like percepts and affects. Shortly after I returned home, an announcement was posted on social media of an upcoming release of the Material/Master Musicians of Jajouka show I recorded in Gent, Belgium in 2015. A live SIMRIT concert album from this tour is currently in the planning stages. All of the shows on this tour were recorded multitrack into Pro Tools via a MADI usb output from the Soundcraft. </div><br />The day after the first concert was a watershed day in other ways and I blame it all on the music. SIMRIT played their first concert and the next day I felt hardwired into contact with the friendly nonhuman guide I vaguely call the HGA - Holy Guardian Angel - as some attempt to explain the extremely bizarre series of synchronicities and coincidences that blew my mind and woke me up to the recognition of transiting through the bardo. That kind of direct contact rarely happens to me outside of a special environment like a floatation tank or an invocational chamber ... and just when you least expect it; the music opened a portal.<br /><br />At breakfast, I read Simrit the short paragraph about Brian Jones recording the Master Musicians. Some music history commentators reckoned that this was the beginning of "World Music," and it very well could have been in the sense of that genre becoming a marketable brand to expose Westerners to different cultures of music. I heard that story from Bill Laswell in Jajouka. SIMRIT is a devotional world music group with strong Indian, African, and European influences along with ties to hip hop and dub reggae. Storytelling to pass along the Jajouka baraka, all completely unplanned and unexpected.<br /><br />I continued to read the Rolling Stones book while everyone got ready to get on the road to St. Petersburg and was startled to read a line directly lifted from E..J. God's<i> Clear Light Prayer</i>: "Nothing is happening, nothing ever has happened or ever will happen." This is the prayer from<i> The</i> <i>American Book of the Dead</i> to be read to the voyager immediately upon physical death, and that is the second line. Cohen changed it by making it three separate sentences. It was in a chapter that went into Gram Parson's last days and death. It told the story of how his manager drove a hearse into the airport and hijacked Parson's body so he could burn it at Joshua Tree based on a pact they had made. Joshua Tree, in the desert outside of Los Angeles, was the location of SIMRIT's first concert after I finished this tour.<br /><br />As I continued to devour <i>The Sun & The Moon & The Rolling Stones</i> over the next few days it became apparent that this was no ordinary rock star biography. Without being morbid or sensationalistic, Rich Cohen writes about death far more that you see in a book of this kind, as if he's a covert bardo agent sugar-coating death with popular culture. Chapter titles include, <i>The Death of Brian Jones Part 1</i>, <i>The Death of Brian Jones Part 2</i>, <i>Death Fugue</i>, <i>Thanatos in Steel</i>. The first chapter title really gives away it as a bardo guide book: <i>Rock Stars Telling Jokes</i>.<br /><br />Also included are close encounters with death seldom reported before. For instance, the time Sonny Barger stuck a gun into Keith Richards' gut at Altamont and told him to play or he would kill him. Barger reports that Keith proceeded to play his heart out. Another time, during a Stones concert in Paris, Richards received the tragic news that his infant son had just died from crib death. It was immediately before he had to sing the lead vocal for the song <i>Happy</i>. Cohen wonders about the emotions going through him as he sings. It seems to me that through circumstance, intentional or not, that the song became a way to deliver bardo instructions to his son. <i> </i>The song<i> Happy</i> became his <i>Clear Light Prayer</i> for that moment<br /><br />Cohen makes himself a character in the book relating childhood memories, his experiences as a reporter covering the Stones, and his journeys to significant locations in their history. I realized that this book was his bardo journey. Coming of age as a live sound technician with the former Stones cover band, The Tickets, I could strongly relate ... and resonate, one bardo sequence keys in another, or as Deleuze puts it, a resonance across different series (of events and states of affairs ) to create a disjunctive synthesis.<br /><br /><div style="text-align: center;"><span style="font-size: large;"><b>Through The South</b></span></div><br />Finally on the road to St. Petersburg. Simrit mentioned that she read my review of Led Zeppelin's <a href=""><span style="color: magenta;"><i>Celebration Day</i></span></a> that I had sent to her yesterday after she described them as a strong influence. She also mentioned having read up somewhat on Aleister Crowley hoping to gain more insight into Jimmy Page. Being uncharacteristically unfiltered in the mouth that morning, I attempted to distill the essence of the initial stage of Crowley's teaching in a few sentences: Thelema = an ancient Greek word that means Will. It qabalistically adds to 93, the same enumeration as Agape - divine love; therefore Thelema = love under will - love as a material force that can be concentrated, placed and directed, often in some type of healing modality like a traveling group of musicians. This is The Resistance. Crowley strongly advised that all initial experiments in magick be directed toward the Knowledge and Conversation of the Holy Guardian Angel, an absurd philosophical term he appropriated to avoid speculation and debate about what it actually "is." As Deleuze and Guatarri emphasize in <i>Anti-Oedipus</i> regarding the contents of the unconscious mind, it's not a question of what it means, but rather, how does it work, how does it function, what can it do? At its most accessible point of contact, the HGA functions as a spiritual guide. The HGA operation occurs in <a href=""><span style="color: magenta;">Tiphareth</span></a> - I used the chakra attribution to characterize it that day. The realization of the HGA = the discovery of one's True Will, the dynamic process that becomes an answering to the question, why are we here? Carlos Casteneda put it plainly when he had Don Juan say: "follow the path with heart." Crowley's genius was to realize and present a framework for the intelligence of the heart to act as an (apparently) external guide. This is The Resistance.<br /><br />At that point I told Simrit that Thelema had to do with surviving death. To skeptics of this notion, I suggest reading the quote from Pythagoras that begins the <i>Introduction</i> to <i>Magick in Theory and Practice</i> (Aleister Crowley). Simrit mentioned that her husband, Jai Dev, had just finished teaching a workshop on death. Within about a minute of saying that, he called.<br /><br />The conversation ended, to be continued, and I resumed my perch watching the highway traffic, signs and scenery flow by like a river. I was sitting in the last row in the Mercedes van sharing it with guitars, tablas and other more delicate band equipment. That became my spot for the entire tour. I greatly enjoyed the view of the road from there, it felt like being in the crow's nest of a sailing ship. Approximately ten to twelve minutes after our conversation, a semi-truck with large, white, stenciled letters that read CROWLEY drove by. All of these incredible synchronicities made me realize that we were in the bardo in this journey through Southeast America. The Miami edition of SIMRIT had died, shed that particular skin, and were transiting toward rebirth as a new iteration of SIMRIT in the next town. <br /><br />St. Petersburg was our next stop. I kept imagining P.D. Ouspensky introducing G.I. Gurdjieff to the local Intelligentsia there just before the Russian Revolution, but it was nothing like that at all. The venue was a small theater with nice acoustics though a little on the dead side (no pun intended) I opted to plug our mixing desk into their sound system gambling, but with a high probability, that it was better than our portable QSC front end. Their speakers did sound good, but were completely unbalanced between left and right. The liason for the venue knew nothing about the sound system, their technician was on vacation, but he was able to show me where the amp room was and between the two of us, we got the P. A. balanced for all practical purposes. Also ran into a logic problem with the Soundcraft, I'm still not convinced it wasn't Russian hackers; either that, or a ghost in the machine. These issues kept me scrambling to finish the soundcheck before the doors opened and I made it by five minutes. The show went well though I did get get a complaint from an elderly gentlemen who said he was leaving due to the level of bass in the house. That comment got emotionally cancelled out for me when Simrit introduced the Sound Engineer. Someone turned around and locked eyes with such a deep look that the world disappeared for a second or two.<br /><br />Heading north on Highway Three Oh One enroute to Asheville, North Carolina. Led Zeppelin's <i>How The West Was Won</i> live soundtrack blasts through the van's stereo at about 110 dB for about an hour followed by Creedence Clearwater Revival. The signs along the highway tell ten thousand stories: many of the billboards are hand drawn:<br /><br /><div style="text-align: center;">CEREMONIAL FIREWORKS</div><div style="text-align: center;">OPEN EVERYDAY</div><div style="text-align: left;"><br /></div><div style="text-align: left;">Reminds me of magick. A while up the river/road we see:</div><div style="text-align: left;"><br /></div><div style="text-align: center;">SWEET HOMEGROWN WATERMELONS</div><div style="text-align: center;"><br /></div><div style="text-align: left;">We pass a roadside tombstone business with its wares on display, conveniently located a quarter mile from a funeral home where I'm told the clients are just dying to get in. Location, location, location is the key to sales. The van's soundtrack has changed to Shannon practicing guitar along with Electric Howling Wolf. Germination of another strange coincidence: Tripp and I are talking at one of the pit stops. I ask him if he needs any catfish bait - a bottle of such substance reposes on a shelf nearby. He mentions that Catfish was one of his childhood nicknames bestowed on him by a friend. I told him of Dylan's song <i>Catfish</i> about the famous Oakland A's/New York Yankee's pitcher who was the first baseball player to make a million dollars a year and was from North Carolina. Two days later, I received a FB friend request from a woman named Cathe' Fish.</div><div style="text-align: left;"><br />The venue in Asheville was a small theater in an historic Masonic Hall that held about 400 people including the balcony. The ceiling was domed, resulting in some interesting acoustics that made it feel like surround sound in certain spots. The stage was very deep with a dark multi-layered forest set that looked like it had been there for years. I kept wondering if something like a creature from a Lovecraft novel might jump out of the shadows.<br /><br />Another unusual occurrence took place that goes in the category of contact with the HGA. Our local promoter and producer, Joshua, offered to run some errands. My small flashlight that I rely heavily upon was on the fritz and I asked for a replacement. He came back saying that he'd looked for one in the store, but they had nothing. When he came out, there was a guy there asking if anyone wanted a small pocket flashlight, and gave it to Joshua. It was exactly what I'd requested, didn't cost a cent, and served well for the rest of the tour; thank-you, Coincidence Control!</div><div style="text-align: left;"><br />The next concert landed in Washington, D.C, the heart of the insurrection. This venue was a nondenominational church of some kind or maybe a church that had been deterritorialized from its native religion; no pews or altar props yet still the form and acoustics of a church. It did have some beautiful stained glass windows filtering the light and the overall ambience of a Benedictine monastery. The music from the show went another step up; the synergy of the musicians becoming greater each time. <br /><br /><div style="text-align: center;"><span style="font-size: large;"><b> New England</b></span></div><br />The theater we played in Westbury, Connecticut is one of the oldest in America. It had been saved, restored and its history kept alive by Paul Newman and his family some years before. The walls in the hallway between the Green room and the dressing rooms were lined with publicity shots of performers who had worked there over the years - many, many stars. I was most proud to be setting up on the same stage that Gene Wilder and Groucho Marx had graced. The ghosts of actors past seemed to positively condition the present with the gravitas of serious theatrical tradition . The transcendental empiricism of this night's music altering moods and banishing all sorts of worries and concerns for a 2 1/2 hour timeless moment of presence. I mixed this show from above, in the balcony.<br /><br />The Boston concert was in a church that looked less secular. The band played extremely well. Simrit sounded very strong and expansive, reaching all dimensions. It's considered one of the best shows of the tour. During the concert, I walked upstairs to the balcony-like area to check the sound and was surprised to see a pair of women stretching out in yoga asanas, one of them in the Lion's Pose.<br /><br /><div style="text-align: center;"><span style="font-size: large;"><b>Return Home</b></span></div><br />We decamped from our hotel and drove down to New York City the day after playing Boston, going straight to Norfolk Street in the Lower East Side. The venue was to be one of the best of the tour, the Angel Orensanz Foundation for the Arts located less than a block south of Houston Street (pronounced "house-ton," unlike the city in Texas). It had a very heavy (meaning extremely light) vibe in the space. It had been the oldest synagog in New York prior to reterritorializing as an Arts center for Special Events. I had mixed this room before for the 1997 release party of Material's <i>Seven Souls</i> cd that included additional remixes. Off the top of my head, the musicians that played that night included Bill Laswell, Laariji (electric zither), Bill Buchen (tablas) and Nicky Skopelitis. Russell Mills constructed a Light Sound Installation while the music played, and, befitting the bardo nature of Seven Souls, there was a good supply of the Moroccan delicacy, majoun on hand. It had been a memorable evening, and for me in this space, a good omen for tonight's concert.<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="473" src="" width="640" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">SIMRIT at Angel Orensanz, NY</span></div><div style="text-align: center;"><span style="font-size: x-small;">photo by Theresa Banks</span><br /><br /><div style="text-align: left;">It often seems that performances in music centers like New York or Los Angeles become showcases for your peers in the business and tonight was no exception. The stakes always seem a little higher. I heard that the incredible singer, India Arie was in attendance. A highly regarded vocal teacher was there. My friend, percussionist Daniel Moreno took a break from producing Awa Sangho's next album to catch the show. He had been invited by Salif. Up and coming musicians will also drop in to check you out. <a href="" target="_blank"><span style="color: magenta;">Riley Pinkerton and Henry Black</span></a>, both of whom have new recordings being prepared for release, made it out. The band delivered a moving and powerful concert. </div></div><br />The sound system was perhaps the most powerful on the tour as befitting a New York venue. Again, I plugged in our desk to the venue's front end. We also used our own stage monitors. The house sound tech, Maidson, wanted me to set up the mix position by the side of the stage, he actually had a board for me there, but I easily persuaded him to let me set up in the room so that I could hear what I was mixing.<br /><br />It felt great to be back in New York again! We had rooms at the same hotel in Chelsea where I had stayed for the <a href="" target="_blank"><span style="color: magenta;">Exploring the Hidden Music</span></a> performance put together by Christopher Janney and Bill Laswell a year and a half before. My top floor window had a great view of midtown Manhattan including the looming presence of the Empire State building (a bardo marker, for me) a mere eight blocks away, its crown illuminated by white spotlights. The next morning, the top of that building disappeared from view due to a thick fog rolling in. I walked about lower Manhattan, enjoying the sights, sounds, and vigorous energy of New York, making my way to St. Mark's Place to rendezvous with Riley for a visit. She wasn't able to make it, but I was able to indulge in my latest favorite drug, matcha green tea latte, in a specialist tea shop called <i>Physical Graffiti</i>. It got its name because it was in the center of a row of buildings photographed and graphically designed for the front cover of Led Zeppelin's <i>Physical Graffiti. </i>I stepped outside and took a look. Sure enough, there was the foundation of the Led Zeppelin cover still recognizable after all these years. Another bardo trigger: <i>Physical Graffiti</i> had been a gift from my stepmother on my fifteenth birthday. It was wonderful coincidence that the matcha latte there remains the best one I've had to date.<br /><br />The next big city performance would be in Toronto, but first a show in Ithaca, NY (not the long sought home of Odysseus in Ancient Greece) on the way north. We dropped the equipment off at the theater then went out to find some lunch in the downtown outdoor mall area. Maybe it was the contrast from the City that made the streets of Ithaca seem almost deserted. The older, faded, colonial-style buildings and the ghostown-like ambience provided a very strong, bardoesque quality to the proceedings. It felt like being on the set of a <i>Twilight Zone</i> episode, or <i>Lost In Space</i> when they encounter a simulated earth environment. Another strange coincidence tipped me off: on the ride into downtown I read an anecdote about Peter Fonda, Dennis Hopper and the film <i>Easy Rider</i> from the book,<i> Laurel Canyon: The Inside Story of Rock and Roll's Legendary Neighborhood</i>, and as soon as I stepped out of the van, I spied a film theater down the road with <i>Easy Rider</i> on the marquee. This timing made it seem that the book was projecting itself out of its pages in 3D. Or maybe I had projected myself into the book and was partially living in that reality, that parallel Universe, as Robert Anton Wilson might speculate. Even the lunch spot felt like a bardo chamber. Part of it was under construction. Construction areas almost always feel like bardo zones to me, buildings in transition, but that might be partially explained by my past history as an apprentice millwright. After lunch we watched a street magician doing tricks and illusions on the mall. Apart from the magician, we were the only people on the street </div><br />The theater felt like television studios I've been in without the big cameras. The show felt quite intimate. The rows of seats were tiered like a Roman or Greek amphitheater, so that even at the back, you felt like you were close, hovering over the band. I tied into their speakers and the sound was quite good. The intimacy of the space meant that the mix position was close to the mains for a change. The sound system did give some push back to the invocation in the last half hour of the show with the loud distorted cry of an ailing speaker or amplifier. It happened only about a half dozen times on certain transients, but it was loud in one area of the theater; an uninvited, random audio guest had joined us. Both the theater's tech and I backed off on the volume which may have mitigated the problem. It didn't appear to interfere with the enjoyment of the concert. I was a little frustrated and silently questioned why certain theaters couldn't get their sound together. Then I remembered where I was and put it in perspective: there had been a lot less obstacles and we got to the home-space in Ithaca much quicker and easier than Odysseus had in the Illiad. <br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="font-size: large;"><b>Canada</b> </span><br /><br /><div style="text-align: left;"><span style="font-size: normal;">Toronto is another city I love, though this was only my third time visiting. Growing up in Calgary, Toronto became a kind of Promised Land where young bands could travel, put on a showcase in a local club, like the El Mocambo where the Stones played, and hopefully get signed by a major record label. My first visit to T.O. was with such a band. This time it was a sold-out concert in a small church just north of the Kensington Market area. During one transition between songs, Simrit explained the origins of her elaborate head dress from the Minoan civilization of Ancient Crete. She said that their remarkably advanced culture was guided by women who wore these head dresses when they met in council. This is part of Simrit's biological lineage. She connects and resonates with this ancient matriarchal wisdom communicating it through her being in the music. </span></div><div style="text-align: left;"><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="320" /></a></div><br /></div><div class="separator" style="clear: both; text-align: center;"></div><div style="text-align: left;"><br /></div></div><div style="text-align: left;">Whenever possible, I like to step out of the venue after soundcheck and go for a short exploratory walk to get a lay of the land; find out where we our situated in space/time, scope out the local environment. R.U. Sirius recounts in <i>Timothy Leary's Trip Through Time</i> that Leary stressed the importance of being aware of your geographical coordinates at all times. Where are you on the body of the Earth at this moment? This seems especially important when constantly traveling, and also seems like good bardo voyaging advice. I soon found myself in the Kensington Market district with its wide range of ethnic diversity reflected in the restaurants, food bars and shops. I noticed a large white building prominently advertising itself as a medical marijuania dispensary which I thought a little bold, but then reflected that the mother of the current Prime Minister used to party with the Rolling Stones in Toronto. I found a good hot matcha drink on the way back to the church to clear the mind and invoke presence in preparation for the night's music. </div><div style="text-align: left;"><br />Our nomadic troop checked into a hotel late at night following the concert and loadout. We had the next day off. I went out mid-morning for a long walk up Yonge Street, a walk I'd taken on my initial visit to this town. The temperature was brisk, but not too cold if one kept to a vigorous pace. A lot had changed in the 35 years since walking this way before. It had an air of faded glory, like it had seen it's time, but the real action was now somewhere else. I ended up walking over to the famed Maple Leaf Gardens which is like the Vatican, the holy shrine, to young Canadian kids growing up in the culture of ice hockey in the '60's, '70's and 80's. Maple Leaf Gardens is to Toronto what Madison Square Garden is to New York, iconic spaces for special events - not only sports, they've both held their fair share of rock concerts. Why "Gardens?" Maybe it suggests a space or a perception of primal paradise, perhaps the natural state after the ego programming gets temporarily dismantled and removed due to a powerful music event. Back at the hotel, I noticed some construction zones where they were renovating some of the floors..<br /><br />In Gurdjieff's scheme of things, to keep the intention of on ongoing process from going off course, one requires, at certain critical moments, an influx of energy or stimulus from something outside that process, or what he called a "shock." These shocks, when they work, allow the process to pass through the critical final interval and reach the next octave. I was fortunate to get this influx of energy in a big way when meeting up with my friends Terry, Lisa and Jody Tompkins, first at the SIMRIT concert, then again the next night over a delicious Japanese dinner. Terry and Lisa are songwriters and musicians who have been in and around the Canadian music industry for many years. Jody is a rising sound engineer star. Their review of the concert was very positive. They gave me some excellent feedback, particularly Lisa, who explained the importance of the reverb effects on Simrit's voice, something Simrit and I had spent time fine tuning. Terry described a sense of blissfulness that the music guided him toward. It was great to get this kind of educated viewpoint from people who know, and really appreciate diverse types of music and who are players themselves.<br /><br />A large, Universalist Church was the site of our next concert in Ottawa. A massive, working pipe organ took up the whole back wall behind the stage/altar area. Most of the pipes were vertical except for a small row in the middle set on a horizontal plane. I imagined them as small trumpets for the cherubim when they got really cooking. The acoustics were amazing, quite possibly the best on the tour. I took some moments to quietly sit in the space about an hour before the doors opened after almost everyone left for dinner. Salif was playing his kora in an antechamber to the church we had reterritorialized as a concert space. The door was open between the two rooms. The kora has a soft, delicate sound when not amplified like a <i>mezzo-piano</i> African harp. Yet the reverberations in the large room from the kora's indirect sound filled it with a distant, guiding refrain. A sound promising a distant road home.<br /><br />These glorious acoustics inspired me to relay a memory to Simrit of seeing a Canadian hippie folksinger named Valdy play the Jubilee Auditorium many years ago. Valdy had departed from the form of his first song to vocally improvise like scat singing, almost yodeling at times. He apologized to the audience afterwards saying it was a rare treat to have golden acoustics like these to bounce his voice off of. It seemed like Simrit really stretched out that night taking full advantage of the room's natural sound. To my perception, SIMRIT, the collective assemblage, went to a whole new level, breaking out of a certain stasis to try different things, taking more musical risks. A moderate snow storm didn't keep the hardy souls of Ottawa away. It did make loading out a little trickier especially when it became apparent that this was the perfect weather for a snowball fight.<br /><br />A club called Lion d'Ors in Montreal was our next and last stop on the tour. It was unique for being the only venue that wasn't a church, theater or an amorphous performance space. It was a cabaret. I experienced one more incident of Coincidence Control providing extraordinary help. The power supply for Simrit's "in ear" monitor system had gone missing. It would be much more difficult for Simrit to hear herself without it, the whole band would have to adjust. It seemed that musically the shows had climbed another notch each time. I was concerned that this issue would throw that evolution off course. We tried another power supply, but it was the wrong voltage and didn't work. It was a Sunday and the music stores weren't open yet. I mentioned this to the house sound tech. He took a look through the flotsam and jetsam of spare cables, turn-arounds, and adaptors, and found a power supply that worked. Another band had left it behind, he had no use for it so he gave it to us. A crisis and major inconvenience averted.<br /><br />This was our only afternoon show though the nightclub ambience and shuttered windows made it seem like it could have been any time after the show began. I took a quick walk around the neighborhood and discovered the Sacre Coeur church just down the street. Across from that, a little further down, was the modest Sacre Coeur medical clinic. This was another bardo marker for me. I had begun my experiments recording the ambience of sacred spaces at the Basilica du Sacre Coeur in Paris in 1990 as a way of investigating the use of sound for bardo navigation. At the time, I didn't know enough French to translate "sacre coeur" and had only chosen it because its prominence in the Parisian skyline showed it to be an interesting piece of architecture.<br /><br />It was yet another stellar concert by SIMRIT. I perceived it as a continuation of the level of quality they reached in Ottawa. After the show, an attractive woman, one of the volunteers, approached and asked if she could help me in any way. I said, " no, I was good," whereupon she excxlaimed, "this was the best sound I ever heard. She qualified this extravagant statement by saying that she had worked in the music biz for twenty years with artists like Led Zeppelin (the L.Z. refrain again) and Jethro Tull, and had a close friendship with Robert Plant. I was grateful to hear this comment and attributed it to the ecstatic place the music had brought her to - you know, that place where everything is the best you've ever experienced.<br /><br />I don't know the effect SIMRIT's music had on the current American political regime, it's not measurable. I did have direct personal experience on several occasions of people being profoundly moved such as Robert Plant's friend. For a brief period of time, during these eleven concerts, a portal had been opened into another dimension, i.e. another way to measure space and time, taking them out of the world-illusion of egos, countries, and the grinding capitalist machine (the Trump regime) to connect with something real. This is The Resistance. Peace.</div><img src="" height="1" width="1" alt=""/>Oz Fritz Wake and Music<i>Waywords and Meaningsigns</i> is an ongoing project run by Derek Pyle that invites musicians and sound artists to construct a piece of music or create an audio environment of some kind set to a passage from <i>Finnegans Wake</i>. The deadline for the 20017 edition is looming, it's May 4th - I am late in getting this posted - but there's still time for a submission. As those familiar with this epic work know, <i>Finnegans Wake, </i>apart from including actual songs with musical notation, has many passages that sound like music when read aloud. At times, it seems that James Joyce places more value in the rhythm, sounds and implied melodies the words make, relegating their meaning to a secondary role. James Joyce was an accomplished singer who had the literary ability to sing through his text.<br /><br />This amazing project follows the hallowed footsteps of no less a musical icon than John Cage who composed <i>Roarotorio, an Irish circus on Finngeans Wake</i>. I intend to participate though my submission will be for next year's edition.<br /><br />I plugged in the word "music" to a Finnegans Wake concordance and this was the first entry, from page 48:<br /><br /><span style="color: yellow; font-size: large;">a choir of the O'Daley O'Doyles doublesixing</span><br /><span style="color: yellow; font-size: large;">the chorus in Fenn Mac Call and the Seven Feeries of Loch Neach</span><br /><span style="color: yellow; font-size: large;">Galloper Troller and Hurleyquinn the zitherer of the past with his</span><br /><span style="color: yellow; font-size: large;">merrymen all, zimzim, zimzim. Of the persins sin this Eyrawyg-</span><br /><span style="color: yellow; font-size: large;">gla saga (which thorough readable to int from and, is from tubb </span><br /><span style="color: yellow; font-size: large;">to bottom all falsetissues, antilibellous and nonactionable and this</span><br /><span style="color: yellow; font-size: large;">apllies to its whole wholume) of poor Osti-Fosti, described as </span><br /><span style="color: yellow; font-size: large;">quite a musical genius in a small way and the owner of an</span><br /><span style="color: yellow; font-size: large;">exceedingly niced ear, with tenorist voice to match, not alone,</span><br /><span style="color: yellow; font-size: large;">but a very major poet of the poorly meritary order (he began</span><br /><span style="color: yellow; font-size: large;">Tuonisonian but worked his passage up as far as the we-all-</span><br /><span style="color: yellow; font-size: large;">hang-together Animandovites) no end is known.</span><br /><br /><br /><dd><br /></dd>Text like this almost begs for musical accompaniment to frame and enhance the music already there.<br /><br />Here is the official press release about the project:<br /><br /><span style="font-family: "calibri" , "arial" , "helvetica" , sans-serif; font-size: 16px;">A diverse cast of musicians, readers, and artists are creating what may be the year's most innovative musical-literary project: James Joyce’s Finnegans Wake set to music. </span><br /><span style="font-family: "calibri" , "arial" , "helvetica" , sans-serif; font-size: 16px;"><br /.<br /><br />.”<br /><br / <a href="" id="x_m_-1738909858841928584m_7555220753167481164LPlnk676562" target="_blank"></a>. </span><span style="background-color: white; font-family: "calibri" , "arial" , "helvetica" , sans-serif; font-size: 16px;"></span><br /><div style="font-family: Calibri, Arial, Helvetica, sans-serif; font-size: 16px;"><div class="x_m_-1738909858841928584h5"><div id="x_m_-1738909858841928584m_7555220753167481164LPBorder_GT_14902763135550.25416336953639984" style="margin-bottom: 20px; overflow: auto; width: 766.15625px;"><table cellspacing="0" id="x_m_-1738909858841928584m_7555220753167481164LPContainer_14902763135480.410825090482831" style="background-color: white; border-bottom-color: rgb(200, 200, 200); border-bottom-style: dotted; border-bottom-width: 1px; border-top-color: rgb(200, 200, 200); border-top-style: dotted; border-top-width: 1px; margin-top: 20px; overflow: auto; padding-bottom: 20px; padding-top: 20px; width: 689px;"><tbody><tr style="border-spacing: 0px;" valign="top"><td colspan="1" id="x_m_-1738909858841928584m_7555220753167481164ImageCell_14902763135500.4750122148543596" style="padding-right: 20px; width: 250px;"><div id="x_m_-1738909858841928584m_7555220753167481164LPImageContainer_14902763135500.5174082217272371" style="display: table; height: 250px; margin: auto; width: 250px;">><br /><div style="display: inline-block;">"><img src="" height="250" id="x_m_-1738909858841928584m_7555220753167481164LPThumbnailImageID_14902763135510.9066547816619277" style="border-width: 0px; display: inline-block; height: 250px; max-height: 250px; max-width: 250px; vertical-align: bottom; width: 250px;" width="250" /></a></div>></div></td><td colspan="2" id="x_m_-1738909858841928584m_7555220753167481164TextCell_14902763135520.5682596233673394" style="padding: 0px; vertical-align: top;"><div id="x_m_-1738909858841928584m_7555220753167481164LPRemovePreviewContainer_14902763135530.07142008910886943"></div><div id="x_m_-1738909858841928584m_7555220753167481164LPTitle_14902763135530.26711543393321335" style="color: #0078d7; font-family: wf_segoe-ui_light, 'Segoe UI Light', 'Segoe WP Light', 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif; font-size: 21px; line-height: 21px;"><a href="" id="x_m_-1738909858841928584m_7555220753167481164LPUrlAnchor_14902763135540.6243522621225566" style="text-decoration: none;" target="_blank">Waywords and Meansigns - finnegans wake set to music ...</a></div><div id="x_m_-1738909858841928584m_7555220753167481164LPMetadata_14902763135540.12148219207301736" style="color: #666666; font-family: wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif; font-size: 14px; line-height: 14px; margin: 10px 0px 16px;"><a href="" target="_blank"></a></div><div id="x_m_-1738909858841928584m_7555220753167481164LPDescription_14902763135540.15004594437777996" style="color: #666666; font-family: wf_segoe-ui_normal, 'Segoe UI', 'Segoe WP', Tahoma, Arial, sans-serif; font-size: 14px; line-height: 20px; max-height: 100px; overflow: hidden;">Waywords and Meansigns: Recreating Finnegans Wake in its whole wholume. James Joyce's Finnegans Wake set to music unabridged. Musical adaptation audiobook.</div></td></tr></tbody></table></div></div></div><img src="" height="1" width="1" alt=""/>Oz Fritz and Qabalah<span style="color: cyan;">One cannot help wondering, given passages like this in his later writings, whether or not there is throughout Deleuze's work a kind of secret priority or silent perogative given to esoteric knowledge and practice as a clue to the multiple meanings of immanence, such that to completely comprehend the significance of Deleuze's philosophy one would have to delve more deeply into previous esoteric traditions. </span><br /> - Joshua Ramey, <i>The Hermetic Deleuze, Philosophy and Spiritual Ordeal</i> p.102 -103<br /><br />Indeed! <i>The Hermetic Deleuze</i>.<br /><br /> If you are just joining the conversation, Thelema is a Greek word chosen by Aleister Crowley to represent his line of work. It literally translates as Will, and with the Greek spelling, qabalistically transposes to 93. The word <i>agape</i>,, <i>The Logic of Sense</i> = the logic of Thelema. I alluded to one such connection between Thelema and sense in the first post of this series when stating that Deleuze (in <i>LS</i>) considered Lewis Carroll's fairyland story, <i>Sylvie and Bruno</i>,.<br /><br />The <i>Hermetic Deleuze</i> (<i>HD</i>), <i>Deleuze and the Esoteric Sign</i>, worth the price of admission alone. We find out that one of Deleuze's earliest publications titled<i> Mathesis, Science and Philosophy</i>. "<span style="color: cyan;"> Malfatti's work envisions a medicine that would be effective not through technical proficiency, but as a lived embodiment of knowledge' a practical path to healing through the elaboration of sympathies, symbioses and vibrational patterns." (<i>HD</i> p.90)</span>. Anyone with knowledge of Crowley's approach to arcane wisdom will see how closely Deleuze's <i>Mathesis, Science and Philosophy</i> <i>The Song Remains the Same</i>. Qabalah seems yet another entry point into mathesis.<br /><br />Though there isn't any discussion of qabala in <i>HD</i> the sense of it clearly surfaces at times through quotes Ramey chose to use. They sound exactly like how qabala functions without explicitly making the connection <span style="color: cyan;">" ... the development of symbolic systems is as much a matter of creative encounter as it is a deciphering of signs. ... in poeticizing the world by a multilayered reading of it, always both new and traditional, we risk forgetting that <i>poiein</i> (etymology of poet -ed.) means first of all to create.' <i>HD</i> (p. 204)</span>. These quotes are from the esoteric scholar Antoine Faivre.<br /><br />According to Ramey, Deleuze betrays a close affinity and familiarity with occult theory in <i>Mathesis, Science and Philosophy (MSP)</i>. Deleuze begins the essay by asking what the word "initiated" signifies. I just had an interesting coincidence searching for <i>MSP</i> online. Found it <a href=""><span style="color: magenta;">here at anarchistnews.org</span></a>, scrolled down to see how long it goes, and then read the first comment by someone named Squee: <span style="color: cyan;">"So is this any different than Crowley's work "<i>The Book of Thoth</i>" - or many other numerological texts on the meaning of base 10 numbers?"</span><i> par excellence</i> in the drama of philosophy. <i>MSP</i> seems out of character for that role.<br /><br />The conclusion Ramey reaches here resonates with the practical side of Thelema: <span style="color: cyan;">. (<i>HD</i> p. 207)</span>. Unsurprisingly, there is much material in this book that could apply to Thelema. To this biased observer, Thelema marks the pinnacle of current hermetic thought and practice.<br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><b><span style="font-size: large;">Rhizome and the Tree of Life</span></b></div><div style="text-align: center;"><br /></div><div style="text-align: left;">We will begin our investigation of Deleuze and Guattari's use of qabalah with the concept of the rhizome which they introduced approximately in the middle of their respective careers. The Rhizome serves as the introduction to <i>A Thousand Plateaus</i> (<i>ATP</i>).:</div><div style="text-align: left;"><br /></div><div style="text-align: center;">1. Introduction: Rhizome</div><div style="text-align: center;"><br /></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="258" src="" width="400" /></a></div><div style="text-align: left;":<i> XIV piano piece for David Tudor 4. </i></div><div style="text-align: left;"><br /></div><div style="text-align: left;" <i>ATP</i>. Rhizome seems another phonetic pun; home is where, again? The first sentence of the Introduction reads: "The two of us wrote <i>Anti-Oedipus</i> together." To an imaginative interpreter like myself, the two of Tu-dor connects with the second word, two, thus implying that the two of them make a door. Experience with <i>ATP</i> reveals that it indeed becomes a door into alternate models of abstraction and experience. Further knowledge of the correspondences with daleth, as for instance The Empress tarot card, really shows where they are coming from, as well as making a direct connection with <i>The Logic of Sense</i> as it relates with the definition of Thelema delineated above. Tu-dor also suggests the dormouse from <i>Alice in Wonderland</i>.</div <i>777 and other Qabalistic Writings of Aleister Crowley</i>. There is much supplemental material in <i>The Book of Lies</i>. <i>Stranger in a Strange Land</i> as does Milan Kundera in <i>The Unbearable Lightness of Being</i>.<br /><br />The first plateau in <i>A Thousand Plateaus</i>, the <i>Introduction</i> <a href=""><span style="color: magenta;">paradox and nonsense</span></a>, remember what it said about how qabalists love to play with opposite meanings. Speaking of why they use their own names as authors, the eighth and ninth sentences in the book say: <span style="color: cyan;">"To render imperceptible not ourselves, but what makes us act, feel and think. Also because its nice to talk like everybody else, to say the sun rises, when everybody knows its only a manner of speaking."</span> I see this as important not only for the solar invocation which aligns with and reinforces the correspondences at the top of the intro, but because it also gently states an outdated conception that colors, or programs, our common experience of the world. <i>ATP</i> appears to suggest war machines against that particular kind of sleep; assumptions about how things are we unquestioningly take for granted. The solar invocation also resonates with the smiling sun face found on the cover of every copy of: <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="256" /></a></div><br / <i>ATP</i> can change our experience of life as radically as learning the earth isn't flat?<br /><br / <i>Beelzebub Tales To His Grandson </i>(his magnum opus) when he tells the story of how his Grandmother told him on her deathbed never to do as others do. I see this as a deliberate resonance. The introduction to <i>Beelzebub</i> is titled, <i>The Arousing of Thought</i>, also strongly resonant with Deleuze's project both with and without Guattari, to create a new image of thought. Gurdjieff clearly states the intention of <i>Beelzebub</i>, an intention that sounds like a prime motive for <i>A Thousand Plateaus</i>: "<span style="color: cyan;">To destroy mercilessly and without any compromise whatever, in the mentation and feelings of the reader, the beliefs and views, by centuries rooted in him, about everything existing in the world</span>. To make you see and understand on one level, the literal level of astronomical bodies in Space, that the sun does not rise, the earth spins to greet it.<br /><br />Now we go rhizomatically back to the rhizome. The rhizome concept is one D&G borrowed from botany to describe a nonunified, nonhierarchical, nonlinear proliferation of connections and flows. "In <a href="" title="Botany">botany</a> and <a href="" title="Dendrology">dendrology</a>, a <b>rhizome</b> (<span class="nowrap"><span class="IPA nopopups"><a href="" title="Help:IPA for English">/<span style="border-bottom: 1px dotted;"><span title="/ˈ/ primary stress follows">ˈ</span><span title="'r' in 'rye'">r</span><span title="/aɪ/ long 'i' in 'tide'">aɪ</span><span title="'z' in 'zoom'">z</span><span title="/oʊ/ long 'o' in 'code'">oʊ</span><span title="'m' in 'my'">m</span></span>/</a></span></span>, from <a href="" title="Ancient Greek">Ancient Greek</a>: <span lang="grc"><i>rhízōma</i></span> "mass of roots",<sup class="reference" id="cite_ref-1"><a href="">[1]</a></sup> from <span lang="grc"><i>rhizóō</i></span> "cause to strike root" (<a href=""><span style="color: magenta;">wikipedia</span></a>).: <span style="color: cyan;";</span> bodies without organs = nonorganic bodies.<br /><br /:<span style="color: cyan;"> (<i>ATP</i> p.5)..."</span><br /><br />Here they bring up tree structures within rhizomes and vice versa: <span style="color: cyan;") </span> The second sentence of this quote gives a good instruction for magick and qabalah users. This next quote about music applies as well to the formation of correspondences upon the Tree of Life: <span style="color: cyan;">)</span><br /><br />More great advice and indicative of how numbers work in qabalah: <span style="color: cyan;">The number is no longer a universal concept measuring elements according to their emplacement in a given dimension, but has itself become a multiplicity that varies according to the dimensions considered. (ATP p.8)</span> Compare that with <span style="color: cyan;">"Every number is infinite; there is no difference," </span>the paradoxical fourth line in Crowley's <i>The Book of the Law.</i><br /><br />Next up: Qabalah and The Plane of Immanence<img src="" height="1" width="1" alt=""/>Oz Fritz and Do What Thou Wilt<br /> This is part 3 of the Crowley/Deleuze series with special guest Robert Anton Wilson.<br /><br /><a href=""><span style="color: magenta;">Earlier</span></a>,.<br /><br />, <i>The Soldier and the Hunchback: ? and !</i>. (Equinox I Vol. I). They were both strongly influenced by 18th Century philosopher, David Hume, as was Robert Anton Wilson.<br /><br /?" <br /><br / <i>you </i>wilt<i>," </i>because "<i>you</i>" <i>The Book of Lies</i> for Crowley's O.U.T. formula to get out from ordinary identity.<br /><br />Deleuze tackled the question of the subject in his first book, <i>Empiricism and Subjectivity</i>, subtitled <i>An Essay on Hume's Theory of Human Nature. </i. <br /><br /. <br /><br />The beginning of Deleuze's career as a published philosopher with <i>Empiricism and Subjectivity (ES)</i>. resonates with the Leary, Wilson, Crowley crowd as we shall see. <i>The Preface</i> begins listing Hume's major contributions to philosophy:<span style="color: cyan;"> "He established the concept of <i>belief</i> and put it in the place of knowledge. He laicized belief, turning knowledge into legitimate belief, and on the basis of this investigation sketched out a theory of<i> probabilities</i>. (<i>ES</i> p. ix).</span><a href=""><span style="color: magenta;"> Internet Encyclopedia of Philosophy</span></a> Hume liked to attack his own best theories to expose any inherent contradictions. He kept up a balancing act of coming up with positive theories then tearing them down to expose any fallacies. One method of his skepticism goes like this:<br /><br /><span style="color: cyan;".</span><br /><br />Anyone who has ever read Aleister Crowley's keystone essay on doubt and certainty, <i>The Soldier and the Hunchback: ? and !</i> will immediately recognize the inspiration from Hume's method. Doubt = the Hunchback (?) while the Soldier (!) is what Hume called Judgement. Crowley frames the entire essay on the question "What is skepticism?"<br /><br />I called it a keystone essay because the skeptical method so brilliantly described there seems essential for a successful practice of ritual magick or any kind of shamanic activity. The first major publication for Aleister Crowley's school, the <i>Argenteum Astrum</i> (<i>A.'. A.'.</i>) was a ten volume series called the <i>The Equinox </i>published every six months on the Spring and Autumn Equinoxes from 1909 to 1913. <i>The Soldier and the Hunchback</i> appeared in the very first volume of <i>The Equinox</i>. To emphasize this procedure of checks and balances for any serious aspirant, Crowley begins <i>The Book of Lies</i> with a Hunchback, ?, followed by a Soldier, ! on the following page. If someone only ever wanted to get one book by Crowley, I would recommend that be <i>The Book of Lies</i>. It contains instruction on the entire system of alchemy presented by Crowley. It's ideal for anyone who likes puns and riddles and doesn't mind having their beliefs challenged. No blame if you don't like it because it's all lies anyway.<br /><br />As mentioned before, Robert Anton Wilson began the Crowley 101 class with an examination of <i>The Soldier and the Hunchback</i>.).<br /><br /."<br /><br />In the Translator's Introduction to <i>Empiricism and Subjectivity</i>, Constantin V. Bound states that an important theory of subjectivity runs through Deleuze's entire body of work. He continues: <span style="color: cyan;">"What is remarkable, first of all, about this contribution to a theory of subjectivity is that it combines a radical critique of interiority with a stubborn search for an "inside that lies deeper than any internal world.' In this sense, the search for the <i>fold</i> - "the inside as the operation of the outside" is his own lifelong search."</span><br /> <span style="color: cyan;">- <i>ES</i> p.11</span><br /><br />In <i>ES</i>, Deleuze calls subjectivity,<span style="color: cyan;"> ".. a governing principle, a schema, a rule of construction." (p. 64).</span> Later, he defines the subject: <span style="color: cyan;"> (<i>ES</i> p. 85).</span> What Deleuze translates as mediation Hume calls inference or belief with transcendence being called invention or artifice in Hume's terms. <span style="color: cyan;"> "In short, believing and inventing is what makes the subject a subject.." (ES p.85) </span> We are what we believe ourselves to be combined with all actions and efforts to grow, change, and reinvent ourselves into something new. The tunnel reality of the active subject always looks for lines of flight intended to break through or out of the tunnel.<br /><br />An excellent metaprogramming praxis that directly confronts the subject's beliefs and stimulates invention is <a href=""><span style="color: magenta;">John Lilly's Beliefs Unlimited</span></a>:.<br /><br />Here is a clip where you can hear the entire text. It's only about 4 minutes, you don't have to watch the whole video:<br /><br /><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><div style="text-align: center;"><br /></div><br />Deleuze speaks of the subject in relation to time:<br /><br /><span style="color: cyan;">)</span><br /><br />Deleuze speaks of the subject as a process in this next quote which also shows resonance with Leary and Wilson's ideas of consciousness imprinting:<br /><span style="color: cyan;"><br /></span><span style="color: cyan;". (<i>ES</i> p. 112-113).</span><br /><br />The last words of Gilles Deleuze's first book, <i>Empiricism and Subjectivity</i>, strike up a strong resonance between Do what thou wilt and his concept of subjectivity:<br /><br /><span style="color: cyan;")</span><br /><br / <i>Logic of Sense</i>, a more seasoned Deleuze seems to address 'Do what thou wilt' quite directly, as I see it. My guess is that Deleuze has read Crowley by now (1969). He refers to the subject as the <i>event</i>, to reflect its dynamic nature. The first part of this next quote is referring to Joe Bousquet who philosophically wrote of a wound he sustained as a pure event:<br /><br /><span style="color: cyan;">." (<i>LS</i> p. 148)</span><br /><span style="color: cyan;"><br /></span><span style="color: cyan;">"What does it mean then to will the event? [ i.e. what does it mean to do what thou wilt? - ed.]. Is it to accept war, wounds, and death when they occur? It is highly probable that resignation is only one more figure of <i>ressentiment</i>, since <i>ressentiment</i> has many figures. [ ed. note: <i>ressentiment</i>." (<i>LS</i> p. 149)</span><br /><br />This idea of "death turned on itself" also appears as one of the core ideas at the heart of Thelema: to use a continuous series of simulated deaths to defeat death and reach a place of immortalitiy.<br /><br />It may be because <i>The Logic of Sense </i:<br /><br /><span style="color: cyan;">." (<i>LS</i> p. 178)</span><br /><br />Deleuze gives an answer while stating the problem - the individual transcending his form becomes the individual grasping herself as event - i. e. the concept of "becoming-woman" that Deleuze and Guattari give in <i>A Thousand Plateaus</i>, a concept also at the heart of Crowley's <i>Book of Lies, </i>as discussed in the previous post.<br /><br />He goes on to describe the individual not as an isolated discrete unit separate from the environment, but as one connected to everything else. Our identity gets determined by the assemblages (to use another concept from <i>ATP</i>;, <i>LS</i> p. 178 though it might require several readings and pondering upon it for comprehension. He then quotes Klossowski to support the point which I found much more clear:<br /><br /><span style="color: cyan;">"the vehement oscillations which upset the individual as long as he seeks only his own center and does not see the circle of which he himself is a part; for if these oscillations upset him, it is because each corresponds to an individuality <i>other</i> than that which he takes as his own from the point of view of the undiscoverable center. Hence, an identity is essentially fortuitous and a series of individualities must be traversed by each, in order that the fortuity make them completely necessary."</span><br /><br />The last sentence is a bit of a puzzler, but I'll leave it for something to ponder. Next up is Deleuze and qabalah.<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz and Nonsense: Crowley and Deleuze # 2This continues the <a href=""><span style="color: magenta;">previous post</span></a>. Once again, the virtual anamesis of Robert Anton Wilson has agreed to join us. Caveat emptor: it can get paradoxical and nonsensical explicating the function of nonsense and paradox; just the nature of the beast.<br /><br />Gilles Deleuze supplies a metaphysics for Thelema, thank-you Gilles! Aleister Crowley presented an orientation and methodology for the voluntary evolution and continuous transformation of the human animal. They both emphasized the use of paradox and nonsense to introduce an element of disequilibrium for the purpose of breaking set; to shatter and destroy our habitual ways of seeing things in order to introduce something new. Another way to put it, they use paradox in an attempt to blow apart commonly held belief systems in order to move around in bigger, better, more beautiful, humorous and creative reality tunnels. (for an excellent essay that covers "breaking set," see Christopher Hyatt's Introduction to the <i>Eye in the Triangle</i>, by Israel Regardie.) Robert Anton Wilson and his early associates took it further and developed a religion out of paradox and nonsense called Discordianism with its motto, "we stick apart." Wilson's later development of the literary technique <a href=""><span style="color: magenta;">Guerilla Ontology</span></a> shows a direct formative relationship to paradox and nonsense.<br /><br />The books in which Deleuze and Crowley dive deepest into paradox are both considered tour de forces in their respective literary careers. For Gilles Deleuze, this is <i>The Logic of Sense</i>, a title that appears paradoxical in itself. Logic indicates a formal reasoning of some sort. How does reasoning formalize sense? It might help if we knew what he meant by sense? (The sense of sense? I'll try not to introduce additional paradoxes and confusion) He clearly indicates that sense represents more than the limited definition of sense as "meaning." In the second paragraph in the <i>Preface: From Lewis Carroll to the Stoics</i> Deleuze tells us what sense "is": <span style="color: cyan;">"We present here a series of paradoxes which form the theory of sense. It is easy to explain why this theory is inseparable from paradoxes: sense is a nonexisting entity, and in fact,maintains very special relations with nonsense."</span><br /><br />Every chapter in <i>The Logic of Sense</i> is called a Series with the first one being: <i>First Series of Paradoxes of Pure Becoming</i>. They are series, not chapters, to convey a more dynamic, kinetic and nonlinear approach to both the writing and reading of it, as we shall see in a moment.<br /><br />"Sense is a nonexisting entity" obviously sounds paradoxical. It might even seem like nonsense making it even more of a paradox. How can something nonexistent have relations, special or otherwise? Later in the book he tells us that sense is very fragile. How can something nonexistent have a fragile quality? So he doesn't really tell us what sense is, only that it has life, an entity is alive, and that it doesn't exist; two completely opposite meanings. This could be the ultimate agnostic statement. If you follow the meaning in both directions, it cancels. That proposition may appear like nonsense paradoxically intended to convey what sense is. Deleuze uses examples from <i>Alice in Wonderland</i> and <i>Through the Looking Glass</i> to show how Carroll uses nonsense to communicate a sense of something. In the Deleuzean formulation, nonsense can donate sense to a proposition. Also, the title of the Preface, From<i> Lewis Carroll to the Stoics</i> appears paradoxically out of time as the Stoics wrote nearly 2000 years before Carroll.<br /><br />In the third paragraph of this short Preface Deleuze points out the nonlinear nature of the book:<br /><br /><span style="color: cyan;"> "Thus to each series there correspond figures which are not only historical but topological and logical as well. As on a pure surface, certain points in one figure of a series refer to the points of another figure: an entire galaxy of problems with their corresponding dice-throws, stories and places, a complex place; a "convoluted story." This book is an attempt to develop a logical and psychological novel."</span> <br /><br />Later on, in a remarkably magical passage from <i>The Logic of Sense</i> (LS) I will demonstrate that Deleuze uses puns to communicate on multiple levels, as would any self-respecting fan of James Joyce. I will also demonstrate that Deleuze uses qabala from time to time. If you were to substitute the word "series" in the above quote with either "sephiroth" or "path on the Tree of Life" then you get an excellently poetic and concise description of how qabala works. The last sentence in the quote appears paradoxical in its common meaning, the book has no obvious resemblance to any kind of novel, postmodern or otherwise, and it's not presented as fiction. Looking at it as a magical pun, it appears Deleuze presents the aim of transformation into something new: "...a logical and psychological novel;" logic referring to the logic of sense - the logic of "pure becoming" (known in its static representation, a state it never reaches, as being; the logic of being); novel = new; esoterically dramatized in film as the character "Neo" from the <i>Matrix</i> trilogy. Deleuze puts "convoluted story" in quotes for some reason. That the "c" and "s" initials add to 68 looks very significant to me. The number 68 appears on the first page of both <i>Illuminatus!</i> and<i> Masks of the Illuminati</i>, by Robert Anton Wilson. I've written about its importance before (Tiphareth + Hod, Christ + Mercury, The Sun + communication; see Crowley's, <i>The Paris Working</i> for the magical genesis of that concept). Taking this interpretation here in <i>LS</i> may appear like confirmation bias on my part, but in the subsequent post <i>Deleuze and Qabalah</i> I will confirm that bias even further with examples.<br /><br />Robert Anton Wilson reports keeping a copy of <i>The Book of Lies</i> by Aleister Crowley on his nightstand for years referring to it frequently. It encouraged me to take up this practice, too. Wilson loved all the puns, literary and logical puzzles and the qabalistic riddles. He illustrates a few of the paradoxes therein in <i>Cosmic Trigger I.</i> The full name of the book is: <b>THE BOOK OF LIES WHICH IS ALSO FALSELY CALLED BREAKS, THE WANDERINGS OR FALSIFICATION OF THE THOUGHT OF FRATER PERDURABO. </b> A contraction of the full title sprang up: <i>The Book of Lies (Falsely So-Called)</i>. This rendering highlights the title's paradoxical character. A book of lies falsely so-called is a book of truth. Why would a book of truth start with a falsehood? Crowley has a commentary for the Title Page and jumps right in with what sounds like either nonsense, paradox or both, following it up with a statement he appears to contradict later.<br /><br /><span style="color: yellow;">"...However, the "one thought is itself untrue," and therefore its falsifications are relatively true.</span><br /><span style="color: yellow;">This book therefore consists of statements as nearly true as is possible to human language."</span><br /><br />A different view gets expressed in the Commentary to Chapter 45 <i>Chinese Music:</i><br /><br /><span style="color: yellow;">"The Master (in technical la</span><span style="color: yellow;">nguage the Magus)</span><span style="color: yellow;">;does not concern himself with facts; he does not care whether a thing is true or not: she uses truth and falsehood indiscriminately, to serve his own ends. Slaves consider hir immoral and preach against hir in Hyde Park."</span><br /><br />This disregard for "truth" may seem wild and anarchistic, but as Deleuze points out in<i> LS</i>, the production of sense ("pure becoming; the event) has nothing to do with truth or falsehood. A proposition can be factually wrong yet still give a strong sense of something. Absolute truth requires an omniscient, transcendental agency of some kind to arbitrate and judge what is true. Deleuze in his antipathy to omniscient transcendental agencies grabs ahold of Antonin Artaud's fiercely cathartic radio play title, <span style="font-size: large;"><i>To Have Done With The Judgement of God</i> </span>for a rallying cry. <br /><br />The first page in <i>The Book of Lies</i> (<i>BL</i>) consists of a sole, centrally located question mark. In the first book he ever wrote, <i>Empiricism and Subjectivity, An Essay On Hume's Theory of Human Nature </i>published in 1953, (ES) Deleuze says:<br /><br /><span style="color: cyan;">"... a philosophical theory is an elaborately developed question, and nothing else; by itself and in itself, it is not the resolution to a problem, but the elaboration, <i>to the very end,</i> of the necessary implications of a formulated question. " </span><br /><br />"<i>To the very end,"</i> which Deleuze italicizes in the text recalls Aleister Crowley's motto, his subject for <i>BL</i>, Perdurabo, that translates as <i>"I will endure unto the end." </i>After the question mark is a page with a central exclamation point - symbolizing the question taken to its limit? These two pages also refer to Crowley's seminal essay, <i>The Soldier and the Hunchback</i> on the subject of skepticism and certainty. The commentary on the question mark and exclamation point calls it "The Chapter that is not a Chapter."<i> </i> It begins with a paradox.<br /><br /><br /><div style="text-align: center;"><span style="font-size: large;"><b>Alice in Wonderland</b></span></div><div style="text-align: center;"><br /></div><div style="text-align: left;"><span style="color: cyan;">Is not Humpty Dumpty himself the Stoic master? Is not the disciple's adventure Alice's adventure?</span></div><div style="text-align: left;"><br /></div><div style="text-align: right;">- <i>Logic of Sense</i> p.142<br /><div style="text-align: left;">Crowley called his feminine persona Alice. </div></div><div style="text-align: left;"><br /></div><div style="text-align: left;">Lewis Carroll's <i>Alice in Wonderland</i> and <i>Through the Looking Glass</i> appears highly regarded by many of the best contemporary esoteric writers. A<span style="font-size: small;">leister Crowley included both books in the curriculum of the A.'. A.'. with the note "Valuable to those who understand Qabala." Along with the Stoic philosophers, Gilles Deleuze makes analysis of the Alice books the basis for his study of sense and paradox in <i>The Logic of Sense</i>. He also includes Carroll's adventure's of fairyland characters Sylvie and Bruno as part of the study calling it a masterpiece. A complete reading of both parts of Sylvie and Bruno will show Deleuze's bias to what Crowley called The Great Work. Crowley calls the Alice stories "Valuable to those who understand Qabala." They were certainly quite valuable to Deleuze. I will assert that Deleuze understood and communicated using Qabalah in a subsequent post. </span></div><div style="text-align: left;"><br /></div><div style="text-align: left;"><span style="font-size: small;">The Stoic master Humpty Dumpty turns up in a clear reference on the first page of <i>Finnegans Wake</i> (FW), " .. that humptyhillhead of humself ..." right after "the fall" and Joyce's first hundred-letter thunderword that he then connects with a fall off a wall. In the analysis of nursery rhymes in<i> Magick, Book 4</i>, Crowley says that Humpty Dumpty's fall symbolizes the descent of spirit into matter. This seems a good way to start an epic work like FW. James Joyce has a line that renders a similar interpretation through the lens of Qabalah: "... sends an enquiring one well to the west in quest of his tumptytumtoes.." one = kether, the most refined spirit; toes = the material world by qabalistic reckoning that superimposes a human body over the Tree of Life for one of its rhizomatic tendrils of correspondence and association. "Humptyhillhead" suggests, to me, the climb up to the Knowledge and Conversation of the Holy Guardian Angel, to use Crowley's nomenclature; "tumptytumtoes" suggests tummy, thus food and the sense of nourishment from spirit (we return to that theme in the next post); "humself" followed by the rhythm and rhyme of what follows suggests the flow of music. The influence of music in the form of <i>FW</i>, as well as JJ's use of qabala seems well established in both academic and nonacademic circles. Humself lets us know that he's not giving us a static subject, but rather one that changes and flows like the river that starts the book. It might also suggest the subject bringing itself into musical being/becoming, but perhaps I'm getting carried away.</span><br /><br /><span style="font-size: small;">Crowley quotes from<i> Jabberwocky </i>for the title of Chapter 48 <i>BL</i>: <i>Mome Raths. </i> The whole chapter outlines a glyph for working hard. In the note under the <i>Commentary</i> for this chapter, he quotes the whole line, " The mome raths outgrabe" and remarks that mome is also Parisian slang for "young girl" while rath = Old English for "early." He then quotes a line from Milton that uses rath and communicates more information about what the early work hopes to produce. It's a short, but important chapter worth studying. When students of HGA conversation encounter the number 48 in unusual or coincidental ways, they will tend to attempt 'kicking it up a notch or two." The "young girl" refers to the aspirant, an association that becomes more obvious when discovering that the <i>BL </i>explicates and implicates, using paradox and nonsense among several other techniques, a process that Delueze calls "becoming-woman." This, of course, has nothing to do with human gender, but rather describes a necessary shamanic step for working beyond the normal body.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">One quick way to demonstrate this claim to resonance with "becoming-woman," is to look at the very beginning of <i>BL</i> and the very end. The first chapter title is O!, meaning chapter zero. In the next chapter, 1, he begins with the exact same figure, O!, only this time indicating it as the letter O. The full first line reads: <span style="color: yellow;">O!, the heart of N.O.X., the night of Pan</span>. Right away, Crowley tells us to pay attention to puns, that the same exact image can have multiple meanings. O corresponds with The Devil in the tarot, the "medieval blind" for archetypal male energy. The final chapter 91 only has one word, presented as an unanalyzed formula. This word asymmetrically ends <i>BL</i> with A.M.E.N.; definitely seems a pun there, one that presents a view of the book as a journey of becoming-woman.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">For a Crowlean interpretation of "outgrabe" (that's what the mome raths are doing) see Chapter 23 <i>BL</i> wherein he gives the O.U.T. formula.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">Another interesting thing with that first line of Chapter 1 is that Deleuze maintains that the investigation into any process or cycle begins most productively in the middle and that's exactly what Crowley does with, N.O.X., the prime formula of <i>BL</i>.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">So far we have established that three major artists at the top of their fields, the Occult, Philosophy, and Literature i.e. Aleister Crowley, Gilles Deleuze, and James Joyce, were profoundly influenced by Lewis Carroll's <i>Alice</i> stories. I'm sure we could find dozens or hundreds references to \Wonderland in contemporary culture - I once saw an A</span><span style="font-size: small;">lice play that put a strongly affective Gurdjieffian spin on the drama. I'll limit myself to a few more references of interest. </span><br /><i><span style="font-size: small;"><br /></span></i><span style="font-size: small;"><i>The Matrix</i> trilogy of films contains a great deal of esoteric knowledge. This includes blatant qabala - for example, the female protagonist is Trinity; also next time watching, as a student of Magick or proactive Philosophy, pay attention to the beginning location, you'll see a sign that clearly labels the building. A little later, as we get into the story, Neo begins getting obscure signs and coincidences directing him to some kind of hidden point of contact, as one might with the HGA. His computer tells him to "follow the white rabbit," not long before he notices a white rabbit tatooed on girl inviting him to join their group on the way to a night club. He first turned the invitation down, then saw the tatoo and changed his mind in order to follow the instruction. Neo meets Trinity for the first time at the club and she gives him a piece of the puzzle. The white rabbit is, of course, straight out of <i>Alice In Wonderland</i>; following the rabbit is how she got into Wonderland; following the white rabbit eventually puts Neo into a completely different world, it totally changes his life.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">There's a great reference to Wonderland right off in Shea and Wilson's Illuminatus!: . </span><span style="color: cyan;"><span style="font-size: small;">" For instance, I am not even sure who I am, and my embarrassment on that matter makes me wonder if you will believe anything I reveal.</span></span><span style="font-size: small;"><span style="color: cyan;">"</span> (p.7)</span><br /><span style="font-size: small;"> The phrase, "I am not even sure who I am" is a mirror reflection of "I am that I am," Yahweh's answer to Moses when asked for his name. This corresponds to Kether, the title of the chapter. That phrase is also the gist of what Alice tells the hookah-smoking caterpillar when she is asked, "Who are you?" It seems very helpful to read the first few paragraphs from the chapter in <i>Alice, Advice from a Caterpillar</i> to catch the transformational theme inherent to <i>Illuminatus! </i>In the very next sentence following the one quoted above, the Alice-like character describes being aware of a squirrel in Central Park "leaping from one tree to another." That squirrel appears cognate with the white rabbit, and if this is true, then perhaps the authors are suggesting following this avatar from one Tree of Life to another; in other words, paying attention to Qabalah. This interpretation may appear farfetched until one realizes that the alchemical motherlode strata of <i>Illuminatus! </i>serves as a guide to Qabalah. </span><br /><br /><span style="font-size: small;">About ten years ago, E.J. Gold asked if I knew <i>Alice in Wonderland</i>. I did as a familiar story, but had never put much study into it. He suggested I reread it and said I should revisit it every five years as a sort of barometer. About five years before that I recorded and mixed the album <i>Alice</i> for Tom Waits. It comprised songs he'd composed for Robert Wilson's play of the same name about the relationship between Carroll and the real Alice the stories were told to. It's an extremely evocative, mood-drenched album with slight echoes of the Wonderland otherworldliness in between the grooves. It was mixed at lightening speed by high velocity; rushed through the bardo.</span><br /><span style="font-size: small;"><br /></span><br /><div style="text-align: center;"><span style="font-size: small;"><b><span style="font-size: large;">Paradox and Mirror Reflection</span></b></span></div><br /><span style="font-size: small;"> In<i> First Series of Paradoxes of Pure Becoming</i> (the Kether chapter of <i>LS</i>, if you will), Deleuze starts by invoking Alice and Through the Looking Glass using her growing and shrinking to explain the nature of paradox. <span style="color: cyan;"> "Good sense affirms that in all things there is a determinable sense and direction; but paradox is the affirmation of of both senses or directions at the same time." p. 1</span></span><br /><span style="font-size: small;"> In this case, he means the two opposite directions of Alice growing and shrinking - to affirm them both at once. "Good sense," in Wilson/Leary nomenclature = the societal/cultural belief systems programmed into us, i.e. our ordinary way of seeing the world; that which we try to peek past from time to time to go out.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">Learning to affirm two opposite meanings as possible and true as well as looking at things backwards to FIND the opposite meaning, reversing directions, contemplating both directions at once becomes fundamental practices to students of Qabalah. One of AC's exercises involves thinking and believing the exact opposite to some strong opinion, or position you hold as a kind of waveform cancellation; another way to break set, to temporarily knock through belief systems and reality tunnels. Affirming both senses or directions at the same time shines a lot of light on Crowley's mystique - the self-annointed Anti-Christ who said his school could produce Christs - as well as the Great Work in general.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;">We find a qabalistic lesson of reversed direction in <i>The Book of the Law II 19</i>: "Is a God to live in a dog?" An excellent example of looking in a reversed direction to unlock the sense of something occurs in the Marx Brothers film <i>Animal Crackers</i> when Groucho remarks that there is a dog missing in the fake painting put up to replace the one that's been stolen. The plot of the film then revolves around the stolen painting. The whole film appears a masterpiece of qabalistic transmission; highly recommended for regular study. One can see <i>Animal Crackers</i> as a very literal title related to the BL/ becoming woman project of Deleuze and Crowley.</span><br /><span style="font-size: small;"><br /></span><span style="font-size: small;"><i>Schrodinger's Cat</i>, RAW's continuation of <i>Illuminatus!</i> in its aspect of a guide to Qabalah, or, as it's literally put in the book, A Shamanic Manual, has the character Blake Williams - an obvious reversal of illuminated poet William Blake. Wilson includes a subtler reversal between Williams' party dialog and the qabala implied. The qabala sounds more like William Blake. </span><br /><br /><div style="text-align: center;"><span style="font-size: small;"><span style="font-size: large;"><b>More Nonsense </b></span></span></div><span style="font-size: small;"><br /></span><span style="font-size: small;">At the end of the <i>Nineteenth Series of Humor,</i> a chapter which nearly begins with a crack of the Zen Masters staff, with the word "staff" seeming like a pun on a musical staff, Deleuze describes a different relationship between sense and nonsense: <span style="color: cyan;">"Becoming-mad changes shape on its way to the surface ... and the same thing happens to the dissolved self, the cracked I, the lost identity, when they cease being buried and begin, on the contrary, to liberate the singularities of the surface. Nonsense and sense have done away with their dynamic opposition in order to enter into the co-presence of a static genesis - as the nonsense of the surface and the sense which hovers over it. The tragic and the ironic give way to a new value, that of humor. ... humor is the co-extensiveness of sense with nonsense." <i>LS </i>p. 141</span></span></div><div style="text-align: left;">He goes on to say more about what humor does, basically saying that it leads to an enlightening state.<br /><br />The use of nonsense and humor to produce sense appears to aptly describe the best works of two prominent occult writers, Robert Anton Wilson and James Joyce, but it also describes the writing style of Aleister Crowley and sometimes of Deleuze and Guattari.<br /><br />In some of his works of fiction Wilson explored the cut-up technique which he picked up from Burroughs and Gysin. This technique of cutting up any writing, from Shakespeare to the daily newspaper, then randomly rearranging it to see what new combinations get made by chance, becomes a way to generate sense out of nonsense. This technique has been successfully used to come up with great song lyrics by both David Bowie and the Rolling Stones. <br /><br />Robert Anton Wilson quite brilliantly uses humor and nonsense, with a dash of paradox for flavor in his <i><a href=""><span style="color: magenta;">Introduction</span></a></i> to the play <i>Wilhelm Reich in Hell</i> to communicate a particular kind of sense. Our old friends the Mome Raths show up in this introduction - that's the only contribution from Alice which seems to echo Crowley's use of <i>Mome Raths</i> in <i>BL</i> 48</div><div style="text-align: left;"><span style="font-size: small;"><br /></span></div><div style="text-align: left;"><span style="font-size: small;">To be continued ...</span></div><img src="" height="1" width="1" alt=""/>Oz Fritz and Magick: Deleuze and Crowley with Special Guest Robert Anton WilsonMagick could be called applied philosophy. Philosophy can provide blueprints and start the <i>ignis</i> for affirmative action and intentional change. The two disciplines have been entwined dating back to antiquity. The pre-Socratic philosopher Empedocles introduced the division of matter into the four elements: Air, Water, Fire, Earth that continues as one fundamental principle of ritual magick to this day. <a href=""><span style="color: magenta;">According to the Internet Encyclopedia of Philosophy</span></a>, Empedocles: "has been regarded variously as a materialist physicist, a shamanic magician, a mystical theologian, a healer, a democratic politician, a living god, and a fraud." Except for the democratic politician, that could pass for a description of Aleister Crowley. The IEP goes on to say: ."<br /><br />An essential work of contemporary magical literature<i>, The Tree of Life, A Study in Magic</i>, by Israel Regardie, presents a clear and comprehensive overview of Golden Dawn-style magic. The beginning of Chapter 3 starts with the section: "<i>Necessity for philosophic training prior to undertaking practical work</i>." Regardie makes the point quite clear:<br /><br /><span style="color: yellow;"."</span><br /><br /.<br /><br /><div style="text-align: center;"><b><span style="font-size: large;">Antecedents</span> </b></div><br / <i>Confessions</i> <i>Historical Illuminatus</i> series, <i>Nature's God</i>. Wilson quotes Spinoza in <i>Schrodinger's Cat</i> at the beginning of the chapter <i>Dancing Photons</i>: "The intellectual love of things consists in understanding their perfections."<br /><br /, <i>Nietzsche and Philosophy</i>, <i>Difference and Repetition</i>. His interpretation disavows the common one, that everything repeats exactly the same, instead making the theory stand on its head to affirm difference as that which repeats. The Eternal Return = repetition AND difference. The film <i>Groundhog Day</i> provides an oversimplified example: it's always the same day, but there's always something different. The Eternal Return, as it appears in <i>Finnegans Wake</i> by James Joyce, became an early topic of discussion in the <i>Tales of the Tribe</i> course that Robert Anton Wilson gave. <i>Finnegans Wake</i> perfectly illustrates the difference and repetition of the Eternal Return. Various cycles repeat themselves, sometimes frequently, yet they reveal something different every time. Deleuze, for his part, borrowed the portmanteau term "chaosmos" - chaos + cosmos - from <i>Finnegans Wake</i> to describe the mixture of randomity and chance (chaos) with the ancient Greek philosophers who attempted to overlay order upon the world (cosmos).<br /><br /><div style="text-align: center;"><span style="font-size: large;"><b> The Will to Power and Do What Thou Wilt.</b></span></div><br />It's said of some early 20th Century philosophers that one of their projects was to provide a<br / <i>Deleuze and Guattari,</i> Deleuze defines the will to power as:<br /><br /><span style="color: cyan;">the genealogical element of force, both differential and genetic. <i>The will to power is the element from which derive both the quantitative difference of related forces and the quality that devolves into each force in this relation. </i> The will to power here reveals its nature as the principle of the synthesis of forces. (Nietzsche & Philosophy, p. 50, 56.) </span><br /><br />Bogue gives an interpretation of Deleuze's interpretation:<br /><br /><span style="color: cyan;">It seems that Deleuze is here positing the will to power as a kind of inner center of force, a general orientation of becoming that only manifests itself in specific forces but goes beyond individual forces to link them in a line of development.</span><br /><br /." (<i>Magick</i>, p.129). In the book <i>Dialogues</i> <i>The Book of the Law</i>, <i>The Book of Lies</i> and elsewhere in his writings.<br /><br / <i>The Book of the Law</i>), Wilson began and ended his posts in the same way making them all acts of love under will. He appeared quite fastidious about that for a time.<br /><br / <i>Illuminatus!</i>. <br /> <i>The Logic of Sense</i>, Deleuze uses the "contesting of Alice's personal identity" in Lewis Carroll's <i>Alice in Wonderland</i> and <i>Through the Looking Glass</i> stories as an example of language and identity. Deleuze writes:<br /><br /><span style="color: cyan;">"But when substantives and adjectives begin to dissolve, when the names of pause and rest are carried away by the verbs of pure becoming and slide into the language of events, all identity disappears from the self, the world and God.'</span><br /><br / <i>The Book of Lies</i>: "Man is only himself when lost to himself in the charioteering;" i.e. the subject gets lost in the process or what Deleuze calls the event.<br /><br /<i> Pure Immanence</i> to reflect the nature of his passion.<br /><br /.<br /><br /:<br /><br /><span style="color: yellow;".</span><br /><br /><div style="text-align: right;"> - <i>Magick</i>, p. 130, (translation modified).</div><div style="text-align: right;"><br /></div><div style="text-align: left;">One of the most significant books in Aleister Crowley's secondary literature is <i>Illuminatus!</i>: </div><div style="text-align: left;"><br /></div><div style="text-align: left;"><span style="font-size: large;">It was the year when they finally immanentized the Eschaton.<span style="font-size: small;"> </span></span><br /><br /><!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Version>15.00</o:Version> </o:DocumentProperties> <o:OfficeDocumentSettings> <o:AllowPNG/> </o:OfficeDocumentSettings></xml><![endif]--></div><div-TW<-size: small;"><span style="font-family: inherit;"><span style="line-height: 107%;"><a href=""><span style="color: magenta;">Wikipedia</span></a>, the source of all knowledge, says that the phrase originated in 1952 as a political theory in Eric Voegelin’s. <i>The New Science of Politics</i>. <i>Illuminatus! </i>sounds remarkably like Lewis Carroll’s Alice when she’s unsure about who she is. <i>Illuminatus!</i> begins right off with uncertainty about personal identity while, as mentioned, Deleuze confronts this point almost immediately in <i>The Logic of Sense</i>. Uncertain personal identity challenges the reality and validity of the subject getting replaced by the dynamic process, or the event. “I seem to be a verb, “ as Buckminster Fuller used to say.</span></span></span> <br /><br /><span style="font-size: large;"><span style="font-size: small;">For further research: this first sentence, "It was the year when they finally immanentized the Eschaton." adds to 80.</span></span></div><div style="text-align: left;"><br /><div style="text-align: center;"><span style="font-size: large;"><span style="font-size: small;"><span style="font-size: large;"><b>Repetition and Love Under Will</b></span></span></span></div><br />In <i>Difference and Repetition</i>, Deleuze radically redefines the regular meaning of repetition. He divides repetition into two kinds, bare and clothed. A ba<span style="font-family: inherit;">re repetition is something that rep</span>eats.<br /><br />Repetition + Difference + Intention = Magick.<br /><br /><i>Difference and Repetition</i> was Gilles Deleuze's first book devoted to his own philosophy. Up until that time, 1968, all his publications were historical sketches of other philosophers. <i>Difference and Repetition</i> was his doctoral thesis. On page 2 he writes:<br /><br /><span style="color: cyan;">The head is the organ of exchange, but the heart is the amorous organ of repetition. (It is true that repetition also concerns the head, but precisely because it is its terror or paradox)."</span><br /><br /.<br /><br /. <i>Illuminatus!</i> <i>Illuminatus!</i> unless it was Shea.<br /><br />Stay tuned for Part 2 of the Crowley/Deleuze show featuring the use of paradox.<br /><br /><br /><br /><br /><br /><br /></div><div style="text-align: left;"><span style="font-size: large;"><span style="font-size: small;"><br /></span></span></div><div style="text-align: left;"><span style="font-size: large;"><span style="font-size: small;"><br /></span></span></div><div style="text-align: left;"><span style="font-size: large;"><span style="font-size: small;"><br /></span></span></div><div style="text-align: left;"><br /></div><div style="text-align: left;"><br /></div><br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz, Leary's S.M.I L.E. and the 23 Enigma"Technology invariably trumps ideology. We develop ideologies as a way of coping with technologies; technology as drivers, ideologies as attempts to steer."<br /><br /><div style="text-align: right;"><i> - Mass Consensual Hallucinations with William Gibson </i></div><div style="text-align: right;"><br /></div><div style="text-align: left;">The <a href=""><span style="color: magenta;">previous post</span></a> gave information on the technology of Orb Running; more generally, it gave information on a technology for transformative brain change. S.M.I.<sup>2</sup>L.E<b>., </b>an acronym devised by Timothy Leary<b>, </b>formulates<i> </i>an open-ended, endlessly ramifying ideology for the future: Space Migration + Intelligence Increase + Life Extension. It serves as a practical formula for individuals on any kind of evolutionary trajectory as well as providing a conceptual basis for the advancement of collective human endeavor; a reach for the stars.<br /><br /><i>Neuromancer</i>, by William Gibson, gives a compelling and visceral literary expression of the S.M.I.<sup>2</sup>L.E<b>. </b>paradigm. For example, the book populates the <a href=""><span style="color: magenta;">L4 and L5 orbital belts</span></a>, where Gerard K. O'Neil and Timothy Leary wanted to establish space colonies, with worlds that resemble Leary's High Orbital Mini Earths (H.O.M.E.s), but with a realistic, gritty, human portrayal as opposed to Leary's more utopian vision. That covers Space Migration in the conventional exterior sense. Space Migration also gets implied in the interior sense through the characters adventures in cyberspace. Life Extension turns up in two prominent ways. The power-elite clan, the Tessier-Ashpools, keep their own meat carcasses frozen in cryogenic suspension with timed intervals of reanimation in order to extend their physical life span. Online immortality gets a play through the character of Dixie Flatline whose mind and personality managed to get downloaded onto a storage device before his meat carcass died in a cyberspace misadventure. Dixie seems mentally as sharp as ever when the personality/mind recording (a soul recording?) from his deceased body gets uploaded back into the matrix. He frequently becomes Case's (main protagonist) guide and informant in the cyberspace realm whenever Case jacks into the matrix. Both of these forms of Life Extension get a dystopian treatment in <i>Neuromancer</i>, a radical departure from Timothy Leary and Robert Anton Wilson's hyperbolic optimism on the subject. The Tessier-Ashpools complain of the cryogenic cold they can feel, the patriarch ends up committing suicide to get away from it. They are the richest, most powerful family and they are also the coldest. They're almost all cold. No social/political/economic metaphor there! Dixie Flatline hints at some dark existential suffering and asks Case to delete him after his duties have been discharged.<br /><br />The central part of the S.M.I.<sup>2</sup>L.E<b>. </b>formula,<b> </b>Intelligence Increase, seems the least obvious, the most occult and hidden in the book, yet also the most optimistic. Most of the events in <i>Neuromancer</i> get put into motion by a huge Artificial Intelligence named Wintermute, a veritable V.A.L.I.S. - a Vast Active Living Intelligence System. In this regard, it's interesting to hear Gibson in a 2010 interview with Steve Paikin suggest that Google is an Artificial Intelligence; "[it's a] vast hive mind that consists of us." Wintermute was designed and put into existence by one of the Tessier-Ashpools (3Jane if I remember correctly) to mute the winter, the incessant coldness that seeps into the bones of the cryogenically frozen. This coldness seems more than physical discomfort and pain, a sense gets conveyed of emotional and existential coldness as well. That the AI Wintermute becomes a solution to this problem implies that whoever designed it can transfer their awareness and cognitive abilities out of their frozen meat carcasses and into its vast active living intelligence system. I would call that an increase in intelligence to have that ability.<br /><br />Gibson borrows the idea of I.C.E., which stands for Intrusion Countermeasure Electronics, from fellow science fiction writer, Tom Maddox, to protect the architectonic structures of propietary corporate data. To penetrate any large system of data in cyberspace you first have to cut through the ICE. Qabalistically speaking, ice is frozen water and water always relates to emotions. In this light, ICE becomes a metaphor for Wilhelm Reich's concept of emotional armor. The name Wintermute suggests a shedding of this ice, this emotional armor, on a vast scale. Intrusion Countermeasures Electronics seems one of those puns with two completely opposite meanings. The intelligence increase communicated in<i> Neuromancer</i> primarily concerns emotional intelligence of the higher kind; what Leary and Wilson refer to as circuit 6 in their model. This emotional intelligence appears refreshingly free of sentimentality; sentimentality = sense the mental, not real emotional intelligence at all.<br /><br /<i> Neuromancer</i> based on the book. He also included the two obvious life extension methods Gibson put in the novel in a 1991 essay for Magical Blend magazine<i>: 22 Alternatives to Involuntary Death</i>. This got expanded and is currently available as the book <i><a href=""><span style="color: magenta;">Alternatives To Involuntary Death.</span></a></i><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="240" /></a></div><br /><br />In an interview Leary did with Gibson, the good doctor mentioned that the only book he'd ever annotated besides <i>Neuromancer </i>was <i>Gravity's Rainbow</i> by Thomas Pynchon. He went on to relate how he'd received <i>Gravity's Rainbow</i> in prison after a long spell of no books in solitary confinement; like eating an incredible meal when starving. No wonder he took a strong imprint with that book. Gibson related that when he got <i>Gravity's Rainbow</i> he retired from all other activity for several days to read and reread it; voluntary solitary confinement. <i>Neuromancer</i> and <i>Gravity's Rainbow</i> are two very different books, but what they both have in common is the frequent and visceral portrayal of death, so much so that you could say it becomes a character or an underlying omnipresent condition. <i>Neuromancer</i> (the name of the book, but also the name of an AI character in the book, Wintermute's twin, thus revealing the book as a form of AI) gives it away in the first sentence, "The sky above the port was the color of television, tuned to a dead channel." Leading with, "The sky," ending with "dead channel" suggests viewing death as a transcendent change as opposed to an absolute nihilistic end or some other terrible thing. The title <i>Gravity's Rainbow</i> commonly gets explained as indicating the rainbow-like trajectory of the V-2 rocket as gravity pulls it to Earth. Pynchon, known for his multiple meanings and levels of writing as well as his expertise in qabalah (see <i>Against the Day</i>), could just as well have named it <i>Gravity's Rainbow</i> to indicate the trajectory of a person's life as it's brought back down to the ground through gravity of death. In popular mythology, rainbow means God's promise or just hope, so if we see it as the gravity of death, then the rainbow indicates some kind of transcendent promise or hope. Again, death appearing as as transcendent change.<br /><br />In turn, <i>Neuromancer</i> appears to have influenced Pynchon, particularly in his last book, <i>Bleeding Edge,</i> in which the internet and the deep web play as strong a role in the plot's landscape as the matrix did in <i>Neuromancer</i>. The powerful antagonist putting up great obstacles in <i>Bleeding Edge</i> is named Gabriel Ice. Pynchon would know that Archangel Gabriel represents the element Water in qabalah; Gabriel Ice reinforces the notion of water (emotions) that is frozen. Pynchon seems to have to same intent as Gibson did with ICE though connecting it more with the everyday human world by making it a main character. <br /><br />There are 24 chapters in <i>Neuromancer</i> and there are 24 stages in Leary's 8 Circuit model of consciousness as given in his book <i>The Game of Life</i>. I remember Leary prefacing a lot of the stages and circuits with neuro: neurosomatic, neuroelectric, neurogenetic, neuroatomic etc. then a few years later out comes <i>Neuromancer</i> which seems like a doctoral thesis on S.M.I.<sup>2</sup>L.E<b>.</b><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="258" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">I believe this illustration is by Bobby Campbell, but I'm not certain.</span></div><br />We see more I<sup>2 </sup>information in the names Gibson gives his characters. One of them, Finn, is a surrogate used by Wintermute to deliver messages and help out Case. He seems to pop up at random times throughout such that when he reappears you could say, "There's Finn again." I made the connection to Finnegans Wake in the first post, but there's more. The initials of the main male character in Finnegans Wake is HCE, in Neuromancer it's HDC (Henry Dorsett Case). The H in Finnegans Wake stands for Humphrey. We have Humphrey and Henry as the protagonists in the two books. We are told HCE also stands for Here Comes Everybody in Finnegans Wake suggesting that James Joyce wrote the character to represent everyone or anyone. Except for one instance, Case is always referred to by his last name. The pun in his name seems obvious, Case could potentially be anyone, a test subject for the next step. His middle name, Dorsett = door + set; that appears an obvious qabalistic reference to higher emotional intelligence; door = daleth = the letter "d" = Venus. The difference between HCE and HDC is the letter D in the latter. The main female character, Molly Millions, suggests Tiphareth because of the 6 zeroes in the numerical form of her last name. Except for one mention, her last name is hidden throughout, she's only known as Molly.<br /><br />At some point toward the end of my most recent voyage through <i>Neuromancer</i> I began to wonder if Gibson had ever read Robert Anton Wilson. I knew he was very influenced by William Burroughs, it becomes quite obvious at times. The <a href=""><span style="color: magenta;">23 Enigma </span></a>represents one clear point of conjunction between Wilson and Burroughs. Burroughs first noticed the coincidence of the number 23 in relation to two disasters, a ferry boat sinking and a plane crash he heard about on the radio. No record of that plane crash has been found so it's possible he made the whole thing up or was implanted with a false memory to get the information out. It certainly didn't stop synchronicities with 23 from wreaking ontological havoc with many otherwise skeptical minds. Not long after I began this wondering, actually almost instantly, I came across the following passage on p. 189:<br /><br /><span style="color: yellow;"<b> </b></span><br /><span style="color: yellow;">Her chip pulsed the time.</span><br /><span style="color: yellow;">:04:23:04</span><br /><br /></div>The character climbing up is Molly with Case there virtually. He has a device that lets him switch from the matrix to jack into her nervous system and experience everything she does. This is the first instance we see a time readout, it recurs about 4 or 5 more times though never again with a 23. I couldn't tell if Gibson was hip to the 23 phenomena until I read the first sentence of chapter 23. Most people, after they get afflicted by this condition, ask, "what does it mean, all these 23s?" Wilson writes in <i>Cosmic Trigger</i>, " I accepted the 23 engima as something I should attempt to decipher." If we consider that this is one of those 23s and that it relates to her climbing out of gravity then a meaning is suggested that connects 23 with some kind of greater or lesser transcendent experience, climbing up the ladder one rung at a time. I consider it a good sign when I encounter synchs with 23.<br /><br />The opening sentence of Chapter 23 reads:<br /><br /><span style="color: yellow;">Molly fished the key out on its loop of nylon.</span> <br /><br />I could compose a whole 'nother blog about the qabalistic correspondences in this densely informational innocent looking sentence, but I'll try to restrain this tendency.<br />fish = Nun = death<br />both "out" and "on" represent different magick formulas in Crowley's language.<br />the key = death ("fished the key") ???<br />theMy job when I write a book is to access a lot of parts of myself that are magical, and they're not particularly remarkable, but they're not available to me ordinarily, they became available to me through the process of writing the book. So I sometimes get the strange sense of sitting there and watching it happening, which is great! It's good work when you can get it. I don't get it that often.</span><br /><br /><div class="separator" style="clear: both; text-align: center;"><br /></div><br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz Runners: Metaprogramming, Magick and NeuromancerThe metaprogramming world appears mostly blue and very watery. To activate a different metaprogramming module in this world, to enter a new set of instructions into the Deep Self, one has to swim through a channel of cool clear water; the modules are connected through canals of water. Metaprogramming code doesn't get written on the surface, it gets written in the depths to be played out on the surface. One has to dive deep into the depths, a potentially hazardous activity, or bring the depths to the surface in order to reprogram the code; to make a significant change. Metaprogramming - a computer programming term adapted by Dr. John Lilly for the purposes of self-induced, voluntary evolution. It means programming our programming, changing our habits and ways of functioning, our automatic, reflexive responses, how we habitually see the world. This is a post about a technology making possible conscious change in the depths and on the surface.<br /><br />Orb Runners jack into the Virtual Reality (VR) of the Prosperity Path Orbs like Case jacking into the cyberspace matrix in William Gibson's dystopian Sci-Fi thriller, <i>Neuromancer</i>., "<i>Who's on First?</i>" We call it voyaging the Macrodimensions of the Labyrinth, in bardo terminology. Ariadne's thread becomes the thread of consciousness; maintain the thread of consciousness.<br /><br />We model orb running after <i>Neuromancer</i> for several obvious reasons. Just read from the title to the first line in <a href=""><span style="color: magenta;">this pdf here </span></a> remembering that the metaprogramming world renders blue. The first line of the book reads: <span style="font-size: large;">"<i>The sky above the port was the color of television, tuned to a dead channel</i>." </span>Tell your vision Mr. Gibson. Or check out these initial descriptions of getting jacked in to cyberspace. They correspond point for point with orb running:<br /><br /><span style="color: yellow;">"...)</span><br /><br />"Corporate systems" = body.<br /><br />Compare this to when Case (the protagonist) has his Fall (which happens right near the beginning just as in <i>Finnegans Wake, </i>another Book of the Dead):<br /><span style="color: yellow;"><br /></span><span style="color: yellow;">)</span><br /><br />Gibson also has a character named Finn in <i>Neuromancer</i>; Another bardo writer, William Burroughs is another obvious influence as is, I suspect, Thomas Pynchon. On page 49 Case is asked if he's ever worked with the dead. Then on p. 51 we get another direct connection to orb running:<br /><br /><span style="color: yellow;">"The matrix has its roots in primitive arcade games," said the voice-over, "in early graphics programs and military experimentation with cranial jacks."</span><br /><br /.<br /><br /.<br /><br /.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="398" src="" width="640" /></a></div><br /><br />Most of the orbs are intended to either increase the intensity of a quality that's lacking (eg. the <i>Courage</i> orb) or remove/reduce an excess of an undesireable quality (eg. the <i>Worry</i>, <i>Obsession</i>, <i>Anger Detox</i> orbs.), or perform a specific function (<i>Chakra Cleanse</i>, <i>Karma Burn</i>, <i>Get Well Soon</i>, <i>Clear Light</i>, etc) Some orbs are designed to impart or help strengthen a skill (eg.<i> Astral Trainer</i>).<br /><br />The <a href=""><span style="color: magenta;">Orb Selection Portal</span></a> divides the orbs into 8 categories. The majority of orbs I run are in the Remedies or Cleansing categories. The<i> Get Well Soon</i> orb, found in the Power category, has an obvious use for Healers. One runner I know has recently been running this orb for the United States. Other frequent fliers are found in the Specialty category: <i>Peace</i>,<i> 6 Worlds</i>, <i>Metaprogramming</i> and <i>Stress Relief </i>are some of those. Many of the orbs have a similar structural form and/or shared aspects that cut across categories. For instance the <i>Panic</i> and <i>Find It</i>.<br /><br /.<br /><br />As soon as you - in the embodiment of your cyberspace avatar brought to life with your attentions - step into many of the orbs, a voice, sometimes female, sometimes male, says:<br /><br /><span style="color: yellow;">You are presently Out of Body. Proceed ahead for full HUD boost.</span><br /><br />Just as Case "jacked in to a custom cyberspace deck that projected his disembodied consciousness into the consensual hallucination of the matrix." HUD stands for <a href=""><span style="color: magenta;">Heads Up Display</span></a>. More explanation on these game details is found in <a href=""><span style="color: magenta;">an earlier post</span>.</a> That post also fleshes out the transformational potential, the magick, of these orbs.<br /><br />Several orbs have a black Cube with 9 discs on each of the 6 faces. When you pick it up, the voice of a Guide says:<br /><span style="color: yellow;"><br /></span><span style="color: yellow;">Your Matrix Attunement was successful, COUPLING FACTOR is in.</span><br /><br />Matrix connects with <i>Neuromancer</i> while also suggesting the <i>Matrix</i> trilogy of films which also has much valuable information pertinent to voyaging in computer simulated worlds. There appear several points of contact and overlap between <i>Neuromancer</i> and the <i>Matrix</i><i> Stress Relief</i>, <i>Pain</i>, <i>Panic</i>, <i>Amy's Beauty Boost,</i> or <i>Find It </i>orbs and experience the sensation of cooling off in the human operator.<br /><br /." (<i>The Book of Thoth</i> p.193). Acquiring the Cube in the orb occultly activates the quality of balance. The very first book in Aleister Crowley's school found at the beginning of the <i>Equinox Volume I Number I</i> is <i>Liber Librae</i>. Librae = Libra = the scales of Justice = balance. The first book Lon Milo Duquette assigned us to read in his online magick course was <i>Liber Librae</i>. This Cube, found one way or another at the start of almost all the orbs, resonates the note of "balance" with the beginning of the Hermetic path as presented by Crowley and Duquette. It's worth quoting the opening three verses of <i>Liber Librae</i>:<br /> <span style="font-size: small;"><span style="font-family: inherit;"> </span></span><br /><span style="color: yellow;"><span style="font-size: small;"><span style="font-family: inherit;">0. Learn first — Oh thou who aspirest unto our ancient Order! — that Equilibrium is the basis of the Work. If thou thyself hast not a sure foundation, whereon wilt thou stand to direct the forces of Nature</span></span><span style="font-size: small;"><span style="font-family: inherit;"> </span></span></span><br /><br /><span style="color: yellow;"><span style="font-size: small;"><span style="font-family: inherit;">1. Know then, that as man is born into this world amidst the Darkness of Matter, and the strife of contending forces; so must his first endeavor be to seek the Light through their reconciliation. </span></span><span style="font-size: small;"><span style="font-family: inherit;"> </span></span></span><br /><br /><span style="font-size: small;"><span style="font-family: inherit;"><span style="color: yellow;">2. Thou then, who hast trials and troubles, rejoice because of them, for in them is Strength, and by their means is a pathway opened unto that Light. </span> </span></span><br /><br /><br /> <a href=""><span style="color: magenta;">Liber Librae</span></a>.<br /><br />We find a similar image in <i>Neuromancer</i>:<br /><br /><span style="color: yellow;")</span><br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="" width="384" /></a></div><br / <i>Courage</i> or <i>Hero</i>.<br /><br / <i>Peace</i> Orb or any of the other orbs with lush, verdant landscapes.<br /><br /.<br /><br />We get some help from <i>Neuromancer</i> for jacking into an Orb avatar. This describes Case's awareness when it goes into another body:<br /><br /><span style="color: yellow;")</span><br /><br /?<br /><br / <i>Anger</i>, <i>Guilt </i>and <i>Energy</i> orbs as compared to others orbs like<i> Stress Relief</i>, <i>Peace </i>or <i>Karma Wash</i>.<br /><br />Different orb runs can get stacked, played one after the other, to form a series. I've had success combining the <i>Courage</i> and<i> Hero</i> orbs when preparing for excursions out of the country or even travel outside my zip code. <br /><br /<i> Amy's Beauty Boost</i>,.<br /><br />Another way to notice differences in orb run repetitions is to pay attention to the juxtaposition of spoken word statements ("You are now carrying a copy of the <i>American Book of the Dead</i>". <br /><br /><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="" width="640" /></a></div><br / <i>Neuromancer</i> when Case is jacked into the matrix trying to navigate through the ice, the protective software of large cyberspace entities.<br /><br /.<br /><br />TO BE CONTINUED ...<br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz Diary: Riley Pinkerton and Signs<div style="text-align: center;"><span style="color: yellow;"> And life was black and white; the Technicolor was just around the corner, but it wasn't there yet in 1959. <span style="font-size: x-small;">P</span>eople really do want to touch each other, to the heart. That's why you have music. if you can't say it, sing it.</span> - Keith Richards,<i> Life</i>, p.56 </div><br /.<br /><br /?<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="320" /></a></div><div style="text-align: center;"><span style="font-size: x-small;"> Riley Pinkerton</span></div><div style="text-align: center;"><span style="font-size: x-small;"> photo by Bryan Thunderheart Spitzer</span></div><br />When you hear all the details, it appears obvious that something extraordinary was going on, something in the realm that William Burroughs called The Magical Universe. Last spring, Riley sent me her EP, <i>Do You Have A Car</i>,.<br /><br />I had never known anyone named Riley before. Within a month of signing on to the project a college student named Riley took an internship at Ancient Wave, the local studio where I mix and master. I was reading Henry Miller's, <i>Time of the Assassins</i>.<br /><br / <a href=""><span style="color: magenta;">Tree of Life</span></a> from Chesed (Glory) to Geburah (Power). I made it to the gate just as they called for my boarding group (5); another good sign. <br /><br /.<br /><br /, <i>Twilight of the Idols</i> for $6.<br /><br />.<br /><br / <i>Inna Gadda Da Vida</i>. I first heard <i>Stairway to Heaven</i>.<br /><br />Rimbaud called. I decided to try to get<i> The Time of the Assassins</i> for Riley. The subtitle is: <i>a study of Rimbaud</i> by Henry Miller; a concise, easy-to-read book that nicely summarises much of the artist's misson, a subject I brought up in conversation with Riley. Rimbaud, the French symbolist poet whose most famous works are<i> A Season In Hell</i> and <i>Illuminations</i>,:<br /><br /><span style="color: yellow;".</span><br /><br />Miller rants about his current (1940's and '50's yet still relevant) state of Art: <br /><br /><span style="color: yellow;"? <i>Or what dreams?</i> ....</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">If the mission of poetry is to awaken, we ought to have been awakened long ago. Some have been awakened, there is no denying that. But now all WoMan have to be awakened - and immediately - or we perish.</span><br /><br />'Ol Henry probably would have been delighted to see Bob Dylan win a Nobel prize for Literature.<br /><br /: <i>The bizarre secrets of his greatest albums. </i> Well, that was something I could fact check so I picked up a copy along with cds of The Ramones first album and David Bowie's <i>Station to Station</i>. It proved an interesting article but the "secrets" on the albums I recorded with him appear exaggerated, inaccurate, and sometimes completely wrong. The magazine came with a compilation cd called <i>Ones From The Heart</i>. One of the artists on it is Ryley Walker. The store had a good Henry Miller selection that didn't include <i>The Time of the Assassins</i>. I've never read anything else by Miller, have never been interested in his popular titles, but I did pick up a slim volume by him that looked intriguing called <i>The Smile at the Foot of the Ladder.</i><br /><br /, <i>Take 5</i> that appeared on the 1959 album <i>Time Out</i> <i>Filipino Box Spring Hog</i>. In the dream he gets a call from his 5 year old son's kindergarten teacher telling him that his son is disturbing the other children by singing <i>Filipino Box Spring Hog</i>. This sounded a little farfetched to me, but Dylan swore it was true and recounted the dream again. The drum sound on that track is one of the secrets from recording<i> Mule Variations</i>, another coincidence.<br /><br /: <span class="null"> "My guitar is a 1962 Gibson LG-1 that I grabbed for a steal from a weird pawn shop in Michigan." </span>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="300" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">Dylan Sevey at Orange Music</span></div><div style="text-align: center;"><span style="font-size: x-small;">photo by Riley Pinkerton</span></div><div style="text-align: center;"><br /></div><div style="text-align: left;">" height="400" src="" width="285" /></a></div><div style="text-align: center;"><span style="font-size: x-small;"><span style="font-size: x-small;"> Riley checking out a take</span></span></div><div style="text-align: center;"><span style="font-size: x-small;"><span style="font-size: x-small;">photo by Bryan Thunderheart Spitzer </span> </span></div></div><br /><br /.<br /><br /.<br /><br />On break, the conversation drifted around to the <i>American </i>and <i>Tibetan Books of the Dead.</i>.<br /><br /!<br /><br /.<br /><br /.<br /><br / <i>Eyeland</i>..<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="400" /></a></div><div style="text-align: center;"><span style="font-size: x-small;"> Control room view of Florence Wallis recording underneath a Neumann U47</span></div><div style="text-align: center;"><span style="font-size: x-small;">photo by Riley Pinkerton</span></div><br />Riley set Florence up to stay the night at a Jersey Air bnb, there were more parts to record the following day. She asked Riley for a book to read, hers was almost done. Riley loaned her <i>The Smile at the Foot of the Ladder</i> which lead down a rabbit hole of synchronicity to some small degree. I had picked up Miller's book because it reminded me of Timothy Leary's S.M.I.<sup>2</sup>L.E<b>.< <a href=""><span style="color: magenta;">this one</span></a>. But, also, in my opinion: Music = Space Migration (changing moods, going into different interior spaces) + Intelligence Increase (gnostic experiences, etc) + Life Extension (time dilation; temporal effects). Music = S.M.I.<sup>2</sup>L.E<b>.</b><br /><br />The book begins with:<br /><br /><span style="color: yellow;">Nothing could diminish the lustre of that extraordinary smile which was engraved on Auguste's sad countenance. In the ring this smile took on a quality of it's own, detached, magnified, expressing the ineffable.</span> <br /><br />The synchronicity of <i>The Smile at the Foot of the Ladder, </i:<i> smiling, smiling, smiling</i>,.<br /><br / <a href=""><span style="color: magenta;">Rockit </span></a>by Herbie Hancock came about. Bill said of the restaurant ambience that it felt like being in a time machine. The neon pastel lights and Japanese atmosphere had me flashing on Tokyo in the late 80's.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="400" /></a></div><div class="separator" style="clear: both; text-align: center;"></div><div style="text-align: center;"><span style="font-size: x-small;">Mike Sopko, Bill Laswell and myself on 23rd Street.</span></div><div style="text-align: center;"><span style="font-size: x-small;">photo by Yoko Yamabe</span></div><div style="text-align: center;"><br /></div><div style="text-align: left;"></div>The last day of recording at Orange Music was spent mainly with Riley nailing four or five lead vocal overdubs. She also played a part on an electric guitar going through a pedal that emulated a mellotron. We finished in time to catch a train into the City to meet up with Riley's father, John McCurry at another sushi restaurant in Alphabet City. Riley's nonstage name is Riley Pinkerton-McCurry. John McCurry is a longtime New York resident and worked as a top session guitar player for many years including a 6 year tenure in Cyndy Lauper's band. We had mutual close friends in the business including Jason Corsaro and Jeff Bova, both old time Laswell cohorts. He had worked at Platinum Island studios where I had started out. McCurry had that paradoxical Irish quality of genuine sincerity mixed in with a bit 'o the blarney to much good humor. He treated Riley, Reggie and myself to dinner along with an uber ride back to Jersey. It was a dinner of celebration.<br /><br />Gilles Deleuze constructs a taxonomy of signs in <i>Proust & Signs</i>, his study of Marcel Proust's magnum opus, <i>In Search of Lost Time</i>.:<br /><br /><span style="color: yellow;"."</span> <br /><br />Interpreting the language of signs from the environment hardly seems new. In <i>The History of Magic</i>, Eliphas Levi tells us that Oswald Crollius, an alchemist in the 14th Century wrote <i>The Book of Signatures</i>, or <i>True and Vital Anatomy of the Greater and Lesser World</i>. Levi writes:<br /><br /><span style="color: yellow;".</span><br /><br /.<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="300" /></a></div><br />I've said nothing about the actual music because it's still in process awaiting final overdubs and a mix. Why saddle it with representation (i.e. a classification or even a description) before it has been born?<br /><br /!! <br /><br />ps On the train ride into New York for our last supper Reggie asked me to recommend some books to read. The ones I can remember suggesting are:<br /><br />1. Cosmic Trigger, The Final Secret of the Illuminati by Robert Anton Wilson<br />2. Stranger in a Strange Land by Robert Heinlein<br />3. The Stars My Destination by Alfred Bester<br />4. A Thousand Plateaus by Gilles Deleuze and Felix Guattari.<br /><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="320" /></a></div><br /><div style="text-align: center;"><span style="font-size: x-small;">Florence, Oz, Riley, Reggie</span></div><br /><img src="" height="1" width="1" alt=""/>Oz Fritz the Production of Music How to do it? Record company budgets for developing new artists are virtually nonexistent compared to 25 years ago before the internet changed the way music reproduction gets monetized. Prior to that, a certain percentage of profits got fed back into the music making machine. This allowed the process to continue as well as providing funds for new artist development. The profits from one hugely successful group could finance a whole roster of less commercial, but aesthetically brilliant artists. That all changed with the advent of free, downloadable music files. The previous model may have been far from ideal - the nature of Capitalism exploits and dupes the unaware - but at least it sustained an economy of music with enough leeway to finance more adventurous, esoteric, and experimental projects.<br /><br />We <i>Turn On Your Love Light</i> while Led Zeppelin suggested building a <i>Stairway To Heaven</i>.<br /><br /.<br />,<i> Heart Nouveau</i>..<br /><br />Sarah is recording a solo album and I'm helping with the production. A crowd funding campaign has been initiated to finance this project: <a href=""><span style="color: magenta;">Wild Belonging: A Song Pilgrimage.</span></a>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="300" src="" width="400" /></a></div><br />The songs on <i>Wild Belonging</i> connect with the spirit and intent of the Walking Water pilgrimage.<br /><br />Here's a preview from the new album, a live version of <i>Little Baby</i>:<br /><br /><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><br />I first heard about the <a href=""><span style="color: magenta;">Walking Water project</span></a>.<br /><br /.<br /><br />John Lilly mentions in <i>Center of the Cyclone</i> that his father told him at one point that if he wanted to be a serious scientific researcher, he'd have to learn how to ask for money to fund it. <a href=""><span style="color: magenta;">This crowd funding campaign</span></a>. <br /><br />And for a final proof of concept, I give you this video, <i>Just Fine</i>..<br /><br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="420"></iframe></div><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz African girl and the North SeaExactly a year ago today a young girl, Jessica Phiri on vacation from Zambia, tragically died off the coast of Holland. My friend, Ruud Houweling, a longtime resident of the resort town where the family was staying, wrote <i>Night Falls On The Town</i> to mark the mood and atmosphere of the the three days that Rescue Crews searched the Sea in vain. Ruud's story of the song's genesis is <a href=""><span style="color: magenta;">here</span></a>.<br /><br />We recorded <i>Night Falls On The Town</i> and the other songs that make up Houweling's forthcoming album release, <i>Erasing Mountains</i>,.<br /><br /.<br /><br />The video does an outstanding job of visually reinforcing the bardo space <i>Night Falls On The Town</i> evokes. The story contrasts the carefree life of the tourists against tragic death and what goes in between:<br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><br /><img src="" height="1" width="1" alt=""/>Oz Fritz Love Bomb and other SynchronicitiesWe are in the dog days of summer, I'm active in a <i>Cosmic Trigge</i>r online discussion and Coincidence Control is working overtime (over time) on the case. <i>Cosmic Trigger</i>, for those who may not know, is a richly entertaining classic in the literature of High Intelligence and Alchemical Transformation. Among its multiplicities, the various avenues of spiritual research author Robert Anton Wilson reported on in the book, is a look at synchronicities, meaningful coincidences - but meaningful for what? Wilson reports on the '23 enigma,' a phenomena he first heard about from William Burroughs where the number 23 pops up more often then usual and in surprising, unexpected ways. Wilson compared his experience with the 23 enigma to the key for cracking the genetic code of DNA. This insightful observation suggests paying more attention to coincidences as a form of spiritual guidance. <i>Cosmic Trigger</i> is perhaps the first, and still one of the only philosophical treatises I know of that valorises synchronicities, but not without much cautious skepticism. It's also one of the most lucid and rational introductions to the work and mission of Aleister Crowley - to turn the switch ON i.e. illuminate the world. Not only does it make Crowley's work known, <i>Cosmic Trigger</i> provides key data for penetrating into and practically applying this work such as the enigmatic Knowledge and Conversation of the Holy Guardian Angel, or, as I call it, the lazy person's approach to finding a spiritual guide.<br /><br />Went.<br /><br / <i>blessedness</i> should be reserved for these active joys: they appear to conquer and extend themselves within duration.", (Deleuze, <i>Spinoza, Practical Philosophy</i> p. 51) Love under will means that these affects can get directed. Spinoza's first name, Baruch, means blessed.<br /><br />Joe was familiar with <i>Cosmic Trigger.</i>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" src="" width="640" /></a></div><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="font-size: x-small;"> Atomic Love Bomb drummer Mike Brown setting-up</span></div><br />To get a vocal sound I asked singer Courtney Ballardo to sing a verse acapella. She surprised me with the first verse of Leonard Cohen's <i>Hallelujah</i>, <i>West Wing</i>. The best version of Cohen's <i>Hallelujah</i>, for my money, is the one Courtney sang for Atomic Love Bomb for this new lp. Segue to an Iggy Pop quote:<span style="font-size: large;"> "A good lp is a Being, it is not a product. It has a life force, a personality and a history just like you and me. It can be your friend."</span> This is what their lp is shaping up to become.<br /><br />Three days before getting keyed into the memory of Robert Anton Wilson's death through <i>Hallelujah</i>, a post appeared on the RAWIllumination.net blog called <a href=""><span style="color: magenta;">RAW's Poignant Goodbye.</span></a>.<br /><br />After one of those horrific school shootings a few years back I wrote a <a href=""><span style="color: magenta;">position paper </span></a."<br /><br />I mixed a set for Ma Muse at the World Music Festival today, we went on at 10 am. One of the songs they did for soundcheck was their song <i>Hallelujah</i>,.<br /><br />They didn't play this today, but it fits the theme of this post, so I leave you with this:<br /><br /><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><div style="text-align: center;"> </div><br /><br /><br /><br /><br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz WorrellBernie Worrell could play keyboards like Jack Kerouac could write or Robin Williams could do comedy, it flowed out of him spontaneously and effortlessly. It was almost always brilliant the first time, first take.I don't remember doing a lot of retakes with him. He was a master of improvisation, only it didn't seem like improvisation more like tapping into an immanent field of musical choices he could directly access. He was a storyteller in song. This was demonstrated in the many concerts he opened with a 10 - 15 minute tour of the musical universe quoting a range of references from Bach to Cosmic Slop, from Monk to the theme from Ghostbusters, or the current top 40 pop hit. It always sent you on a journey at the speed of sound, musical affect and the imagination.<br /><br />Bernie makes a good argument for reincarnation. He gave his first concert at the age of 4, wrote a piano concerto at 8, and performed with a Symphony Orchestra when he was 10. These two quotes from an <a href=""><span style="color: lime;">excellent</span> </a><span style="color: lime;"><a href="">interview</a> </span>by Torsten Schmidt candidly describes Bernie's approach and talent in his own words:<br /><span style="color: magenta;"><br /></span><br /><div class="ng-scope"><span style="color: magenta;">I don't deal with realization. I was born with perfect pitch, so anything I hear I can play. Whatever the gift God gave me, I don't sit and decipher; I just do it. And the way I hear - everyone has a different way of hearing - so the way I hear, I can hear the relationships. I can hear the same scale or mode in a classical piece, you can find the same mode in a gospel hymn. Same mode in a Indian raga, same mode in a Irish ditty, same mode in a Scottish ditty, or whatever you wanna call it. Same mode in Latin music, African. It's all related. It's how you hear it. And then on hearing and recognising, "Oh, yeah. I heard that in a pop song." Same chord progression, you know? Everything is related. I just happen to be able to hear that.</span><br /><br />Bernie on his influences:<br /><div class="text-speaker ng-scope"><br /></div><div class="ng-scope"><span style="color: magenta;">I didn't look up to them, I was influenced. No one should look up to anybody. What's that mean? OK, Ray Charles, Keith Emerson, Thelonious Monk, Herbie Hancock. Victor Borge, he was this Danish keyboardist who's one of my favorite, my antics on-stage now, where I get a lot of my stuff from, because he'd be a serious classical piece and then fall off the bench. Just stuff. And that's my other way of... I guess... so serious. Have some fun. Put some humor into it. That's what I like to do. I play, ’Nah nah nah nah', in the middle of a classical piece. I'll do it on purpose, just to, "Man, wow, where'd that come from?" Make you think. "Don't be so uptight, we have a song now. If you want things to be alright, stop being so uptight and move on." Part of the uptightness in you, if you don't let it go, you're gonna be... It's like a P-Funk song: "Free your ass and your mind will follow" Breathe</span></div><div class="ng-scope"><br /></div><div class="ng-scope">Bernie had a thing for purple, always wearing either a purple scarf, hat, jacket or something else. I don't know why. He was wearing a purple cowboy hat when a small group of us went to Disneyland in Tokyo. Spike Lee was criticized for wearing a purple outfit to an awards ceremony a day or two after Bernie moved on. The media reported as being a tribute to Prince, but I suspect it was just as much an homage to G. Bernard Worrell Jr.<br /><br /> Coincidentally enough, today I read a summary of Goethe's color theory and how figure comes into existence:<br /><br /><span style="color: magenta;">From Goethe's color theory, then, we can extract a three-tiered genesis of the visible, a passage from an invisible, blinding pure light, through an indistinct halo or atmosphere of black and white to the colors and contours of distinct figures, white darkening into yellow, black into blue, yellow and blue reaching their maximum intensity in purple. </span><br /><span style="color: magenta;"> </span> - Ronald Bogue, <i>Deleuze on Literature</i><br /><br />Purple is the royal color. It served as an important signifier in the magick I used to become a better engineer; it corresponds on the King Scale to Mercury, the Roman trickster god of communication and psychopomp to the dead. Bernie could be a trickster.</div><br /><span style="color: magenta;"> <span class="ng-scope"><span class="body db transcript"><span class="text-layout--center db ng-isolate-scope"><i>Worrell moves to the organ and plays a long, improvisational sequence that blends big dynamic moments with nursery rhymes and other musical references, ending with snatches of "Let It Be" and "The Wind Cries Mary." Worrell goes back to the couch and sits down / applause</i></span></span></span></span><br />(from Schmidt's interview )<br />"I communicate better through music and song than I do with words," to paraphrase from the interview.<br /><br />With his connection to purple and that fact he had quite a lot of genius mojo going on, it hardly surprises me to find him wearing a winged Mercury helmet, flashing the famous Worrell grin.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">photo credit unknown</span></div><div style="text-align: center;"><span style="font-size: x-small;"> </span></div>Don't know if it was somehow due to this archetypal connection we shared with purple, but he always seemed interested in my extracurricular activities and did what he could to support them. For instance, there was a day of press interviews while Material was touring Japan. Bernie asked me to sit with him. The journalists would start to ask the same predictable questions, whereupon he would say something like, "What I'm really excited about and want to talk about today is my friend Oz's art gallery." A big chunk of the Bernie Worrell interview would then be about the gallery." He could care less about self-promotion. They sent me the magazines when the articles were published. They were in Japanese, obviously, so I couldn't tell how they segued from Mr. Worrell's music career to his friend's art gallery in Brooklyn.<br /><br />In the early days of working with Bernie at Platinum Island and Greenpoint I frequently experimented with placing art images around the studio and control room. At some point I acquired a shoebox full of <i>Alien All-Stars </i>bardo trading cards. These were laminated, baseball-card sized abstract drawings of aliens by E. J. Gold. I gave a dozen or so of these to Bernie and later, from a photo, saw that he had placed these around his Hammond B3 at a gig in similar fashion that I did at the mixing desk.<br /><br />By bardo trading cards, it indicates that the images had one intention of subtly familiarizing the viewer to the intensity consciousness faces after the body and brain permanently die. In other words, the space Bernie might hang out in right now according to several ancient traditions ranging from Tibet to Egypt to Peru. Who fucking knows, really? The point is that Bernie took to this material like a fish to water, not because he needed it - I suspect he was well-prepared for death long before I met him - but from some kind of resonance or recognition. Out of any musician I've ever worked with, he seems the most equipped to deal with the high stresses and intensities of life without a body and brain. Still, I do Clear Light bardo runs for him with the <span style="color: magenta;">PP Orbs</span>. It's a video game-like environment on a platform hovering in a virtual sky. Colors serve as important signifiers and mood changers in these orbs. Got a sense of surprised recognition to observe that the platform that holds the whole thing up is purple.<br /><br />Bernie seemed like he could cross over between the two worlds with ease. He would draw out musical ideas, atmospheres, moods, textures, dialogue, etc. from some wholly Other place as easily as flipping a switch. Though it couldn't be proven, in my opinion, he's the best example of how a life devoted to music and its mastery can alchemize a powerful spiritual being, a force of nature. <br /><br />It felt like he might have taken me over to the other side one night in Europe, or perhaps we visited it together? Late at night, after eating, after a gig, a group of us walking to the hotel. Bernie tells me I can go to the studio to meet Keith Richards when he's recording with him in the near future in NY ( I never made it.) Somehow, we start talking about UFOs and possible Intelligence from Outer Space, that kind of thing. I start to tell him something along those lines when I get this realization that he already knows what I'm talking about, I say something like that to him adding: "because you are a Space Brother!" He just flashes the famous Worrell grin and we both laugh.<br /><br />Bill Laswell wrote this for him (<span class="short_text" id="result_box" lang="la"><i><span class="">ingenio</span> <span class="">ingenium</span> </i><span class=""><i>in</i>):</span></span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="" style="cursor: move;" width="433" /></a></div><br /><br /></div><img src="" height="1" width="1" alt=""/>Oz Fritz You Have A Car - Riley Pinkerton<span style="font-family: "arial" , "helvetica" , sans-serif;">It's a statement, not a question, though it appears as a question disguised as a statement. <i>Do You Have A Car</i>. Without the defining punctuation of a question mark or exclamation point, it could be either. The ambiguity in the title of Riley Pinkerton's new five song EP hints at the labyrinthian depths explored in her songs. I also interpret it to ask/demand of the listener whether they're equipped with the necessary aesthetic vehicle to follow where the music will take you. This offering sounds like pages from a diary of artistic experimentation expanded through the eyes and understanding of an apprentice seer finding her vision; a folk musician ascending, like a young Joni Mitchell, but with her own voice and musical sensibility. <i>Do You Have A Car</i> became a catch-phrase as part of the events surrounding Riley's decision to become a solo artist and move from Michigan to New York City. A major change, a big transition, a death from an old life into a new that bore intriguing musical fruit along the way - hauntingly evocative folk songs that reach deep inside exposing the pain and mysteries of life. She explains further in a short interview I did with her below. Riley was formerly a member of the DeCamp Sisters whose EP, <i>Quick, Efficient and Deadly</i>, I wrote about<a href=""><span style="color: magenta;"> </span><span style="color: magenta;">here.</span></a></span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><br /><div class="separator" style="clear: both; text-align: center;"><span style="font-family: "arial" , "helvetica" , sans-serif;"><a href="" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="" width="400" /></a></span></div><span style="font-family: "arial" , "helvetica" , sans-serif;"><span style="color: magenta;"> </span> </span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;">The, <i>In His Image.</i></span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif; font-size: large;">Go <a href=""><span style="color: magenta;"> here.</span></a> to buy or listen to it. Head to the <a href=""><span style="color: magenta;">website</span></a> to see the DYHAC lyrics.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;">The first song, <i>Marina<.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;">The second track, <i>Frankenstein</i>, <i>Frankenstein</i>.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;"><i>In His Image</i>,.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><i><br /></i></span><span style="font-family: "arial" , "helvetica" , sans-serif;"><i>We're All Wild</i>.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;"><i>The Queen's Brigade</i> <i>The Fairy Queene, </i>the epic 16th Century prose poem.that influenced Shakespeare and Crowley among many others, including, on an intuitive level at least, Riley Pinkerton.</span><br /><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;".</span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="265" src="" width="400" /></a></div><span style="font-family: "arial" , "helvetica" , sans-serif;"><br /></span><span style="font-family: "arial" , "helvetica" , sans-serif;">Riley graciously and candidly answered a few questions I posed about her new EP and future recording plans:</span><br /><br /><div dir="ltr" id="docs-internal-guid-eafe2fa0-e329-cb63-0d0d-e8b130cc355d" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt;"><span style="color: white;"><span style="background-color: transparent; font-family: "arial"; font-size: 14.666666666666666px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline;">1. What inspired the title <i>Do You Have A Car</i>?</span></span></div><div dir="ltr" id="docs-internal-guid-eafe2fa0-e329-cb63-0d0d-e8b130cc355d";">2. What are some of your musical influences? Your melodies sound like you might be familiar with traditional Irish or English folk ballads?< </span><span style="background-color: transparent; font-family: "arial"; font-size: 14.666666666666666px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline;";">3. You recently moved from Michigan to New York City. How has that affected your musical direction?<?</span></span></div><div dir="ltr" style="line-height: 1.38; margin-bottom: 0pt; margin-top: 0pt;"><span style="color: white;"><br /></span></div><span style="color: white;"><span style="background-color: transparent; font-family: "arial"; font-size: 14.666666666666666px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline;"> </span><span style="background-color: transparent; font-family: "arial"; font-size: 14.666666666666666px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline;">Thank you, Oz; that is very kind. I have a considerable amount of new material which I’ve been regularly taking out for a spin at live shows. There’s been a shift in my songwriting concerning subject matter; I went through a phase of focusing almost entirely on writing fictional/metaphorical story-songs. Lately, my writing has shifted into a first-person, more cathartic or emotionally analytical mindframe. As far as recording, I’m aiming to get back into the studio to record my first full-length album this September. The arrangements on Do You Have A Car were extremely minimal and sparse; I plan to work with a band (drums/electric bass/guitar) for my full-length. DYHAC is definitely reverb-heavy and I would like to experiment with different approaches in that regard; I don’t plan on reverb playing a key role in my sound, though I suppose I won’t know for sure until I get there. As far as links between DYHAC and my full-length: while as much as I’d love to go hog-wild with a band, I want to be sure to maintain a sense of intimacy and feature songs recorded as simply and honestly as those on DYHAC. Two of the tracks on DYHAC I was able to record completely live (playing and singing simultaneously), and that’s something I’d like to put into practice as much as physically possible while recording my album.</span></span><br /><br /><span style="font-size: large;"><span style="font-family: "arial" , "helvetica" , sans-serif;">A further description and additional reviews of <i>D<span style="font-family: "arial" , "helvetica" , sans-serif;">YHAC </span></i>is <a href=""><span style="color: magenta;">here</span></a>.</span></span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="147" src="" width="400" /></a></div><img src="" height="1" width="1" alt=""/>Oz Fritz the Book: Folklore by Jack and the Bear<div style="text-align: center;"><span style="color: cyan;"><span class="null" style="font-size: large;">Pulling inspiration for sound from a lucid nightmare also proved to be one of the biggest contributors to the aesthetic of this record. I realize I will always hear the songs a little differently in the sense that I am revisiting once subconscious thought now translated through sound. </span></span></div><span class="null"> - Adam Schreiber </span><br /><span class="null"><br /></span><span class="null"><i>By the Book: </i></span><span class="null"><i>Folklore by Jack and the Bear </i> <a href=""><span style="color: magenta;">here </span></a>where you can also stream the album.</span><br /><span class="null"><br /></span><span class="null".</span><br /><br /><span class="null"><span style="color: cyan;". <br />After roughly twenty years of warfare, a select group of "self-elected, self-praising, privileged business enthusiasts took it upon themselves to plot and start a new civilization. </span><br /> </span><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="320" /></a></div><br /><div style="text-align: left;"><span class="null", <i>Greed's Theme Part 1</i>, <i>Metropolis</i>, Terry Gilliam's <i>Brazil</i> and the film version of Pink Floyd's <i>The Wall</i>.</span></div><span class="null"><br /></span><span class="null">Here's one video interpretation, a tragic love song called <i>Smokestacks</i> that might be a play on words as Smoke is also the name of a female character in this saga:</span><br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><br /><span class="null"><br /></span><span class="null">This sound of this production is spacious with vast rooms of depth to get immersed into. It makes for easy induction into their self-described lucid nightmare. Maybe they should call upon Tim Burton to direct the <i>By the Book</i> film? The sonic environment is always interesting especially with the connecting link of industrial machinery stomping, clanking, and letting off sharp whistling blasts of steam in the background. </span><br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="270" src="" width="400" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">Jack and the Bear</span></div><br /><span class="null">The process of how this Art came into existence is fascinating. I asked one of the writers in Jack, Brandon James, about this:</span><br /><br /><span class="null"><span style="color: cyan;"</span></span><br /><br /><span class="null"><span style="color: cyan;". </span> </span><br /><span class="null"><br /></span><span class="null">I asked producer/engineer Adam Schreiber if their environment played any part in the sound:</span><br /><br /><span style="color: cyan;". </span><br /><br />I asked Adam about his vocal processing. The narrator goes through a variety of characters and situations each with a distinctive sound. He was quite candid:<br /><br /><span style="color: cyan;">.</span><br /><br />Brandon told me what they learned making this album:<br /><br /><span style="color: cyan;">.</span> <br /><br />.<br /><br />I recorded their first album and wrote about it <a href=""><span style="color: magenta;">here.</span></a> <br /><br /><a href=""><span style="color: magenta;">Facebook Page</span> </a>with booking and press contact info; and their <a href=""><span style="color: magenta;">website</span></a>.<img src="" height="1" width="1" alt=""/>Oz Fritz Sections - Libby DeCampFans of the music of Tom Waits will love this album. Musically stark and often dark, it recounts a broad range of the often painful vicissitudes of life in a variety of characters and situations. Yet some unspeakable quality in Libby DeCamp's vocal delivery, the affects produced by the sound of her voice, invariably hints at redemption of some kind, if only by telling the tale, immortalizing the tragedy, immortalizing humanity with all its flaws, thus affirming life. <br /><br />Mavis Staples speaking of a young Bob Dylan wonders how anyone that young could speak with such authority and experience about subjects beyond his years. Libby DeCamp has a similar quality of wordly wisdom in her voice and an ability to assume characters far outside her lived experience. She makes them and their stories real: the rise and fall of the ghetto sage in <i>Seattle</i>; the farmer in <i>Put The Kettle On</i>; the <i>Old Witch</i> in a twisted adult Nursery Tale; <i>Elroy</i>, the failed hero; the outlaw in <i>Black Suit Man</i> - perhaps a speakeasy operator, singing to his nemesis, Mr. Hoover likely J. Edgar, but could also apply to Herbert. The lyrics throughout contain much rich, suggestive imagery; poetic, sometimes whimsical and offbeat, a mixture of ironic comedy and profound tragedy without being the least bit cynical or nihilistic. The authentic, weathered flavor of the music for each song provides the atmosphere and movement to draw the listener in to the intimacy of the stories - the delicate fragile scarred emotions of fractured, unfulfilled lives - lives that get some measure of glory and validity by having their stories told. <i>Cross Sections</i> - slices of life and death from odd, different and unusual angles; cross sections exposing the depths of the ancient American underbelly.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="320" /></a></div><div style="text-align: center;"><br /></div><div style="text-align: center;"><span style="font-size: large;"> You can get it <a href=""><span style="color: magenta;">HERE</span></a></span></div><br />This is a warm and clear production with lots of spatial depth courtesy of Adam Schreiber who also provided drums and percussion. His brother, Brandon James, anchored the Upright Bass. They're both from the Michigan based band Jack and the Bear whose new release, <i>By the Book</i>, I'll be writing about fairly soon. I wrote about the album I recorded with them <a href=""><span style="color: magenta;">here</span></a>.<br /><br />The warm sound and seductive grooves of <i>Cross Sections</i> makes you want to listen, it draws the attention in. Musically you could loosely describe this as folk blues aesthetically related a bit in sound and mood to the Tom Waits <i>Mule Variations</i> era. DeCamp calls this music "Broken Folk." The second track<i>, Seattle,</i> recalls the production values of the T. Bone Burnett produced <i>Raising Sand </i>by Alison Krause and Robert Plant. The starkness of the sixth track, <i>Charlie</i>, just a very close vocal and pump organ telling the old drifter's story, carries the same sense of desolate emptiness as Bruce Springsteen's <i>Nebraska</i>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="277" src="" width="320" /></a></div><div style="text-align: center;">Adam Schrieber & Libby DeCamp</div><div style="text-align: center;"><br /></div><div style="text-align: left;">DeCamp's ability as an artist to absorb and express a wide range of diverse influences, to convincingly invoke the struggles of the human condition, invites comparison to other epic works of art with similar aims. Fanciful or not, I couldn't help but noticing the opening lyrics of <i>Elroy</i>, the first song on <i>Cross Sections</i> has the character say: " I could have crossed the river deep..." which suggests to the literary mind the "riverrun.." that begins James Joyce's Finnegans Wake. Both use the river as a metaphor for life; cross sections from the river of life.<br /><br />Related to this album - A concept I've been struggling to understand the past few months, comes from Deleuze in <i>Nietzsche and Philosophy</i>:<span style="color: cyan;"> "The tragic is the aesthetic form of joy, not a medical phrase or a moral solution to pain, fear or pity."</span> While I'm still not to the point of being able to explain that further, listening to <i>Cross Sections</i> will impart an experiential feeling for that idea. DeCamp's sings against a plaintive, sometimes slow, bano-picking, blues-based musical environment that underscores the tragic elements, but also moves and emotionally communicates an aesthetic form of joy. In <i>Birth of Tragedy</i>, Nietzsche illustrates the importance of tragedy in making relevant art. He signifies the wild, instinctual, chaotic depths of artistic creation after the Greek god, Dionysus. Good music, real music makes known this Dionysian current. Under the heading <i>The Essence of the Tragic</i>, <i>ibid</i>., Deleuze writes: <span style="color: cyan;">" Dionysus affirms all that appears, 'even the most bitter suffering,' and appears in all that is affirmed. Multiple and pluralist affirmation - that is the essence of the tragic. This will become clearer if we consider the difficulties of making <b>everything</b> an object of affirmation. ... When anguish and disgust appear in Nietzsche it is always at this point: can everything become an object of affirmation, <b>that is to say of joy</b>?"</span> I submit that the music of <i>Cross Sections </i>fulfills this function magnificently with elegance and soul. Paradoxical as it may sound, it brings joy to listen to these tragic tales; the proactive listener, moved by this music to affirm life, plays just as much of a redemptive role as the singer and musicians. Listening to and connecting with <i>Cross Sections </i>brings clandestine joy into the world in the form of tragedy redeemed and immortalized. <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="213" src="" width="320" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">DeCamp and her choice weapon of affirmation</span></div><br /><br />I've said very little about DeCamp's writing influences and musical history. Her <a href=""><span style="color: magenta;">Facebook page </span></a>reveals it most eloquently:<br /><span style="color: cyan;"><br /></span><span style="color: cyan;"><span style="font-size: small;"><span style="font-family: inherit;">Out from the quiet orchards of Romeo, Michigan, Libby DeCamp has spent an adolescence in close companionship with bodies of <span class="text_exposed_show">music and literature, among hinterlands of horses and history. Driven by a will to connect on a raw, human level and stir to compassionate action, she has been writing and playing songs since her early teens under several different outfits, namely Michigan folk duo, "The DeCamp Sisters." After its dissolve in spring of 2015, she has harnessed experience and verve into a new sound to be shared. <br /> <br /> Honeyed vocals ride atop of primarily banjo-crafted ballads, chanties, toe-tappers, and blues propelled by unconventional percussion and accent instruments. Steeped in the rich cuttings of American roots music and sprigs of inspiration from the curiosities of man and nature, Libby delivers a heartfelt and engaging live performance with a passionate, playful relevance to causes both near and dear, and dusty bygones. Dabbling in an array of genres, the soundscape is captivating; innocently dark and best described as “Broken Folk.”</span></span></span></span><br /><br />Libby posted all the lyrics to <i>Cross Sections</i> on her <a href=""><span style="color: magenta;">website</span></a>. Enjoy!</div><img src="" height="1" width="1" alt=""/>Oz Fritz Jim CrowEvidence that we still live on a very backwards planet shows up in how we treat people who have broken society's rules such that they have been incarcerated in prison. If we can't figure out a better way for convicts to pay their debt to society than by locking them up we can at least compassionately offer aesthetic lines of escape from the barbarity of the prison mentality and lifestyle. One such line, music, is being given to prisoners by an assemblage that includes my friend Doctor Israel (Method of Defiance, Heavyweight Dub Champion). Doc wrote me recently about their current project, <i>Die Jim Crow</i>:<br /><br /><span style="color: yellow;"><span class="">...it's a record about racism and prejudice in the U.S. Prison Industrial Complex. </span></span><span style="color: yellow;"><span class=""><span class="">We've been recording inside of U.S. prisons and with formerly incarcerated individuals on the “outside.” Currently we are releasing an EP based on 4 days of recording that we did at</span>Warren Correctional Institution, a close security state prison in Ohio. The EP is designed to build awareness for the project and to be used as a calling card to gain access to more prisons.</span></span><br /><br />Doc is co-producing and engineering this. From their <a href=""><span style="color: magenta;">website</span></a>:<br /><br /><span style="color: yellow;">The album title is inspired by Michelle Alexander's book"<i>The New Jim Crow</i>" which equates the U.S. prison system to a modern day racial caste system similar to the old form of Jim Crow segregation in America</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">The album addresses this human rights crisis through song</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">Inspired by Pink Floyd's 1979 concept album "<i>The Wall</i>,"<i> Die Jim Crow </i>explores the journey of the contributing artist through intimate first-person narrative, overarching political themes, and haunting musical through-lines. Fusing several genres of traditionally African-American music, the album features rock n roll, jazz, blues, r & b, hip-hop, and more.</span><br /><span style="color: yellow;"><br /></span><span style="color: yellow;">EP release: 5/1/16</span><br /><span style="color: yellow;">LP release 2018</span><br /><br />There is still a few days left in what looks to be a successful Kickstarter campaign to support the project which you can check out and contribute to <a href=""><span style="color: magenta;">HERE</span></a>. That link will take you to a video that shows the Die Jim Crow project in action, explains it more fully and introduces you to the Producer of the project, Fury Young and to Doctor Israel. It's very worthwhile to take 5 minutes and listen to what they have to say.<br /><br />Here's a 39 second teaser, but the real meat of the message is in the 5 minute video.<br /><div style="text-align: center;"><br /></div><div style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="315" src="" width="560"></iframe></div><br /><br />There is a history of philosopher/activists advocating for prisoner's rights one way or another. In the early '70s Gilles Deleuze and Michel Foucault were guiding lights of the GIP (Group for Information on Prisons) that held sit-ins and demonstrations in France on behalf of prisoner's rights where they were joined by Jean Paul Sartre and other prominent French intellectuals. Before that, in the early '60's, Timothy Leary led a group experimenting with psychedelic mushroom therapy with prisoners that showed successful results. And of course, we can't forget Johnny Cash. Fury Young and Doctor Israel are moving this tradition forward. They are already making a difference as can be seen in the two videos mentioned above.<img src="" height="1" width="1" alt=""/>Oz Fritz Part 3Layng Martine III was the main assistant engineer at Greenpoint for a number of years in the latter part of the studio's existence. He lived in the basement; maybe why I sometimes sensed a subterranean, troll-like quality about him from time to time like he didn't get out enough. He was very good at what he did, on the world professional level like anyone else at Greenpoint; efficient, and pleasant to work with; very dry humor. When he moved out following his tenure, he left behind a complete facsimile collection of Aleister Crowley's original<i> Equinox</i>, the thick, hardbound periodicals Crowley put out every 6 months in the early 1900s presenting the magical instruction he was hawking, i.e. his School in the guise of a literary journal. Clearly, those books, a University course of magick, belonged more to the space at Greenpoint than they did to Layng.<br /><br />Im, <i>Turath</i>,.<br /><br /<br /><br /. <br /><br / <i>The Handbook for the Recently Deceased</i> by Claude Needham. The title is derived from the handbook in Tim Burton's <i>Beetlejuice</i>.<br /><br />Bill eventually negotiated a record deal for Buckethead with Sony for the release that became <i>Giant Robot</i>. It has the amusement park theme running throughout. The second track is <i>Welcome to Bucketheadland</i> and it closes with <i>Last Train to Bucketheadland</i>..<br /><br />Chop Top (actor Bill Mosely from <i>Texas Chainsaw Massacre 2</i>) <i>Neuropolitique</i>. Mosely said Leary saw the play a few times and was upbeat and supportive. He said it got quite freaky and eerie when a few Manson family members turned up occasionally, sometimes heckling and creating a scene.<br /><br />Iggy Pop came by Greenpoint one day for a few hours to lay down some narration for <i>Giant Robot. </i> He seemed a little reserved at first, but then got completely into character as the proprietor of<i> Buckethead's Toy Store</i> starting with the intro premise that the Universe is doomed "<b><i>unless the force of cruelty can be conquered by an influx of fun</i></b>" <i>Post Office Buddy </i. <br /><br /><i>Giant Robot</i> <i>Giant Robot</i>>I Love My Parents</i>.>I Love My Parents</i> as a theme song such is the powerful affects and percepts the song emits.<br /><br /.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="310" src="" width="320" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">Giant Robot in front of Bucketheadland</span></div><br / <i>Holy Mountain</i>, Jodorosky's classic surrealist take on alchemy which looked extremely interesting though a bit of a blur at that late hour. I fell asleep watching it and had strange dreams about monsters and heroes subconsciously programmed by <i>Holy Mountain</i>. I awoke in the morning a different person.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="235" /></a></div><br /><br /.<br /><br />.<br /><br / <i>The Moonbeam Show</i>, <i>Beelzebub's Tales To His Grandson</i>,.<br /><br /><i>The Moonbeam Show</i>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="122" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">Typical of the artwork in the show</span></div><br />.<br /><br /<i> The Birth of Tragedy</i>, the archetypal journey through the Underworld that seems necessary to see the whole picture complete. <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="240" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">"Bare Bulb" from the Dark Hours series.</span></div><br />Later on, I found this space excellent for ritual practice.<br /><br />The opening for the Moonbeam show was attended by about 300 people including a handful of music industry professionals and at least one other iconoclastic performance artist - the infamous <a href=""><span style="color: magenta;">Rammellzee</span></a>..<br /><br /.<br /><br />After 6 months <i>The Moonbeam Show</i> moved to Los Angeles and the Troov Gallery changed forms becoming curators of shows at the Cedar Tavern and at the H. Heather Edelmann gallery in Soho. The latter was a collaboration between E.J. Gold and John Cage called <i>A Lecture On Nothing from Silence.</i> <i>A Lecture On Nothing from Silence</i>. <br /><br /.<br /><br /. <br /><br /?<br /><br / <i>Basquiat</i>.<br /><br />It seems I engineered the last project at Greenpoint - mixing <i>Chakra: Seven Centers</i>.<br /><br />The first record I worked on at Greenpoint was <i>The Third Power</i> by Material, the last one was <i>Chakra: Seven Centers</i>.."<br /><br /</a><><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><img src="" height="1" width="1" alt=""/>Oz Fritz Post On Sigils<div style="text-align: left;"><span style="font-size: large;"><span style="font-size: small;"> This guest post on Sigils is an excerpt from Klaas Pieter van der Tempel's "<i>Pause, Play: A Higher Consciousness Handbook</i>." It's very good. Readers interested in seeing more can purchase the book<a href=""><span style="color: magenta;"> </span><span style="color: magenta;">here</span></a> for under $3.</span><b> </b></span></div><div style="text-align: center;"><span style="font-size: large;"><b> Sigils</b></span></div><div> </div><div><b>What: </b>Impregnating reality with your artistically rendered will and imagination. Why: You decide. How: Find your will, express it artistically, then release it and let the unconscious manifest it for you.</div><div> </div><div.”</div><div> </div><div.</div><div> </div><div><b>If you draw or write something with a specific intent, whatever you have just created is like a magical letter delivered to the unconscious. This is a sigil. </b></div><div> </div><div. </div><div> </div><div. </div><div> </div><div.</div><div> </div><div.*</div><div> </div>For serious sigilizing I recommend the book <i>Visual Magick </i>by Jan Fries.<br /><br />* Technically, a symbol isn’t a sigil because it clearly represents something recognizable. So a smiley face is bending the rules. In a good way. <img alt="Smiling face (black and white)" src="" title="Smiling face (black and white)" /> <img src="" height="1" width="1" alt=""/>Oz Fritz Thousand Plateaus - A Contemporary Grimoire Part 2"Spiritual life is not dream or fantasy, but the realm of clear-headed decision making, a kind of absolute stubbornness, the choice of existence."<br /><br />"Real abstraction is non-organic life. This idea of non-organic life is everywhere in <i>A Thousand Plateaus</i>, and this is precisely the life of the concept."<br /><br /> - Gilles Deleuze, <i>Two Regimes of Madness, </i>p. 288 & p. 178<br /><br />"Of course, there is no reason to think that all matter is confined to the physicochemical strata: there exists a submolecular unformed Matter. Similarly, not all life is contained to the organic strata: rather, the organism is that which life sets against itself in order to limit itself, and there is a life all the more intense, all the more powerful for being anorganic. There are also nonhuman Becomings of human beings that overspill the anthropomorphic strata in all directions. But how can we reach this "plane," or rather, how can we construct it, and how can we draw the "line" leading us there?"<br /> <br /> - Deleuze & Guttari, <i>A Thousand Plateaus</i>, p.503<br /><br />If following along with your copy of <i>ATP</i> at home, continue reading and hear their extremely bardoesque description of attempting life outside the organic strata followed by a severe warning: "...must therefore observe concrete rules of extreme caution ..." then some dire consequences of what could go wrong; caveat emptor.<br /><br />Spiritual Engineering: methods of creating the kind of non-organic life they call "nonhuman Becomings of human beings," or what alchemists call "higher bodies." These bodies survive the death of the organism. D&G write about the "body without<i> </i>organs" (BwO) a term borrowed from Antonin Artaud<i>; </i>BwO<i> = </i>a non-organic body.<i> ATP</i> as a manual for spiritual engineering resonates with the role they give to machines in the creation process with their concept of "abstract machines" that give genesis to mechanical creative processes. The last sentence and the last word of <i>ATP</i>: "Mechanosphere." Engineer your mechanosphere.<br /><br />Spiritual engineering appears foreshadowed and anticipated in <i>Anti-Oedipus, Capitalism and Schizophrenia Part I </i>when D & G presented the factory model of the Unconscious Mind as opposed to the Freudian conception of the Unconscious as a theater where the contents of this mind represent and symbolize something else usually having to do either literally or metaphorically with family. The unconscious "factory" is motivated by desire and this desire can become actualized or produced externally in the conscious world hence the D&G term: "desiring-production" as a term to describe the inner workings and function of the Unconscious or Deep Self. Discovering and bringing to light one's deepest desires then finding out how to produce them, how to make one's dreams come true, appears what Aleister Crowley means when he beseeches humankind to "<i>Do what thou wilt</i>." Desiring-production = <i>Do what thou wilt.</i> Of course, the complete formula Crowley gives is: "<i>Do what thou wilt shall be the whole of the law. Love is the law, love under will.</i>" How does this relate with desiring-production? If it seems D&G don't have an obvious connection to the second half of the formula consider that Deleuze cites Lewis Carroll as one primary source for "<i>The Logic of Sense</i>" particularly the <i>Alice</i> stories and <i>Sylvie & Bruno</i>. The latter seems an overlooked masterpiece.<br /><br />Modeling and mapping out the unconscious or subconscious mind with the intention of making it known and thus more functional, examining the inner mechanisms of the human biological machine, puts D&G squarely in the company G.I. Gurdjieff and Aleister Crowley who both stated at different times that a primary intention of their methods was to render the subconscious mind conscious. This is also one effect of bardo voyaging; bardo training shares the intention to make the subconscious conscious through various exercises including past life recalls, certain ways of video gaming etc. etc. Another way to say it - the systems or approaches Gurdjieff, Crowley, and D&G present include different forms of bardo training. Deleuze, Gurdjieff and Crowley also have in common extremely obscure, idiosyncratic and singular language that makes much of their core writings nearly impenetrable when encountered for the first time. A safety net to winnow out the unwary before it gets too real may provide one, but certainly not the only explanation for their particular writing styles. All three also share a penchant for creating/reinterpreting various concepts relating to spiritual work. They are all fond of introducing neologisms, coining words and phrases creating nomenclature to further their communications and to make and sustain a self-referential lexicon of terms and aesthetics for practical use. Upon experimentation, many congruencies between the three systems will be noticed, overlapping, helping to explain and filling in blanks in each other. The underlying operational similarities between the three appear so close at times that it seems they comprise radically different ways of communicating the same information. It's the Sufi story of the 5 blind men and the elephant where each one describes a different aspect of the elephant then they put the information together to grasp the whole. Since some of their concepts and language appear obscure even after years of praxis and study it can prove quite helpful to cross-pollinate the systems for more complete understanding. They all contribute to a rhizomatic Tree of Life; the eclectic method of bardo training which, of course, can expand out to include any system or practice with the intention of making the subconscious conscious. Despite appearing less flamboyant and relatively scandal free, I strongly contend that Deleuze worked as an avatar of this era just as much as those other two rascals.<br /><br />D&G practiced what they preached. They experimented with their work and their lives with the philosophy they wrote about. One key concept in <i>ATP</i> is the <i>assemblage</i>; the usefulness of looking at the larger picture of how systems and groups get formed between individual things; the connections between things, how they interact and affect each other. They use the example of the orchid/wasp relationship, the wasp carrying pollen to the orchid as an example of one kind of assemblage. Deleuze and Guttari each had strong individual voices, were innovators and forces to contend with in their respective fields before joining forces to write four books that quite effectively proves and validates the power of the assemblage to create.<br /><br />The first time I attended a workshop and convention at I.D.H.H.B. in 1990 there was an emphasis placed throughout on forming small groups for more effectively carrying out whatever it is you want to do. I attended a lecture by Timothy Leary shortly after returning and was shocked by the coincidence when he delivered the exact same message: a strong recommendation to form small, independent, autonomous, groups of like-minded individuals. The suggestion to form assemblages seemed so uncannily similar that I imagined they could be in cahoots with each other somehow, either that or Coincidence Control was having its way with me again. This same notion found a radical and anarchistic expression in Hakim Bey's <i>Temporary Autonomous Zone</i> published around this time.<br /><br />Assemblages relate to Buckminster Fuller's approach of viewing the behavior and aesthetics of whole systems as opposed to only looking at the parts. His recognition of the synergy made apparent through the formation of assemblages may help explain its importance to D&G. Assemblages form whenever musicians get together to make music. If you consider these assemblages to have a non-organic life of their own able to communicate through music then it appears easy to see music as a group invocation, a drawing down from above. Every magical act results from an assemblage of some kind even if it's an assemblage of a solo magician, his temple, robe and weapons. Crowley's assemblage for the reception of <i>The Book of the Law</i> included his wife Rose, Egyptian mythology, stele 666 at the Boulak museum and his apartment in Cairo among other things. All of Crowley's major works resulted from collaborations with other people; he was constantly forming and changing assemblages to further his research and experiments.<br /><br />I've read <i>ATP</i> twice now and have noticed no deliberate use or mention of qabala, although one of Deleuze's revered sources, Antonin Artaud, studied and practiced it. However, one clear allusion to Crowley and the aeon of Horus in the form of a pun on birds does appear. The assemblage of Deleuze and Guttari clearly resembles the archetype of "twins," in particular the twin forms of Horus, a god comprised of an active aspect, Ra Hoor Kuit, and a passive or silent aspect, Hoor pa Kraat. These twins get recapitulated in posture every time the student practices a Star Ruby, Crowley's adaptation of the Lesser Banishing Ritual of the Pentagram. Thrusting out the fiery pentagram from the forehead with arms extended making the Sign of Horus (The Enterer) puts one in the position of Ra Hoor Khuit, the active. This gets immediately followed by the Sign of Hoor pa Kraat with the forefinger to the lips in the traditional sign of silence, also a sign of defence. This twins motif also relates to the concept given in <i>ATP</i> Ch.3 that morphogenesis, the creation of forms, always has a double articulation with, as they basically say, one side facing out, the other side facing in. It can also prove interesting to compare the twins refrain with Deleuze's discussion of crystal-images in <i>Cinema 2 The Time-Image</i>. These crystal-images are one half actual, one half virtual, reflect each other and change places.<br /><br />Besides being a highly innovative experimental psychoanalyst and theorist, Guttari was also an extremely energetic political activist constantly forming groups and organizing meetings for social change. At one point he was described as a militant Trotskyite - militant in the sense of being hard core and active, he never advocated violence as a solution and distanced himself from those elements though he did get beat up for his activism in the early days. He was also directly involved with the widespread protests, general strikes and university occupations across France that occurred in May of '68 which basically took over the country and brought the economy to a temporary halt. Guttari traveled frequently and was actively involved with one cause or another for social, political, or ecological change until the end of his life. Deleuze, on the other hand, stayed more in the background, more often then not expressing social activism by publicly voicing support as for example his essays on the Palestinian situation. Health reasons may have contributed to his largely staying off the front lines, but he wasn't completely retiring getting involved in demonstrations against repression in prisons with Michel Foucault and J.P. Sartre in the early '70's that sometimes resulted in violent clashes. Deleuze's main gig apart from writing was as a teacher of philosophy. His classes at the University of Paris at Vincennes/St. Denis became renowned. He prepared rigorously for them, attracted students from around the world and regularly lectured to overflowing crowds. One devoted student attended every seminar he gave from 1970 - 1987. Deleuze hated to travel and was married to the same woman from 1956 until his death in 1995. Guttari, on the other hand, had a succession of female partners throughout his life. <i>Intersecting Lives</i> by Francois Dosse provides excellent biographical portraits of these two iconoclasts.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="298" src="" width="320" /></a></div><div style="text-align: center;"><span style="font-size: x-small;">Gilles Deleuze & Felix Guttari</span></div><br /><br /><i>ATP</i> Chapter 10. 1730: <i>Becoming-Intense, Becoming-Animal, Becoming-Imperceptible</i> <i>... </i>seems very shamanic in the sense of describing states of consciousness, modes and "becomings" beyond the ordinary; mapping out and modeling areas beyond common human existence. Becoming-imperceptible seems a recommended way to go though the authors appear extremely circumspect about favoring one course of action over another. Again, the authors live up to their words by becoming-imperceptible with their bias, presenting their visions without apparent moral or ethical judgement. It should be noted that becoming-imperceptible is not the same as being completely imperceptible. Their bias can be deduced and also shows a little more when the language gets more transparent. Still, in my novitiate experience, it's impossible to tell who is speaking, Deleuze or Guttari. Their individual opinions become imperceptible from one another. The D&G assemblage has formed what another assemblage, Burroughs and Gysin, called the Third Mind.<br /><br />Becoming-imperceptible directly relates to the importance of silence in Crowley's mysticism as well as the extensive experimentation he did with invisibility in Mexico City. Crowley's invisibility or becoming-imperceptible practice served him well years later when he discharged his pistol in an attempted mugging in Calcutta and had to disappear into the night to get away. More on silence<a href=""><span style="color: magenta;"> here.</span></a><br /><br />Deleuze seems a <i><span class="short_text" id="result_box" lang="fr"><span class="hps">magicien</span> <span class="hps">d'excellence </span></span></i><span class="short_text" id="result_box" lang="fr"><span class="hps">because his magick appears mostly imperceptible. It's not immediately obvious that his philosophy can activate several different approaches or lines of work to spiritual growth - to the 'nonhuman Becomings of humans.' </span></span><img src="" height="1" width="1" alt=""/>Oz Fritz
http://feeds.feedburner.com/TheOzMix
CC-MAIN-2017-43
refinedweb
47,501
50.36
Errata for The Definitive ANTLR 4 Reference The latest version of the book is P (28-May-15) Paper page: 5 The Windows commands to run ANTLR on this page are not correct. Below I have some example commands that I've tested in Windows. I kept the paths the same to be consistent with the book, but you may have to adjust the minor version number of the ANTLR 4.x *.jar files. There should also be some code to set the CLASSPATH environment variable either from the command line or via Control Panel for the Windows instructions, since the commands assume it is set. set CLASSPATH="C:\jars\antlr-runtime-4.4.jar;C:\jars\antlr-4.4-complete.jar;" doskey antlr4=java -jar C:\libraries\antlr-4.4-complete.jar $* doskey grun=java org.antlr.v4.runtime.misc.TestRig $* --Keith Wanta - Reported in: P2.0 (09-Jan-15) PDF page: 36 Throughout the book, cross-reference links to other pages are missing a space between the comma and the words "on page NN". Presumably, this is a mistake in a repeating template of some kind. I'm on page 36 and mention this because I've seen it so often it has become an irritant by now. This particular case is: "Chapter 5, Designing Grammars,on page 59."--Jonathan Cottrill - Reported in: P2.0 (28-May-15) Paper page: 39 I found that you cannot have a label on a rule containing a single condition (no alternatives). I found that it's helpful for debugging purposes to use labels when troubleshooting a grammar when giving source code as input to the generated parser. I have been using them for a reference when validating entry and exit events for grammar unit tests. As a trick/tip to the reader, it might be worth mentioning that you must have at least two alternatives to use these labels. --Keith Wanta - Reported in: P2.0 (29-Dec-14) PDF page: 40 The source for tour/EvalVisitor.java is no longer valid for Antlr 4.4. Where are the modified sources? - Reported in: P1.0 (12-Sep-14) PDF page: 49 In the tour/Data.g4 example, there's the following piece of code: sequence[int n] locals [int i = 1;] : ( {$i<=$n}? INT {$i++;} )* // match n integers ; Doesn't work for me the way it's described in the book. The tree is wrong, grouping n+1 characters instead of n. Looks like $i<=$n should be $i<$n - exit condition is 1 character too long in the book/examples.--Archie - Reported in: P2.0 (19-Sep-14) PDF page: 49 Hi, I am using Antlr4.4. I have adapted the example tour/Data.g4 as follows: sequence[int n] locals [int i = 42;] : ( {$i < $n}? INT { System.out.println($i); ++$i; } )* // match n integers ; It seems that the initialisation of the local variable i fails. Instead of being initialised to 42, the variable i always starts out at 0. This seems to be more of a bug in Antlr than a bug of the book.--Karl Stroetmann - Reported in: P2.0 (29-Dec-14) PDF page: 52 “mode” should be purple-boldfaced to represent it as a keyword.--Ravi Ponamgi - Reported in: P2.0 (16-Feb-15) PDF page: 59 Ultimately, we need the ability to divine a language’s structure from a set of representative input files. There is a difference between godlike and splitting a language.--Bob Niewold - Reported in: P2.0 (14-Mar-15) PDF page: 68 Section 4.5 Cool Lexical Features Last paragraph on page 68: >>Each line of that output represents a token and contains the token index, the start and stop character, the token text, the token type, and finally the line and character position within the line. Should probably be "the start and stop character position". --RedTailedHawk - Reported in: P2.0 (16-Mar-15) PDF page: 68 Would be clearer to either change "grun XML" to "grun XMLLexer", or to clarify that the suffix "Lexer" is implicit in TestRig: >>Here’s how to do a build and launch the test rig: >>➾ $ antlr4 XMLLexer.g4 >>➾ $ javac XML*.java >>➾ $ grun XML tokens -tokens t.xml i.e. state that both "grun XML" and "grun XMLLexer" work since you have the option of omitting "Lexer". -RedTailedHawk --RedTailedHawk - Reported in: P1.0 (22-Sep-14) Paper page: 70 Chapter 5.4: the right association examples uses the old syntax: The book still shows the V4.2 style assoc while v4 has it changed running the example in the book: UNRECOGNIZED_ASSOC_OPTION public static final ErrorType UNRECOGNIZED_ASSOC_OPTION Compiler Warning 157. rule rule contains an assoc element option in an unrecognized location In ANTLR 4.2, the position of the assoc element option was moved from the operator terminal(s) to the alternative itself. This warning is reported when an assoc element option is specified on a grammar element that is not recognized by the current version of ANTLR, and as a result will simply be ignored. The following rule produces this warning. x : 'x' | x '+'<assoc=right> x // warning 157 |<assoc=right> x * x // ok ;--Stanislas Rusinsky - Reported in: P1.0 (21-Sep-14) PDF page: 74 On page 73 at the bottom of the page, the link to the java grammar does not work. --Karl Stroetmann - Reported in: P2.0 (16-Aug-15) Paper page: 77 In the subsection "Matching Numbers" there is a parenthetical note "(See Section 6.5, Parsing R, on page 104 for lexical rules that match full floating-point numbers and even complex numbers like 3.2i.)" Nowhere in section 6.5 are lexical rules to match floating-point numbers discussed. There are rules for matching (complex) floating-point numbers in the source code file code/examples/R.g4 I suggest removing the parenthetical note.--EDeiman - Reported in: P2.0 (26-Nov-14) PDF page: 79 This rule (near the top of the page(: assign : ID (WS|COMMENT)? '=' (WS|COMMENT)? expr (WS|COMMENT)? ; should be: assign : ID (WS|COMMENT)* '=' (WS|COMMENT)* expr (WS|COMMENT)* ; --David Morrill - Reported in: P2.0 (29-Dec-14) PDF page: 86 [final sentence of the page, the word "of" is missing, I suspect:] "... on the right side OF rule 'file'."--Ravi Ponamgi - Reported in: P2.0 (19-Nov-14) PDF page: 87 In the example "examples/CSV.g4", the syntax highlight seems to be incorrect, i.e. the second line is highlighted as if it was a string, but in fact it is a lexer rule. Similar problems are elsewhere in the book, from the top of my head is in "examples/JSON.g4" on PDF page 93.--Ondrej - Reported in: P2.0 (20-Mar-15) PDF page: 89 Reference to bad URL on antlr.org in footnote #3: 3. h-t-t-p:// Note: I couldn't enter the full URL due to spam prevention--RedTailedHawk - Reported in: P2.0 (21-Sep-14) PDF page: 102 On page 102 the rule for `expr` is stated as follows: ~~~ expr: ID '(' exprList? ')' // func call like f(), f(x), f(1,2) | ID '[' expr ']' // array index like a[i], a[i][j] | '-' expr // unary minus | '!' expr // boolean not | expr '*' expr | expr ('+'|'-') expr | expr '==' expr // equality comparison (lowest priority op) | ID // variable reference | INT | '(' expr ')' ; ~~~ The part about array indexing seems to be wrong since, as given, the rule does not permit an array index of the form `a[i][j]`. However, the comment states that `a[i][j]` is a legal array index. Furthermore, the parse tree on the next page suggests that the alternative responsible for array indexing should be given as | expr '[' expr ']' Regards, Karl Stroetmann--Dr. Karl Stroetmann - Reported in: P2.0 (28-May-15) Paper page: 113 There is a code snippet on this page for the section 7.2-Implementing Applications with Parse-Tree Listeners. The method named "PropertyFileBaseVisitor" should probably be named "PropertyFileBaseListener". The code is also incorrect as it should implement PropertyFileListener, not PropertyFileVisitor. I'm guessing what happened is that section 7.3-Implementing Applications with Visitors was written first, and the source code snippet was copied to 7.2, and didn't get corrected.--Keith Wanta - Reported in: P2.0 (08-Jun-15) PDF page: 145 In DefPhase.java, the statement: int typeTokenType = ctx.type().start.getType(); There is no explanation of what the "start" field is. I found an explanation at. Reading that web page, it seems like "getStart()" would be a better way to access the initial token in the context. Suggestion: mention that "getStart()" returns the initial token in the context.--Luc Longpre - Reported in: P2.0 (03-Oct-14) PDF page: 152 When I run antlr4 on Simple.g4 I get the error message: error(65): Simple.g4:18:52: unknown attribute text for rule stat in $stat.text error(65): Simple.g4:20:54: unknown attribute text for rule stat in $stat.text --Dr. Karl Stroetmann - Reported in: P2.0 (03-Oct-14) PDF page: 157 The examples errors/TestE_Dialog.java and errors/TestE_Listener2.java do not compile because of the import directive import com.sun.istack.internal.Nullable; They do compile after this import directive is changed to import org.antlr.v4.runtime.misc.Nullable; --Dr. Karl Stroetmann - Reported in: P2.0 (06-Feb-15) PDF page: 175 The sample errors/TestBail.java contains extends SimpleLexer I cannot find the class SimpleLexer in ANTLR4 java download. There is a class Lexer and there is a discussion in the book about making a simple lexer, which may be are mixed up.--Bob Niewold - Reported in: P1.0 (02-Feb-15) Paper page: 237 In method consume() the assignment charPositionInLine = 0 should be charPositionInLine = -1. This will correct the erroneous output of TestSimpleMyToken on page 241 where the last four tokens have wrong coordinates for the character position: 'abc' 2:1 should be 2:0, etc.--Gerald Struck
https://pragprog.com/titles/tpantlr2/errata
CC-MAIN-2015-40
refinedweb
1,651
59.19
Tnetstrings A Forward ReferenceHaving. First, (and you can see this in the comments to the previous post) I wrote my original code in a REPL and pasted it into the blog. Unfortunately, this caused me to miss a forward reference to the parse-tfunction. On my first iteration of the code, I wasn't trying to parse all the data types, to the map of parsers didn't need to recurse into the parse-tfunction. However, when I updated the map, the parse-tfunction had been fully defined, so the references worked just fine. TestingThat brings me to my second and third points: testing and Leining: lein new tnetstrings. I'll get on to Leiningen in a moment, but for now I'll stick with the tests. Clojure tests are easy to set up and use. They are based on a DSL built out of a set of macros that are defined in clojure.test. The two main macros are deftestand is. deftestis used to define a test in the same way that defnis used to define a function, sans a parameter definition. In fact, a test is a function, and can be called directly (it takes no parameters). This is very useful to run an individual test from a REPL. The other main macro is called " is" and is simply used to assert the truth of something. This macro is used inside a test. My tests for tnetstrings are very simple: (ns tnetstrings.test.core (:use [tnetstrings.core :only [parse-t]] [clojure.test])) (deftest test-single (is (= ["hello" ""] (parse-t "5:hello,"))) (is (= [42 ""] (parse-t "2:42#"))) (is (= [3.14 ""] (parse-t "4:3.14^"))) (is (= [true ""] (parse-t "4:true!"))) (is (= [nil ""] (parse-t "0:~")))) (deftest test-compound (is (= [["hello" 42] ""] (parse-t "13:5:hello,2:42#]"))) (is (= [{"hello" 42} ""] (parse-t "13:5:hello,2:42#}"))) (is (= [{"pi" 3.14, "hello" 42} ""] (parse-t "25:5:hello,2:42#2:pi,4:3.14^}")))) Note that I've brought in the tnetstrings.corenamespace (my source code), and only referenced the parse-tfunction. I always try to list the specific functions I want in a useclause, though I'm not usually so particular when writing test code. You'll also see clojure.test. As mentioned, this is necessary for the deftestand ismacros. It is worth pointing out that both of these useclauses were automatically generated for me by Leiningen, along with a the first deftest.. Something else that caught me out was that when I parse a floating point number, I did it with java.lang.Float/parseFloat. This worked fine, but by default Clojure uses doublevalues instead, and all floating point literals are parsed this way. Consequently the tests around "4:3.14^"failed with messages like: expected: (= [3.14 ""] (parse-t "4:3.14^")) actual: (not (= [3.14 ""] [3.14 ""])) What isn't being shown here is that the two values of 3.14 have different types (float vs. double). Since Clojure prefers double, I changed the parser to use java.lang.Double/parseDoubleand the problem was fixed. LeiningenFor anyone unfamiliar with Leiningen, here is a brief rundown of what it does. By running the newcommand Leiningen sets up a directory structure and a number of stub files for a project. By default, two of these directories are src/and test. Under src/you'll find a stub source file (complete with namespace definition) for the main source code, and under test/you'll find a stub test file, again with the namespace defined, and with clojure.testalready brought in for you. In my case, these two files were: src/tnetstrings/core.clj test/tnetstrings/test/core.clj To get running, all you have to do is put your code into the src/file, and put your tests into the test/file. Once this is done, you use the command: lein test to run the tests. Clojure gets compiled as it is run, so any problems in syntax and grammar can be found this way as well. However, one of the biggest advantages to using this build environment, is the ease of bringing in libraries. Using Leiningen can be similar to using Maven, without much of the pain, and indeed, Leiningen even offers a pomcommand to generate a Maven POM file. It automatically downloads packages from both Clojars and Maven repositories, so this feature alone makes it valuable. Leiningen is configured with a file called project.cljwhich is autogenerated when a project is created. This file is relatively easy to configure for simple things, so rather than delving into it here, I'll let anyone new to the system go the project page and sample file to learn more about it. project.cljalso. I'm also in the process of copying Alex Hall's setup for pre-compiling Antlr parser definitions so that I can do the same with Beaver. Again, it's great that I can do this with Leiningen, but it's annoying to do so. I shouldn't be too harsh though, as the way that extensions are done look more like they are derived from the flexibility of Clojure than Leiningen itself.
http://gearon.blogspot.com/2012_08_01_archive.html
CC-MAIN-2017-09
refinedweb
862
74.69
- Sequences and prediction - Deep NN for Time Series - Sequence bias - Feeding windowed datasets into NN - RNN for TS - Real-world time series data This is my note for the 4 3 - NLP in Tensorflow. - Sequence models: focus on time series (there are others) -- stock, weather,... - At the end, we wanna model sunspot actitivity cycles which is important to NASA and other space agencies. - Using RNN on time series data. Sequences and prediction Time Series 📙 Notebook: introduction to time series. + explaining video. => How to create synthetic time series data + plot them. - Time series is everywhere: stock prices, weather focasts, historical trends (Moore's law),... - Univariate TS and Miltivariate TS. - Type of things can we do with ML over TS: - Any thing has a time factor can be analysed using TS. - Predicting a forecasting (eg. birth & death in Japan -> predict future for retirement, immigration, impacts...). - Imputation: project back into the past. - Fill holes in the data. - Nomalies detecction (website attacks). - Spot patterns (eg. speed recognition). - Common patterns in TS: Trend: a specific direcion that they're moving in. Seasonality: patterns repeat at predictable intervals (eg. active users for a website). Combinition of both trend and seasonality. Stationary TS. Autocorrelated TS: a time series is linearly related to a lagged version of itself.. There is no trend, no seasonality. Multiple auto correlation. May be trend + seasonality + autorrelation + noise. Non-stationary TS: In this case, we base just on the later data to predict the future (not on the whole data). Train / Validation / Test Fixed partitioning (this course focuses on) = splitting TS data into training period, validation period and test period. If TS is seasonal, we want each period contains the whole number of seasons. We can split + train + test to get a model and then re-train with the data containing also the test period so that the model is optimized! In that case, the test set comes from the future. Roll-forward partitioning: we start with a short training period and we gradually increase it (1 day at a time or 1 week at a time). At each iteration, we train the model on training period, use it to focast the following day/week in the validation period. = Fixed partitioning in a number of times! Metrics For evaluating models: errors = forecasts - actual # Mean squared error (square to get rid of negative values) # Eg. Used if large errors are potentially dangerous mse = np.square(errors).mean() # Get back to the same scale to error rmse = np.sqrt(mse) # Mean absolute error (his favorite) # this doesn't penalize large errs as much as mse does, # used if loss is proportional to the size of err mae = np.abs(errors).mean() # Mean abs percentage err # idea of the size of err compared to the values mape = np.abs(errors / x_valid).mean() # MAE with TF keras.metrics.mean_absolute_error(x_valid, naive_forecast).numpy() Moving average and differencing 📙 Notebook: Forecasting. + explaining video. Moving average: a simple forecasting method. Calculate the average of blue lines within a fixed "averaging windows". - This can eliminate noises and doesn't anticipate trend or seasonality. - Depend on the "averaging window", it can give worse result than naive forecast. Take the average on each yellow window. MAE=7.14 (optimal is 4). def moving_average_forecast(series, window_size): """Forecasts the mean of the last few values. If window_size=1, then this is equivalent to naive forecast""" forecast = [] for time in range(len(series) - window_size): forecast.append(series[time:time + window_size].mean()) return np.array(forecast) Differencing: remove the trend and seasonality from the TS. We study on the differences between points and their previous neighbor in period. Left image: we find the differencing of original values, then we find the average (orange line). Right image: restore the trend and seasonality. MAE=5.8 (optimal is 4). Above method still get the noises (because we add the differencing to the previous noise). If we remove past noise using moving average on that. Smoothing both past and present values. MAE=4.5 (optimal is 4). Keep in mind before using Deep Learning, sometimes simple approaches just work fine! Deep NN for Time Series Preparing features and labels - We need to split our TS data into features and labels so that we can use them in ML algos. - In this case: features=#values in TS, label=next_value. - Feature: window size and train to predict next value. - Ex: 30 days of values as features and next value as label. - Overtime, train ML to match 30 features to match a single label. 📙 Notebook: Preparing features and labels. 👉 Video explains how to split to features and labels from dataset. # create a very simple dataset dataset = tf.data.Dataset.range(6) arr = [val.numpy() for val in dataset] print(arr) # [0, 1, 2, 3, 4, 5] # make equal (drop_remaninder) windows dataset = dataset.window(5, shift=1, drop_remainder=True) dataset = dataset.flat_map(lambda window: window.batch(5)) # instead of val.numpy for each val in each window for window in dataset: print(window.numpy()) # [0 1 2 3 4] # [1 2 3 4 5] # split the last value to be label dataset = dataset.map(lambda window: (window[:-1], window[-1:])) # [0 1 2 3] [4] # [1 2 3 4] [5] # shuffle dataset = dataset.shuffle(buffer_size=6) # construct batch of 2 dataset = dataset.batch(2).prefetch(1) # x = [[1 2 3 4], [0 1 2 3]] # y = [[5], [4]] Sequence bias Sequence bias is when the order of things can impact the selection of things. It's ok to shuffle! Feeding windowed datasets into NN 📙 Notebook: Single layer NN + video explains it. # Simple linear regression (1 layer NN) dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)) print("Layer weights {}".format(l0.get_weights())) forecast = [] for time in range(len(series) - window_size): forecast.append(model.predict(series[time:time + window_size][np.newaxis])) # np.newaxis: reshape X to input dimension that used by the model forecast = forecast[split_time-window_size:] results = np.array(forecast)[:, 0, 0] 📙 Notebook: DNN with TS + video explains it. # A way to choose an optimal learning rate lr_schedule = tf.keras.callbacks.LearningRateScheduler( lambda epoch: 1e-8 * 10**(epoch / 20)) optimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9) model.compile(loss="mse", optimizer=optimizer) history = model.fit(dataset, epochs=100, callbacks=[lr_schedule], verbose=0) lrs = 1e-8 * (10 ** (np.arange(100) / 20)) plt.semilogx(lrs, history.history["loss"]) plt.axis([1e-8, 1e-3, 0, 300]) Loss w.r.t different learning rates. We choose the lowest one, around 8e-6. 📙 Notebook: DNN with synthetic TS. RNN for TS - RRN is a NN containing Recurrent layer. - The different from DNN is the input shape is 3 dimensional ( batch_size x #time_step x dims_input_at each_timestep). - Re-use 1 cell multiple times in different layers (in this course). Idea of how RNN works with TS data. The current location can be impacted more by the nearby locations. Shape of input to RNN 👉 Video explains the dimensional and sequence-to-vector RNN. - Suppose: window size of 30 time steps, batch size of 4: Shape will be 4x30x1 and the memory cell input will be 4x1 matrix. - If the memory cell comprises 3 neurons then the output matrix will be 4x3. Therefore, the full output of the layer will be 4x30x3. - is just a copy of . - Below figure: input and also output a sequence. Dimension of input to RNN. Sequence to vector RNN - Sometimes, we want only input a sequence but not output. This called sequence-to-vector RNN. I.E., ignore all of the outputs except the last one!. In tf.keras, it's default setting! Sequence to vector RNN. # Check the figure below as an illustration model = tf.keras.models.Sequential([ tf.keras.layers.SimpleRNN(20, return_sequences=True, input_shape=[None, 1]), # input_shape: # TF assumes that 1st dim is batch size -> any size at all -> no need to define # None -> number of time steps, None means RNN can handle sequence of any length # 1 -> univariate TS tf.keras.layers.SimpleRNN(20), # if there is `return_sequences=True` -> sequence-to-sequence RNN tf.keras.layers.Dense(1), ]) Illustration with keras. Lambda layer 👉 Video explains the use of lambda layer in RNN.. model = tf.keras.models.Sequential([ tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1), # expand to 1 dim (from 2) so that we have 3 dims: batch size x #timesteps x series dim input_shape=[None]), # can use any size of sequences tf.keras.layers.SimpleRNN(40, return_sequences=True), tf.keras.layers.SimpleRNN(40), tf.keras.layers.Dense(1), tf.keras.layers.Lambda(lambda x: x * 100.0) # default activation in RNN is tanh -> (-1, 1) -> scale to -100, 100 ]) Simple RNN - Loss function Huber (wiki): less sensitive to outliers. => we use this because our data in this case get a little bit noisy! 📙 Notebook: Simple RNN with a TS data + videos explains it. LSTM 📙 Notebook: LSTM with a TS data + videos explains it. # clear internal variables tf.keras.backend.clear_session() dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size) model = tf.keras.models.Sequential([ tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1), input_shape=[None]), # LSTM here tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)), # tf.keras.layers.Dense(1), tf.keras.layers.Lambda(lambda x: x * 100.0) ]) 📙 Notebook: LSTM with synthetic TS. Real-world time series data - We are going to predict the sunspot actitivity cycles (download dataset). - Combine CNN + LSTM. 👉 Andrew's video on Optimization Algo: Mini-batch gradient descent. 📙 Notebook: Sunspot dataset with CNN+LSTM. + video explains it. 📙 Notebook: Sunspot dataset with DNN only + explaining video. 👉 Video explains train & tune the model (how to choose suitable values for sizes)
https://dinhanhthi.com/deeplearning-ai-tensorflow-course-4/
CC-MAIN-2022-33
refinedweb
1,616
52.66
6646 Terrible Ordeal(HELP)! Jing Han Hello, I really hope you get this fast. I could not inform everyone about my trip to Ukraine for a program because it was impromptu. The program was jing han Jan 23#6646 6645 I set namespace of response object but different one is returned Here's a good one. I have a SOAP service at work that uses different WSDL files to implement the API, each with its own namespace. Working fine, but lately we Rich T_ Dec 3, 2013#6645 6644 Re: Figuring out SOAP::Lite dependencies I think I found my problem!!! I wrote a short script to loop my SOAP call and then have the SOAP::Lite dump its contents when it used the on_fault handler. Joe Tseng Oct 8, 2013#6644 Fetching Sponsored Content... 6643 Re: Figuring out SOAP::Lite dependencies ...And the error came back, despite the fact I upped the length value to 99999 (and I haven't seen anything larger than that). I have a test system that NEVER Joe Tseng Oct 7, 2013#6643 6642 Re: Figuring out SOAP::Lite dependencies Looks like upping the value might have did the trick! I just got a feed with an object of size 13178. Thank you for the tip! (I say might because I'm still Joe Tseng Sep 27, 2013#6642 6641 Re: Figuring out SOAP::Lite dependencies Hi Joe, Of course the version of the module could be just *one* of the differences between your production and test environment. While I would recommend you'd Michiel Beijen Sep 4, 2013#6641 6640 Re: Figuring out SOAP::Lite dependencies Some additional details: The first symptom of this issue was when I saw an email that was sent from my SOAP object's on_fault handler; the error said "200 OK". Joe Tseng Sep 4, 2013#6640 6639 Figuring out SOAP::Lite dependencies I maintain some scripts that read XML data from our data provider's SOAP methods. Earlier this morning I discovered my scripts on my production server weren't jtsengorg Sep 3, 2013#6639 6638 Re: Help trying to send attachment to SoapLite service ... Page Not Found This question was voluntarily removed by its author. ... Posting your perl code somewhere accessible would definitely help :) Dave Howorth Aug 27, 2013#6638 6637 Help trying to send attachment to SoapLite service Hi everyone, My first post on a PERL list! Well I'm in deep over here and though someone on this list could be my savior. I'm working with a SOAP service that nathan nobbe Aug 26, 2013#6637 6636 Re: When is a fault not a fault? Thanks to everybody for your help on this. I asked my Sys Admin to install v1.0 today, but unfortunately that did not solve the problem. I can get the bill.costa_01 Jul 25, 2013#6636 6635 Re: When is a fault not a fault? I spoke unclearly here so I should correct myself. I am not suggesting that any modules are no longer being hosted on CPAN, just that some module authors are Michael Brader Jul 10, 2013#6635 6634 Re: When is a fault not a fault? Many (most) CPAN modules host their source on github so I doubt it will be disappearing from CPAN. I don't know anything beyond what's in the blog post which I Michael Brader Jul 9, 2013#6634 6633 Re: When is a fault not a fault? Wow, I did miss that. Is SOAP::Lite going to continue to be on CPAN, or ... ??? This blog post indicates a 1.0 version. CPAN still has 0.716. is the github Andrew Hicox Jul 9, 2013#6633 6632 Re: When is a fault not a fault? No it doesn't. In Bill's test case the returned object is undefined, so the code examples in that link will raise an exception. on_fault handlers will not run. Michael Brader Jul 9, 2013#6632 Fetching Sponsored Content... 6631 Re: When is a fault not a fault? handling Seems to cover your specific scenario. ... handling Seems to cover your specific Mithun Bhattacharya Jul 8, 2013#6631 6630 When is a fault not a fault? Under certain circumstances SOAP::Lite is receiving valuable fault information from the server, but I can't figure out how to cleanly retrieve it. Consider BC Jul 8, 2013#6630 6629 httpd.conf Apache SOAP Lite " Hi I have configured apache httpd.conf file so that it runs correctly all perl scripts unless there is used SOAP::Lite module. Even examples from Internet pax0@... Apr 19, 2013#6629 6628 SOAP Lite NESTED ARRAYS/BUG " Dear All, we have the problem that SOAP Lite does not understand array in array. See this pax0@... Apr 16, 2013#6628 6627 Re: How to retreive the original xml-code of the soap body? Hi Lazlo, set $soap->outputxml(1); See (outputxml is the configuration method in question). Best regards, Martin Martin Kutter Apr 8, 2013#6627 6626 How to retreive the original xml-code of the soap body? Hi, I'd like to retreive the original xml-code of the soap body (and not a deserialized hash reference of it). How can I do that? I know, that there are Laszlo Apr 7, 2013#6626 6625 SOAP::Lite incompatible usage of HTTP::Headers SOAP::Transport::HTTP seems to be using a deprecated way of using HTTP::Headers. I am currently using version 0.714 and looking at SOAP/Transport/HTTP.pm +806 Mithun Bhattacharya Mar 12, 2013#6625 6624 lary_ecker Feb 12, 2013#6624 6623 Help with WSDL file Hello, I have an old SOAP service using SOAP::Lite. Now I need add WSDL file to the service. What's the best way to create one? Thanks, Min minbook4 Dec 28, 2012#6623 6622 Question on Capturing '500 Internal Server Error' I am running several perl scripts using SOAP::Lite and I need to capture if we receive an error, specifically a '500 Internal Server Error'. Is there a James Jun 22, 2012#6622 6621 Please Help, Need to add several namespaces to Envelope using Perl I've taken over some code for my company and need some help. We have a soap lite script which is called from another module. The calling module contains the James Jun 21, 2012#6621 6620 SOAP::LITE client timeout makes ALL my Catalyst app to wait Hi!, in my Catalyst app, I have a very important connection to a remote server using SOAP with WSDL. Everything works fine, but when the remote server goes Miguel Barco Jun 15, 2012#6620 Fetching Sponsored Content... 6619 Re: Failing to connect with webservice when using SSL with ClientAut Thanks to Mark Allen on the LWP mailing list, the answer can be found here: (In case that link noorarshad Jun 7, 2012#6619 6618 Failing to connect with webservice when using SSL with ClientAuth Hi, I'm new to SOAPLite and am struggling to solve this problem; hopefully, someone more knowledgeable can help me get past this. ... #!perl -w use SOAP::Lite noorarshad Jun 6, 2012#6618 6617 Soap Server handling multiple requests in the same envelope Hello, I am trying to design a SOAP server which should be able to process multiple requests in the same message. For example, the message looks like this: atpetkov Jun 4, 2012#6617 View First Topic Go to View Last Topic
https://groups.yahoo.com/neo/groups/soaplite/conversations/messages
CC-MAIN-2014-10
refinedweb
1,237
71.44
About Me - Also see my RSS simple services site. Subscribe Some feeds have no use, at least for the majority of us, outside of a regular feed reader like Bloglines or FeedDemon. I call these "news feeds" whether they are feeds of world news from CNN.com or Shelley Powers' personal blog postings. Perhaps "news feeds" is not the best name and I should change this habit. Now that I'm an a-lister I should be more precise, maybe. ;) I don't like to just use the word "feeds" to describe them all, because I think feeds that have more granular data in them need to be distinguished. I call these "data feeds". Most feedreaders won't be able to parse the additional data in the feeds, so they should still have title and descriptions, etc. Some feed readers will (For example, Nick Brabury's FeedDemon supports Yahoo's media RSS extension). Previously, I pointed out that many of the Yahoo RSS feeds could be much more useful to developers if they were "data feeds". These feeds are documented on the Yahoo Developer Network pages, but lets face it - the majority of them are NOT for developers at all. They're for feed readers. Jeremy Zawodny asked for more suggestions, so here's a quick rundown of the "big list" of Yahoo RSS feeds. Of course some of these feeds, IMO, are supposed to be "news feeds". They're supposed to be read inside a feed reader and have no real use for developers. For example: Ask Yahoo!, Yahoo! Answers, Yahoo! Autos Custom - not to be confused with the Yahoo! Autos feed, Yahoo! Education, Yahoo! Health, Yahoo!Message Boards, Yahoo! News, Yahoo! Next, Yahoo! Picks, etc). Jeesh...I'm tired of typing "Yahoo!" so I'm just going to stop now. Some feeds could have use for developers, but their usefulness is limited by the content of the feed itself. For example: Other Yahoo! feeds are useful for developers, but the data that they provide fits nicely inside existing syndication formats without any extensions (blo.gs, del.icio.us, 360 blogs and comment feeds, Directory, and Groups). Also, some of the Yahoo! feeds are already very useful for developers because of their use of RSS module extensions to provide more information about each item (Flickr, Upcoming.org, Yahoo! Traffic Alerts, Yahoo! Music makes good use of the media and ymusic namespaces, Search and My Search, and Weather). Feed developers: Technorati : API, ATOM, Feeds, RSS, Yahoo Skin design by Mark Wagner, Adapted by David Vidmar
http://geekswithblogs.net/lance/archive/2006/08/21/88657.aspx
crawl-002
refinedweb
425
66.64
Something we've done in MAAS — which is Python 2 only so far — is to put: from __future__ import ( absolute_import, print_function, unicode_literals, ) __metaclass__ = type str = None at the top of every source file. We knew that we would port MAAS to Python 3 at some point, and we hoped that doing this would help that effort. We'll find out if that's the case soon enough: one of our goals for this cycle is to port MAAS to Python 3. The str = None line forces us to use the bytes synonym, and thus think more about what we're actually doing, but it doesn't save us from implicit conversions. In places like data ingress and egress points we also assert unicode or byte strings, as appropriate, to try and catch ourselves slipping up. We also encode and decode at these points, with the goal of using only unicode strings internally for textual data. We never coerce between unicode and byte strings either, because that involves implicit recoding; we always encode or decode explicitly. In maas-test — which is a newer and smaller codebase than MAAS — we drop the str = None line, but use tox to test on both Python 2.7 and 3.3. Unfortunately we've recently had to use a Python-2-only dependency and have had to disable 3.3 tests until it's ported. six to bridge some gaps ( text_type in a few places, PY3 in setup.py too), but nothing invasive. My fingers are crossed that this experience is repeated with MAAS.
http://voices.canonical.com/tag/python/?page=2
CC-MAIN-2017-09
refinedweb
259
70.63
The full power of XML stems from combining the flexibility to create tags using whatever names you want and in whatever structure you want with enforcing strict compliance to that structure. The rules that are used to enforce this strict compliance are called XML schemas. Word provides you with the ability to manage the schemas you have available and to control which schemas are enforced for a given document. An XML schema is an abstract description of the structure you expect to use in an XML file. In the schema file (normally named with an extension of .xsd), you will find things such as these: Namespace definition Object/tag types (element, complex type, attribute, and so on) Object/tag names Data types (string, date, and so on) Object/tag relationships (hierarchy, min and max occurrences, and so on) What you won't find in an XML schema is actual data, transformation or presentation logic, or information related to the implementation of the structure. Before Word can start applying a schema to a document, you need to add the schema to the document. You can add as many different schemas to a document as you need. To add a schema to your document, follow these steps: Choose Tools, Templates and Add-Ins and then select the XML Schema tab (see Figure 25.1). Click the Add Schema button to get to the Add Schema dialog (see Figure 25.2). Browse to the schema file you want and click Open. In the Schema Settings dialog (see Figure 25.3), enter an Alias name for the schema. This is not required but is highly recommended. If no alias is entered, the schema name will always be shown as the long namespace definition (starting with http://). This is not always easy to decipher later. If you enter a friendly alias name (like "Contacts List"), it will be more obvious what the schema controls when you have multiple schemas loaded. If you want this schema definition to be available for all users, clear the Changes Affect Current User Only check box. Click OK to add the schema. NOTE When you add a schema, Word references it using the local file path. If you move or rename the schema file after having added it to Word, you will need to update the schema settings to correct the path (see the section "Managing Schemas in the Schema Library," later in this chapter). You'll now see the schema show up in the Available XML Schemas list (see Figure 25.4), and it will be checked, indicating that it has been applied to the document. When applying a schema to a document, you also have some options that control how Word will validate your document (see Figure 25.4): Validate Document Against Attached Schemas: If you clear this check box, Word will not attempt to validate the XML content against the selected schemas. This can allow more flexibility when the specific rules of the schema don't match with how you want to construct the XML. You are not prevented from saving the changes; you just don't see the graphical display of the validation in the XML Structure task pane (see the section "Using the XML Structure Task Pane," later in this chapter). This option is checked by default. Allow Saving as XML Even If Not Valid: If you clear this check box, Word will not allow you to save a document in XML format if the XML content cannot be validated against the schema. This setting can be very useful when you want to preserve your changes to the document before you have completed the entire XML structure. Technically, the XML you are saving is valid and well formed; it just does not adhere to the rules specified by the schema. After you have completed the data, you can turn this option back off to protect the integrity of the data. This option is not checked by default. Anytime you add library (see the section "Managing Schemas in the Schema Library," later in this chapter). This makes it very convenient to use the schemas in the future. To choose an existing schema from the schema library to apply to your document, follow these steps: Choose Tools, Templates and Add-Ins and then select the XML Schema tab (see Figure 25.4). Locate the schema you want to apply in the Available XML Schemas list. If they are not already checked, check the boxes next to the schemas you want to apply. Click OK. When you add an XML schema to a document, it is also added to Word's Schema Library. The Schema Library allows you to maintain your schema references as well as work with XML Solutions (see the section "Working with XML Solutions," later in this chapter). To access the Schema Library, click the Schema Library button on the XML Schema tab of the Templates and Add-Ins dialog (see Figure 25.4). The Schema Library dialog is shown in Figure 25.5. The Schema Library allows you to perform the following functions: Add a schema by clicking the Add Schema button (see the section "Adding an XML Schema to a Document," earlier in this chapter). Modify schema settings by clicking the Schema Settings button (see Figure 25.5). From the Schema Settings dialog you can modify the alias name used for the namespace, change the path to the schema file, or change whether your updates to the schema library affect other users. Delete a schema reference by clicking the Delete Schema button. This only removes the reference to the schema from Word. It does not remove the schema file from disk. At this point you are probably wondering exactly what an XML schema looks like. We'll need a basic schema later in this chapter, so a sample schema for managing contact information is shown next. We'll call this XML contact dialect "ContactML." <?xml version=" 1.0" ?> <xs:schema <xs:element <xs:complexType> <xs:choice <xs:element <xs:complexType> <xs:sequence> :element </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> If you are not familiar with XML schemas, take a few minutes to scan the example carefully. You will find that the structure is made to be a list of contacts, with each contact consisting of a full name, address, edit date, email, phone numbers, and comments. The full name is made up of a prefix, first name, middle name, and last name. An address has a type, company, street address, city, state, and ZIP. Phone numbers have a type and a number. If you want to follow along to try out some of the examples shown later, create a text file now named contactml.xsd and enter the preceding schema information into it. A full discussion of XML schemas is outside the scope of this chapter and indeed is a topic that can require an entire book itself.
http://etutorials.org/Microsoft+Products/microsoft+office+word+2003/Part+V+Word+the+Internet+and+XML/Chapter+25.+Using+Word+to+Develop+XML+Content+and+Use+XML+Applications/Working+with+XML+Schemas/
CC-MAIN-2018-51
refinedweb
1,163
69.31
Bart De Smet's on-line blog (0x2B | ~0x2B, that's the question) My recent series of "cookbook" posts has been very well-received and coincidentally I got mail today about MMC 3.0 snap-ins. I wrote on the subject a while (read: Vista RC1 timeframe) ago, so in this post I'll revisit the topic in cookbook style in order to provide the foundation for my next post on MMC 3.0 and PowerShell layering, a topic I talked about on TechEd EMEA 2007 but that never made it to a blog post. For the record, my previous cookbook posts include the following: For regular readers of my blog, step 1 and 2 will sound repetitive but in true PowerShell-style I'd say "verbosity is your friend" (J. Snover), especially in cookbooks. Step 1 - Create a Class Library project Create a new (C#) class library project, e.g. called MyMmcSnapIn: Step 2 - Import references In Solution Explorer, right-click the project node and select Add Reference... On the Browse tab, navigate to the %programfiles%\Reference Assemblies folder and locate the Microsoft\mmc\v3.0 subfolder: Note: Reference Assemblies are installed by the Windows SDK - a must-have for each platform developer. In there, select the Microsoft.ManagementConsole.dll file: Click OK. Next, go back to the Add Reference dialog and select System.Configuration.Install from the .NET tab: Step 3 - Create your snap-in Snap-ins derive from the SnapIn class. Go ahead and rename Class1.cs to MySnapIn.cs. Next, inherit the class from SnapIn which will require to import the Microsoft.ManagementConsole namespace: For sake of this post, let's keep things simple and just implement the bare minimum, i.e. setting the RootNode property to some node: I'm using C# 3.0 syntax to do this, as shown below: resulting in this piece of code: A real implementation (see next post) would likely create a node class that derives from ScopeNode to create a custom node that consumes data (e.g. from PowerShell, see next post). Step 4 - Adding metadata Our snap-in needs to carry some metadata using the SnapInSettings custom attribute. This one needs a GUID so go to Tools, Create GUID to create one: Click Copy and Exit which will put a GUID on the clipboard: Now add the SnapInSettings custom attribute to your class: and specify DisplayName and Description (other properties are not really required in this case): Step 5 - The installer In order to register the snap-in on the machine we need to add an installer class. This is as easy as creating a class deriving from SnapInInstaller: Here's the resulting complete code: Step 6 - Compile and register Time to compile the project. Next, open up a Visual Studio 2008 Command Prompt running as Administrator and cd into the bin\Debug folder of your project. Now run installutil on the created assembly: To verify the installation was successful, you can take a look in the registry under HKLM\Software\Microsoft\MMC\SnapIns and look for a key called FX:myguid where myguid is the one specified on the SnapInSettingsAttribute. It should point at your newly created assembly: Step 7 - Create an MMC console for debugging Time to test our snap-in. Go to Start, Run and specify mmc.exe. In the MMC console go to File, Add/Remove Snap-In (CTRL-M). You should see the registered MMC snap-in in there: Notice the name and description. Select it and click Add. Finally click OK. The result should look like: Quite minimalistic, I agree, but we're alive and kicking! Finally choose File, Save and save the console configuration to a file called Debug.msc under your project's folder: Finally, close the MMC console (otherwise the loaded snap-in dll would remain locked, blocking subsequent builds). Step 8 - Setting up the debugger Back in Visual Studio, go to the project properties. On the tab Debug enter the path to mmc.exe (in the system32 folder) and specify the relative path (starting from bin\Debug) to Debug.msc created in the previous step for the command-line arguments: Set a breakpoint in the code: and press F5. You'll see the breakpoint getting hit: Congratulations - your MMC debugging dinner is ready to be served! Back in manageability land. On TechEd EMEA Developers 2007 I delivered a talk on "Next-generation Pingback from Daily Bits - February 29, 2008 | Alvin Ashcraft's Daily Geek Bits How can I localize the SnapIn attributes? Help file redirection, as explained at msdn2.microsoft.com/.../ms692743(VS.85).aspx, does not work as I would like in Windows XP and Server 2003, and the SnapInHelpTopicAttribute class is sealed, so I cannot customize help support in a derived class. Alon Fliess and I have presented at three Open House sessions at Microsoft on the subject of the upcoming Last week, I had the honor to speak at TechEd 2008 South Africa on a variety of topics. In this post
http://blogs.bartdesmet.net/blogs/bart/archive/2008/02/27/the-managed-mmc-3-0-snap-in-cookbook.aspx
crawl-002
refinedweb
836
62.88
This is the first article I have written for this forum. I've enjoyed and benefited from the many wonderful articles on The Code Project and thought it might be a good time for me to contribute something. I've recently finished a long-term project for a client (actually I'm still tweaking DOCs and a few minor things) who has graciously granted permission to place a generic version of the developed code in the public domain. This was a very large project that employed C#/.Net (to the extent possible) to integrate legacy code in a platform-independent fashion. The application is NDE (Non-Destructive Evaluation) and involves the coordination of multiple real-time processing assets and sophisticated analysis functions that operate on 2-D, 3-D and higher-dimensional datasets. I'll talk just a bit later on about the application, but not in detail unless somebody asks me to. Originally, I was to play the role of a project manager for an "in-house" project that would be augmented with outside contractors to supply some of the .Net programming expertise. Unfortunately, when the project actually geared up, we found a dearth of capable .Net programmers. I ended up hiring a project manager and doing most of the system architecture work myself, as an individual contributor. I also performed much of the programming of the framework that was developed to support the application. My involvement in the actual software development ended up being much more substantial than was originally anticipated. This was a tough and long-winded assignment for me. In recompense, I learned a great deal from some very brilliant (and kind) people, so I am thankful to have been involved in this major project. I will talk about the overall framework a little bit in a following section, just to give perspective on why we did (and are doing on the generic project) things in certain ways. I've been trying to figure out which part of the project code to talk about and release first. My problem has been that I want to have everything perfect before releasing anything in order not to embarrass myself. After a few weeks of cleaning up one thing and then another, then another, I realized I might never get anything released until I was too senile to remember what the project was about. So I decided to pick a simple concept and try to write something about it that might be useful to people and put some code up on The Code Project website just to get my feet wet. Even after this landmark decision, it's taken a while to dis-entangle namespace dependencies and refactor things a bit so I did not have to put all of the code up here at once in order to run anything. I've actually had to stub out a few references out and/or replicate functionality locally, but the download size is now manageable, so I guess everything worked out fine. I was originally going to put the code for our service manager up here, but then I remembered that I wanted to introduce some concurrent processing so I could initialize some services on background threads. So I decided to work for a bit on concurrency management and this ended up being a project all in itself. So I guess the service manager will be article number two or maybe three. In writing this article, I have taken a tutorial approach. I've been training folks with varied backgrounds who are new to .Net for a while now. Usually I lose people if I don't provide a bit of explanation of how .Net compares to other platforms and also explain some of its more advanced features. I've tried to provide some tutorial explanations as they are needed when I describe various code features. I hope this is useful. The code documentation is comprehensive. I use my code for teaching and thus it must be so. I should also say that there are some advanced (arcane??) constructs used at different times. We were pushing the envelope of managed code on this project to a large extent and we just needed to do some strange things. I've tried to note in the code where you probably should not do certain things unless you really need to. The reader might also note that there is great deal of duplication in the various code examples. Sensible design practices (OO and otherwise) would dictate that duplication of code be minimized. This would entail factoring and inheriting and all the other good stuff that smart programmers do. However, it's difficult to demonstrate different variations on a theme if there is a complex inheritance or composition structure in the demonstration code. So, I like to keep things flat in the examples unless I am trying to demonstrate some specific structural design. OK, time to get serious... The NDE field is characterized by the need to handle massive amounts of data derived from various types of sensors (ultrasound, X-ray, electrooptical, etc..) that are formed into different types of datasets for analysis. In a production environment, the NDE system will typically need to coordinate the activities of multiple processors of multiple types, all working toward the common goal of performing an accurate analysis of the quality of a certain material or part under inspection. The NDE data processing world today involves massive parallelism. The current state-of-the-art in data processing and transfer is exemplified by products like those produced by Texas Memory Systems (). A network of parallel processing nodes provides 192 GFlops of processing power with 16 GBytes/sec of shared storage bandwidth at a cost of somewhere under $250K. In such systems, data is processed quickly and moves quickly. Our framework was developed to take advantage of these modern processing assets. We want to distinguish between "embedded" and "real-time" systems. Our NDE systems are not embedded in another system, though they have a hard real-time requirement. Not all embedded systems have any real-time requirement, though many do. Definitions differ, but in our context "hard" real-time means that a missed "deadline" is never acceptable. Embedded processors in consumer products often have a "firm" or "soft" real-time requirement, specifying that they must keep up with processing only on an average basis. C#/.Net was selected to implement a framework for integrating/rewriting legacy image processing and analysis algorithms and also, to the extent possible, to control high-speed processing assets. Much of the time-critical data processing is done in special-purpose machines, with their own execution systems. There is much functionality that is also implemented in the "Host" processors that has to do with moving data and performing high-level processing, analysis and display. There is a great deal of middle ground, here, where the boundary between managed code and unmanaged code was not clear. As the project has evolved, we've learned a bit more about how to decide such things. Hopefully we'll have a chance to share some of this knowledge in a few articles. There are a number of good reasons why existing implementations of .Net are not directly suitable for many real-time operations. First, the VES imposes some additional overhead as compared to unmanged code. Our experience with this is that some standard operations can take up to four times longer, or so. Lot's of things run much faster and various optimizations can be performed for specific applications, though. A more important reason has to do with memory management and garbage collection. First, many hard real-time systems can't afford to have the garbage collector run during a processing loop - ever. In some time-critical applications, an object falling out of scope and becoming a candidate for garbage collection must be considered equivalent to a memory leak in an unmanaged code application. One simply cannot afford the time for a collection. Purveyors of .Net technology are rather cavalier about simply letting the garbage collector take care of things behind the scenes, since it "runs so fast". Well, there's fast and then there's FAST. Often real-time applications cannot spare even a few milliseconds. As a result, an execution environment must allow the developer to write code that effectively reuses data items without discarding too many over the life of the application run. Keep in mind that these real-time systems often run millions of iterations in a typical processing task. In an unmanaged implementation, one instance of a malloc and free inside a processing loop, even on a small data item, can ruin one's whole day. Technically, it shouldn't if the heap manager were designed right but...... As a result, many real-time programmers spend a lot of time designing pooling schemes and custom memory managers. The facilities of a general-purpose OS are generally not designed to do this. Real-time OS's handle some of this, but one still must write the application code in such a way as to require minimal intervention by memory management facilities. There are a variety of manufacturers who make OS extenders (some folks call them "shims" - another overused term) that are designed to augment an OS to make it more useful for real-time applications. These extenders usually handle low-level hardware synchronization details and prevent ongoing processing tasks from being interrupted by the main OS at an inopportune time. This idea works fine if the main OS has to do only a few simple things during the processing loop, like maybe send a message to the screen indicating the status of the real-time operation. It does not work if the OS needs to do serious work (like managing memory) that has to fit between strokes of a cutting head (or whatever). Problems with implementations of garbage collectors in .Net are described in [Lutz03] and [Zerzelidis05], for example, and still have not been adequately addressed. One of the major problems with garbage collection is the problem of latency of control. When a data buffer full of scanned data needs to be unloaded or a tool head needs to be moved, the execution environment has to respond right away. If the OS is doing a garbage collection or something similar, it has to stop immediately and service the real-time request. Even if the average time the garbage collector spends in compacting memory could be tolerated, its work must be interruptable to service real-time requests almost instantaneously. [Zerzelidis05] points out this problem. An interesting report [NIST99] that predates the emergence of .Net covers some of the same issues for the Java platform. This report defines some of the terminology that has been adopted in more recent studies. It also helped drive the definition for the Real-Time Specification for Java (RTSJ). When we were first planning this project, we looked a number of real-time OS's and OS extenders. We found none of these technologies that supported .Net (and C#) in a platform-independent way. One solution is do a lot of processing in unmanaged code and coordinate that processing through either Pinvoke or COM interop. That is the the approach we took in our project (mostly Pinvoke, since COM support was not there on Mono) and it worked fine. One just needs to keep the amount of processing done in unmanaged code high relative to the amount of time spent in performing Pinvokes. Pinvokes are costly, but not THAT costly, especially if any data transferred is in the form of blittable Types. Packing data and control information into a single native int or byte array with mapping/unmapping helps considerably. In the NDE field there is a high premium placed on data integrity and correctness of results (how could a flawed data collection/analysis system be expected to perform Quality Assurance inspections?). In many cases, users of the system will expect that there will never be one single mistake in the various data manipulations performed, ever. NDE applications are not alone in this requirement. A computer-controlled machine tool must perform its operations on the correct schedule, every time, or the part being manufactured could be destroyed. This fact drove the choice of concurrency management techniques we adopted for our work. Our options for concurrency management techniques have always been limited by the fact that a major goal of the project was platform independence. We've spent significant effort over the past couple of years 1) researching the Microsoft DOCs to see how a certain thing could be accomplished in .Net, then checking out 2)Whether it was spelled out the same way in ECMA and 3)Checking out whether Mono had it yet. With regards to Mono, it was never enough to check if it was in their Docs, but whether their compiler and CLR actually implemented it fully and correctly. We've been burned a couple of times by this. For example, their compiler accepts the new [SecurityCritical]attribute from the Security namespace, but doesn't do anything with it and doesn't inform the code author of this fact!! Don't misinterpret our comment - the effort by everyone working on Mono is spectacular. To be developing an open-source version of .Net functionality substantially in parallel with Microsoft (or soon after) is a wonderful accomplishment and a noble goal. It's just that one must spend a little time checking the status of things. When our company was involved in product development, we built a major multi-platform product under a government contract. It was so difficult that it almost brought the company to it's knees. The tools just weren't there for this type of effort. The platforms were PCs running Win32 (just out) connected to SUNs running Solaris communicating through PC-NFS. Reconciling code across the two platforms was primarily a manual operation and cross-platform testing was a nightmare. The network always seemed to be down. So things are much better these days - we're not complaining [SecurityCritical] Prior to .Net 2.0, things like Semaphores were not available in managed code so we relied on rather simplistic locking mechanisms using Mutexes and Monitors. As a result of the platform issues, we are still staying away from anything that is not verified as stable on Mono. We don't need anything sophisticated at the moment, since our synchronization requirements in managed code are fairly simple. Managed thread synchronization is done currently within our framework's managed code, but in a piecemeal way. We've rewritten some simple concurrency management code under 2.0 to provide something that is a bit cleaner and more reusable. To the extent possible, we've stayed entirely within the Virtual Execution System (VES) using Monitor, .et .al. At the moment, all we need to do is run a few services that are not time-critical on background threads. However, we are anticipating the conversion of more real-time control processing into managed code, so we want the work to be reusable for this purpose. We'll see how this goes.... While studying up on System.Theading under .Net 2.0, we had occasion to stumble across the methods of the Interlocked class. We'd seen them (and used them) before, but we noticed a certain exposition concerning the ADD method that we found troublesome. (The ADD method is new in 2.0.) There were apparently several other people who noticed that the description was at least peculiar, based on some forum entries that have appeared. We are starting the technical discussion with an explanation and a demonstration of the technique that was described in this piece and why its not a good idea to use it. Or, better said, why one needs to be very careful with it. We have a bit of heartburn when we see it's use advocated in a cavalier fashion, since we go through such great pains to use it safely and correctly. System.Theading The exposition in question describes how an atomic CompareExchange operation can be used in a loop to build an ADD function that is also atomic in SOME sense. For the uninitiated, the concept of an "atomic" operation is part of the jargon employed in multiprocessing (and in other sub-disciplines of the computer field) to describe an operation that is guaranteed to take place all at once. The term is commonly applied when referring to a procedure that reads a data item, modifies it somehow and then writes it back, all in one operation. What is meant by this is that no one else gets to touch the data item during this sequence of three steps. Contrast this to an ordinary sum = sum + summand; instruction in C#. This operation is not guaranteed to be atomic - in fact most compilers treat it as three separate steps of read - modify - write. In multi-threaded applications, the sequence can be pre-empted by other threads accessing the very same variable in between the steps. The idea behind atomic operations is that this cannot happen, the instruction normally being mapped to a hardware instruction for a particular processor that locks memory for the duration of the read - modify - write operation. Atomic operations (and concurrency management in general) are becoming more important with the advent of Hyperthreaded and multichip CPUs. These issues are no longer solely within the purview of the multiprocessing folks, so it's worthwhile to discuss them just a bit. CompareExchange sum = sum + summand; The way one implementation of an ADD function is suggested in the descriptive piece in question is shown in generic (not .Net Generic) form in figure 1. Figure 1. "Retry Loop" Caller Logic. In this figure, the CompareExchange method, which is a true atomic operation, is used in a loop to iteratively implement an addition. We call this a "pseudo-atomic" operation, since it is not truly atomic. I've taken a tiny bit of license with this diagram, since I wanted to illustrate the general idea of the retry loop. We'll present the code a bit later. The loop works as follows: This procedure was discussed at least as early as [Herlihy93]. In this paper, he discusses the use of "retry loops" (our quotes) that attempt an operation that changes some target object, then use an atomic operation to confirm and commit the change if things go as planned. If a "collision" is detected by the atomic operation, the OP is retried on the new state of the target, with the retry loop being executed again and again until it succeeds. "Back in the day", many discussions of non-blocking synchronization techniques such as this focused on database applications. It makes sense that many database operations (e.g.adding money to an account) could just be tried again if collisions were detected. Some can't, though. If the transaction is a withdrawal, for example, it's probably wise to check for an overdrawn condition before blindly making another withdrawal. Thus, it is critical to place the check for a negative balance inside the retry loop, not simply to perform it once before entering the loop. For more general applications, one needs to understand how this technique works and when it is useful. Let's get back to the case at hand and consider the situation when multiple threads are all trying to add numbers to a common target. This might be useful when a tally is being made of the number of operations of another type each thread has performed. The add operation may function correctly, depending on one's definition of the sum. The addition operation is commutative and the resulting sum does not depend on the order in which the summands appear (1+2 = 2+1). If the loop executes more than once, it just updates the sum until it has detected no further collisions. We say "MAY" come out alright. It depends on what is expected to be returned as the result of each thread's access to the integer. Is it the CURRENT state of the sum when the pseudo-atomic operation is entered? If so, the results will almost surely be incorrect if there are any collisions (unless someone is adding 0's). The only way it will be correct is if the user expects the result to be the ultimate value of the sum that has been continually updated by sidestepping any collisions that may have occurred within the loop. Furthermore, this result would be closely tied to the pseudo-atomic operation implementation. It could be made correct by capturing the FIRST sum calculated and saving it for eventual return to the caller, while still continuing with the update loop so that the final sum is calculated correctly. Why would one possibly care if the sum returned was the state at one instant or one millisecond before? In most cases it would be irrelevant. It is not irrelevant in our application, since the correctness of our results often depend on timing and ordering of specific operations. Another point to consider is that the correctness of the concurrent addition process just described is contingent on the fact that all threads are accessing the data item with an add operation. Let's, instead, say that one thread is resetting the number to zero if it exceeds a certain value and the rest are adding, as usual. A moment's thought will convince the reader that the results will not be the same as if true atomic operations were involved. Worse yet is the case when a main thread (say) is performing a tally of how many times other threads have accessed the shared data item since the main thread's last access. Obviously, retry loops are not appropriate for performing audits of any characteristic based on timing of thread access. Some seasoned authors who embrace this technique have argued that only in rare cases will the loop execute more than once. This may be true, but it's not guaranteed. Furthermore, in our application, even one collision (as defined above) is entirely unacceptable. When we perform an operation that we are counting on to be atomic, we need to lock the data so that no one else can read or write it. Let me reiterate that retry loops are very useful in many applications. They are a non-blocking technique and are very useful (when applied correctly) because they can eliminate deadlocks. We implement techniques similar to those described in [Anderson97] to make effective use of retry loops in our hard real-time application. One just has to think think things through and make sure that the results are correct in a particular scenario. This is a very good place to start this article, because it demonstrates the need for a verification methodology that can reveal problems in the application of a given synchronization technique. We will get our start by demonstrating how our simple testbench can shed some light on the operation of retry loops. System.Threading.Threads In this section, we will demonstrate a simple test of the pseudo-atomic operation style that uses a retry loop. We don't use it in our implementation, but it's a simple example to start with to demonstrate concepts. We display the code implementing our retry loop in listing 1. The method shown is part of the test class QATester_MultiProccessing and accepts a delegate to perform a binary operation on a System.Int32. The definition of the delegate (which we use quite a bit) can be found in AtomicUtils_Article.cs. For those readers unfamilair with C# delegates, they are very similar to function pointers in the C languages. C# delegates, however, include a specification for the Types of parameters and return value (if any). Any method matching the pattern in the delegate definition (including the Types) may be passed as a parameter wherever a given delegate is called for. There is again a bit of confusion concerning nomenclature, since C#'s definition of delegate is but a compiler token that allows access the the fundamental CLR Type System.Delegate. We try to differentiate the two by using case and color (Delegate vs. delegate). class QATester_MultiProccessing delegate System.Int32. delegate System.Delegate Delegate For a discussion of how the C# language compiler maps the C# delegate into the rather complex facilities of System.Delegate, see [Lowy2005] (pg. 131). [Duffy06] (pg. 519) provides a deep treatment of a System.Delegate's representation inside the .Net Common Type System(CTS). Our delegate in listing 1 accepts a source parameter and a byRef target parameter which is to be updated. As can be seen in the listing, the logic of the method centers on the call to CompareExchange. The CompareExchange method provides true atomic operation, comparing the third parameter with the first (the target) and replacing the target with the second (the opResult) if and only if the comparison succeeds. The CompareExchange method always returns the value of the first parameter at the instant itis called. This allows the operation to be tried on the updated value over and over again until it succeeds. The CELOOPPseudoAtomicInt32Caller method returns a value indicating whether or not a collision occurred (whether another Thread snuck in and changed our Int32 when we weren't looking). The code shown here allows us to assign different operations to different Threads and also wrap delays inside the OPs to simulate Thread timing and loading dynamics. byRef CompareExchange CELOOPPseudoAtomicInt32Caller Int32 // Delegate for a binary Int32 operation. public delegate System.Int32 Int32Op(ref System.Int32 target, System.Int32 source); // Caller for an Int32 OP. internal static System.Boolean RetryLOOPPseudoAtomicInt32OpCaller( ref System.Int32 target, System.Int32 source, Int32Op oP, out System.Int32 lastValue) { // This variable stores a local copy of the original value of the target // that is read before the OP and the atomic exchange. It is used to // compare with the most recently fetched value from the atomic exchange // to see if it has been modified by another Thread. System.Int32 workingValue = target; // This variable stores a local copy of the most recent value of the // target as returned from the atomic exchange operation. System.Int32 lastUpdatedValue = target; // This variable will be set to <C>true</C> if we undergo a collision. System.Boolean hadCollision = false; // Result for our oP; Int32 opResult; // Repeat until we get no more collisions. do { // Set the working value to the last update. workingValue = lastUpdatedValue; // Perform the OP on the local opResult variable. opResult = workingValue; oP(ref opResult, source); // Make the switch only if the target has not changed from our // last working value. lastUpdatedValue always receives the current // value of target as returned by CompareExchange. lastUpdatedValue = Interlocked.CompareExchange(ref target, opResult, workingValue); // Report progress if we want.... if(QATester_MultiProcessing_Testdata.s_reportToScreen) Console.WriteLine(" >Processed a Number on ManagedThreadID #: " + Thread.CurrentThread.ManagedThreadId.ToString()); lastValue = lastUpdatedValue; // If the two values are different, this means that we had a collision. if(lastUpdatedValue != workingValue) hadCollision = true; // Keep LOOPng and RETRYing if we have had a collision. } while(lastUpdatedValue != workingValue); return hadCollision; } Listing 1. Caller Method for a Binary Int32 Operation Int32 In figure 2 we display some results of running the retry loop shown above on a few Threads. We will describe and diagram the full architecture that we employ to support such tests a bit later in the article. For the moment, we'd like to introduce it with this simple example. Our testbench has the ability to create and start a number of worker Threads, each running a "caller" such as RetryLOOPPseudoAtomicInt32OpCaller a specified number of times, with the same target. Please forgive the long-winded name of the method. There are a large number of experimental "callers" in the testbench and the descriptive names help keep them straight. (They are all included in the download). In the first experiment in our test set, we create a total of five "spawned" Threads, in addition to the main Thread. All our tests are designed to optionally do some processing in the main program in addition to processing on a user-specifiable number of Threads that are created and started by the the main program (referred to as the "Main Thread" in what follows). This type of arrangement is also used to simulate a situation where a "host" is acting as a controller of some parallel processing assets. The "ManagedThreadID" printed in the output is nothing but the ManagedThreadID property pulled off the various executing Thread class instances. "Worker Thread #n" just indicates the n'th Thread that the main program has fired up. The testbench includes a random number generator that is used to synthesize both random delays and random data for the tests. The random data is usually applied to the "source" parameter to the caller methods, which is done in the test shown here. In this test, random delays have been applied inside the oP delegate. This first test uses a simple replacement operation as the delegate, which simply replaces the target with a new randomly-generated source integer. The only reason we need the source of integers here is to tell if the numbers have been overwritten or not. In this case, we are not doing any examination of the results outside of the retry loop caller. This is obviously a degenerate example, since the replace operation is redundant with that of the CompareExchange method call. The point of the test is to illustrate that a retry loop does not implement an atomic operation. If Threads collide, one doesn't always get the expected result...... RetryLOOPPseudoAtomicInt32OpCaller ManagedThreadID ManagedThreadID Figure 2. Output from Retry Loop Caller Showing Collisions. Why would we ever need such a capability as a "testbench" with random numbers and these sorts of things for concurrency testing? The problem is that validation of any concurrency mechanism involves verifying a negative hypothesis - that data will never get corrupted or out of synchronization or deadlocked because of a design error. A program accomplishing concurrent data access may run for years in support of a given application without any sort of failure. One never knows whether the program will provide reliable operation under all conditions. It often happens that concurrent programs will fail under conditions for which they were not originally tested. In practice, this usually occurs when some strange combination of events occurs, quite often under an improbable circumstance. While it's never possible to test for all eventualities, it helps a great deal to stimulate a concurrency management architecture with statistical sources. This testing methodology can help identify problems by subjecting the design to a rather large combination of events in a reasonable time. Any statistical testbench should be capable of generating fixed (non-random) events as well, in order to subject the design to certain specific conditions that may be suspected to be troublesome. Some statistical testing of a design on the front end of a project can reduce the nightmare of debugging concurrent systems to some tolerable level (It's still awful). Concurrency problems have a well-deserved reputation of being the worst problems to debug and solve in the software world. Microsoft Corporation devised a special locking mechanism for use in .Net. It involves a table of entries called a "sync table" which is populated with indicators describing which objects in the GC heap have been locked by a client that wishes exclusive access. This facility is accessed through the Base Class Library (BCL) System.Threading.Monitorclass and implicitly through the C# lock keyword. [Richter06] provides a scholarly treatment of this synchronization mechanism (p. 630) as well as the .Net garbage collector (p. 457) as implemented in the Microsoft .Net 2.0 CLR. Interested readers can find a comprehensive treatment there. This facility is now also part of ECMA, although the implementation through a "sync table" is a platform-specific detail, not part of ECMA. It suffices to say here that the locking capabilities afforded by Monitor are only available for Objects on the heap. This means, unfortunately, that access to our Int32 cannot be synchronized with the Monitor class. All is not lost, however, since a ValueType can be wrapped inside a C# class and the class can, in turn (being an Object), be synchronized with Monitor. There are specific reasons why we wish to employ this technique in our work. We will describe these reasons in detail in a later section. System.Threading.Monitor ValueType Object There are a number of additional obvious ways that almost any design could make use of Monitor and its Object-locking capabilities. Many elementary books on .Net indicate the possibility of simply locking an instance of a class when synchronized access to its members is desired. Usually these same books will admonish the user to refrain from doing so, since a hostile party could also take out a lock on the same Object (if accessible) and deny the rightful client(s) access to the Object. Things get even worse for locks taken out on class-level object, which would occur when synchronizing access to a Type's static variables by locking the Type itself. The solution that is usually proposed is to place a private class of some sort as a member variable on a class. Methods needing to access synchronized member data can then (consistently) lock on the private Object and everything works just fine. We won't provide further detail here, but we refer the reader to [Richter06] or [Lowy05] where examples abound. Type Type private Object There are several facilities specified within the ECMA standard which map to kernel mode operations in Microsoft's CLR. These facilities, such as Mutex and Semaphore are wrappers for classic Win32 functions of the same variety. We have employed these facilities at various times and in various places in the past. As stated previously, we are attempting to operate in user mode to the extent possible, with plain-vanilla synchronization features of the CLR. We do this for speed and to avoid any implementation inconsistencies that tend to crop up across platforms when employing features that haven't been in use for long enough to get the bugs out. For the moment, we are attempting to go as far as we can with monitor and lock, seeing just what we can accomplish within the CLR. Mutex Semaphore There are a number of very useful facilities made available through the .Net System.ThreadPool class. We've used these in many places in the past and continue to do so. However, for the rewrite/unification/whatever of our concurrentcy architecture, we need to be able to abstract away the notion of threads entirely. We are trying to make our MultiProcessing classes general so that from the client's point of view, it is immaterial whether a task is carried out on a piece of hardware or on another machine or on another Thread (of course with the advent of MultiCPU machines the concept of "another machine" is becoming ill-defined). Asynchronous delegates support some of this, but we need something quite general that we can wrap and expose different functionality for different purposes. That, plus the fact that we need to do hierarchical management of MultiProcesses and support specialized MultiProcess queues and a few other things makes it unfeasible to use the standard Thread pool. System.ThreadPool Our "TestBench" is a set of classes that can perform statistical tests on various concurrency management architectures to HELP gain confidence that their operation is correct. It contains various "TestRunner" methods that can be run under the NUnit testing framework. These can also be run from an ordinary command prompt, for those who do not have NUnit installed or choose not to use it. See the NUNIT_IN_USE constant at the top of QAUtils.Article.cs. It is sometimes easier to debug programs from within tools like Visual Studio when they are not run from NUnit. By providing these simple classes, We're hoping to provide folks with a starting point for concurrency work. NUNIT_IN_USE The tests are performed within an architecture that resembles that in figure 3. The "Caller" method (see listing 1) is shown in general form in the diagram, along with its internal OP delegate. Recall the test results in listing 1 were generated with a simple replacement OP. We make extensive use of delegates in our multiprocessing architecture. The .Net System.Threading library makes extensive use of delegates and we also find them quite useful in allowing us to run different types of processes from our MultiProcessControllers. In figure 3, delegates are shown in the boxes with rounded edges, colored in red. We normally like to use UML diagrams when possible. What needed to be described here seemed a bit too convoluted to be adequately detailed with a reasonable combination of UML diagrams. Thus this diagram - a mishmash of different paradigms. If anybody can make a better diagram, send it to us and we'll be grateful....... System.Threading Figure 3. Architecture of a Typical TestCaller As can be gleaned from the figure, the Caller method is actually itself a delegate that is supplied to a "CallerProcess" that is responsible for invoking the caller and supervising its operation. The CallerProcess is, in turn, a delegate of the form called for by one overload of the Thread.Start() method. One of the convenient enhancements to the System.Threading namespace in .Net 2.0 is the ability to pass a data object into a Thread process. The new "ParameterizedThreadStart" delegate allows a System.Thread to be created with reference to a delegate that can accept a System.Object when the Thread is started. This is much more convenient than passing auxiliary static data that has to be kept reconciled with the active Threads, etc.. This is more consistent with a true multiprocessing architecture where a processor is associated with its own data store. Caller CallerProcess CallerProcess Thread.Start() ParameterizedThreadStart System.Thread System.Object The name QATester_MultiProcessing derives from the fact that prior to the use of NUnit, we did our own unit testing through reflection. Instead of using attributes, we employed a certain naming convention for test classes and methods. This whole thing is explained in files within the MPFramework.AppCore.QualityAssurance namespace for the interested reader. For the article, we created the set of TestRunners within QATester_MultiProcessing_Article by simplifying some of our control methods to make them more accessible. We have attempted to design the various TestRunner, CallerProcess and Caller methods in an evolutionary fashion, starting simple (just the retry loop functionality), then adding features to create more advanced versions. We provide a large variety of these methods simply because it's tough to figure out how to do certain things unless they have been seen before (been there). Hopefully, though, we've structured things so that the examples are understandable. Note that all of the NUnit test methods in QATester_Multiprocessing_Article are qualitative - they were created for this article and they just scroll results to the screen. Test methods in the accompanying QATester_ReferencedValueTypes_Article class are quantitative - they employ NUnit assertions to ensure numerically correct results. MPFramework.AppCore.QualityAssurance QATester_ReferencedValueTypes_Article The blue lines in figure 3 indicate the data that is passed down from the testing framework. There are higher-level caller methods in the QATester_MultiProcessing_Article class that are the actual NUnit test methods. For those unfamiliar with NUnit, the NUnit testing framework currently employs the facilities of the .Net 2.0 System.Reflection namespace to scan assemblies for methods decorated with the [Test] attribute and runs them, collecting test results as it goes along its way. Living above the TestRunners is a number of these methods. These are not on the diagram because it's too complicated already System.Reflection In our MultiProcessing classes, we apply various C# interfaces to the "CallerObject" indicated in figure 3 to invoke supervisory protocols. Again, in the interest of simplicity, we don't deal with any of this in QATester_MultiProcessing_Article. We did extract one very useful concept for use in the TestBench, however. As can be seen in the figure, there is an indication of a "Control" and "Status" capability which is exposed to both the TestRunner and the CallerProcess. In our full-up system, we have a set of registers that form a "virtual front-panel" implementing various supervisory functions. This provides an emulation of an actual hardware interface. For these simple demonstrations, one version of CallerObject includes two Int32 variables - one a StatusRegister and one a ControlRegister. We use these in one of our experiments to demonstrate how executing Threads can report their progress and how the TestRunner can control running Threads. [Lowy2005] (pg. 247) illustrates a simple version of this technique. We use it extensively in our Framework. Referring again to the figure, Callers are designed to operate in a loop, with a default number of iterations specified in an input parameter. The presence of the StatusRegister allows the TestRunner to receive reports from the CallerProcess on its progress. The TestRunner, on the other hand, can issue commands to the CallerProcess by writing to the ControlRegister. Each of these registers is normally only writable from one side of the interface. This completely eliminates the need for managing concurrent access to these data items. This is similar to the type of interaction that is afforded through a memory-mapped hardware interface. There are usually a number of other registers (e.g. programmed I/O register, DMA control register, etc., etc..), but these two suffice to demonstrate the concept. interface CallerObject StatusRegister ControlRegister TestRunner Note that the TestRunner has the capability to start multiple Threads. The developer of a test may pre-store data for individual Threads in the CallerObjects array before the test is run. This data may include a Caller delegate and an OP delegate. Thus, each Thread may have a different Caller and a different OP. In this way, it's possible to create Threads that are performing different activities, such as adding, counting, resetting and so forth, as mentioned in an earlier section. It is also possible to customize the random number generators for each Thread that is created. Each Thread maintains an independent copy of the data random number generator and the delay random number generator, as indicated in the figure. Although it's possible to customize each Thread individually, it's also possible to create some custom Threads and clone the rest from a "standard" Thread. An indication can be made to a TestRunner (not the simpler ones) that the data for certain Threads should be cloned. In this case, the TestRunner will create new random number generators for each "cloned" Thread by copying the parameters from an existing set of random number generators and using the Thread.ManagedThreadIDs as seeds for the new independent generators. This is a convenience for those cases where it is desired to create a large number of similar Threads along with one or a few unique Threads. We will describe this further in sections on the AuditingRandomNumberGenerator and the CallerObject. CallerObjects AuditingRandomNumberGenerator CallerObject We have developed an interface for a Generic random number generator that allows access to some internal bookkeeping capabilities. In our work, it has proven useful to record the sequence of numbers that have been generated, for example. This is sometimes used in an analysis of what went wrong in certain concurrent operations. We don't use these capabilities in any of our experiments in QATester_MultiProcessing_Article, but this is the origin of "Auditing" in IAuditingGenerator<T>. IAuditingGenerator<T>. This is the first time we are touching the concept of Generics. Generics are new in .Net 2.0 and have added a great deal of power to the .Net Framework. There are many areas in which Generics are helpful. For a full treatment of Generics in .Net 2.0, see [Golding05]. The main benefit of generics in our work is the ability to deal with System.ValueType (henceforth termed ValueType) data items in the .Net Framework without boxing. In C#, these data items are either primitive Types (e.g. int, float...), struct (user-defined ValueTypes) or enums. It's mostly hidden from direct view of C# programmers, but these C# Types are all derived from the abstract System.ValueType Type (a .Net Class) within the .Net Common Type System (CTS). We use the capitalized version of the word (i.e. "Type") when we want to refer to the specific categories of data items in .Net. The ValueType Class derives directly from System.Object and contains no data members. ValueType-derived Types are unique in they can exist in either boxed or unboxed form. The terminology gets tough here already, since the C# class keyword refers to a .Net Class that is not derived from System.ValueType - i.e., a C# class is a Reference Type. Confused? It's OK - it is VERY confusing. We try to use the blue highlighting for C# keywords when we are referring to C# concepts. System.ValueType ValueType int float System.ValueType [ECMA335] (12.1.6.1) develops the concept of a "HOME" for a Type's databytes (we use the term "databytes" for a Type's data to help disambiguate terms). We capitalize HOME, since it is a critical pedagogical term from our viewpoint. In boxed form, the HOME of a ValueType's databytes is within an object slot on the managed heap. In unboxed form, a ValueType's databytes can be in a HOME somewhere outside the heap. Most C# programmers are accustomed to passing primitive Types and structs to methods. In this case, their HOME can be on the evaluation stack of the VES (if passed by copy). We use the term "passed by copy" to avoid an ambiguous use, this time of the term "value". In C# code, ValueTypes can also have a HOME in local storage, like this: int myInt = 1234; . Note that the HOME of a non-ValueType's databytes is always on the heap. This is true for all C# classes. Microsoft has tried to make it easy for developers with a background in the c languages to step up to .Net (to their credit) by using the names "struct" and "class" that are familiar to those coming from the c world. However, as soon as the underpinnings of the CTS begin to be revealed, things start to get confusing. C# compiles to a fundamentally different method of execution from the c languages and requires a bit of explanation. One of the fundamental difficulties in interacting with unmanaged real-time code is moving databytes from a HOME on the heap to a HOME outside the heap (and back again) in an efficient way. int myInt = 1234 struct class Another issue that arises in the context of interoperability is that of "safe" code. Even though ValueTypes can have a HOME outside of the managed heap, their access is still Type-safe. In the VES, a ValueType is always accessed by a TypedReference, no matter where it lives. This is true, at least, when implementing verifiable code. In C#, this is any code which does not employ the unsafe keyword. In CIL, one has to know the rules for verifiability, but ANY CIL code should always be checked with peverify.exe. This will determine whether any unverifiable constructs (analogous to C# unsafe code) are used in the CIL program. In our work, we attempt to keep the amount of unverifiable code to a minimum. It's a good practice in general. TypedReference We deal with unmanaged code interoperability a great deal and it's important for us to be able to handle ValueTypes in an efficient manner. For instance, in C# 2.0, one can create an array of custom structs without having every single one placed in a box. It should be mentioned that much of the inefficient use of managed memory can be overcome through coding directly in CIL. However, this is a ghastly and tedious procedure - eliminating some of it is a boon to the .Net developer community. Generics have helped a lot in this regard. What are Generics? We'll say just a few things here, leaving the rest to the authors of the many fine textbooks that cover the subject. Generics are similar in concept to c++ Templates. They allow operations, containers, classes, etc. to be defined for a "placeholder" data item that is not fully known when the Template/Generic is written. The placeholder data item is sometimes referred to as a "parameterized type". Templates/Generics allow a common set of behaviors, structures and interrelationships to be defined for an abstraction of a data item. A single Template/Generic can be specialized to many different data items, obviating the need to replicate much of the same code over and over again for each. In this regard, c++ Templates and .Net Generics are similar. There are significant differences, however. c++ Templates are "parameterized" at compile time or, at best, at link time. The compiler must have complete knowledge of the type of the data item that the template will operate with. In contrast, .Net Generics are "constructed" at JIT compile time, when the needed Type is loaded. A .Net Generic Type that has been constructed through the JIT compilation process is also known as a "closed" Type, as opposed to the "open" designation of an unconstructed .Net Generic Type. Additionally, the .Net community seems to favor the use of "TypeParameter" to refer to the placeholder in a Generic Type. We will use this term in what follows. There are advantages to both c++ Templates and .Net Generics. An often-mentioned advantage to .Net Generics is the ability to only construct the closed Types that are accessed during a particular invocation of an application. This avoids code "bloating". In fact, the notion of an "open" .Net Generic Type exists both at the source code level and at runtime, whereas in c++ it is a source code notion only. It's quite useful to be able to create constructed Generic Types dynamically, though reflection. The System.Reflection namespace has been updated with a full complement of capabilities for handling Generics. [Golding05] (pg. 187) covers this topic comprehensively, but there is also some useful material in [Smachia05] (pg. 410) not found elsewhere. To be entirely accurate, we should mention that the situation is slightly more complex for .Net Generics. It's possible to supply a closure for a Generic at language compile time, before the Type is ever used (Note that we must sometimes employ the term "lanaguage compile time", since the advent of JIT compilation has caused an ambiguity in the term "compile time" in some cases). This can be done, for example, if a given custom .Net Type inherits from a Generic Type and supplies a concrete TypeParameter with the Type definition. This would look like: classmyGenericClassClosedAsIntClass:myGenericClass<int> {}. With .Net Generics that have more than one TypeParameter (have "arity" greater than 1 in the standard .Net jargon) it would also be possible to close some TypeParameters and leave others open when inheriting from the Generic. TypeParameter classmyGenericClassClosedAsIntClass:myGenericClass<int> {} Java Generics are also quite a bit different from .Net Generics. If .Net Generics were implemented in the same fasion as Java Generics, they wouldn't do much for us. Generics in Java are primarily a type-checking mechanism to ensure type-safety when a given pattern (the Generic) is applied to a data item. Java bytecode generated at compile time is independent of the type of the data item[Venners04]. The Java compiler acts, in effect, by ensuring that a given sequence of bytecode can be safely applied to a given data item. The bytecode is not specialized to serve the needs of a particular data item and thus no increased efficiency ensues. Contrast this to .Net where the metadata corresponding to the Generic and the Type are combined at JIT compile time to create an efficient representation of the Type T and an customized implementation of the manipulations defined by the Generic. Actually, this is a bit of an oversimplification. JITted Generic code is shared in .Net across all Reference types. This is done because all Reference Types are accessed through pointers into the managed heap, anyway, so one really doesn't save anything by generating specialized code. However, (important for us!!!), .Net Generic code is specialized for each and every ValueType that closes a given Generic. This is important, for example, because collections of ValueTypes can be laid out flat (end-to-end) in memory without being partitioned into boxes. And, of course, ValueTypes can also be moved to a HOME on the stack, which is where we need them for unmanaged calls. It is due to the existence of ValueTypes in .Net that the addition of Generics to the .Net Framework is so much more important than the incorporation of Generics into Java (Java is a closed environment with classes and primitive types only). SUN actually terms this environment the "Java Ecosystem". To be sure, they are handy in Java, but there they affect syntax only, not the internal efficiency in the way Java types can be handled. For a definitive treatment of the way Generics are handled in Java vs. Net, see [Estrada04]. The incorporation of Generics into .Net has allowed us to move large portions of our project from unmanaged to managed code. Effectively, we are able to break unmanaged code access into smaller "pieces" and move more of the control into the managed world. This will become obvious as we move forward. Having sung the praises of .Net Generics we must be fair and mention that there are some drawbacks compared to c++ Templates. c++ Templates can essentially be thought of as macros. At compile time the macro is filled out with a token corresponding to a specific data type (say an "int") and that string is substituted anywhere the placeholder token appears. Thus, for example, it's possible to have an indication of one data item being added to another with the standard "+" sign. We can write token3 = token1 + token2; and if it is an int or a float that we are parameterizing the tokens with, everything works out just fine - we get either an int or a float addition. If the placeholder data type does not support an addition, the compiler will generate an error. Such is not the case with .Net Generics, unfortunately. Since the language compiler does not know the TypeParameter at compile time it can't just assume that whatever Type it is can support the "+" operator, for example. Well, what good are Generics, then, if they can't even do a simple addition? The approach .Net takes is to constrain a TypeParameter Y to implement interfaces. The style is to define a math library with an interface containing methods like Add(), Sub(), Or(), And() and all the rest for primitive Type manipulators. Some consider this to be a serious restriction. On legacy code conversion projects we have managed, it has been our experience that this style is quickly assimilated and provides great benefits in terms of generality. Furthermore, interfaces allow easier runtime definition of the operations we might desire a Type to support. token3 = token1 + token2; TypeParameter Y Add() Sub() Or() And() Our generators are Generic for the simple reason that we want to be able to generate different data Types. Handling generators through an interface provides the usual benefits of handling Types through interfaces (in the general sense) - being able to abstract and separate certain functionality of Types from any specific implementation. An interface that is also defined generically (such as IAuditingGenerator<T>), allows a further level of abstraction, this time on the data. What the declaration "IAuditingGenerator<T>" announces to the world is that it is a definition of a set of methods, some of which contain placeholders for arguments or return values, and that those placeholders are for an (as yet) unknown Type "T". Thus, a Generic interface allows the definition of both the functional implementation and the concrete data Type to be postponed until the functionality needs to be realized in a specific application. To give a feeling of how this works, the methods of IAuditingGenerator<T> are shown in figure 4. IAuditingGenerator<T> "IAuditingGenerator<T>" Figure 4. Type Relationships for AuditingRandomGenerators. This figure was generated with the "Class Diagram" tool within VS2005. Is does a very nice job when one doesn't need to diagram something as complex as the TestCaller in figure 3. This tool is accessed by selecting a VS project in the Project window and then adding a new "Class Diagram" item. Then just drag a C# file onto the design surface that comes up and the tool will create the diagrams. The "AuditingGenerators.cd" file in the download project is the result of dragging the whole "QATester_MultiProcessing_Articles.cs" file onto the design surface and then deleting everything but the AuditingGenerator-related items. We are going to describe the use of Generic Types and Generic interfaces just a little bit in order to prepare for later work. First, the methods of IAuditingGenerator<T>, out of order... Any sensible generator would need a "Next()" method - this gets the next number in the sequence. The numbers could be deterministic (e.g. a square-wave generator), but the two generators in our test code are random. Our generator implementations wrap the standard System.Random class that provides a pseudo-random stream of Int32's. We do internal conversions to get random Type T's out of the generators. No problem if T is Int32. No problem if T is a Single or Double - just use the standard CLR conversion functions. But wait - what if we wanted to generate floating point variables that are uniform on the interval (-10.0, 10.0)? That's the reason that interfaces are useful - we could build a different generator and stick it behind the interface if we wanted. Fortunately, our basic implementation of the generator provides a virtual conversion function that the user can override to provide a custom mapping from Int32's to Type T's. However, the entire generator Type could be replaced if it was desired. So with a Generic interface, customization of both the functional implementation and the data is possible. System.Random The constructors of our default generators accept an Int32 seed, an Int32 minimum value and an Int32 maximum value. The minimum and maximum values are immutable once the generator is instantiated. The "Reset" methods allow the generator to be reset to a certain internal state. The parameterized version allows the generator to be set to an arbitrary state. The unparameterized version always returns the generator to it's state when first constructed. Reset The "SpawnGenerator(int initialState)" method allows a clone of an existing generator to be created. The only thing that changes is the state of the generator. The TestRunners make use of this to create identical generators with different seeds derived from individual Thread characteristics. Note that the output Type of the SpawnGenerator(...) method is another copy of IAuditingGenerator<T>. It's quite useful for interface methods to work with interface Types. Generic interfaces are no different. SpawnGenerator(int initialState) SpawnGenerator(...) "ConvertNumber(Type outputType)" allows the Int32 generated internally to be converted to an arbitrary Type, whose System.Type will be dynamically determined at runtime. It is sometimes useful in our work to be able to generate "auxiliary variables" whose type is not known at language compile time. Since the type of the output number is dynamic, it must be output as a System.Object. The databytes of ValueTypes are output in their boxed form, with the System.Object reference. There is no reason why the variable that is output could not be a C# class. Someone would have to define a conversion function internally. ConvertNumber(Type outputType) System.Type System.Object The final methods defined by the interface are the "GetNumberHistory" and the "GetOperationHistory" methods. These methods are used in advanced scenarios to extract the sequence of random numbers from any generator and also to extract a sequence of results from certain operations. We don't use these in these examples. They are employed extensively in stress testing of our remote service architectures. They will show up again in future articles. GetNumberHistory GetOperationHistory There are two classes that provide implementations of IAuditingGenerator<T>. We do not discuss these in detail in this article, but point the reader to the C# source code, which is thoroughly documented. The first, AuditingInt32RNGenerator, is a concrete implementation of the IAuditingGenerator<T> closed with Int32 as the TypeParameter. The second, AuditingRNGenerator<T>, is an open Generic implementation of the interface. Why two? We included the first because it is easier to understand and because it shows how a concrete implementation of a Generic interface can be optimized for a particular TypeParameter or set of TypeParameters. In this case, we know that the TypeParameter is the same as the underlying Int32 number. Thus, we don't have to do any conversion to T. The class is simpler, in general. When we need the full generality of the open Generic implementation, we can switch it in behind the scenes. This is a design/implementation/refactoring/whatever technique that is used often in our framework with Generic interface implementations. Provide generality first, then customize for efficiency when hotspots and/or most-used cases are identified. Another reason that one would wish to provide a constructed Type at language compile time is to export functionality outside managed code. Unmanaged code cannot consume Generic Types. By providing a specific concrete closure, a Generic Type can be accessed from COM or through Pinvoke facilities. This particular generator needs a bit more work to expose to COM, though - there are a few more things than just the Generic that require modification before a COM wrapper can be built. But that's a whole different article....... AuditingInt32RNGenerator TypeParameter AuditingRNGenerator<T> TypeParameters Note that both of these generators inherit from an abstract class, AuditingRandomGenerator. This class provides common methods for accessing the internal System.Random random number generator from the .Net BCL. There are actually no abstract methods in AuditingRandomGenerator (C# allows this). We wanted to provide an indication that this class doesn't really do anything and it is not sensible to instantiate it. Instantiation could also be prevented by making all constructors protected. However, the abstract attribute of the class shows up nicely in Class Diagrams and also in documentation, so we usually choose that approach when we can. AuditingRandomGenerator System.Random AuditingRandomGenerator There is one additional general matter that should be mentioned in conjunction with our Generic implementation in AuditingGenerator<T>. Recall it was stated that constraints are sometimes placed on Generic TypeParameters. This is so the language compiler knows all the things that can be done with TypeParameter T ahead of time. Sometimes it is not reasonable or desirable to provide full information about TypeParameter T. Consider the simple case of type conversions. Surely, it's possible to convert between a variety of simple .Net Types. We use the standard BCL utilities that support that sort of thing. However, ParameterType T can be absolutely anything - we need it to have this flexibility. We might want to generate an arbitrary class with some random characteristic. In this case there is really no general way to bound the nature of ParameterType T. In other words, there is no way to make such a Generic Type entirely type-safe. This would be possible, if one could limit the universe of TypeParameters that could close a Generic. It would be convenient to be a able to specify, in a constraint, a list of valid concrete Types that T could take on. The current version of .Net does not support this. The next best thing is to provide this list of Types to a constructor for the Generic Type and have the constructor check for a valid Type. This doesn't provide a compile-time (either language or JIT) type check, but it at least allows the use of an unsupported Type to be discovered early, hopefully with an understandable exception message. One way to constrain the Type T would be to define an interface that it must implement - IConvertIntToType<T> or something like that. This seems a bit much for a simple test generator. Last, but not least, proper documentation assists the users of a Generic Type to establish what TypeParameters are valid. AuditingGenerator<T> TypeParameter T TypeParameter T ParameterType T IConvertIntToType<T> The CallerObject, like the the delegate methods described in previous sections, comes in various flavors. Recall that this is the generic System.Object that is passed into a System.Thread process delegate (in our case the CallerProcess) upon startup. We do a lot of work with it in our system, mostly implementing a variety of control procedures, MultiProcess tasking, scheduling, etc.. For our experiments here, we keep things very simple. The most complex CallerObject in QATester_MultiProcessing _Article, IRVTConcurrentOpCallerObject , is diagrammed in figure 5. Every CallerObject contains fields that expose the the OP delegate and the Caller delegate that are to be used in a particular experiment. Additionally, copies of the two random number generators are supplied so that each System.Thread can have an unique source of numbers. The DataGenerator is called from within the CallerProcess and supplies the source parameter in each Caller's argument list. The DelayGenerator's numbers are applied to cause a delay either within an OP delegate or within a CallerProcess. The NumCallsOnThread Property determines the number of times the Caller will be invoked by default from within the CallerProcess. The Target field is either an initial value for the common synchronized target or a reference to it, depending on the variety of the CallerObject. IRVTConcurrentOpCallerObject adds the ControlRegister and StatusRegister fields that are shown in figure 5. The reader will note that IRVTConcurrentOpCallerObject is actually a generic class parameterized by the Type of the target (which is the same as the source). System.Thread IRVTConcurrentOpCallerObject source NumCallsOnThread IRVTConcurrentOpCallerObject ControlRegister Figure 5. Class Diagram of a Typical CallerObject. Although we don't do it here, it's possible to abstract the specifics of a given CallerObject's internal implementation through the use of interfaces. A caller object might be defined for a particular MultiProcess and have specific fields associated with that MultiProcess. It's useful to provide an abstraction layer in the form of interfaces to allow manipulation by a higher-level MultiProcessController (another of our base Type names). We've defined two Properties on IRVTConcurrentOpCaller<UValueType> that indicate this Type of abstraction. It's useful for the MultiProcessController (in our examples, the TestRunner plays this role) to be able to monitor the progress of an iterative task by examining its CurrentIteration property. Similarly, the executing MultiProcess (in our examples, the CallerProcess plays this role) needs to examine the control register to determine when to stop. The stop command is exposed in an abstracted way through the ThreadStopNow Property. In our Framework, these sorts of basic control and status functions are exposed through various interfaces. We use the two abstracted Properties here just to indicate what's possible in a concurrency management design. IRVTConcurrentOpCaller<UValueType> CurrentIteration The architecture shown in figure 3 is not limited to working with primitive Types, such as the Int32 within our retry loop. As alluded to in the introduction, it's possible to work with Monitor and Lock to perform synchronization entirely within the VES. There are two limitations. Monitor can synchronize only objects - not unboxed ValueType's. The second limitation is that a single Monitor can only take out a lock on one object. It's possible to use multiple Monitors, but it's not possible to lock multiple objects atomically in one call. Both of these limitations are overcome in a concurrency architecture we have used for some time. We do need to employ ValueTypes in many circumstances, since we need to pass certain data structures to unmanaged code. We do this by wrapping ValueTypes in a ReferenceType and providing various interfaces to access the members of the ValueType. The problem of needing to lock multiple objects is solved naturally in our design by accessing objects hierarchically. An object provides a "gateway" to objects of lower level in a hierarchy of objects that undergo concurrent access. Additionally, object access can be "ordered" in our design. In many situations, there are dependencies between tasks that are to be performed on objects. Task 4 cannot be performed on object 3 until tasks 1 and 2 have been performed on object 1 and task 3 has been performed on object 2, and so forth. In our architecture, an object often acts as a controller for objects of lower level in a hierarchy of processes. We will not describe the details of this architecture in this article. We will concentrate on the methodology for wrapping a ValueType and providing efficient access to it. We accomplish this with certain Types defined in our MPFramework.AppCore.Manufacturing.SpecializedTypes namespace called ReferencedValueTypes (RVT)s. The files from this namespace that relate to RVT's are included in the download. MPFramework.AppCore.Manufacturing.SpecializedTypes The approach to wrapping ValueType data items is to provide two interfaces that support placing a struct inside a class in a boxed form. A base non-Generic interface provides inheritance support, legacy code support and a method of handling heterogeneous RVT collections. A Generic interface inherits the methods of the non-Generic interface and adds support for manipulating wrapped ValueType data items as Generic Types. The methods of the two classes and their inheritance relationship is diagrammed in figure 6. The main Property of IReferencedValueType is BoxedValue. This is a managed pointer to an object on the managed heap which contains a boxed C# struct. Without the help of Generics, there is not much we can do with the internal ValueType, except identify its Type, compare it with other ValueTypes and swap its databytes with another. A class implementing IReferencedValueType can be specialized to support a given custom struct (think control registers, virtual front panels, etc.), without the use of Generics. This has to be done on a case-by-case basis, however, and is a bit tedious. With Generics, code to manipulate the ValueType into and out of the box can be written once, and provided in a consistent format to clients closing the Generic Type with a specific TypeParameter. Figure 6. IRVT interfaces and Inheritance Relationship. Note: We had to export the Class Diagram in figure 6 into Visio and add the "where UValueType : struct" string. Constraints don't appear on VS - generated Class Diagrams for some reason. (Just so somebody doesn't pull their hair out trying to figure out why it doesn't work!!) IReferencedValueType<UValueType> extends IReferencedValueType and provides access to both boxed and unboxed versions of the wrapped struct. Note the decorating text "where UValueType : struct" applied to the interface name. This is one form of a constraint that can be applied to a TypeParameter (see [Golding05]( pg. 111) or [Troelsen05] (pg. 337)). In this case it simply states that the Type must be a C# struct (a Type deriving from ValueType). This is significant. As mentioned previously, the CLR treats C# structs very differently than C# classes. The struct constraint is what allows us to access the internal representation of a boxed UValueType with a ValueType reference. We won't discuss it here, but the code documentation describes why it's useful to discriminate a System.ValueType reference from an ordinary System.Object reference. where UValueType : struct It is important for our application to be able to switch between a boxed and an unboxed version of a ValueType in an efficient manner. The most important issue for us is to be able to "paint" the inside of box with data from the managed code side without ever having the boxed struct reallocated (and moved). A comprehensive set of sample RVTs written in the C# language is provided in ReferencedValueTypes_Articles.cs. In C#, the options for moving data items into and out of a box are somewhat limited. Unsafe code can be used to define unmanaged pointers into a ValueType's data bytes. interfaces can be defined for a UValueType to read/write its fields within a box. Reflection can be used to access fields on a boxed ValueType, but as is noted in the code samples, that does not gain us much. It will write the inside of a boxed value alright, but we have to box an incoming variable to pass to the reflection-based field setter. If this is in a scan loop in our NDE MultiProcess, we'll get garbage collections again. The problem of the unavoidable copy/box operation associated with ValueType Types in C# is a grave one for us. In our application this is unacceptable. The problem is not only one of overloading the garbage collector (or even running it at all). In our application, we must work out of unmanaged memory segments that our Generic ValueTypes occupy within a HOME on the managed heap. For this reason, our critical RVTs are implemented directly in CIL code through the vehicle of the Microsoft symbolic assembler, ILasm. The VES allows data to be written directly into a ValueType's box, without creating additional allocations on the managed heap and without calling through an interface. If there is an interest in the internal details of implementing RVT's, I'll be happy to do another article on it. We have a full set of profiling results for CIL versus C# implementations. I'm just not sure if this is a topic of general interest. QATester_RunTest_WorkerProcessControl_a() In figure 7a, We can see the main Thread firing up the various Worker Threads. A soon as LongRunningThread (ManagedThreadID#3) is started, it processes rapidly. Note, also, that LongRunningThread does a lot of processing even before the main Thread has a chance to get started. SlowRunningThread (ManagedThreadID#4) doesn't manage to get much work done before it is shut down, due to the fact that it's delays are so long. Once the normal Thread (ManagedThreadID#5) gets started, it moves right along with a few passes of its own. Once the main Thread gets started, however, it completes all of it's iterations before anything else runs again. This is just random chance, however. Results will vary on different machines and between different runs on the very same machine. LongRunningThread SlowRunningThread Figure 7a. First Screen of WorkerProcessControl() Output. In figure 7b, We can see the main Thread shutting down the various Worker Threads. Note that, although the main Thread finishes its work fairly quickly, it can't shut down the Worker Threads until it has verified that each Worker Thread has performed at least 3 iterations. This doesn't happen until the languishing SlowRunningThread has completed its third iteration near the bottom of the console window. Note, also, that there is a bit of latency for SlowRunningThread to respond to the STOP command, stopping only after 4 iterations, not 3. It starts another iteration after it updates its StatusRegister and before it reads the ControlRegister at the end of its processing loop. Note that Worker Thread number three never receives the STOP command, since it finishes its work early, before the Main Thread broadcasts the command to all executing Threads. LongRunningThread, on the other hand, is only a small way through its 1000 iterations, so it will also be running when the STOP command is issued. Figure 7b. Last Screen of WorkerProcessControl Output. WorkerProcessControl The moral of the story here is that Threads (and threads, in general) can be controlled in a variety of ways. The more structured the tasks that threads must perform, the more flexibility can be designed into the method of control. It really is a function of the logic that is implemented within a Thread's delegate (in our examples the CallerProcess) and its control process (in our examples the TestCaller). Our final listing is that of the Caller for an IRVT that is employed in the experiment just run. Again, this caller is designed to be simple - just enough to demonstrate the concept of using Monitor to synchronize a wrapped ValueType. Once more, the Caller uses a delegate for an operation that is designed to perform a binary operation - this time on our Generic interface, IReferencedValueType<UValueType>. The advantage to handling wrapped ValueTypes through the interface is that implementors are free to provide the functionality of an IRVT on any class. This may be accomplished by constructing special facilities on a class containing a UValueType as a member or delegating to a contained class implementing IRVT or through any other means. IReferencedValueType<UValueType> // Delegate for a binary UValueType - valued operation. public delegate UValueType IRVTOp<UVALUETYPE> (IReferencedValueType<UVALUETYPE> target, IReferencedValueType<UVALUETYPE> source) where UValueType : struct; // Caller for a binary IRVTOp. public static System.Boolean IRVTConcurrentOpCaller<UVALUETYPE>( IReferencedValueType<UVALUETYPE> target, IReferencedValueType<UVALUETYPE> source, IRVTOp<UVALUETYPE> oP, out UValueType lastValue) where UValueType : struct { // These variables are working storage for our internal generic // UValueType. UValueType oldValue; UValueType opResult; // This one has the usual purpose - it should never be true in this // method, however.... bool hadCollision = false; // Lock the IRVT's underlying System.Object and perform the OP. lock(target) { // Save the last value. oldValue = target.Value; // Do the OP. opResult = oP(target, source); lastValue = opResult; } // Report progress if we want.... if(QATester_MultiProcessing_Testdata.s_reportToScreen) Console.WriteLine(" >Processed a Number on ManagedThreadID #: " + Thread.CurrentThread.ManagedThreadId.ToString()); // If the two values are different, this means that we had a // collision. Note that you should define a Type-specific "Equals" // on your own UValueType since the CLR does it through reflection // on arbitrary structs (slow), but you don't have to if you have a // specific concrete closure!! Note also, that we will be BOXing // again if we use something expecting a System.Object, so you // probably would want to define an UValueType.Equals(UValueType) // ala an implicit <code lang="cs">interface</CODE> implementation of Equatable<UVALUETYPE> // if you needed an equality comparison. // // This obviously should never be true, since we have the target locked. if(!Equals(oldValue, opResult)) hadCollision = true; return hadCollision; } Listing 2. Caller Method for a Binary Generic IRVT Operation Closed on an Int32. The Caller is designed to perform the same role as the Caller in listing 1, which implements the retry loop. In this case, we are simply carrying the integer around inside of an RVT. We must, of course, employ a concrete RVT class to enclose our working Int32. This does not appear in listing 2, since this Caller manipulates the RVT through its interface. We won't detail it here, but a closure of a class in ReferencedValueTypes_Articles.cs: public class ReferencedValueType<UValueType>: ReferencedValueType, IEquatable<IReferencedValueType>, IReferencedValueType<UValueType>where UValueType :struct is used to wrap the Int32 by specifying it as the TypeParameter UValueType. This class provides only the simplest of functionality to work on the wrapped Type. In the Caller method shown here, a random UValueType is passed in, exactly the same as before. This time, however, it's passed in within it's RVT wrapper, handled through the interface. The only thing we need to know about an RVT is how to get at its internal value - with the IReferencedValueType<UvalueType>.Value Property. We need this in our loop to get an unboxed version of our (in this case) Int32 in order to compare it with the result of the OP. As explained in the code, this check should never be necessary. We leave it in here just to attempt an analogy to the retry loop case. Actually, another Caller, IRVTNonAtomicConcurrentOpCaller(), provides a closer analogy to the retry loop. It is actually a retry loop, but uses a Monitor to lock the RVT only AFTER the OP has been performed, leaving the data unlocked for the read and OP part of the code, just like the CompareExchange loop. This Caller will undergo collisions. Its test is in QATester_RunTest_IRVTNonAtomicConcurrentCaller_a(). public class ReferencedValueType<UValueType>: ReferencedValueType, IEquatable<IReferencedValueType>, IReferencedValueType<UValueType>where UValueType :struct TypeParameter UValueType IReferencedValueType<UvalueType>.Value IRVTNonAtomicConcurrentOpCaller() QATester_RunTest_IRVTNonAtomicConcurrentCaller_a() The ReferencedValueType<UValueType> class has most of its methods defined as virtual for inheritance support. It is a "demonstration" class, however, filled with different examples of how to access wrapped System.ValueTypes, perform comparisons and other things. A inheritor of the class will probably want to remove any functionality that is not needed. ReferencedValueType<UValueType> System.ValueTypes Currently, there seems to be a dearth of good books on concurrency in .Net. There is a very nice E-book by Josoeph Albahari that is free: for download. There are a number of Java - related books that I like that are general in their treatment of threading and concurrency issues. Try [Goetz06] or [Oaks04], for example. Both of these do things from a perspective of 1.5 or later, although Goetz's book is more recent. Goetz has a very good chapter on testing of concurrent systems. For .Net Generics, the general .Net books covering 2.0 are fine. [Golding05] is comprehensive. I've enjoyed writing this article. I'd like to know if readers would like me to continue with this topic or not. I was hoping that the code posted here might give interested readers an elementary starting point for performing concurrency experiments. Our concurrency issues, being somewhat hardware-related, are not entirely mainstream. There are lots of other parts of our framework I could talk about (and release). Interop, Service Managers, Type Handling, Remoting, are parts of the Framework that are fairly clean and would be easy to develop articles on. I am placing this code into the public domain without restriction. Anyone can use it for any purpose, including in commercial products. I may start an open-source project at some point, but I don't have the time at this very instant. If you find anything that is wrong or that could be improved or that is even unclear, please let me know. I would like to improve the code (and its DOCs) to make it more useful. If I use your bug fix or suggestion, I will give you credit - I promise. I'll be releasing more of the Framework as time goes on, in one way or another. I'd like to thank Marc Clifton for being kind enough to review the article. His many helpful suggestions have improved it a great.
http://www.codeproject.com/Articles/17171/Some-Useful-Concurrency-Classes-and-A-Small-Testbe?fid=376078&df=90&mpp=25&sort=Position&spc=Relaxed&noise=3&prof=True&view=None
CC-MAIN-2014-35
refinedweb
13,774
54.93
Hi There I used to develop C programming some 5 years back using Visual Studio. Now I am on my way to develop C++ using Visual Studio .Net 2003. I started of to create new project, there are numbers of different type to choose (Win32 Console Project, Console Application (.Net), Windows Forms Application (.Net)). So, I just tried eash of them. Then I tried out this code: #include <iostream> using namespace std; int main() { cout<<"HEY, you, I'm alive! Oh, and Hello World!\n"; cin.get(); } Somehow, none of those project recognize the code, I get this error. d:\C Language\First In C\Win32\Win32.cpp(13): fatal error C1010: unexpected end of file while looking for precompiled header directive Maybe I shd get clear each of those project. Anyone can provide me some guide would be much appreciated. Thanks.
https://www.daniweb.com/programming/software-development/threads/122756/using-visual-c-net-2003
CC-MAIN-2017-17
refinedweb
142
76.22
How to fix "cannot import name '***'" in python how to fix phone how to fix stuff how to fix everything book how to fix a zipper how to fix broken things how to fix things around the house how to fix everything lyrics I'm using python3.6 and I'm having this error: "ImportError: cannot import name 'video_transforms'". I'm trying to import using: from . import video_transforms as transforms This video_transform.py file is this file: And he is importing this file: Once I had this problem inside my program, I decided to do something simpler, I went into python shell and just did: from . import video_transforms as transforms Got the same error. I read a lot about this error, and I found most of the people got this because of circular problems, but here I can't see that this si the case. I'll be happy for your help, Thanks! Replace this: from . import video_transforms as transforms With this: from .import video_transforms as transforms How to Fix ANYTHING, Timestamps 00:01 Slime cleaning trick 02:29 Coca-cola rust removal 02:55 Wall repair trick 03 Duration: 13:56 Posted: Apr 21, 2020 Here's how: 1. Navigate to the Windows 10 Advanced Startup Options menu. On many laptops, hitting F11 as soon as you power on will 2. Click Startup Repair. You can try sys.path.append('path/to/file') before the import How To Repair Almost Everything, Here's how to fix it. Text by Jen Rose Smith and illustrations by Max Pepper, CNN . Updated 4:07 AM ET, Thu August 20, 2020. Mouth breathing through the night� iFixit is a global community of people helping each other repair things. Let's fix the world, one device at a time. Troubleshoot with experts in the Answers forum—and build your own how-to guides to share with the world. I got this headache many times. The dot . in import (or from) lines says that this file is trying to import something from other files when we treat all the files wrapped inside a so-called package. I just clone Pytorch-MFNet from Github to reproduce your error. The code itself is nothing wrong and runnable. Two ways for you to test the code in ipython or Python Shell (I recommend using ipython since we can use Tab for text completion): Treat all the files in data as the modules of package data. So, you open your python shell outside data directory. # cd ./Pytorch-MFNet ---> Now we are in Pytorch-MFNet directory # import anything you want in data package. # any lines below work properly, take one to test from data import video_transforms from data.video_transforms import * import data.video_transforms as video_transforms # test to_tensor = video_transforms.ToTensor() Treat all the files in data as normal modules So, you can go inside the data directory and import anything from files. However, you must remove . in video_transforms.py as follows: # in video_transforms.py from image_transforms import Compose, \ Transform, \ Normalize, \ Resize, \ RandomScale, \ CenterCrop, \ RandomCrop, \ RandomHorizontalFlip, \ RandomRGB, \ RandomHLS Now go to data directory and enjoy your checking with the following code in python shell # cd ./Pytorch-MFNet/data from video_transforms import * from video_transforms import ToTensor # any above code should work! Hope this helps. Mouth breathing might be ruining your sleep. Here's how to fix it, How to Fix (Just About) Everything: More Than 550 Step-by-Step Instructions for Everything from Fixing a Faucet to Removing Mystery Stains to Curing a� Easy: The . indicates, that you want to load from a package the module is in (see here) Effectively you'll have to import the functions into the package namespace. You want the following file layout: app.py data/ __init__.py video_transforms.py image_transforms.py In your /data/__init__.py you can then do an relative import from . import video_transforms However, this assumes that your program lives in app.py There you can do something like from data import video_transforms How to Fix (Just About) Everything: More Than 550 Step-by-Step , New Fix-It-Yourself Manual: How to Repair, Clean, and Maintain Anything and Everything In and Around Your Home [Reader's Digest] on Amazon.com. *FREE* � How to Fix the Most Annoying Things in Windows 10 Stop Auto Reboots. Windows 10 updates are regular and seemingly never-ending, and pretty much out of the user's control Prevent Sticky Keys. If you hit the Shift key five times in a row in Windows, you activate Sticky Keys, a Windows Calm the New Fix-It-Yourself Manual: How to Repair, Clean, and Maintain , Learn how to fix your broken appliance yourself, no repairman needed. Select the appliance that is giving you trouble and you'll find information on the common � Here are 6 steps to fix it yourself. Don't get frustrated and give up on a slow PC, take a few minutes to troubleshoot and remedy it. Jason Cipriani. May 7, 2020 3:00 a.m. PT. How To Fix A Broken Appliance, This educator's guide provides articles, videos & other resources to aid in teaching about tools, common home repair projects and vocabulary to students. Minor holes and tears in window screening are also common problems. Use screen repair tools like glue, an awl, metal thread and pre-manufactured patches to patch a window screen in three easy steps. This guide will teach you how to replace and repair your window screens. How to Fix It Yourself, Klayman explains, “A key principle of future-focused feedback is to avoid talking about why things went wrong in the past. This runs counter to� To repair the corrupted files manually, view details of the System File Checker process to find the corrupted file, and then manually replace the corrupted file with a known good copy of the file. More Information - Can you elaborate on this? I can't find anything in the docs about that space being significant... - Strange because for me this works. sys.path.append("C:/Users/tibszucs/Desktop/") import video_transforms - I have main.py and those two files in the save directory. so I created an init.py file with the line you said. and than I tried to import using: "import .video_transforms as video_transforms" this gave me a syntax error. And When I import using: "from .import video_transforms as transforms" Still getting the same error... Did I understand your solution correctly? - @albert1905 It must be an init.py file, I edited the answer to make it more clear
https://thetopsites.net/article/55827663.shtml
CC-MAIN-2021-25
refinedweb
1,082
65.73
You have 12 months of data in some raster form... You want some statistical parameter... There are areas of nodata, the extents are all the same... and ... you have a gazillion of these to do. Sounds like you have a 'cube'... the original 'space-time' cube' . You can pull space from a time slice... You can slice time through space. At every location on a 'grid' you have Z as a sequence over time. Here is the code. I will use ascii files, but they don't have to be, you just need to prep your files before you use them. Source data originally from .... here .... thanks Xander Bakker. import os import numpy as np from textwrap import dedent, indent import arcpy arcpy.overwriteOutput = True ft = {'bool': lambda x: repr(x.astype('int32')), 'float': '{: 0.3f}'.format} np.set_printoptions(edgeitems=3, linewidth=80, precision=2, suppress=True, threshold=80, formatter=ft) np.ma.masked_print_option.set_display('-') # change to a single - # ---- Processing temporal ascii files ---- # Header information # ncols 720 # nrows 360 # xllcorner -180 # yllcorner -90 # cellsize 0.5 # NODATA_Value -9999 # ---- Begin the process ---- # cols = 720 rows = 360 ll_corner = arcpy.Point(-180., -90.0) # to position the bottom left corner dx_dy = 0.5 nodata = '-9999' # # ---- create the basic workspace parameters, create masked arrays ---- # out_file = r'c:\Data\ascii_samples\avg_yr.tif' folder = r'C:\Data\ascii_samples' arcpy.env.workspace = folder ascii_files = arcpy.ListFiles("*.asc") a_s = [folder + '\{}'.format(i) for i in ascii_files] arrays = [] for arr in a_s: a = np.mafromtxt(arr, dtype='int', comments='#', delimiter=' ', skip_header=6, missing_values=nodata, usemask=True) arrays.append(a) # # ---- A sample calculation from the inputs.... calculate the mean ---- # N = len(arrays) # number of months... in this case arr_shp = (N,) + arrays[0].shape # we want a (month, col, row) array msk = arrays[0].mask # clone the mask... assume they are the same e = np.zeros(arr_shp, 'int') # one way is create a zeros array and fill for i in range(len(arrays)): e[i] = arrays[i] a = np.ma.array(e, mask=e*msk[np.newaxis, :, :]) # the empty array is ready # # ---- your need here... ie. Calculate a mean ---- # avg = a.mean(axis=0) # calculate the average down through the months # # ---- send it out to be viewed in ArcMap or ArcGIS Pro ---- # value_to_nodata = int(avg.get_fill_value()) out = avg.view(np.ndarray, fill_value=value_to_nodata) g = arcpy.NumPyArrayToRaster(out, ll_corner, dx_dy, dx_dy) g.save(out_file) So the basic process is simple. I have coded this verbosely and used input parameters read manually from the ascii header since it is the quickest way.... and you would probably know what they are from the start. So in this example... 12 months of some variable, averaged accounting for the nodata cells. Do the map stuff, define its projection... project it, give it some symbology and move on. I will leave that for those that make maps. Modify to suit... maybe I will get this into a toolbox someday NOTE..... Now in the linked example, there was a need to simply convert those to rasters from the input format. In that case you would simply consolidate the salient portions of the script as follows and create the output rasters within the masked array creation loop ...... for arr in a_s: a = np.mafromtxt(arr, dtype='int', comments='#', delimiter=' ', skip_header=6, missing_values=nodata, usemask=True) value_to_nodata = int(a.get_fill_value()) out = a.view(np.ndarray, fill_value=value_to_nodata) r = arcpy.NumPyArrayToRaster(out, ll_corner, dx_dy, dx_dy) out_file = arr.replace(".asc", ".tif") r.save(out_file) del r, a ..... So for either doing statistical calculations for temporal data, or for format conversion... there are options available where arcpy and numpy play nice.
https://community.esri.com/blogs/dan_patterson/2017/8
CC-MAIN-2020-34
refinedweb
598
62.85
I while ago -- while discussing this with Stuart Ballard -- I realised that with the proposed C# 3.0 language extensions, in particular "extension methods" it should be possible to make Java collections foreach-able with little effort: namespace java.util { public static class CollectionExtensionMethods { public static IEnumerator GetEnumerator(this java.util.Collection col) { return new CollectionEnumerator(col); } } } For those who don't know how extension methods work, basically the above code (note the this keyword before the argument type) adds a method to java.util.Collection that feels like an instance method. Given the way foreach works, I had expected that it too would recognize this GetEnumerator method and therefore work on all Java collections, but alas that is not the case.If you want to see this changed before C# 3.0 is released, please vote. Alternatively, if you're Miguel and on the ECMA C# committee, it should be obvious what to do A new release candidate based on GNU Classpath 0.91. I did some perf work and a fair bit of restructuring in the way class loaders work, to better support ikvmc and ikvmstub on assemblies loaded in the ReflectionOnly context (on .NET 2.0). The perf work resulted in a significantly improved startup time for Eclipse (IKVM 0.26: 1 minute 23 seconds, IKVM 0.28: 55 seconds). Updated japi results are available here. The comparison is against JDK 1.5 now and ignores the generics metadata. Changes: Files are available here: ikvm-0.28.0.0.zip (sources + binaries), ikvmbin-0.28.0.0.zip (binaries), ikvmbin-generics-0.28.0.0.zip (binaries built from generics branch) Hopefully someday Java will support more than the current simplistic scheme where classes are either public or non-public. In the meantime, I've added support to ikvmc for marking classes (and members) as internal (i.e. private to the assembly they live in). By marking a public class with the @ikvm.lang.Internal annotation ikvmc (and IKVM.Runtime.dll) will only allow access to the class by other code also living in the same assembly. I've also added a switch to ikvmc for making an entire package tree internal (the switch is named -privatepackage:<prefix>). In addition, I've now enabled 1.5 support in the mainline version. Many of the 1.5 APIs that previously were only available on the GNU Classpath generics branch have been ported to the trunk, so it is starting to make more sense to enable 1.5 support in the VM by default. The code is in cvs, although SourceForge has been having some problems, so it might not yet be available thru anoncvs. Development snapshot binaries are available here.. Microsoft released Rotor 2.0. Rotor is the Shared Source implementation of the CLI (and shares a large part of the code with the .NET Framework 2.0). Congratulations and thanks to the Rotor team! I finally got around to releasing the 0.26 bits (identical to rc2). Get them here.. Files are available here: ikvm-0.26.0.1.zip (sources + binaries), ikvmbin-0.26.0.1.zip (binaries), ikvmbin-generics-0.26.0.1.zip (binaries built from generics branch). Files are available here: ikvm-0.26.0.0.zip (sources + binaries), ikvmbin-0.26.0.0.zip (binaries), ikvmbin-generics-0.26.0.0.zip (binaries built from generics branch) Nat commented on the previous entry: I just tried to run ikvm against eclipse 3.1.2. It failed with the following message: !ENTRY initial@reference:file:plugins/org.eclipse.core.runtime_3.1.2.jar/ 0 0 2006-02-02 11:49:09.218 !MESSAGE FrameworkEvent.ERROR !STACK 0 org.eclipse.core.runtime.InvalidRegistryObjectException: Invalid registry object... This turns out to be caused by a SoftReference that is being cleared too eagerly. Since .NET has no soft references and there is no way to determine if the managed heap is running low, I used a hack to always promote objects referenced by a soft reference to generation 2 and from there on treat them as weak references, which effectively means they will be collected the next time a full GC is run and there are no more strong references to the object. Strictly speaking clearing them before running out of memory is not incorrect, because the Java doc for SoftReference says:. OutOfMemoryError However, Eclipse depends on soft references not being cleared (at least during a particular window while it is starting up). I realised that always promoting the object to generation 2 is not correct either (because you may run out of memory before the object gets there). So considering the complexity and possible performance implications of the current hacks, I decided to simply never clear SoftReferences. In conclusion, the .NET Framework needs something like soft reference support and until that happens, it won't be possible to implement SoftReference correctly and efficiently. Update: Nat points out in the comments that there is a workaround: As a workaround, you can start up eclipse with the following command line eclipse -vm c:\tools\ikvm-0.24.0.1\bin\ikvm.exe -vmargs -Declipse.noRegistryFlushing=true I
http://weblog.ikvm.net/default.aspx?date=2006-05-16
CC-MAIN-2017-30
refinedweb
860
59.3
fstab - static information about the filesystems #include <fstab.h> `none'. If the name of the mount point contains spaces these can be escaped as `040'. The third field, (fs_vfstype), describes the type of the filesystem. The system currently supports these types of filesystems (and possibly others - consult /proc/filesystems): ``noauto'' (do not mount when mount(8). The fifth field, (fs_freq), is used for these filesystems by the dump(8)?1?). The documentation in mount(8) is often more up-to-date. getmntent(3), mount(8), swapon(8), fs(5) nfs(5) The fstab file format appeared in 4.0BSD. 1?: the use of dump(8)? is discouraged under Linux, since there is no way for it to get a consistant view of the file system. 15 pages link to fstab(5):
http://wiki.wlug.org.nz/fstab(5)
CC-MAIN-2015-22
refinedweb
131
76.72
On 07/11/2015 04:38 AM, Chris Angelico wrote: > On Sat, Jul 11, 2015 at 6:33 PM, Ben Finney<ben+python at benfinney.id.au> wrote: >>> >>And, for folks who still prefer to prefix all their field references >>> >>with 'self.', the proposal in no way prevents them from doing so. It >>> >>merely allows the rest of us to be a bit less wordy and more pithy in >>> >>our code. >> > >> >Python requires explicit declaration of the namespace for names. That >> >protects me from ambiguities that would otherwise be very common in >> >other people's code. I appreciate that and do not want it threatened. > Not quite true; Python requires explicit declaration of names when > they're bound to, but is quite happy to do a scope search (local, > nonlocal, global, builtin) for references. But the rules are fairly > simple. Aside from the possibility that someone imports your module > and sets module.len to shadow a builtin, everything can be worked out > lexically by looking for the assignments. I think some don't realise the names in a class block are not part of the static scope of the methods defined in that same class block. The methods get the static scope the class is defined in, but that excludes the names in the class block. If a class inherits methods defined in another module, those methods get the static scope where they were defined, and the methods local to the child class get a completely different static scope. But usually it's not a problem, thanks to "self". ;-) Cheers, Ron
https://mail.python.org/pipermail/python-ideas/2015-July/034605.html
CC-MAIN-2022-21
refinedweb
261
71.65
Rpi python DRV8833 motor driver setting up and troubleshooting DC motor driving problem Ask QuestionAsked todayActive todayViewed 21 times1 So what I am trying to do is to get the motor to spin but I want to raspberry pi between the motor so I can spin it clockwise for 5 seconds and then spin it anti-clockwise for 5 seconds. But initially, I just want to make sure it works. Here is my circuit: enter image description here And here is the code I am running, should this code should output some voltage if I have a volt meter on the aout pins? import RPi.GPIO as GPIO # Declare the GPIO settings GPIO.setmode(GPIO.BOARD) # set up GPIO pins GPIO.setup(19, GPIO.OUT) # Connected to AIN2 GPIO.setup(26, GPIO.OUT) # Connected to AIN1 # Drive the motor clockwise GPIO.output(26, GPIO.HIGH) # Set AIN1 GPIO.output(19, GPIO.LOW) # Set AIN2 # Wait 5 seconds time.sleep(5) GPIO.output(12, GPIO.LOW) # Set AIN1 GPIO.output(11, GPIO.LOW) # Set AIN2 raspberry-pi-osdc-motorShareEditFollowCloseFlagedited 56 mins agotlfong013,77733 gold badges88 silver badges2222 bronze badgesasked 8 hours agoPatrick Hession1122 bronze badges New contributor - 1Frankly it is unclear what you actually have or are asking. List components and connections and preferably a circuit. Attempting to power a motor with a 9V battery is unlikely to work. With the wiring is is likely to be faulty use proper connections. None of the pins listed in your code seem to be connected. – Milliways 8 hours ago - 1Why is a 9V battery no good? I will also address your other concerns now. Thanks so much for your answer though 🙂 – Patrick Hession 8 hours ago - 1Those batteries are designed for low power electronic devices. They can’t supply sufficient current to run a motor. If it actually turns it won’t for long. – Milliways 8 hours ago - 1Oh..the DRV8833 component wants power between 2v and 10v though.. – Patrick Hession 8 hours ago - 1I have added some more info to my question now. Hope this helps 🙂 – Patrick Hession 8 hours ago - This EESE Q&A might help: (1) How to troubleshoot a DRV8833 motor driver module problem? – rpi.se 2020nov09, Viewed 698 times: electronics.stackexchange.com/questions/531470/…, (2) DRV8833 Motor Driver Test – Youtube 2020nov18, 174 views youtube.com/watch?v=31-qPfkHcbg. Cheers. – tlfong01 4 hours ago - My above linked answer refers to the TI’s DRV8833 datasheet: (3) DRV8833 Dual H-Bridge Motor Driver Datasheet – TI 2015jul ti.com/lit/ds/symlink/…. This datasheet gives principles of operation, use of the input/output pins, and example application schematic. You might like to let me know which schematic in the datasheet you are using, then I would suggest how to assign logical values to the pins to do the troubleshooting. – tlfong01 4 hours ago - (4) Actually you don’t need to us Rpi to do online testing/troubleshoot. You can put Rpi aside and just use DC level signals to make sure your drv8833 is not fried. (5) You can see in my answer, before I use a Rpi program to do the testing, I use a cheapy 555 astable to as input to drv8833. (5) It is only after the preliminary basic offline testing, then I move on to write a simple python program to move the motor. – tlfong01 4 hours ago - (6) In case you find any thing you don’t understand when reading the drv8833 datasheet, you are welcome to ask me any newbie questions, and I would try to entertain your questions, by perhaps writing up an answer. Happy learning, cheers. – tlfong01 4 hours ago - (7) You seem to have forgotten to short ASEN (A sense) to ground. The coil current needs to go to ground through this sense terminal, with or without any current sensing resistor, otherwise motor won’t move! 🙂 – tlfong01 just now Edit 2 Answers Answer - I would suggest to do the hardware setup in Appendix A for preliminary testing. - For this preliminary testing, no online Rpi and programming is need. We can do offline DC level signals input to DRV8833 and test one of the two outputs. - We don’t even need any motor for testing. - I would suggest the following wiring:4.1 Motor voltage 6V (or 12V)4.2 Status LED with serial current limiting resistor to simulate motor coil.4.2 Testing signals summary: AIN1 - 5V, 0V AIN2 - 5V, 0V BIN1 - N.C. BIN2 - N.C nSleep - 5V, 0V nFault - N.C AOUT1 - serial current protecting resistor, to status LED Anode. AOUT2 - LED Cathode BOUT1 - N.C. BOUT2 - N.C. ASEN - Ground BSEN - Ground - Testing procedure:5.1 Set nSleep to enable drv88335.2 By hand, use jumper wire to connect AIN1 to High (5V)5.3 By hand, use jumper wire to connect AIN2 to Low (0V)5.4 LED should be now switched on by DRV8833, implying that if motor is used instead of (or at the same time as) LED, current will pass motor coil, and motor would move in one directions (CW or CCW).5.5 Now connect AIN1 to Low, and AIN2 to High, LED should be switched off.5.6 Replace LED by motor. Motor should move (a) in one direction if AIN1, AIN2 are connected by jumper wires to High, Low, and (b) in opposite direction if AIN1, AIN2 are connected to Low High.5.7 Use a NE555 timer to generate 0.5Hz square pulse (1 second High, 1 second Low), motor should repeatedly move in one direction for 1 second, and opposite direction for 1 second.5.8 Use a NE555 timer to generate PWM signals, say 1kHz and different duty cycles, to adjust the speed of the motor, (or the brightness of the status LED). For this motor speed adjustment test, AIN1 is set to High or Low, AIN2 is connected to the PWM signal.5.8 Then test the OP’s python program in the question. / to continue, … References (1) DRV8833 Dual H-Bridge Motor Driver Datasheet – TI 2015jul (2) How to use motor drivers with H-bridge and PWM input, to control direction and speed of DC motors? – EESE 2020jul16 (3) How to troubleshoot a DRV8833 motor driver module problem? – EESE, 2020nov09, Viewed 701 times (4) DRV8833 Motor Driver Test Demo Youtube Video – 2020nov18 / to continue, … Appendices Appendix A – Suggested hardware setup for troubleshooting DRV8833 / to continue, … ShareEditDeleteFlagedited 4 mins agoanswered 2 hours agotlfong013,77733 gold badges88 silver badges2222 bronze badgesAdd a comment1 You need to do some more research. I suggest you start with something simpler! Preferably light a few LEDs. You use GPIO.setmode(GPIO.BOARD) BUT then use BCM numbering. You DO NOT have a Gnd connection between the devices – this is ABSOLUTELY essential for all circuits. You DO NOT have proper connections to the device. Sticking pins through the holes is not good enough! If you are lucky it may work, but then a loose connection may fry your Pi. Better I suggest you try gpiozero which is simpler, is well documented and has good examples. I do not know what a DRV8833 is or its connections. Maybe someone does, but YOU should supply this information.ShareEditFollowFlagedited 6 hours agoanswered 6 hours agoMilliways48.7k2424 gold badges8080 silver badges160160 bronze badges - 1Great thanks for the help. Here is a link to the component I am using: adafruit.com/product/3297 – Patrick Hession 6 hours ago - 1@PatrickHession DO NOT put detail in Comments. Edit your Question so others will see this. – Milliways 6 hours ago Categories: Uncategorized
https://tlfong01.blog/2021/05/29/drv8833-motor-driver-notes/
CC-MAIN-2021-25
refinedweb
1,262
73.78
Homework 5 Due by 11:59pm on Tuesday, 9/27 Instructions Download hw05 Question 1:('loki')]), ... loki frigg freya thor sif freya freya >>> laerad == yggdrasil # Make sure original tree is unmodified True """ "*** YOUR CODE HERE ***" Use OK to test your code: python3 ok -q replace_leaf Question 2: Required Questions Question 3: Interval) Question 4: Question 5: Sub Interval 6: Question 7: Question 8:? Write a function that returns a string containing a written explanation of your answer: def multiple_references_explanation(): return """The multiple reference problem...""" Question 9: Extra Questions Extra questions are not worth extra credit and are entirely optional. They are designed to challenge you to think creatively! Question 10: Polynomial' """ "*** YOUR CODE HERE ***" Use OK to test your code: python3 ok -q polynomial
https://inst.eecs.berkeley.edu/~cs61a/fa16/hw/hw05/
CC-MAIN-2021-49
refinedweb
124
50.97
One of the revolutionary features of C++ over traditional languages is its support for exception handling. It provides a very good alternative to traditional techniques of error handling which are often inadequate and error-prone. The clear separation between the normal code and the error handling code makes programs very neat and maintainable. This article discusses what it takes to implement exception handling by the compiler. General understanding of the exception handling mechanism and its syntax is assumed. I implemented exception handling library for VC++ that is accompanied with this article. To replace the exception handler provided by VC++ with my handler, call the following function: install_my_handler(); After this point, any exception that occurs with in the program - from throwing an exception to stack unwinding, calling the catch block and then resuming the execution - is processed by my exception handling library. The C++ standard, like any other feature in C++, doesn't say anything about how exception handling should be implemented. This means that every vendor is free to use any implementation as he sees fit. I will describe how VC++ implements this feature, but it should be a good study material for those as well who use other compilers or Operating Systems [1]. VC++ builds its exception handling support on top of structured exception handling (SEH) provided by Windows operating system [2]. For this discussion, I will consider exceptions to be those that are explicitly thrown or occur due to conditions like divide by zero or null pointer access. When exception occurs, interrupt is generated and control is transferred to the operating system. Operating System, in turn, calls the exception handler that inspects the function call sequence starting from the current function from where the exception originated, and performs its job of stack unwinding and control transfer. We can write our own exception handler and register it with the operating system that it would call in the event of an exception. Windows defines a special structure for registration, called EXCEPTION_REGISTRATION: EXCEPTION_REGISTRATION struct EXCEPTION_REGISTRATION { EXCEPTION_REGISTRATION *prev; DWORD handler; }; To register your own exception handler, create this structure and store its address at offset zero of the segment pointed to by FS register, as the following pseudo assembly language instruction shows: mov FS:[0], exc_regp prev field signifies linked list of EXCEPTION_REGISTRATION structures. When we register EXCEPTION_REGISTRATION structure, we store the address of the previously registered structure in prev field. So how does the exception call back function look like? Windows requires that the signature of exception handler, defined in EXCPT.h, be like: EXCEPTION_DISPOSITION (*handler)( _EXCEPTION_RECORD *ExcRecord, void * EstablisherFrame, _CONTEXT *ContextRecord, void * DispatcherContext); You can ignore all the parameters and return type for now. The following program registers exception handler with the Operating System and generates an exception by attempting to divide by zero. This exception is caught by the exception handler which does not do much. It just prints a message and exits. #include <span class="code-keyword"><iostream></span> #include <span class="code-keyword"><windows.h></span> using std::cout; using std::endl; struct EXCEPTION_REGISTRATION { EXCEPTION_REGISTRATION *prev; DWORD handler; }; EXCEPTION_DISPOSITION myHandler( _EXCEPTION_RECORD *ExcRecord, void * EstablisherFrame, _CONTEXT *ContextRecord, void * DispatcherContext) { cout << "In the exception handler" << endl; cout << "Just a demo. exiting..." << endl; exit(0); return ExceptionContinueExecution; //will not reach here } int g_div = 0; void bar() { //initialize EXCEPTION_REGISTRATION structure EXCEPTION_REGISTRATION reg, *preg = ® reg.handler = (DWORD)myHandler; //get the current head of the exception handling chain DWORD prev; _asm { mov EAX, FS:[0] mov prev, EAX } reg.prev = (EXCEPTION_REGISTRATION*) prev; //register it! _asm { mov EAX, preg mov FS:[0], EAX } //generate the exception int j = 10 / g_div; //Exception. Divide by 0. } int main() { bar(); return 0; } /*-------output------------------- In the exception handler Just a demo. exiting... ---------------------------------*/ Please note that Windows strictly enforces one rule: EXCEPTION_REGISTRATION structure should be on the stack and it should be at a lower memory address than its previous node. Windows will terminate the process if it does not find such to be the case. Stack is a contiguous area of memory which is used for storing local objects of a function. More specifically, each function has an associated stack frame that houses all the local objects of the function as well as any temporaries generated by the expressions with in the function. Please note that this is a typical picture. In reality, the compiler may store all or some of the objects in internal registers for faster access. Stack is a notion that is supported at the processor level. Processor provides internal registers and special instructions to manipulate it. Figure 2 shows how a typical stack may look like when function foo calls function bar and bar calls function widget. Please note that in this case the stack grows downwards. This means that the next item to be pushed on the stack would be at lower memory address than the previous item. The compiler uses EBP register to identify the current active stack frame. In current case, widget is being executed and as the figure shows, EBP register points at widget's stack frame. Function accesses its local objects relative to the frame pointer. The compiler resolves at compile time all the local object names to some fixed offset from frame pointer. For instance, widget would typically access its local variable as some fixed number of bytes below the frame pointer, say EBP-24. The figure also shows the ESP register, stack pointer that points at the last item in the stack, or in current case, ESP points at the end of widget's frame. Next frame would be created after this location. Processor supports two operations for the stack: push and pop. Consider: pop EAX means read 4 bytes from the location where ESP is pointing and increment (remember, stack grows downwards in our case) ESP by 4 (in 32 bit processors). Similarly, push EBP means decrement ESP by 4 and then write the contents of EBP register at the location where ESP is pointing. When compiler compiles a function, it adds some code in the beginning of the function called prologue that creates and initializes the stack frame of the function. Similarly, it adds code at the end of the function called epilogue to pop the stack frame of the exiting function. Compiler typically generates the following sequence for the prologue: Push EBP ; save current frame pointer on stack Mov EBP, ESP ; Activate the new frame Sub ESP, 10 ; Subtract. Set ESP at the end of the frame The first statement saves the current frame pointer EBP on the stack. The second statement activates the frame for the callee by setting EBP register at the location where it stored the EBP of the caller. And the third statement sets the ESP register at the end of the current frame by subtracting ESP's value with the total size of all the local objects and the temporaries that the function will create. Compiler knows at compile time the type and size of all the local objects of a function, so it effectively knows the frame size. The epilogue does the reverse of the prologue, It has to remove the current frame from the stack: Mov ESP, EBP Pop EBP ; activate caller's frame Ret ; return to the caller It sets ESP at the location where its caller's frame pointer is saved (which is at the location where callee's frame pointer points), pops it off in EBP thus activating its caller's stack frame and then executes return. When processor encounters return instruction, it does the following: it pops off the return address from the stack and transfer's control at that address. The return address was put on the stack when its caller executed call instruction to call it. Call instruction first pushes the address of the next instruction where control should be returned and then jumps to the beginning of the callee. Figure 3 shows a more detailed view of the stack at runtime. As the figure shows, function parameters are also part of the stack frame of the function. The caller pushes callee's arguments on the stack. When the function returns, the caller removes the callee's arguments from the stack by adding the size of the arguments to the ESP which is known at compile time: Add ESP, args_size Alternatively, callee can also remove the parameters by specifying the total parameter size in return instruction which again is known at compile time. The instruction below removes 24 bytes from the stack before returning to the caller, assuming total parameter size is 24: Ret 24 Only one of these schemes is used at a time depending upon callee's calling convention. Please note that every thread in a process has its own associated stack. Recall that I had talked about EXCEPTION_REGISTRATION structure in the first section. It is used to register the exception callback with the operating system that it calls when exception occurs. VC++ extends the semantics of this function by adding two more fields at the end: struct EXCEPTION_REGISTRATION { EXCEPTION_REGISTRATION *prev; DWORD handler; int id; DWORD ebp; }; VC++, with few exceptions, creates EXCEPTION_REGISTRATION structure for every function as its local variable [3]. The last field of the structure overlaps the location where frame pointer EBP points. Function's prologue creates this structure on its stack frame and registers it with the operating system. The epilogue restores the EXCEPTION_REGISTRATION of the caller. I will discuss the significance of the id field in the next sections. When VC++ compiles a function, it generates two set of data for the function: a) Exception callback function. b) A data structure that contains important information about the function like the catch blocks, their addresses, the type of exception they are interested in catching etc. I will refer to this structure as funcinfo and talk more about it in the next section. funcinfo Figure 4 shows a broader picture of how things look like at runtime when considering exception handling. Widget's exception callback is at the head of the exception chain pointed to by FS:[0] (which was set by widget's prologue). Exception handler passes widget's funcinfo structure's address to __CxxFrameHandler function, which inspects this data structure to see if there is any catch block in the function interested in catching the current exception. If it does not find any, it returns ExceptionContinueSearch value back to the operating system. Operating system gets the next node off the exception handling list and calls its exception handler (which is the handler for the caller of the current function). __CxxFrameHandler ExceptionContinueSearch This continues until the exception handler finds the catch block interested in catching the exception in which case it does not return back to the operating system. But before it calls the catch block (it knows the address of the catch block from funcinfo structure, see figure 4), it must perform stack unwinding: cleaning up the stack frames of the functions below this function's frame. Cleaning of the stack frame involves nice little intricacy: The exception handler must find all the local objects of the function alive on the frame at the time of the exception and call their destructors. I will discuss more about it in a later section. The exception handler delegates the task of cleaning the frame to the exception handler associated with that frame. It starts from the beginning of the exception handling list pointed to by FS:[0] and calls the exception handler at each node, telling it that the stack is being unwound. In response, the handler calls destructor for all the local objects on the frame and returns. This continues until it arrives at the node that corresponds to itself. Since catch block is part of a function, it uses the stack frame of the function to which it belongs. Hence the exception handler needs to activate its stack frame before calling the catch block. Secondly, every catch block accepts exactly one parameter, its type being the type of exception it is willing to catch. Exception handler should copy the exception object or its reference to catch block's frame. It knows where to copy the exception from funcinfo structure. The compiler is generous enough to generate this information for it. After copying the exception and activating the frame, exception handler calls the catch block. Catch block returns it the address where control should be transferred in the function after try-catch block. Please note that at this moment, even though the stack unwinding has occurred and frames have been cleaned up, they have not been removed and they still physically occupy the space on the stack. This is because the exception handler is still executing and like any other normal function, it also uses the stack for its local objects, its frame present below the last function's frame from where the exception originated. When catch block returns it needs to destroy the exception. It is after this point that the exception handler removes all the frames including its own by setting the ESP at the end of the function's frame (to which it has to transfer the control) and transfers control at the end of try-catch block. How does it know where the end of function's frame is? It has no way of knowing. That's why the compiler saves it (through function's prologue) on function's stack frame for the exception handler to find it. See figure 4. It is sixteen bytes below the stack frame pointer EBP. The catch block may itself throw a new exception or rethrow the same exception. Exception handler has to watch for this situation and take appropriate action. If catch block throws a new exception, the exception handler has to destroy the old exception. If catch block specifies a rethrow, then the exception handler has to propagate the old exception. There is one important point to note here: Since every thread has its own stack, this means that every thread has its own list of EXCEPTION_REGISTRATION structures pointed to by FS:[0]. Figure 5 shows the layout of funcinfo structure. Please note that the names may vary from the actual names used by VC++ compiler and I have only shown the relevant fields. Structure of unwind table is discussed in the next section. When exception handler has to search for a catch block in a function, the first thing it has to determine is whether the point from where the exception originated from within a function has an enclosing try block or not. If it does not find any try block, then it returns back. Otherwise, it searches the list of catch blocks associated with the enclosing try block. First, let's see how it goes about finding the try block. At compile time, the compiler assigns each try block a start id and end id. These id's are also accessible to exception handler through funcinfo structure. See > figure 5. The compiler generates tryblock data structure for each try block with in the function. In the previous section, I had talked about VC++ extending the EXCEPTION_REGISTRATION structure to include id field. Recall, this structure is present on function's stack frame. See figure 4. At the time of exception, the exception handler reads this id from the frame and checks the tryblock structure to see if the id is equal to or falls in between its start id and end id. If it does, then the exception originated from with in this try block. Otherwise, it looks at the next tryblock structure in tryblocktable. Who writes the id value on the stack and what should be written there? The compiler adds statements in the function at various points that update id value to reflect the current runtime state. For instance, the compiler will add a statement in the function at the point where try block is entered that will write the start id of the try block on the stack frame. Once exception handler finds the try block, it can traverse the catchblock table associated with the try block to see if any catch block is interested in catching the exception. Please note that in case of nested try blocks, the exception that originated from inner try block also originated from outer try block. The exception handler should first look for the catch blocks for the inner try block. If none is found, then it looks for the catch blocks of the outer try block. While laying the structures in tryblock table, VC++ puts inner try block structure before the outer try block. How is the exception handler going to determine (from catchblock structure) if a catch block is interested in catching the current exception? It does so by comparing the type of the exception with the type of the catch block's parameter. Consider: void foo() { try { throw E(); } catch(H) { //. } } The catch block catches the exception if H and E are the exact same type. The exception handler has to compare the types at runtime. Normally, languages like C provide no facility to determine object's type at runtime. C++ provides run time type identification mechanism (RTTI) and has a standard way of comparing types at runtime. It defines a class type_info, defined in standard header <typeinfo> that represents a type at runtime. The second field of the catchblock structure (see figure 5) is a pointer to the type_info structure that represents the type of the catch block's parameter at runtime. type_info has operator == that tells whether the two types are of exact same class or not. So, all the exception handler has to do is to compare (call operator ==) the type_info of the catch block's parameter (available through catchblock structure) with the type_info of the exception to determine if the catch block is interested in catching the current exception. type_info <typeinfo> operator == The exception handler knows about the type of the catch block's parameter from funcinfo structure, but how does it know about the type_info of the exception? When compiler encounters a statement like throw E(); It generates excpt_info strcuture for the exception thrown. See figure 6. Please note that the names may vary from the actual names used by VC++ compiler and I have only shown the relevant fields. As shown in the figure, exception's type_info is available through excpt_info structure. At some point of time, exception handler needs to destroy the exception (after the catch block is invoked). It may also need to copy the exception (before invoking the catch block). To help exception handler do these tasks, compiler makes available exception's destructor, copy constructor and size to the exception handler through excpt_info structure. excpt_info If the catch block's parameter type is a base class and the exception is its derived class, the exception handler should still invoke that catch block. However, comparing the typeinfo's of the two in this case would yield false as they are not the same type. Neither does class type_info provide any member function or operator that tells if one class is base class of the other. And yet, the exception handler has to invoke this catch block. To help it do so, the compiler has generated more information for the handler. If the exception is a derived class, then etypeinfo_table (available through excpt_info structure) contains etype_info (extended type_info, my name) pointer for all the classes in the hierarchy. So the exception handler compares the type_info of the catch block's parameter with all the type_info's available through the excpt_info structure. If any match is found then the catch block will be invoked. etypeinfo_table etype_info Before I wrap up this section, one last point: How does the exception handler become aware of the exception and the excpt_info structure? I will attempt to answer this question in the following discussion. VC++ translates throw statement into something like: //throw E(); //compiler generates excpt_info structure for E. E e = E(); //create exception on the stack _CxxThrowException(&e, E_EXCPT_INFO_ADDR); _CxxThrowException passes control to the operating system (through software interrupt, see function RaiseException) passing it both of its parameters. The operating system packages these two parameters in _EXCEPTION_RECORD structure in its preparation to call the exception callback. It starts from the head of the EXCEPTION_REGISTRATION list pointed to by FS:[0] and calls the exception handler at that node. The pointer to this EXCEPTION_REGISTRATION is also the second parameter of the exception handler. Recall that in VC++, every function creates its own EXCEPTION_REGISTRATION on its stack frame and registers it. Passing the second parameter to the exception handler makes important information available to it like EXCEPTION_REGISTRATION's id field (important for finding the catch block). It also makes the exception handler aware of the function's stack frame (useful for cleaning the stack frame) and the position of the EXCEPTION_REGISTRATION node on the exception list (useful for stack unwinding). The first parameter is the pointer to the _EXCEPTION_RECORD structure through which the exception pointer and its excpt_info structure is available. The signature of the exception handler defined in EXCPT.H is: _CxxThrowException RaiseException _EXCEPTION_RECORD EXCEPTION_REGISTRATION _EXCEPTION_RECORD You can ignore the last two parameters. The return type is an enumeration (see EXCPT.H). As I discussed before, if the exception handler cannot find catch block, it returns ExceptionContinueSearch value back to the system. For this discussion, other values are not important. _EXCEPTION_RECORD structure is defined in WINNT.H as: struct _EXCEPTION_RECORD { DWORD ExceptionCode; DWORD ExceptionFlags; _EXCEPTION_RECORD *ExcRecord; PVOID ExceptionAddress; DWORD NumberParameters; DWORD ExceptionInformation[15]; } EXCEPTION_RECORD; The number and kind of entries in the ExceptionInformation array depends upon the ExceptionCode field. If the ExceptionCode represents C++ (Exception code is 0xe06d7363) exception (which will be the case if the exception occurs due to throw), then ExceptionInformation array contains pointer to the exception and the excpt_info structure. For other kind of exceptions, it almost never has any entry. Other kind of exceptions can be divide by zero, access violation etc and their values can be found in WINNT.H. ExceptionInformation ExceptionCode Exception handler looks at the ExceptionFlags field of the _EXCEPTION_RECORD structure to determine what action to take. If the value is EH_UNWINDING (defined in Except.inc), that is an indication to the exception handler that the stack is being unwound and it should clean its stack frame and return. Cleaning up involves finding all the local objects alive on the frame at the time of the exception and calling their destructors. The next section discusses this. Otherwise, exception handler has to search for the catch block in the function and invoke it if it is found. ExceptionFlags EH_UNWINDING C++ standard says that when the stack is being unwound, destructor for all the local objects alive at the time of exception should be called. Consider: int g_i = 0; void foo() { T o1, o2; { T o3; } 10/g_i; //exception occurs here T o4; //... } When exception occurs, local objects o1 and o2 exists on foo's frame while o3 has completed its lifetime. O4 was never created. Exception handler should be aware of this fact and should call destructor for o1 and o2. As I wrote before, the compiler adds code to the function at various special points that register the current runtime state of the function as execution proceeds. It assigns id's to these special regions in the function. For instance, try block entry point is a special region. As discussed before, the compiler will add statement in the function at the point when try block is entered that will write the start id of the try block on function's frame. The other special region in the function is where the local object is created or destroyed. In other words, the compiler assigns each local object a unique id. When compiler encounters object definition like: void foo() { T t1; //. } It adds statement after the definition (after the point when object will be created) to write its id value on the frame: void foo() { T t1; _id = t1_id; //statement added by the compiler //. } The compiler creates a hidden local variable (designated in the above code as _id) that overlaps with the id field of the EXCEPTION_REGISTRATION structure. Similarly, it adds statement before calling the destructor for the object to write the id of the previous region. id When exception handler has to clean up the frame, it reads the id value from the frame (id field of the EXCEPTION_REGISTRATION structure or 4 bytes below the frame pointer, EBP). This id is an indication that the code in the function up to the point to which current id corresponds executed without any exception. All the objects above this point were created. Destructors for all or some of the objects above this point need to be called. Please note that some of these objects may have been destroyed if they are part of a sub block. Destructor for these should not be called. Compiler generates yet another data structure for the function, unwindtable(my name), which is an array of unwind structures. This table is available through funcinfo structure. See figure 5. For every special region in the function, there is one unwind structure. The structure entries appear in the unwindtable in the same order as their corresponding regions appear in the function. unwind structure corresponding to objects is of interest (remember, each object definition denotes special region and has id associated with it). It contains information to destroy the object. When compiler encounters object definition, it generates a short routine that knows about the object's address on the frame (or its offset from the frame pointer) and destroys this object. One of the fields of unwind structure contains the address of this routine: unwindtable typedef void (*CLEANUP_FUNC)(); struct unwind { int prev; CLEANUP_FUNC cf; }; unwind structure for try block has a value of zero for the second field. prev field signifies that the unwintable is also a linked list of unwind structures. When exception handler has to cleanup the frame, it reads the current id from the frame and uses it as an index into the unwind table. It reads the unwind structure at that index and calls the clean up function as specified by the second field of the structure. This destroys the object corressponding to this id. The handler then reads the previous unwind structure from unwind table at an index as specified by prev field. This continues until end of list is reached (prev is -1). Figure 7 shows how a unwind table may look like for the function in the figure. Consider case of the new operator: T* p = new T(); The system first allocates memory for T and then calls the constructor. If constructor throws an exception, then the system must free up the memory allocated for this object. To achieve this, VC++ also assigns id to each new operator for a type that has a non-trivial constructor. There is corresponding entry in the unwind table, the cleanup routine frees the space allocated. Before calling the constructor, it stores id for the allocation in EXCEPTION_REGISTRATION structure. After constructor returns successfully, it restores the id of the previous special region. Furthermore, the object may have been partially constructed when the constructor throws exception. If it has member sub objects or base class sub objects and some of them had been constructed at the time of exception, destructor for those objects must be called. Compiler generates same set of data for a constructor as for any normal function to perform these tasks. Please note that the exception handler calls the user-defined destructors while unwinding the stack. It is possible for the destructor to throw an exception. The C++ standard says that while the stack is unwinding, the destructor may not throw an exception. If it does, the system calls std::terminate. a) Installing the exception handler. b) Catch block rethrowing the exception or throwing a new exception. c) Per thread exception handling support. Please look at the Readme.txt file in the source distribution for build instructions [1]. It also includes a demo project. The first task is to install the exception handling library, or in other words, replace the library provided by VC++. From the above discussion, it is clear that VC++ provides __CxxFrameHandler function that is the entry point for the all the exceptions. For each function, the compiler generates exception handling routine that is called if the exception occurs with in this function. This routine passes funcinfo pointer to the __CxxFrameHandler function. install_my_handler() function inserts code at the beginning of __CxxFrameHandler that jumps to my_exc_handler(). But __CxxFrameHandler resides in readonly code page. Any attempt to write to it would cause access violation. So the first step is to change the access of the page to read-write using VirtualProtectEx function provided by Windows API. After writing to the memory, we restore the old protection of the page. The function writes the contents of jmp_instr structure at the beginning of __CxxFrameHandler. install_my_handler() my_exc_handler() VirtualProtectEx //install_my_handler.cpp #include <span class="code-keyword"><windows.h></span> #include <span class="code-string">"install_my_handler.h"</span> //C++'s default exception handler extern "C" EXCEPTION_DISPOSITION __CxxFrameHandler( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ); namespace { char cpp_handler_instructions[5]; bool saved_handler_instructions = false; } namespace my_handler { //Exception handler that replaces C++'s default handler. EXCEPTION_DISPOSITION my_exc_handler( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) throw(); #pragma pack(1) struct jmp_instr { unsigned char jmp; DWORD offset; }; #pragma pack() bool WriteMemory(void * loc, void * buffer, int size) { HANDLE hProcess = GetCurrentProcess(); //change the protection of pages containing range of memory //[loc, loc+size] to READ WRITE DWORD old_protection; BOOL ret; ret = VirtualProtectEx(hProcess, loc, size, PAGE_READWRITE, &old_protection); if(ret == FALSE) return false; ret = WriteProcessMemory(hProcess, loc, buffer, size, NULL); //restore old protection DWORD o2; VirtualProtectEx(hProcess, loc, size, old_protection, &o2); return (ret == TRUE); } bool ReadMemory(void *loc, void *buffer, DWORD size) { HANDLE hProcess = GetCurrentProcess(); DWORD bytes_read = 0; BOOL ret; ret = ReadProcessMemory(hProcess, loc, buffer, size, &bytes_read); return (ret == TRUE && bytes_read == size); } bool install_my_handler() { void * my_hdlr = my_exc_handler; void * cpp_hdlr = __CxxFrameHandler; jmp_instr jmp_my_hdlr; jmp_my_hdlr.jmp = 0xE9; //We actually calculate the offset from __CxxFrameHandler+5 //as the jmp instruction is 5 byte length. jmp_my_hdlr.offset = reinterpret_cast<char*>(my_hdlr) - (reinterpret_cast<char*>(cpp_hdlr) + 5); if(!saved_handler_instructions) { if(!ReadMemory(cpp_hdlr, cpp_handler_instructions, sizeof(cpp_handler_instructions))) return false; saved_handler_instructions = true; } return WriteMemory(cpp_hdlr, &jmp_my_hdlr, sizeof(jmp_my_hdlr)); } bool restore_cpp_handler() { if(!saved_handler_instructions) return false; else { void *loc = __CxxFrameHandler; return WriteMemory(loc, cpp_handler_instructions, sizeof(cpp_handler_instructions)); } } } The #pragma pack(1) directive at the definition of jmp_instr structure tells the compiler to layout the members of the structure without any padding between them. Without this directive, size of this structure is eight bytes. It is five bytes when we define this directive. #pragma pack(1) jmp_instr Going back to exception handling, when the exception handler calls the catch block, the catch block may rethrow the exception or throw a completely new exception. If catch block throws a new exception, then the exception handler has to destroy the previous exception before moving ahead. If the catch block decides to rethrow, the exception handler has to propagate the current exception. At this moment, the exception handler has to tackle with two questions: how does the exception handler know that the exception originated from with in a catch block and how does it keep track of the old exception? The way I solved this problem is that before the handler calls the catch block, it stores the current exception in exception_storage object and registers a special purpose exception handler, catch_block_protector. The exception_storage object is available by calling get_exception_storage() function: exception_storage get_exception_storage() exception_storage* p = get_exception_storage(); p->set(pexc, pexc_info); register catch_block_protector call catch block //.... If exception is (re)thrown from within a catch block, the control goes to catch_block_protector. Now this function can extract the previous exception from exception_storage object and destroy it if catch block threw new exception. If the catch block did a rethrow (which it can find out by inspecting first two entries of ExceptionInformation array, both are zero. See code below), then the handler needs to propagate the current exception by copying it in ExceptionInformation array. The following snippet shows catch_block_protector() function. catch_block_protector() //------------------------------------------------------------------- // If this handler is calles, exception was (re)thrown from catch // block. The exception handler (my_handler) registers this // handler before calling the catch block. Its job is to determine // if the catch block threw new exception or did a rethrow. If // catch block threw a new exception, then it should destroy the // previous exception object that was passed to the catch block. If // the catch block did a rethrow, then this handler should retrieve // the original exception and save in ExceptionRecord for the // exception handlers to use it. //------------------------------------------------------------------- EXCEPTION_DISPOSITION catch_block_protector( _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) throw() { EXCEPTION_REGISTRATION *pFrame; pFrame = reinterpret_cast<EXCEPTION_REGISTRATION*> (EstablisherFrame);if(!(ExceptionRecord->ExceptionFlags & ( _EXCEPTION_UNWINDING | _EXCEPTION_EXIT_UNWIND))) { void *pcur_exc = 0, *pprev_exc = 0; const excpt_info *pexc_info = 0, *pprev_excinfo = 0; exception_storage *p = get_exception_storage(); pprev_exc= p->get_exception(); pprev_excinfo= p->get_exception_info();p->set(0, 0); bool cpp_exc = ExceptionRecord->ExceptionCode == MS_CPP_EXC; get_exception(ExceptionRecord, &pcur_exc); get_excpt_info(ExceptionRecord, &pexc_info); if(cpp_exc && 0 == pcur_exc && 0 == pexc_info) //rethrow {ExceptionRecord->ExceptionInformation[1] = reinterpret_cast<DWORD> (pprev_exc);ExceptionRecord->ExceptionInformation[2] = reinterpret_cast<DWORD>(pprev_excinfo); } else { exception_helper::destroy(pprev_exc, pprev_excinfo); } } return ExceptionContinueSearch; } Consider one possible implementation of get_exception_storage() function: exception_storage* get_exception_storage() { static exception_storage es; return &es; } This would be a perfect implementation except in a multithreaded world. Consider more than one thread getting hold of this object and trying to store exception object in it. This will be disasterous. Every thread has its own stack and own exception handling chain. What we need is a thread specific exception_storage object. Every thread has its own object which is created when the thread begins its life and destroyed when the threads ends. Windows provides thread local storage for this purpose. Thread local storage enables each object to have its own private copy of an object accesible through a global key. It provides TLSGetValue() and TLSSetValue() functions for this purpose. TLSGetValue() TLSSetValue() Excptstorage.cpp file defines get_exception_storage() function. This file is built as a DLL. This is due to the fact that it enables us to know whenever a thread is created or destroyed. Every time a thread is created or destroyed, Windows calls every DLL's (that is loaded in this process's address space) DllMain() function. This function is called in the thread that is created. This gives us a chance to initialize thread specific data, exception_storage object in our case. DllMain() //excptstorage.cpp #include <span class="code-string">"excptstorage.h"</span> #include <span class="code-keyword"><windows.h></span> namespace { DWORD dwstorage; } namespace my_handler { _(); TlsSetValue(dwstorage, p); break; case DLL_THREAD_DETACH: p = my_handler::get_exception_storage(); delete p; break; case DLL_PROCESS_DETACH: p = my_handler::get_exception_storage(); delete p; break; } return TRUE; } As discussed above, the C++ compiler and the runtime exception library, with support from the Operating System, cooperate to perform exception.
https://www.codeproject.com/Articles/2126/How-a-C-compiler-implements-exception-handling?fid=3666&df=90&mpp=25&sort=Position&spc=Relaxed&tid=3481693
CC-MAIN-2017-22
refinedweb
5,804
52.8
Integrating WCAG structures in a ZK page Matthieu Duchemin, Engineer, Potix Corporation Aug. 17, 2021 ZK 9.6.0 Introduction The Web Content Accessibility Guidelines (WCAG) are a set of specifications for web content creation. Content that follows these rules can be easily browsed by users utilizing accessibility technologies, such as screen readers. A large part of accessible design relies on marking elements of the page with attributes to inform the content reader of the nature of each object, as well as their relationship with other elements of the page. In this small talk, we will discuss how to utilize these guidelines in ZK to design accessible web content quickly and easily. Basics of WCAG attributes and page structure The main goal of assistive technologies is to provide information in addition to the visual page in a web browser. This additional information can be processed by a screen reader, highlighted, or used to provide a page outline for easier navigation. In this example, we will use the case of a screen reader, but the same principle applies regardless of the accessibility tools employed by the end-user. We will focus on a specific aspect of accessible design: headings and landmarks. Headings are specific elements that can be interpreted by a screen reader to organize the page content. This can be seen like an automatically generated table of content. By introducing elements that have a natural heading level (h1, h2, etc.), or by marking elements with the role="heading" and aria-level attributes, we can organize the page content in a way that can be traversed by the screen reader. Here's a screenshot of how a screen reader software will parse the headings of the page (screenshot). If the user open the headings panel, they will be able to browse the headings, organized by level. In a similar manner, landmarks create a list of zones by “function”. In both cases, the screen reader will be able to pick up on these hints, and to provide convenient tools for the end-user. With these tools, the end-user will be able to navigate through the page to locations of interest, and to quickly move through the different sections of the page. Here's a screenshot of how a screen reader software will parse the landmarks of the page (screenshot). If the user open the landmarks panel, they will be able to browse the landmarks, organized by functionality. WCAG in ZK Framework ZK has built-in accessibility support for out-of-the-box components, with the ZA11Y package. This dependency adds automatic aria attributes generated from the component values and automates a lot of accessibility design building. Complex ZK components, such as Grids or Dateboxes, will automatically add accessibility labels based on the component state when using the ZA11Y dependency. For example Grids will add information regarding the paging and row navigation. Datebox will add information such as labels for the selected day of the month. Since this is part of standard operation, the default values will more often than not be appropriate for the use case. This said, designing for a specific goal often requires deliberate choices, and the ability to go further than the default use cases. This is the case for headings and landmarks. We want to add additional information on top of the default generated labels and attribute. We also want to be fully in control of where this information is added, in order to better guide the user through our UI. See example of the searchbox component (screenshot). The component automatically generates relevant attributes based on its state and on user actions. For further reading on accessibility design in ZK, please refer to the dedicated documentation page. Basic UI composing with xhtml elements The most basic manual WCAG implementation in a zul page is done by simply adding aria-attributes to DOM elements of the resulting page. This can be done either by using native HTML elements, or XHTML elements in zul. While the default namespace for a zul file is zul (the namespace containing classic out-of-the-box ZK components), it is also possible to generate elements from different namespaces. In this case, we add a native <h3> node to our page. Native elements will result in a one-to-one html node in the resulting page. As such, any attribute added to this node will be applied to the result node in the page. Adding native node also allows us to benefit from default browser behaviors. Since the <h3> (heading 3 element) is already a heading by browser definition, it will appear in the header list without further action on our part. 1 <zk xmlns: 2 ... 3 <n:h3Best seller</n:h3> Since these elements are transcribed one-to-one in the resulting page’s DOM tree, attributes can be added direction onto the relevant elements. Supplementing ZA11Y in ZK components This is good for simple elements such as divs and headings, but we can do better. ZK components from the zul namespace are much more useful than basic DOM elements, so it’s important to have the ability to also mark them with the relevant WCAG information to make our page more readable for screen readers. For that purpose, we will use the client/attribute namespace. The client/attribute namespace allows us to add arbitrary attributes on ZK components. The structure is simple: Declaring the namespace prefix, then, use the prefix to declare an attribute on a ZK component. 1 <zk xmlns: 2 ... 3 <label ca:Chef's choice</label> In this case, the attribute name and the attribute value can be any string of characters. The DOM node generated in the page will include it as name=”attribute”, which makes it a great option to quickly add WCAG attributes on existing ZK components. Reusable designs: easy templating in ZK Now, to make things reusable. Instead of manually building each individual component with custom WCAG attributes, we can improve on this concept by defining templates and reusing them. A template is simply a fragment of zul code, which can use variables. It can be applied multiple times, with different values. By building in WCAG attributes when creating the template, we can generate WCAG compliant code without having to add attributes to individual node. 1 <vlayout sclass="pizzaCard"> 2 <apply template="pizzaCard" 3 7 </vlayout> 8 <template name="pizzaCard"> 9 <apply template="title" content="${title}"/> 10 <apply template="subtitle" content="${subtitle}"/> 11 <apply template="paragraph" highlight="${highlight}" content="${description}" /> 12 </template> 13 <template name="title"> 14 <label sclass="title" ca:${content}</label> 15 </template> Conclusion You can see a live version of the demo project here. In addition to ZA11Y out-of-the-box accessibility improvements, we can add simple accessibility information to existing pages by leveraging the ability to add client-attributes to components. This allows us to significantly improve the navigation experience of people browsing the page with the help of a screen reader, or other WCAG based assistive tools.
https://www.zkoss.org/wiki/Small_Talks/2021/August/Integrating_WCAG_structures_in_a_ZK_page
CC-MAIN-2021-49
refinedweb
1,168
52.6
Particle physics is full of machine learning. It powered the discovery of the Higgs boson and it is used to decide which data an experiment should record. As well as in many other analyses. There is only one drawback: most of it is based on one library: TMVA. It was written many years ago, which means lots of new techniques and innovations are not available. I actually struggled to pick a good webpage to link to, as the original homepage has not been updated since 2013. This notebook is an introduction to scikit-learn targeted at TMVA users. Read my earlier post explaining how to configure a BDT in sklearn with the defaults from TMVA. By providing a dictionary translating from one package's lingo to the other I hope more people will give scikit-learn a try. This is not meant as an introduction to the various concepts, more of a reference for translating TMVA jargon/procedures to scikit-learn procedures. Read the second post in this series: Advanced scikit-learn for TMVA Users It covers: - How to load ROOT trees - Plotting - comparing the distribution of variables in signal and background categories - scatter plots of two features - boxplots - correlation matrices between features - Training - the training-testing split - training a classifier - ROC curves and performance evaluation - plotting the classifier output for training and testing - How to write the classifier output to a TTree Thanks a lot to Gilles Louppe for proof reading and suggestions. As usual, first some imports: %matplotlib inline import random import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import classification_report, roc_auc_score Data comes first, the excellent root_numpy library makes it easy to read your data stored in a ROOT TTree. Each call to root2array will create a 2D array which contains one row per event, and one column representing each branch you want to use. You can download the dataset used here from figshare: The events are derived from the much larger HIGGS dataset. A description of the variables can be found there as well. from root_numpy import root2array, rec2array branch_names = """"".split(",") branch_names = [c.strip() for c in branch_names] branch_names = (b.replace(" ", "_") for b in branch_names) branch_names = list(b.replace("-", "_") for b in branch_names) signal = root2array("/tmp/HIGGS-signal.root", "tree", branch_names) signal = rec2array(signal) backgr = root2array("/tmp/HIGGS-background.root", "tree", branch_names) backgr = rec2array(backgr) # for sklearn data is usually organised # into one 2D array of shape (n_samples x n_features) # containing all the data and one array of categories # of length n_samples X = np.concatenate((signal, backgr)) y = np.concatenate((np.ones(signal.shape[0]), np.zeros(backgr.shape[0]))) Plotting Variables and Correlations¶ The pandas library provides high-performance, easy-to-use data structures and data analysis tools written in python. We will use it for its plotting capabilities and other nice ways to explore your data. Pro tip: if you want very pretty plots and more powerful plotting check out the seaborn library. It is extremely useful. A DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or a ROOT TTree. import pandas.core.common as com from pandas.core.index import Index from pandas.tools import plotting from pandas.tools.plotting import scatter_matrix # Create a pandas DataFrame for our data # this provides many convenience functions # for exploring your dataset # need to reshape y so it is a 2D array with one column df = pd.DataFrame(np.hstack((X, y.reshape(y.shape[0], -1))), columns=branch_names+['y']) def signal_background(data1, data2, column=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, **kwds): """Draw histogram of the DataFrame's series comparing the distribution in `data1` to `data2`. data1: DataFrame data2: DataFrame column: string or sequence If passed, will be used to limit data to a subset of columns grid : boolean, default True Whether to show axis grid lines xlabelsize : int, default None If specified changes the x-axis label size xrot : float, default None rotation of x axis labels ylabelsize : int, default None If specified changes the y-axis label size yrot : float, default None rotation of y axis labels ax : matplotlib axes object, default None sharex : bool, if True, the X axis will be shared amongst all subplots. sharey : bool, if True, the Y axis will be shared amongst all subplots. figsize : tuple The size of the figure to create in inches by default layout: (optional) a tuple (rows, columns) for the layout of the histograms bins: integer, default 10 Number of histogram bins to be used kwds : other plotting keyword arguments To be passed to hist function """ if 'alpha' not in kwds: kwds['alpha'] = 0.5 if column is not None: if not isinstance(column, (list, np.ndarray, Index)): column = [column] data1 = data1[column] data2 = data2[column] data1 = data1._get_numeric_data() data2 = data2._get_numeric_data() naxes = len(data1.columns) fig, axes = plotting._subplots(naxes=naxes, ax=ax, squeeze=False, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) _axes = plotting._flatten(axes) for i, col in enumerate(com._try_sort(data1.columns)): ax = _axes[i] low = min(data1[col].min(), data2[col].min()) high = max(data1[col].max(), data2[col].max()) ax.hist(data1[col].dropna().values, bins=bins, range=(low,high), **kwds) ax.hist(data2[col].dropna().values, bins=bins, range=(low,high), **kwds) ax.set_title(col) ax.grid(grid) plotting._set_ticks_props(axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot) fig.subplots_adjust(wspace=0.3, hspace=0.7) return axes # Plot signal and background distributions for some # variables # The first two arguments select what is "signal" # and what is "background". This means you can # use it for more general comparisons of two # subsets as well. signal_background(df[df.y<0.5], df[df.y>0.5], column=["lepton_pT", "lepton_eta", "lepton_phi", "missing_energy_magnitude", "jet_3_pt"], bins=20) array([[<matplotlib.axes._subplots.AxesSubplot object at 0x115fdf450>, <matplotlib.axes._subplots.AxesSubplot object at 0x115933c50>], [<matplotlib.axes._subplots.AxesSubplot object at 0x116122490>, <matplotlib.axes._subplots.AxesSubplot object at 0x1161aea10>], [<matplotlib.axes._subplots.AxesSubplot object at 0x116490810>, <matplotlib.axes._subplots.AxesSubplot object at 0x116209810>]], dtype=object) Scatter Plots¶ Can we see anything by plotting one of the features against another? If you want to make a scatter plot of two features use df.plot(kind='scatter'). Here we pick 1000 data points at random, with 1million points the plot would be far too dense to see anything. df.ix[random.sample(df.index, 1000)].plot(kind='scatter', x='lepton_pT', y='jet_3_pt', c='y', cmap='autumn') <matplotlib.axes._subplots.AxesSubplot at 0x1129540d0> In the plot above compares the distribution of the feature lepton_pT vs jet_3_pt. The colour of each point shows which class it belongs to: 0 for background and +1 for signal. Not the most useful plot in this case, but it is here for reference. Boxplots¶ A Box plot is a nice way of visualising a distribution by showing it's quantiles. Below we make box plots for the features lepton_pT, lepton_eta, missing_energy_magnitude and jet_3_pt using df.boxplot(). Each plot shows the distribution of one feature for signal and background. You can also group the distributions by the number of jets in an event, or the value of any other feature in your dataset. df.boxplot(by='y', column=["lepton_pT", "lepton_eta", "missing_energy_magnitude", "jet_3_pt"], return_type='axes') OrderedDict([('lepton_pT', <matplotlib.axes._subplots.AxesSubplot object at 0x10ca08410>), ('lepton_eta', <matplotlib.axes._subplots.AxesSubplot object at 0x153711cd0>), ('missing_energy_magnitude', <matplotlib.axes._subplots.AxesSubplot object at 0x153796550>), ('jet_3_pt', <matplotlib.axes._subplots.AxesSubplot object at 0x1537f9d10>)]) bg = df.y < 0.5 sig = df.y > 0.5 def correlations(data, **kwds): """Calculate pairwise correlation between features. Extra arguments are passed on to DataFrame.corr() """ # simply call df.corr() to get a table of # correlation values if you do not need # the fancy plotting corrmat = data.corr(**kwds) fig, ax1 = plt.subplots(ncols=1, figsize=(6,5)) opts = {'cmap': plt.get_cmap("RdBu"), 'vmin': -1, 'vmax': +1} heatmap1 = ax1.pcolor(corrmat, **opts) plt.colorbar(heatmap1, ax=ax1) ax1.set_title("Correlations") labels = corrmat.columns.values for ax in (ax1,): # shift location of ticks to center of the bins ax.set_xticks(np.arange(len(labels))+0.5, minor=False) ax.set_yticks(np.arange(len(labels))+0.5, minor=False) ax.set_xticklabels(labels, minor=False, ha='right', rotation=70) ax.set_yticklabels(labels, minor=False) plt.tight_layout() # remove the y column from the correlation matrix # after using it to select background and signal correlations(df[bg].drop('y', 1)) correlations(df[sig].drop('y', 1)) The Training and Testing Split¶ One of the first things to do is split your data into a training and testing set. This will split your data into train-test sets: 67%-33%. It will also shuffle entries so you will not get the first 67% of X for training and the last 33% for testing. This is particularly important in cases where you load all signal events first and then the background events. Here we split our data into two independent samples twice. The first split is to create a development and a evaluation set. All development and performance evaluation will be done with the development set. Once the hyper-parameters and other settings are frozen we can use the evaluation set to get an unbiased estimate of the performance. The development set is further split into a training and testing set. The first will be used for training the classifier and the second to evaluate its performance. from sklearn.cross_validation import train_test_split X_dev,X_eval, y_dev,y_eval = train_test_split(X, y, test_size=0.33, random_state=42) X_train,X_test, y_train,y_test = train_test_split(X_dev, y_dev, test_size=0.33, random_state=492) Training Decision Trees¶ Training a AdaBoost Decision Tree in sklearn is straight forward. Import the type of decision tree you want and off you go. Here we set several hyper-parameters to non default values in order to make the classifier as similar to the default BDT in TMVA as possible. See my Matching Machine Learning post for more details on finding these settings. After instantiating our AdaBoostClassifier, call the fit() method with the training sample as an argument. This will train the tree, now we are ready to evaluate the performance on the held out testing set. Pro tip: In TMVA many different ensemble methods that use decision trees as their base estimator are mixed together under the name BDT. Remember this when you discuss things with your local machine learning guru as they will want to know what you are doing in much more detail. from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import classification_report, roc_auc_score dt = DecisionTreeClassifier(max_depth=3, min_samples_leaf=0.05*len(X_train)) bdt = AdaBoostClassifier(dt, algorithm='SAMME', n_estimators=800, learning_rate=0.5) bdt.fit(X_train, y_train) AdaBoostClassifier(algorithm='SAMME', base_estimator=DecisionTreeClassifier(compute_importances=None, criterion='gini', max_depth=3, max_features=None, max_leaf_nodes=None, min_density=None, min_samples_leaf=22445.0, min_samples_split=2, random_state=None, splitter='best'), learning_rate=0.5, n_estimators=800, random_state=None) The fit() method returns the trained classifier. When printed out all the hyper-parameters are listed. Assessing a Classifier's Performance¶ Next let's create a quick report on how well our classifier is doing. It is important to make sure you use samples not seen by the classifier to get an unbiased estimate of its performance. y_predicted = bdt.predict(X_test) print classification_report(y_test, y_predicted, target_names=["background", "signal"]) print "Area under ROC curve: %.4f"%(roc_auc_score(y_test, bdt.decision_function(X_test))) precision recall f1-score support background 0.72 0.71 0.71 104165 signal 0.74 0.75 0.75 116935 avg / total 0.73 0.73 0.73 221100 Area under ROC curve: 0.8082 To illustrate that point, here the same performance metrics evaluated on the training set instead. You can see the estimates of the performance are more optimistic than on an unseen set of events. y_predicted = bdt.predict(X_train) print classification_report(y_train, y_predicted, target_names=["background", "signal"]) print "Area under ROC curve: %.4f"%(roc_auc_score(y_train, bdt.decision_function(X_train))) precision recall f1-score support background 0.72 0.71 0.72 210793 signal 0.75 0.76 0.75 238107 avg / total 0.74 0.74 0.74 448900 Area under ROC curve: 0.8161 Another useful plot to judge the performance of a classifier is to look at the ROC curve directly. from sklearn.metrics import roc_curve, auc decisions = bdt.decision_function(X_test) # Compute ROC curve and area under the curve fpr, tpr, thresholds = roc_curve(y_test, decisions) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC (area = %0.2f)'%(roc_auc)) plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.grid() plt.show() Overtraining Check¶ Comparing the BDT's output distribution for the training and testing set is a popular way in HEP to check for overtraining. The compare_test_train() method will plot the BDT's decision function for each class, as well as overlaying it with the shape of the decision function in the training set. def compare_train_test(clf, X_train, y_train, X_test, y_test, bins=30): decisions = [] for X,y in ((X_train, y_train), (X_test, y_test)): d1 = clf.decision_function(X[y>0.5]).ravel() d2 = clf.decision_function(X[y<0.5]).ravel() decisions += [d1, d2] low = min(np.min(d) for d in decisions) high = max(np.max(d) for d in decisions) low_high = (low,high) plt.hist(decisions[0], color='r', alpha=0.5, range=low_high, bins=bins, histtype='stepfilled', normed=True, label='S (train)') plt.hist(decisions[1], color='b', alpha=0.5, range=low_high, bins=bins, histtype='stepfilled', normed=True, label='B (train)') hist, bins = np.histogram(decisions[2], bins=bins, range=low_high, normed=True) scale = len(decisions[2]) / sum(hist) err = np.sqrt(hist * scale) / scale width = (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.errorbar(center, hist, yerr=err, fmt='o', c='r', label='S (test)') hist, bins = np.histogram(decisions[3], bins=bins, range=low_high, normed=True) scale = len(decisions[2]) / sum(hist) err = np.sqrt(hist * scale) / scale plt.errorbar(center, hist, yerr=err, fmt='o', c='b', label='B (test)') plt.xlabel("BDT output") plt.ylabel("Arbitrary units") plt.legend(loc='best') compare_train_test(bdt, X_train, y_train, X_test, y_test) Writing the Classifier Output to a TTree¶ The final step is writing the classifier's output for each event into a TTree for further processing later on. The numpy_root library can read and write TTrees. We could write out each branch used as a feature as well as the classifier output or simply write out the classifier and then "friend" the resulting TTree with the original one. Doing the latter is a little less typing here so we do that. If you want to recreate the whole tree with each feature, you have to setup the data types and branch names correctly, but otherwise it is the same. from root_numpy import array2root y_predicted = bdt.decision_function(X) y_predicted.dtype = [('y', np.float64)] array2root(y_predicted, "/tmp/test-prediction.root", "BDToutput") The End¶ Thank you for reading. You can refer to this post for recipes how to do the most common things from TMVA with scikit-learn. There will be a second post with more advanced techniques which are not available in TMVA, but very common in the machine learning world. The second post is now public: Advanced scikit-learn for TMVA Users. If you find a mistake or want to tell me something else catch me on twitter. This post started life as a ipython notebook, download it or view it online.
https://betatim.github.io/posts/sklearn-for-TMVA-users/
CC-MAIN-2017-51
refinedweb
2,641
50.94
Asynchronous Programming For Windows Phone 8 Windows Phone 8 brings a lot of new features to developers and behind the scenes there are also some major improvements. The .NET framework 4.5 and the new C# compiler come with several major new features. Networked applications had to rely - in the past - on callbacks, but with the new asynchronous programming capabilities on the windows phone platform, the compiler can make some magic happen and increase productivity. Best Practices in Asynchronous Programming (MSDN Magazine > March 2013 Issue) Windows Phone 8 What is asynchronous Programming? In a console application, with the full .Net framework, to download data from an URL with a WebClient you can do In graphical applications - unlike console applications where the whole execution flow can be driven from a single thread, including all I/O – , the execution flow often ends up being event driven. That means you start your logic after an event (click on a button or application loaded) and instead of waiting for something to complete you have to write more event handling to do something after the completion of your action. With Windows Phone, only the asynchronous version of all I/O operations are available and it forces you to write code like this to accomplish the same task: ... var client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback); client.DownloadStringAsync(new Uri("")); ... public void loadHTMLCallback(Object sender, DownloadStringCompletedEventArgs e) { var textData = (string)e.Result; // Do cool stuff with result Debug.WriteLine(textData); } What is the difference? Obviously the asynchronous case did increase the complexity and number of lines quite dramatically. We already jumped from one line to 6 to achieve the same result. In the first case, the execution thread has to wait all the required time to download the URL (remember network can be slow) and it holds its resources while it waits. In the second example with the asynchronous case, all the resources can be released after DownloadStringAsync and the thread calling this method can continue its execution. The thread that runs the UI code is generally the dispatcher thread and you should let it continue processing other interactions, otherwise your UI will freeze until you finish your method. Asynchronous programming in C# 5.0 Asynchronous programming for .Net adds two new keywords: async and await. Inside an asynchronous context (in general this is simply within another asynchronous method), you can call an asynchronous method in a synchronous way by simply prefixing it with await. Behind the scenes, instead of holding the execution thread to wait for the result (in most cases a network call), the compiler will create callbacks to process the results (and the caller’s thread resources will be released). Essentially await is blocking, but only in the current function - from the perspective of the calling function life continues on until it too is forced to await something. UI events have already an asynchronous context so all you need to do is add async to your event handlers to make your methods asynchronous and call other asynchronous events. So in this initial example, if DownloadString was asynchronous (I will show later how this can be done), we could write and it would be the exact equivalent of the version with callbacks. In the synchronous version, the thread #1 has to wait and download the URL (remember network can be slow). In the second example with the asynchronous case, the caller from Thread #1 (calling this method in an asynchronous context) can continue its execution right before await client.DownloadString. In the most common cases, the asynchronous methods are UI events and the caller is the dispatcher. In the first case, the UI would be frozen waiting for the download to complete, while in the second case the Thread #1 can continue executing other UI events, the rest of the code is executed by a new thread (Thread #2) once the download has completed. In C#, the actual signature of DownloadString has to return a Task<string> instead of a string, the compiler with the await are doing the rest of the magic for you. With any real world network service, you will have a complex workflow to handle (see Toodledo syncing for an example) and you are probably looking at writing at least 10 callback methods which does really add to the complexity of code. Converting existing methods into to C# asynchronous methods TaskCompletionSource<T> is the easiest way to convert existing code into asynchronous. All you need to do is call TrySetResult, TrySetException and TrySetCanceled within the callback. The following example shows how we could convert the DownloadStringAsync into an asynchronous equivalent. public static Task<string> DownloadString; } Asynchronous code for Windows Phone 7 async and await are only available out of the box and fully featured with Visual Studio 2012 and Windows Phone 8. If you haven't yet upgraded to VS 2010 and need the Asynchronous features, the Visual Studio Async CTP adds them to the compiler and visual studio. For Visual Studio 2012 and Windows Phone 7 there is the Microsoft.Bcl.Async nuget package that lets you use the same keywords with .NET 4. The example The solution attached to this article demonstrates these concepts with a real service: Toodledo. Toodledo is a neat service that manages to do lists with many nice features, its REST API is very similar to many other services. We will demonstrate how to use the asynchronous features on the following scenario: - Lookup the toodledo user id using an email - Obtain a session token using the user id - List the tasks for the user id with the session token More details on the REST API and the service can be found on Toodledo with Windows Phone 7 Instead of writing all the REST calls with the plain WebClient, we will use a nice REST library that does all the deserialization work called RESTSharp. With RESTSharp, the code for getting the toodledo tasks would look a little like ... var client = new RestClient(""); var request = new RestRequest("account/lookup.php", Method.GET); client.ExecuteAsync(request, result => { if (resp.StatusCode == System.Net.HttpStatusCode.OK) getTokenId(resp.Value); }); ... public void getTokenId(string userAccount) { var client = new RestClient(""); var request = new RestRequest("account/token.php", Method.GET); client.ExecuteAsync(request, result => { if (resp.StatusCode == System.Net.HttpStatusCode.OK) loadTaskList(resp.Value); }); } Toodledo with asynchronous methods I am cheating a bit here because for each method the actual REST calls are in the method body but this still demonstrates the potential: var username = await getUsername(“email@eail.com”) var token = await getToken(username); var tasks = await getTasks(token); ... public async Task<ToodledoToken> getToken(string userId) { var request = new RestRequest("account/token.php", Method.GET); return (await ExecuteAsync<ToodledoToken>(request)); } ... Adding more magic to the application In a typical application, in addition to these request, you need to manage status message and progress indicators so you need to interleave some GUI code that will run on the dispatcher. - Get the status and progress bar out of the way In this example, I used the reactive framework to handle the progress bar and the status text,. You can learn more about it on … and … - Wrap existing asynchronous methods to use the new keywords Currently many libraries (like REST clients) are not updated yet to work with the new asynchronous framework so it is necessary to transform the callback based methods into the new world that uses Task<T> as return type. Here is how I used the TaskCompletionSource to do wrap a RestRequest into an asynchronous method: private async Task<T> ExecuteAsync<T>(RestRequest request) { var tcs = new TaskCompletionSource<T>(); _client.ExecuteAsync(request, resp => { var value = JsonConvert.DeserializeObject<T>(resp.Content); if (value.ErrorCode > 0) { var ex = new ToodledoException(value.ErrorCode, value.ErrorDesc); tcs.SetException(ex); } else tcs.SetResult(value); }); return await tcs.Task; } Learn more about Asynchronous Programming Official Microsoft documentation - Asynchronous Programming with Async and Await - Async Performance: Understanding the Costs of Async and Await - Control Flow in Async Programs (C# and Visual Basic) I/O and more Asynchronous features are not limited to I/O, in this other article you can learn how to use asynchronous code to simplify UI workflows. Download the solution The zipped solution for this example can be downloaded Media:WPTodo.zip Thanks to Hamish Willee for his constructive comments and feedback. R2d2rigo - Article theme This is an interesting topic to write about, but you can't use it to compete in the current contest; only entries about new, Windows Phone 8 specific features are allowed.And the Portable Libraries section should be reworded, since they were already available prior to VS2012, as a way to share code between Windows, WP7 and Xbox. r2d2rigo 23:36, 5 December 2012 (EET) CadErik -Thanks for feedback. I think asynchronous programming is sort of specific to windows phone 8. Unlike the full .net stack, you have no other way to write network calls - there are no synchronous versions of the I/O methods. CadErik 03:58, 6 December 2012 (EET) Hamishwillee - Not an expert but .... Hi CadErik Let me prefix this by "I am not a WP or .NET expert". Reviewing the literature await is new to Windows Phone 8 and from my understanding of articles like this one the value of await et al is to vastly simplify asynchronous programming by encapsulating much of the creation and daisy-chaining of asynchronous operations/call back boilerplate code. So my take on this is that asynchronous programming (even for these APIs) always existed (since you can run synchronous operations in another thread), but what you cover here makes them much easier to write. If I am correct that makes that makes this a valid "new feature" and hence valid competition entry. I do believe though that there are libraries that emulate the functionality for WP7 and these should be mentioned. I would remove the concentration on visual studio 2012 and refer to these as .Net or platform features - from a user perspective on this wiki this is "new stuff I can use in WP8", and "hey, I can backport to WP7" so that is what I'd focus on - perhaps a title "Improved asynchronous programming in Windows Phone 8" or similar. I would also do something comparative showing the difference in way this programming using both methods so you can show the improvements. I haven't reviewed this in detail, so apologies if I misunderstand. Note also that I am not the final judge - who might take a different view. R2d2rigo - is my position reasonable? RegardsHamish hamishwillee 08:01, 6 December 2012 (EET) R2d2rigo -Well, looking that async/await is a new core feature of WP8 even already being available in W8, I'd consider it valid then. But as Hamishwillee says, I'd focus more the article in how this improves the programming model of WP8, and how projects like Microsoft.Bcl tries to backport this functionality to WP7. r2d2rigo 16:19, 6 December 2012 (EET) Hamishwillee - R2d2rigo - thanks! CadErik, R2d2rigo then summarised my view quite well in previous comment. I think this would be a very useful article if well done. is a good start on the topic but I'm sure it could be done even better and with your examples. R2d2rigo, thanks for your advice/guidance. hamishwillee 01:23, 7 December 2012 (EET) CadErik - Updated articleHamishwillee - R2d2rigo, thanks alot for your feedback and references. I updated the article with references to the other articles and another section. Is the focus better? CadErik 06:50, 7 December 2012 (EET) Hamishwillee - Yes Hi CadErik Yes, I think the focus is much better. I'm still don't completely understand how this works from this article, but that is perhaps a limitation in me. The judges are experts and will be able to assess this better. I think the problem for me is that waiting is a blocking operation, so if you use one of these in a UI thread it looks like you'd be blocking the UI. It might not be the case - I'm envisaging the case where async operation is called if called in a button click handler - does the handler not then complete if await is called in a function in it? Or maybe I'm overcomplicating this - you just wouldn't wait ... but then how would you signal the UI it needs to update with a new property value. Too much Symbian C++ in my past I would also add links to "official" documentation on await/async. There is a missing placeholder here: "You can learn more about it on … and …" RegardsHamish hamishwillee 07:56, 13 December 2012 (EET) CadErik - Hamish,Thanks for the great feedback! I added a diagram, does this answer your question? The handler will complete using a callback, but the code calling the handler will be able to continue its execution right after it sees the await. CadErik 07:20, 16 December 2012 (EET) Hamishwillee - Thanks, the diagram helps Hi I did a lot more research and I believe I "get" it now. Essentially await is blocking, but only in the current function - from the perspective of the calling function life continues on until it too is forced to await something. I'm not completely comfortable with all the implications, but it is cool. More reading for me. I think that "What is asynchronous Programming?" section is probably a little unclear, probably because that title doesn't really match the content - which is about two different forms of asynchronous programming (with callbacks and using the new methods). Then there is some feel of repetition in the next section. Too late for the competition, but this section should probably follow a logical flow showing "synchronous programming is easy because the logical flow is easy to follow", "asynchronous programming used to be hard, because you had all these callbacks, and never new when they would be called and how to daisy chain them", "now asynchronous programming is much easier, because you can write async programming like sync programming - within a function the code will appear to wait synchronously, but within the context of the rest of your code it is as though the function did complete - and you only wait where you "really" need the value. this would then combine with parts of the next section. Anyway, something for you to think about. The diagram you added does help. RegardsHamish hamishwillee 07:16, 19 December 2012 (EET) CadErik -This was a more ambitious article than I originally thought! Great feedback again! I incorporated couple comments as minor edits. CadErik 19:51, 19 December 2012 (EET) Hamishwillee - Yes it is When I get my head around this, and after my holidays, I may try tidy the introduction further myself. Sometimes it helps to be ignorant :-0 RegardsHamish hamishwillee 02:24, 20 December 2012 (EET)
http://developer.nokia.com/community/wiki/Asynchronous_Programming_For_Windows_Phone_8
CC-MAIN-2014-41
refinedweb
2,474
51.58
This is the mail archive of the binutils@sourceware.org mailing list for the binutils project. On 05/20/2015 01:53 PM, Andy Lutomirski wrote: > Egads. Now I understand what that code is. I don't like the balign, > since this has nothing to do with alignment -- we're creating an array > of functions. Actually it does... we align to the beginning of each slot. If .balign could be something other than a power of 2 that would work, too. I was mostly looking to minimize the amount of gas magic we rely on. > Can't we make it explicit? > > #define EARLY_IDT_HANDLER_STRIDE 9 > > ... > > .rept NUM_EXCEPTION_VECTORS > . = early_idt_handlers + i * EARLY_IDT_HANDLER_STRIDE > .if (EXCEPTION_ERRCODE_MASK >> i) & 1 > ASM_NOP2 > .else > pushl $0 # Dummy error code, to make stack frame uniform > .endif > pushl $i # 20(%esp) Vector number > jmp early_idt_handler > i = i + 1 > .endr > > gas will error out if we try to move . backwards, so this should be safe. If that works too with all the versions of gas we care about, that would be fine (and I do appreciate the explicitness.) However, .[b]align is something that will have been well exercised in every version of gas, so I do feel slightly safer with it. -hpa
http://www.sourceware.org/ml/binutils/2015-05/msg00201.html
CC-MAIN-2018-13
refinedweb
201
78.14
audio_engine_channels(9E) audio_engine_playahead(9E) - gain access to a device #include <sys/types.h> #include <sys/file.h> #include <sys/errno.h> #include <sys/open.h> #include <sys/cred.h> #include <sys/ddi.h> #include <sys/sunddi.h> int prefixopen(dev_t *devp, int flag, int otyp, cred_t *cred_p); #include <sys/file.h> #include <sys/stream.h> #include <sys/ddi.h> #include <sys/sunddi.h> int prefixopen(queue_t *q, dev_t *devp, int oflag, int sflag, cred_t *cred_p); Architecture independent level 1 (DDI/DKI). This entry point is required, but it can be nulldev(9F) Pointer to a device number. A bit field passed from the user program open(2) system call that instructs the driver on how to open the file., allow both read and write access. Parameter supplied for driver to determine how many times a device was opened and for what reasons. For OTYP_BLK and OTYP_CHR, the open() function can be called many times, but the close(9E) function is called only when the last reference to a device is removed. If the device is accessed through file descriptors, it is done by a call to close(2) or exit(2). If the device is accessed through memory mapping, it is done by a call to munmap(2) or exit(2). For OTYP_LYR, there is exactly one close(9E) for each open() operation that is called. This permits software drivers to exist above hardware drivers and removes any ambiguity from the hardware driver regarding how a device is used. Open occurred through block interface for the device. Open occurred through the raw/character interface for the device. Open a layered process. This flag is used when one driver calls another driver's open() or close(9E) function. The calling driver ensures that there is one-layered close for each layered open. This flag applies to both block and character devices. Pointer to the user credential structure. A pointer to the read queue. Pointer to a device number. For STREAMS modules, devp always points to the device number associated with the driver at the end (tail) of the stream. Valid oflag values are FEXCL, FNDELAY, FREAD, and FWRITEL — the same as those listed above for flag.. For STREAMS modules, oflag is always set to 0. Valid values are as follows: Indicates that the open() function is called through the clone driver. The driver should return a unique device number. Modules should be called with sflag set to this value. Modules should return an error if they are called with sflag set to a different value. Drivers should return an error if they are called with sflag set to this value. Indicates a driver is opened directly, without calling the clone driver. Pointer to the user credential structure. The driver's open() function is called by the kernel during an open(2) or a mount(2) on the special file for the device. A device can be opened simultaneously by multiple processes and the open() driver operation is called for each open. Note that a device is referenced once its associated open(9E) function is entered, and thus open(9E) operations which have not yet completed will prevent close(9E) from being called. The function should verify that the minor number component of *devp is valid, that the type of access requested by otyp and flag is appropriate for the device, and, if required, check permissions using the user credentials pointed to by cred_p. The kernel provides open() close() exclusion guarantees to the driver at *devp, otyp granularity. This delays new open() calls to the driver while a last-reference close() call is executing. If the driver has indicated that an EINTR returns safe via the D_OPEN_RETURNS_EINTR cb_ops(9S) cb_flag, a delayed open() may be interrupted by a signal that results in an EINTR return. Last-reference accounting and open() close() exclusion typically simplify driver writing. In some cases, however, they might be an impediment for certain types of drivers. To overcome any impediment, the driver can change minor numbers in open(9E), as described below, or implement multiple minor nodes for the same device. Both techniques give the driver control over when close() calls occur and whether additional open() calls will be delayed while close() is executing. The open() function is passed a pointer to a device number so that the driver can change the minor number. This allows drivers to dynamically create minor instances of the device. An example of this might be a pseudo-terminal driver that creates a new pseudo-terminal whenever it is opened. A driver that chooses the minor number dynamically, normally creates only one minor device node in attach(9E) with ddi_create_minor_node(9F). It then changes the minor number component of *devp using makedevice(9F) and getmajor(9F). The driver needs to keep track of available minor numbers internally. A driver that dynamically creates minor numbers might want to avoid returning the original minor number since returning the original minor will result in postponed dynamic opens when original minor close() call occurs. *devp = makedevice(getmajor(*devp), new_minor); The open() function should return 0 for success, or the appropriate error number. close(2), exit(2), mmap(2), mount(2), munmap(2), open(2), Intro(9E), attach(9E), close(9E), ddi_create_minor_node(9F), getmajor(9F), getminor(9F), makedevice(9F), nulldev(9F), cb_ops(9S) STREAMS Programming Guide Do not attempt to change the major number. When a driver modifies the device number passed in, it must not change the major number portion of the device number. Unless CLONEOPEN is specified, the modified device number must map to the same driver instance indicated by the driver's getinfo(9e) implementation. In other words, cloning across different drivers is not supported. Cloning across different instances of the same driver in only permitted if the driver specified in CLONE_DEV in ddi_create_minor_node(9F) is not supported.
http://docs.oracle.com/cd/E19963-01/html/821-1476/open-9e.html
CC-MAIN-2014-15
refinedweb
973
57.27
double pow( double x, double y ) double x; /* a double value */ double y; /* a double value */ Synopsis #include "math.h" The pow function calculates the function xy . Parameters x and y is are double values such that if x is 0, then y must be greater than 0, or if x is less than 0, y must be integral. Return Value pow returns the value of the function. If error occurs, pow sets errno (the system error variable) to EDOM if x is 0 and y is negative, and returns HUGE_VAL (approximately 1.79769e+308). If x and y are both 0, or if x is less than 0 and y is not integral, then pow sets errno to EDOM and returns 0. If pow results in overflow, then errno is set to ERANGE and returns HUGE_VAL if x is positive, and negative HUGE_VAL if x is negative Help URL:
http://silverscreen.com/idh_silverc_compiler_reference_pow.htm
CC-MAIN-2021-21
refinedweb
150
67.08
My program uses pyplot to draw shapes. I have chosen to create the shapes in a very particular way because the program will eventually be solving this problem. Thus, the information for drawn shapes is contained in a data type I have named big_shape. A big_shape is a list of dicts, each dict containing the info needed to draw one 1x1 square, which I have named a unit_square. In the step I am currently struggling with, I have created a function make_copies() that should do the following: 1. Iterate over each unit_square in a big_shape and run the transpose() function -This should in turn create a new, transposed copy of the unit_square 2. Compile the new unit_squares into a second big_shape 3. Combine the new_big_shape with the original to make a third big_shape 4. Return the third big shape so that everything can be plotted. import matplotlib.pyplot as plt def make_unit_square(square_info): ''' A unit square is a 1x1 square. The square_info parameter is a two item list containing coordinates of the square's left top corner point (index [0], given as a list or tuple) and its color (index [1]). make_unit_square returns a dict that will eventually be the information input into a plt.Polygon(). ''' points = [square_info[0],[square_info[0][0]+1,square_info[0][1]],[square_info[0][0]+1,square_info[0][1]-1],[square_info[0][0],square_info[0][1]-1]] return {'type': 'unit square','points': points, 'color': square_info[1]} def make_copies(big_shape): ''' A big_shape is a list of unit_squares. Thus, any function taking a parameter big_shape will iterate over the composite unit squares. The make_copies function should iterate over each unit_square in a big_shape and run the transpose() function, which should in turn create a new, transposed copy of the unit_square. These new unit_squares are compiled into a new big_shape, which is then combined with the old big_shape and returned by the make_copies function so that the two can eventually be plotted at once. ''' def transpose(unit_square,xdistance,ydistance): new_unit_square = unit_square new_points = [ [point[0] + xdistance, point[1] + ydistance] for point in unit_square['points']] new_unit_square['points'] = new_points return new_unit_square #iterate over the big_shape, making a new, transposed copy of each of its composit unit_squares. THIS SHOULD LEAVE THE #ORIGINAL BIG SHAPE UNCHANGED, BUT SOMETHING SEEMS TO GO WRONG. new_big_shape = [transpose(x,0,10) for x in big_shape] #combine the two big_shapes so they can be plotted at once big_shape.extend(new_big_shape) return big_shape plt.axes() #Below is the information for four unit_squares that will make up a big_shape big_shape_1_info = [ [[0,1],'green'], [[0,2], 'green'], [[1,2],'green'], [[1,1],'pink'] ] #Take that information and create a list of unit_squares, i.e. a big_shape. big_shape_1 = [make_unit_square(x) for x in big_shape_1_info] ''' Here we make an even larger big_shape by making a transposed copy of big_shape_1 and saving both the original big_shape and its copy into one new big_shape. However, due to the bug, the unit_squares of big_shape_1 are erroneously changed in this step, so what we get is not the original big_shape and a transposed copy, but rather two transposed copies and no original. ''' big_shape_2 = make_copies(big_shape_1) ''' Next, we plot the new big_shape. This plotting is done by plotting each individual unit_square that makes up the big_shape. ''' for unit_square in big_shape_2: pol = plt.Polygon(unit_square['points'],color=unit_square['color']) plt.gca().add_patch(pol) print(unit_square) plt.axis('scaled') plt.show() When you make what looks an assignment, d = {1:[1,2,3]} D = d you are simply giving a new name to a dictionary object — the same reasoning applies to lists and other mutable objects — the fundamental is the object, and you can now use different names to refer to the same object. No matter which name you use to modify an object, all these names reference the same object d[2] = 3 D[3] = 4 print d, D # --> {1:[1,2,3], 2:3, 3:4}, {1:[1,2,3], 2:3, 3:4} In your use case you want to make a copy of the dictionary... Depending on the contents of your dictionary, you can use the dictionary's .copy() method or the copy.deepcopy(...) function from the copy module. The method gives you a so called shallow copy, so the copy is a new dictionary, but if the items are mutable, when you modify an item also the item in the original dictionary is modified d = {1:[1,2,3]} D = d.copy() D[2] = '2' print d # --> {1:[1,2,3]} --- no new element in original D[1][0] = 0 print d # --> {1:[0,2,3]} --- the original mutable content is modifed if all the items in your dictionary are not mutable (e.g., string, numbers, tuples) then .copy() is OK. On the other hand, if you have mutable items (e.g., lists, dictionaries, etc) and you want independent copies, you want copy.deepcopy() from copy import deepcopy d = {1:[1,2,3]} D = deepcopy(d) D[1][0]=0 print d # --> {1:[1,2,3]} p.s. D = d.copy() is equivalent to creating a new dictionary, D = dict(d): also in this case what you have is a shallow copy.
https://codedump.io/share/lWKwngRQIz16/1/why-does-my-function-change-its-parameter-outside-of-the-function39s-scope
CC-MAIN-2018-22
refinedweb
856
69.52
A generic Tree Property Sheet control Posted by Alexander Berthold on July 25th, 1999 CTreePropertySheetThis class implements a generic tree property control (see picture above). Its features are: - Supports variable width tree control - Autosizing depending on the size of the dialogs contained - As this version is now based upon the CPropertySheet/ CPropertyPage model, all features of these are available. - Various styles(for example, like Netscape Communicator's property sheet) - Extensibility: Allows to integrate user defined controls (like buttons or static text boxes) and easily position them. - Now supports modeless property sheets as well. How to implement a CTreePropertySheet in your application:Step 1. #include "TreePropertySheet.h" in the class implementation file in which you want to use the CTreePropertySheet. void CMyView::OnPropertySheet() { // TODO: ... }Step 4. ... CTreePropertySheet tpsSheet; CGeneralPrefsPage cGeneralPrefs; COtherPrefsPage cOtherPrefs; // All dialogs contained in the property sheet must (now) be allocated from the stack. Caution: To make it work, the dialogs you want to include must have the following style: - Style: 'Child' - Border: None - Caption: Yes - Set the caption to the text you wish to appear when the page is selected. - All other options must be unchecked. ... tpsSheet.AddPage(tps_item_node,&cGeneralPrefs); tpsSheet.AddPage(tps_item_node,&cOtherPrefs);You have to specify the resource ID when adding the dialog. The text argument is the title shown up in the tree control, 'tps_item_node' tells that this is a simple node in the tree. (See below for more information) Step 6. ... int nRetCode=tpsSheet.DoModal(); ...Optionally, you can set a special pre-defined style before DoModal(): ... tpsSheet.SetLikeNetscape(); int nRetCode=tpsSheet.DoModal(); ... RemarksTo set up the tree structure, there are three different attributes for 'AddPage()': To make it clearer, please take a look at the table below: If you want to enhance the CTreePropertySheet by own controls or buttons, this can be done using InsertExtraControl() / InsertExtraSpace(). For more information about these functions, please take a look into the HTML help file(see below) and into the example project. Downloads Download demo project - 52 KB Download source - 14 KB These files can also be downloaded at How can I change the caption of PropertyPage at runtime?Posted by NC on 08/18/2015 05:52am I wanted to add two almost same pages with few method difference int properySheet. So my plan is to have same class for both the pages and just change the caption of page. But some how i'm not able to change the caption of these pages at runtime. How i can change the caption of these pages at runtime.Reply SelChanged vs. SelChangingPosted by Legacy on 05/17/2000 12:00am Originally posted by: Kent Murray It has been my experience that as written this class fails to operate correctly when a category selection fails due to data validation problems during the dialog data exchange that is triggered by the page change. This might not be obvious normally, but I modified the tree control creation to include the always show selection flag. When the validation fails the page is not changed, but the tree control still indicates the selection to be the that of the page which you tried to select. To correct this behavior I handle the selection _changing_ message rather than the selection _changed_ message. In the selection changing message handler I set the result value (second argument) to be the negation of the value returned from SetActivePage(). This will keep the tree control selection from changing when the active page does not change. For example: BEGIN_MESSAGE_MAP(CTreePropertySheet, CPropertySheet) ON_NOTIFY(TVN_SELCHANGING,ID_TREECTRL,OnSelChanging) END_MESSAGE_MAP() void CTreePropertySheet::OnSelChanging( NMHDR* pNotifyStruct, RESULT* pResult) { NMTREEVIEW *pNotify=(NMTREEVIEW*)pNotifyStruct; DWORD dwPage = m_cTreeCtrl.GetItemData(pNotify->itemNew.hItem); LockWindowUpdate(); (*pResult) = !SetActivePage(dwPage); UnlockWindowUpdate(); // Prevent losing the focus when invoked by keyboard if(!(*pResult) && pNotify->action==TVC_BYKEYBOARD) { m_cTreeCtrl.SetFocus(); } InvalidateRect(&m_rcCaptionBar,FALSE); } [Note: I downloaded the class source directly from the author's homepage, and I have not compared it against the source available on CodeGuru.] CTreePropertySheet fix for NT 5Posted by Legacy on 09/10/1999 12:00am Originally posted by: Mario Contestabile Add BEGIN_MESSAGE_MAP(CTreePropertySheet, CPropertySheet) ON_NOTIFY(TVN_SELCHANGEDW,ID_TREECTRL,OnSelChanged) ... END_MESSAGE_MAP() in treepropertysheet.cpp page change error solvedPosted by Legacy on 08/11/1999 12:00am Originally posted by: Andr� Gleichner The error occurs because the treeview control is in UNICODE mode (somebody knows why?) although it's an ANSI build and therefore sends its WM_NOTIFY codes also as UNICODE messages. Here it sends a TVN_SELCHANGEDW instead of TVN_SELCHANGEDA. It seems to be a very common problem as it shows up in several newsgroups with some variations (with ListCtrls, sends only ANSI codes in UNICODE builds, etc). Most people recommend to handle both the ANSI and the UNICODE code (which works here) but that makes it more complicated than necessary (all codes have to be doubled as well as some strings received from treectrl are useless/have to be converted). Simply add the following lines within the CTreePropertySheet::AddTreeView() function right after the CreateEx() call. This will switch the treectrl to the right mode. BOOL tIsUnicode; #ifdef UNICODE tIsUnicode = TreeView_SetUnicodeFormat(m_cTreeCtrl.m_hWnd, 1); #else tIsUnicode = TreeView_SetUnicodeFormat(m_cTreeCtrl.m_hWnd, 0); #endif // UNICODE I somewhere read that the call to InitCommonControls() has something to do with that odd behavior. Anybody there who knows details? Best regards Andr� Gleichner Same problem as Peter: dialogs doesn't update ...Posted by Legacy on 08/06/1999 12:00am Originally posted by: Raymond Pols Hoi, I have the same problem on an NT workstation. The dialog pages doesn't change when selecting them from the treeview. Any idea yet? Thanks. By the way: great work though!Reply Propertysheet doesn't workPosted by Legacy on 07/28/1999 12:00am Originally posted by: Peter Hartmann Hello Alexander, I've compiled your Demo and testet it. The dialogs doesn't change. Nothing happens. Environment : NT 4.0 SP 4 VS 6.0 SP 3 Please have a look... GreetinxReply Peter :-) Originally posted by: Alexander Berthold I am sorry, but i had almost no time to review and update this page. I appreciate your comments, and i know the design of the tree property sheet control had many disadvantages. I'd been in some time pressure ... you know that, don't you ;) Now i have updated the whole thing a lot. I've completely redesigned the control, derived it from CPropertySheet and using the property sheet / property page design. It is now 100% compatible to windows property sheets and almost all of the methods are compatible to the old version. I've sent the update to codeguru today. To access the sources directly, click the link in the CTreePropertySheet page to my homepage. URL: Again, thanks for your time reviewing the code.Reply Is there a way to use API-style dialogs?Posted by Legacy on 05/19/1999 12:00am Originally posted by: Ken Krakman The parameter to the Tree Property Sheet only uses a CDialog. I have an application that has 40 API-style dialog boxes that have code associated with them all (the dialog procs that handle messages). Is there a way to use this class and still re-use all that code? Thanks!Reply TABbing problem with edit-style combo boxes - SolvedPosted by Legacy on 02/02/1999 12:00am Originally posted by: Robert Clark TABbing problem with edit-style combo boxesPosted by Legacy on 02/02/1999 12:00am Originally posted by: Robert Clark Really great work!! I have been playing with the control and I have discovered a problem with edit-style combo-box control in a prop sheet when tabbing. When using the TAB key (TAB or Shift-TAB) from an edit-style combo-box the software freezes up. My guess is a problem with the child edit window, but I have not isolated it yet. Anyone have any ideas or experience with this problem?Reply
http://www.codeguru.com/cpp/controls/treeview/misc-advanced/article.php/c727/A-generic-Tree-Property-Sheet-control.htm
CC-MAIN-2016-26
refinedweb
1,302
55.34
I noticed that the recommended command to import data into the postgresql database from the tutorial here is osm2pgsql -d gis --create --slim -G --hstore --tag-transform-script ~/src/openstreetmap-carto/openstreetmap-carto.lua -C 2500 --number-processes 1 -S ~/src/openstreetmap-carto/openstreetmap-carto.style ~/data/azerbaijan-latest.osm.pbf which lists the openstreetmap-carto style file. The recommended import command for OSM-Bright from osm2pgsql -c -G -U postgres_user -d postgis_database data.osm.pbf My question is do I need to re-import the raw OSM data into the postgresql database everytime I want to change map styles and specify it during data import? The first tutorial specifies a style in the import command while the OSM-Bright tutorial does not. Thanks for any help. asked 13 Sep '18, 22:25 coderunner 41●4●5●10 accept rate: 0% Short answer: Yes. There is no need to reimport data. A style file for osm2pgsql specifies aspects of how osm2pgsql converts OSM data into PostgreSQL tables, how much data is transferred from OSM xml into Postgres database. For example if a style does not display some kind of objects (powerlines, sidewalks etc) there is no much sense in keeping them in the rendering database. By constructing custom style you can filter what objects to include. More on this can be found here: Now to compatibility of openstreetmap-carto.style for OSM-Bright. Though default style that comes with osm2pgsql imports more data comparing to openstreetmap-carto (you can take diff of these two styles to see what objects are filtered) OSM-Bright does not use these data. So you can safely use the OSM-Bright style on the same database you made for openstreetmap-carto style. You can look at layers that are used by OSM-bright in this file - look for SQL statements. This is how data is queried from Postgres to Mapnik for rendering. answered 18 Sep '18, 09:44 getmaps_io 51●2 accept rate: 100% Makes sense, thank you for the explanation of what's going on under the hood. That was very helpful. Probably yes. Rendering database is a special purpose database derivative and this can be very different for different styles. One can make some mappings, but it needs some knowledge about SQL. Quite simple solution (if you have enough of disc space) is to have more databases and just switch them - this is my rough script for this purpose (gis is default database, gis2 is the second one): #!/bin/bash sudo service postgresql restart sudo -u postgres -H -- psql -c "alter database gis rename to temp;" sudo -u postgres -H -- psql -c "alter database gis2 rename to gis;" sudo -u postgres -H -- psql -c "alter database temp rename to gis2;" answered 13 Sep '18, 22:43 kocio 1.6k●18●34 accept rate: 21% edited 14 Sep '18, 03:29 That is a good idea. Thank you. Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: import ×159 postgresql ×140 style ×51 stylesheet ×18 question asked: 13 Sep '18, 22:25 question was seen: 686 times last updated: 18 Sep '18, 16:30 [closed] osm2pgsql shows "Committing transaction for planet_osm_point","WARING there is on transaction in progress" then the progres shut down What is the difference between OSMBright .xml stylesheet and osm2pgsql .style stylesheet How to check Nominatim planet import execution is running in background or terminated? Umap: inherit color from kml-file How much RAM does osm2pgsql required in case the progress won't be killed? (full planet import) Restarting osm2pqsql full planet import because of too low --cache setting? (import runs for 6 days already) Error while following osmosis import to database examples Why is my import of planet-latest.osm KILLED? Osm to postgresql import and basemaps problem osm xml stylesheet configuration First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/65889/importing-osm-data-and-using-osm-bright
CC-MAIN-2019-18
refinedweb
663
61.67
In this article, you'll learn how the mocking capabilities of GrailsUnitTestCase and ControllerUnitTestCase make it easy to unit test Grails artifacts that you'd otherwise assume need to be tested using an integration test. The mockForConstraintsTests(), mockDomain(), and mockLogging() methods all leverage Groovy's metaprogramming magic to make testing your domain classes, services, and controllers a breeze. In "Testing your Grails application," you learned about unit and integration tests: Grails supports two basic types of tests: unit and integration. There's no syntactical difference between the two: both are written as a GroovyTestCaseusing the same assertions. The difference is the semantics. A unit test is meant to test the class in isolation, whereas the integration test allows you to test the class in a full, running environment. That article was written with Grails 1.0 — the current release at the time — in mind. With the subsequent release of Grails 1.1, the testing infrastructure received a major boost in functionality. The introduction of the GrailsUnitTestCase class and its children brings a whole new level of testing ease and sophistication to the process. Specifically, the mocking capabilities of these new test classes allow you gain the speed of a unit test while testing functionality normally found only in an integration test. Figure 1 shows the new testing hierarchy in Grails 1.1.x: Figure 1. The new testing hierarchy in Grails 1.1.x When you create a new domain class and controller in the next section, you'll see a GrailsUnitTestCase and a ControllerUnitTestCase in action. (Full source code for the article's examples are available for download.) Getting started To follow along with the examples in this article, start by creating a new application. At the command prompt, type: grails create-app testing Change to the testing directory ( cd testing), then type: grails create-domain-class User And then: grails create-controller User Add the code in Listing 1 to grails-app/domain/User.groovy: Listing 1. The User domain class class User { String name String login String password String role = "user" static constraints = { name(blank:false) login(unique:true, blank:false) password(password:true, minSize:5) role(inList:["user", "admin"]) } String toString(){ "${name} (${role})" } } Scaffold out the core behavior of grails-app/controller/UserController.groovy, as shown in Listing 2: Listing 2. The UserController class class UserController { def scaffold = true } Now that the basic infrastructure is in place, it's time to add some tests. Mocking in GrailsUnitTestCase Open test/unit/UserTests.groovy in a text editor. The code is shown in Listing 3: Listing 3. The UserTests class import grails.test.* class UserTests extends GrailsUnitTestCase { protected void setUp() { super.setUp() } protected void tearDown() { super.tearDown() } void testSomething() { } } In Grails 1.0, the stubbed-out test created for you by the create-domain-class command extended GroovyTestCase. As you can see, the unit test for a domain class now (with Grails 1.1) extends GrailsUnitTestCase. Consequently, you have some new methods available that enable you to mock out functionality in a unit test that previously would have required an integration test. Specifically, a GrailsUnitTestCase offers the following mock methods: mockForConstraintsTests() mockDomain() mockLogging() To understand how valuable these mock methods are, start by creating a test that will intentionally fail. Change the testSomething() method to the testBlank() method, as shown in Listing 4: Listing 4. A test that will fail void testBlank() { def user = new User() assertFalse user.validate() } You may be asking yourself why this test will fail. After all, it is valid syntactically. The answer is that you are running a unit test. Unit tests are meant to run in isolation, which means that no database is running, no Web server is running, and — most important — no Grails-related metaprogramming occurs. Looking back at the source code of the User domain class in Listing 1, clearly no validate() method is defined. This method (along with save(), list(), hasErrors(), and all of the other Groovy Object Relational Mapping (GORM) methods you are familiar with) gets dynamically added to the domain class by Grails at run time. To run the failing test, type grails test-app at the command prompt. You should see the results shown in Listing 5: Listing 5. Failing test in console output $ grails test-app Environment set to test Starting unit tests ... Running tests of type 'unit' ------------------------------------------------------- Running 2 unit tests... Running test UserControllerTests...PASSED Running test UserTests... testBlank...FAILED Tests Completed in 1434ms ... ------------------------------------------------------- Tests passed: 1 Tests failed: 1 ------------------------------------------------------- Starting integration tests ... Running tests of type 'integration' No tests found in test/integration to execute ... Tests FAILED - view reports in /testing/test/reports. Before you view the failing report, did you notice how quickly the unit tests ran, as well as the noticeable delay in running the integration tests? Type grails test-app -unit to run just the unit tests. Even though the test is still failing, you should see a marked improvement in the speed of the test run. You can, of course, type grails test-app -integration to run just the integration tests. As a matter of fact, you can even combine the unit and integration flags with the name of the test class. Type grails test-app -unit User to target the specific test class you are interested in. (Notice that you drop the Tests suffix from the end of the name — less typing is always a good thing.) Being able to focus your test narrowly run to a single class can make a dramatic difference in how motivated you'll be to write tests in the real world. Knowing that you have a failing test, you probably want to see the error message. Open test/reports/html/index.html in a Web browser. Click through to the failing test class. The results are shown in Figure 2: Figure 2. Report showing the failing unit test The No signature of method: User.validate() error message confirms that Grails, indeed, hasn't metaprogrammed the validate() method onto the User class. At this point, you have two options. The first option is to move this test class into the integration directory. But seeing how long it takes Grails to spin up to run the integration tests, this option is less than appealing. The second option is to mock out the validation behavior and leave the test in the unit directory. Understanding mockForConstraintsTests() To mock out the Grails validation in a unit test, add the mockForConstraintsTests() method, as shown in Listing 6. This method instructs Grails to metaprogram the validation methods onto the specified domain class as it would normally during run time. Listing 6. A test that will pass, thanks to mockForConstraintsTests() void testBlank() { mockForConstraintsTests(User) def user = new User() assertFalse user.validate() } Now, run the test to verify that it passes, as shown in Listing 7: Listing 7. Running the passing test $ grails test-app -unit User Environment set to test Starting unit tests ... Running tests of type 'unit' ------------------------------------------------------- Running 1 unit test... Running test UserTests...PASSED Tests Completed in 635ms ... ------------------------------------------------------- Tests passed: 1 Tests failed: 0 ------------------------------------------------------- Tests PASSED - view reports in /testing/test/reports. To refine your unit test further, you can assert that the validation failed for a specific constraint on a specific field, as shown in Listing 8. The mockForConstraintsTests() method metaprograms an errors collection onto the domain class. This errors collection makes it easy to verify that the proper constraint was triggered. Listing 8. Asserting a specific constraint violation on a specific field void testBlank() { mockForConstraintsTests(User) def user = new User() assertFalse user.validate() println "=" * 20 println "Total number of errors:" println user.errors.errorCount println "=" * 20 println "Here are all of the errors:" println user.errors println "=" * 20 println "Here are the errors individually:" user.errors.allErrors.each{ println it println "-" * 20 } assertEquals "blank", user.errors["name"] } Rerun this test. Did it fail unexpectedly? Look at the report output, shown in Figure 3, to figure out the root cause: Figure 3. Failing caused by nullable instead of blank The error message is expected:<[blank]> but was:<[nullable]>. So validation failed, but not for the reason you might have expected it to. It's easy to get caught by this error. By default, all fields in a domain class are required to be nonnull in Grails. The trouble with this implicit constraint is that you usually interact with Grails via an HTML form. If you leave a String field blank in an HTML form, it comes back to the controller in the params Map as an empty String (that is, "") instead of null. If you click on the System.out link at the bottom of the HTML report, you can see that three of the String fields ( name, login, and password) all threw the nullable constraint violation. Figure 4 shows the output from the println calls. Only the role field — the one that had a default value of user — passed the implicit nullable constraint. Figure 4. The System.out output of the test Adjust the testBlank() test one more time to ensure that validation fails (and therefore, the unit test passes) for the proper reason, as shown in Listing 9: Listing 9. Test that now passes for the right reasons void testBlank() { mockForConstraintsTests(User) def user = new User(name:"", login:"admin", password:"wordpass") assertFalse user.validate() assertEquals 1, user.errors.errorCount assertEquals "blank", user.errors["name"] } Once you've rerun the test to ensure that it passes, it's time to tackle a slightly more tricky constraint: unique. Testing the unique constraint with mockForConstraintsTests() As you saw in the preceding section, testing for most constraints is easy to do in isolation. For example, testing that the minSize of the password field is at least 5 is easy because it doesn't rely on anything except the value of the field itself. Listing 10 shows the testPassword() method: Listing 10. Testing the minSize constraint void testPassword() { mockForConstraintsTests(User) def user = new User(password:"foo") assertFalse user.validate() assertEquals "minSize", user.errors["password"] } But how do you test a constraint like unique, which ensures that the database table contains no duplicate values? Thankfully, mockForConstraintsTests() takes a second argument: a list of domain classes used to mock out (act as a stand-in for) the real database table. Listing 11 demonstrates testing the unique constraint with a mocked-out table: Listing 11. Testing the unique constraint with a mocked-out table void testUniqueLogin(){ def jdoe = new User(name:"John Doe", login:"jdoe", password:"password") def suziq = new User(name:"Suzi Q", login:"suziq", password:"wordpass") mockForConstraintsTests(User, [jdoe, suziq]) def jane = new User(login:"jdoe") assertFalse jane.validate() assertEquals "unique", jane.errors["login"] } The ability to mock out a database table in-memory is a huge time saver, especially when you consider how long it takes to start up an actual database. To add insult to injury, once the database is up and running, you are still faced with the challenge of ensuring that the database table is prepopulated with the records necessary for your assertions to pass. I'm not suggesting that running true integration tests against your production database is a waste of time. I'm suggesting that those long-running integration tests are better suited for a continuous-integration server. In this case, mocking out the database interaction allows you to focus on the Grails functionality, doing it in a fraction of the time it would otherwise take. The ability to mock out database tables extends beyond the mockForConstraintsTests() method. You can do the same thing with the mockDomain() method. Understanding mockDomain() GORM metaprograms a number of useful methods onto domain classes: save(), list(), and a whole host of dynamic finders such as findAllByRole(). As the name implies, the mockForConstraintsTests() method adds the validation methods back onto the domain class for testing purposes. The mockDomain() method adds the persistence methods back onto the domain class for testing purposes. Listing 12 shows the mockDomain() method in action: Listing 12. Using mockDomain() to test GORM methods void testMockDomain(){ def jdoe = new User(name:"John Doe", role:"user") def suziq = new User(name:"Suzi Q", role:"admin") def jsmith = new User(name:"Jane Smith", role:"user") mockDomain(User, [jdoe, suziq, jsmith]) //dynamic finder def list = User.findAllByRole("admin") assertEquals 1, list.size() //NOTE: criteria, Hibernate Query Language (HQL) // and Query By Example (QBE) are not supported } The mockDomain() method models GORM behavior as faithfully as possible. For example, when you save a domain class to a mock table, the id field is populated as it would be in a live application. The id value is simply the ordinal value of the element in the list. Listing 13 demonstrates saving a domain class in a unit test: Listing 13. Saving a domain class in a unit test void testMockGorm(){ def jdoe = new User(name:"John Doe", role:"user") def suziq = new User(name:"Suzi Q", role:"admin") def jsmith = new User(name:"Jane Smith", role:"user") mockDomain(User, [jdoe, suziq, jsmith]) def foo = new User(login:"foo") foo.name = "Bubba" foo.role = "user" foo.password = "password" foo.save() assertEquals 4, foo.id //NOTE: id gets assigned assertEquals 3, User.findAllByRole("user").size() } Mocking out the underlying database isn't the only thing that you can do in a GrailsUnitTestCase. You can also mock out the logging infrastructure. Understanding mockLogging() A GrailsUnitTestCase is useful for more than just testing domain classes. Create an Admin service, as shown in Listing 14, by typing grails create-service Admin: Listing 14. Creating a service $ grails create-service Admin Created Service for Admin Created Tests for Admin Not surprisingly, the AdminService.groovy file appears in the grails-app/services directory. If you look in the test/unit directory, you should see a GrailsUnitTestCase named AdminServiceTests.groovy. Add a hypothetical method to AdminService that only allows users in the admin role to restart the server, as shown in Listing 15: Listing 15. Adding a restart() method to AdminService class AdminService { boolean transactional = true def restartServer(User user) { if(user.role == "admin"){ //restart the server return true }else{ log.info "Ha! ${user.name} thinks s/he is an admin..." return false } } } Testing this service should be pretty straightforward, right? Add a testRestartServer() method to test/unit/AdminServiceTests.groovy, as shown in Listing 16: Listing 16. A service test that will fail void testRestartServer() { def jdoe = new User(name:"John Doe", role:"user") def suziq = new User(name:"Suzi Q", role:"admin") //NOTE: no DI in unit tests def adminService = new AdminService() assertTrue adminService.restartServer(suziq) assertFalse adminService.restartServer(jdoe) } When you run this test by typing grails test-app -unit AdminService at the command prompt, it fails. Just like your initial User test runs, it fails for reasons you might not expect initially. Looking at the HTML report, the familiar No such property: log for class: AdminService message haunts you, as shown in Figure 5: Figure 5. Lack of dependency injection causing unit-test failures This time, however, the failure isn't due to the lack of metaprogramming on a domain class. It's due to the lack of dependency injection. Specifically, all Grails artifacts get a log object injected into them at run time so that they can easily log messages for later review. To inject a mock logger for testing purposes, wrap the AdminService class in a mockLogging() method call, as shown in Listing 17: Listing 17. Service test that will pass, thanks to mockLogging() void testRestartServer() { def jdoe = new User(name:"John Doe", role:"user") def suziq = new User(name:"Suzi Q", role:"admin") mockLogging(AdminService) def adminService = new AdminService() assertTrue adminService.restartServer(suziq) assertFalse adminService.restartServer(jdoe) } This time, the test passes as expected. And any log output is sent to System.out. Remember that you can see this output in the HTML reports. Understanding ControllerUnitTestCase You can easily test domain classes and services with a GrailsUnitTestCase, but testing a controller requires some additional functionality. A ControllerUnitTestCase extends GrailsUnitTestCase, so you can still use mockForConstraintsTests(), mockDomain(), and mockLogging() as you did before. Also, a ControllerUnitTestCase creates a new instance of the controller you are testing and stores it in the aptly named controller variable. This controller variable is how you programmatically interact with the controller during the test. To visualize the core controller functionality better, type grails generate-controller User at the command prompt. This replaces def scaffold = true with the full implementation of the controller code. In the fully implemented grails-app/controllers/UserController.groovy file, you can see that calling the index action redirects you to the list action, as shown in Listing 18: Listing 18. The default index action in UserController class UserController { def index = { redirect(action:list,params:params) } } To verify that the redirect happens as expected, add a testIndex() method to test/unit/UserControllerTests.groovy, as shown in Listing 19: Listing 19. Testing the default index action import grails.test.* class UserControllerTests extends ControllerUnitTestCase { void testIndex() { controller.index() assertEquals controller.list, controller.redirectArgs["action"] } } As you can see, you first invoke the controller action as if it were a method call on the controller. The redirect arguments are stored in a Map named redirectArgs. The assertion verifies that the action key contains the list value. (If the action ends with a render, you can assert against the Map named renderArgs.) Suppose now that the index action is slightly more advanced. It checks the session for a User and redirects based on whether that user is an admin or not. In a ControllerUnitTestCase, both session and flash are Maps that you can populate before the call or assert against after the call. Change the index action as shown in Listing 20: Listing 20. A more advanced index action def index = { if(session?.user?.role == "admin"){ redirect(action:list,params:params) }else{ flash.message = "Sorry, you are not authorized to view this list." redirect(controller:"home", action:index) } } To test your new functionality, change the testIndex() method in UserControllerTests.groovy, as shown in Listing 21: Listing 21. Testing for session and flash values void testIndex() { def jdoe = new User(name:"John Doe", role:"user") def suziq = new User(name:"Suzi Q", role:"admin") controller.session.user = jdoe controller.index() assertEquals "home", controller.redirectArgs["controller"] assertTrue controller.flash.message.startsWith("Sorry") controller.session.user = suziq controller.index() assertEquals controller.list, controller.redirectArgs["action"] } Some controller actions expect incoming parameters. In a ControllerUnitTestCase, you can add values to the params Map just as you did to flash and session. Listing 22 shows the default show action: Listing 22. The default show action def show = { def userInstance = User.get( params.id ) if(!userInstance) { flash.message = "User not found with id ${params.id}" redirect(action:list) } else { return [ userInstance : userInstance ] } } Remember the mockDomain() method from GrailsUnitTestCase? You can use it here to mock out the User table, as shown in Listing 23: Listing 23. Testing the default show action void testShow() { def jdoe = new User(name:"John Doe", login:"jdoe", password:"password", role:"user") def suziq = new User(name:"Suzi Q", login:"suziq", password:"wordpass", role:"admin") mockDomain(User, [jdoe, suziq]) controller.params.id = 2 // this is the HashMap returned by the show action def returnMap = controller.show() assertEquals "Suzi Q", returnMap.userInstance.name } Testing RESTful Web services with ControllerUnitTestCase Sometimes, to test your controller, you need access to the raw request and response. In the case of a ControllerUnitTestCase, these are exposed to you via the controller.request and controller.response objects: GrailsMockHttpServletRequest and GrailsMockHttpServletResponse, respectively. You can review "Mastering Grails: RESTful Grails" for a guide to setting up the RESTful services. Combine that with "Practically Groovy: Building, parsing, and slurping XML" to parse the results, and you have everything you need to test your RESTful Web services. Add a simple listXml action to UserController, as shown in Listing 24. (Don't forget to import the grails.converters package.) Listing 24. Simple XML output in the controller import grails.converters.* class UserController { def listXml = { render User.list() as XML } // snip... } Then add a testListXml() method to UserControllerTests.groovy, as shown in Listing 25: Listing 25. Testing the XML output void testListXml() { def suziq = new User(name:"Suzi Q", login:"suziq", password:"wordpass", role:"admin") mockDomain(User, [suziq]) controller.listXml() def xml = controller.response.contentAsString def list = new XmlParser().parseText(xml) assertEquals "suziq", list.user.login.text() //output /* <?xml version="1.0" encoding="UTF-8"?> <list> <user> <class>User</class> <id>1</id> <login>suziq</login> <name>Suzi Q</name> <password>wordpass</password> <role>admin</role> <version /> </user> </list> */ } The first thing that happens in this test is that you create a new User and store it in the suziq variable. Next, you mock out the User table, storing suziq as the only record. With this preliminary setup in place, you next call the listXml() action. To get the resulting XML from the action as a String, you call controller.response.contentAsString and store it in the xml variable. At this point, you have a raw String. (The content of this String is shown for reference purposes in the output comment at the end of the method.) Calling new XmlParser().parseText(xml) returns the root element ( <list>) as a groovy.util.Node object. Once you have the root node of the XML document, you can use a GPath expression (for example, list.user.login.text()) to assert that the <login> element contains the expected value (in this case, suziq). As you can see, the Grails converters package makes it easy to produce the XML, the native Groovy library XmlParser makes it easy to parse the XML, and the ControllerUnitTestCase makes it easy for you to test the resulting GrailsMockHttpServletResponse. That's a remarkably powerful combination of technologies that takes remarkably few lines of code to test. Conclusion In this article, you learned how the baked-in test classes — GrailsUnitTestCase and ControllerUnitTestCase— make testing your Grails application a snap. The mockForConstraintsTests(), mockDomain(), and mockLogging() methods all dramatically speed you along by allowing you to write fast unit tests instead of considerably slower integration tests. Next time, I'll walk through a few of the community-driven testing plug-ins that make integration tests less painful. Until then, have fun mastering Grails. Download Resources Learn - Mastering Grails: Read more in this series to gain a further understanding of Grails and all you can do with it. - Grails: Visit the Grails Web site. - Grails 1.1 Release Notes: Learn more about the new test framework in Grails 1.1.x. - Discuss - Check out developerWorks blogs and.
http://www.ibm.com/developerworks/java/library/j-grails10209/index.html
CC-MAIN-2014-52
refinedweb
3,748
57.47
1 /*2 * DatabaseConnectionTest.java Mar 26, 20023 *4 * The DbUnit Database Testing Framework5 * Copyright (C)2002-2004, DbUnit.org6 *7 * This library is free software; you can redistribute it and/or8 * modify it under the terms of the GNU Lesser General Public9 * License as published by the Free Software Foundation; either10 * version 2.1 of the License, or (at your option)7 USA20 21 *22 */23 24 package org.dbunit.database;25 26 27 /**28 * @author Manuel Laflamme29 * @version $Revision: 1.4 $30 * @since Mar 26, 200231 */32 public class DatabaseConnectionTest extends AbstractDatabaseConnectionTest33 {34 public DatabaseConnectionTest(String s)35 {36 super(s);37 }38 39 }40 41 42 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/dbunit/database/DatabaseConnectionTest.java.htm
CC-MAIN-2017-30
refinedweb
123
55.84
Process and parse through git log statistic Project description A git log processor for better stats. Setup Install the library with: # From pypi python3 -m pip install git_processor To use it, run the generate_git_logs.sh in where you have all your repository. It will create a stats.txt file. import os from git_processor.data import Projects p = Projects(os.path.abspath("stats.txt")) # Process the git log stats p.clean_up_names() # Get all similar names as one p.df # Get the created dataframe p.total() # Total commits per user Let’s use jupyter to display the information. pyhton3 -m pip install jupyter cd jupyter/ jupyter notebook Once you are in the jupyter notebook, you can display the data and plot the stats. Check in the jupyter/ folder, you can reuse the demo and get your stats in one go. Just click on Run All Cell, or go along with <kbd>shift</kbd> + <kbd>enter</kbd> to run them individually. Testing To find out more info about the testing configuration, check out the tox.ini file. # Run the test suite tox # Run the linter: tox -e lint Local Installation Using a virtual environment: # From pypi python3 -m pip install virtualenv Then set it up and install the package locally # Create the virtual environment python3 -m venv `pwd`/env # Activate it source env/bin/activate # Install from local (env) python3 -m pip install . Project details 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/git-processor/
CC-MAIN-2019-51
refinedweb
253
66.13
in reply to Design Patterns Still Aren't In defence of the Perl Design Patterns, I thought they were quite refreshing, and protrayed well how design patterns should be appropriately used in perl. There *is* a lot of hype around design patterns, and much of it *needs* to be deflated. "Simple things should be simple" is the perl mindset, and the article does an excellent job of showing how to use them simply and effectively. Design Patterns are a prime example of academic self-indulgence, where everything *must* be complex, because simple things are not publishable. Even the simplest pattern, Singleton, is an exercise in seeing how much complexity one can layer on top of a global variable, while providing zero benefits, and lingering problems. (Did anyone notice the note about timely and correct destruction being non-trivial--in the Knuth sense of the word?) In the end you have a Class in your global namespace instead of a variable, and a lot of useless, bloated code. Patterns aren't Language Features. Maybe they aren't in java or C++, but if they *are* in perl or ruby, does that mean we still have to code it ourselves to make it a pattern? This is *exactly* the kind of artificial-complexity that turns design patterns into a tool of evil. I'm not saying that patterns are always useless and bloated. (Well, maybe Singletons are.) They have their uses for solving complex problems, but not all problems are complex, and not all implementations need to be complex. Unfortunately, a culture of complexity has grown around design patterns, such that average programmers have a hard time applying or implementing them correctly. (I say that after having to fix applications by removing the design patterns from them.) Patterns aren't Universally Applicable. and ... how a particular problem fits with a particular solution. Accepted patterns are too complex to be univerally applicable, but too many programmers try to apply them to everything anyway. You should be looking for solutions to your problems, not problems for your solution! It would help immensely if we could dispense with the complexity, and recognize iteration, repetition, and decision as valid patterns. Then patterns *would* be universally applicable, and it would be OK to apply simple solutions to one's problems. Patterns aren't Platonic Ideals ... a ten-year-old collection of patterns from a different language. Um, well said. :) The problem with "distinctly named" patterns is that they become canonic: you should do it this way, even if perl has an easier and better way of doing it. Perl Design Patterns was trying to show the easier and better ways of doing it, instead of showing how to write 10-year-old C++ programs in perl. Is there something wrong with that? Patterns aren't Total Solutions: ... The description of each pattern should review the context in which it is used, acknowledge the tradeoffs involved, and refer to other patterns that offer an alternative approach. First, I agree completely. Second, when was the last time you included comments like this in your code? (Oh wait, we only have to justify the pattern when we invent it, not when we use it, because any use of a pattern must be better than a non-pattern.) If people actually considered the tradeoffs involved (and documented them), complex patterns would only be used where the complexity is appropriate and necessary, or find a simpler way to do it. Patterns aren't Generic Concepts. So looping is not a pattern because it is too generic? Why should I use a loop when an iterator will work just as well? It makes me feel elite, because I've written 10kLOC today. Design Patterns provide solutions for problems, and standardize the names for those solutions. This is good. Design Pattern Culture worships complexity to the point were any simple solution is rejected as a design pattern, and thus tacitly rejected as a solution. This is evil. Hell yes! Definitely not I guess so I guess not Results (41 votes), past polls
http://www.perlmonks.org/?node_id=285355
CC-MAIN-2014-52
refinedweb
678
55.54
Created on 2011-12-14 03:59 by Ramchandra Apte, last changed 2014-05-08 14:46 by aronacher. This issue is now closed. string.Formatter doesn't support empty curly braces "{}" unlike str.format . >>> import string >>> a = string.Formatter() >>> a.format("{}","test") Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> a.format("{}","hello") File "/usr/lib/python3.2/string.py", line 180, in format return self.vformat(format_string, args, kwargs) File "/usr/lib/python3.2/string.py", line 184, in vformat result = self._vformat(format_string, args, kwargs, used_args, 2) File "/usr/lib/python3.2/string.py", line 206, in _vformat obj, arg_used = self.get_field(field_name, args, kwargs) File "/usr/lib/python3.2/string.py", line 267, in get_field obj = self.get_value(first, args, kwargs) File "/usr/lib/python3.2/string.py", line 226, in get_value return kwargs[key] KeyError: '' Attached is patch to fix this issue. Sorry, the patch has an mistake. ValueErro should be ValueError. Attached is a patch for test.test_string to test for this bug. Can somebody please comment on my paches or commit my patches. Why isn't anybody commiting or commenting on my patches? This bug is assigned to me. Sometimes it takes a while before a committer has time to review a bug and act on it. I can assure you that I will review this before the next release of Python. Thank you for the bug report, and especially thanks for the patch! One thing that will definitely need to be developed before this is committed is one or more tests. Either you can add them, or I will before I commit the fix. There are some existing tests for str.format that can be leveraged for string.Formatter. On Thu, Dec 15, 2011 at 1:42 AM, maniram maniram <report@bugs.python.org> wrote: > Why isn't anybody commiting or commenting on my patches? Your patch is much appreciated. Thank you. It takes some time to get things reviewed. Please read the Dev Guide. In particular, the "Lifecycle of a Patch" section:. Also, please quit marking issues as "languishing" unless the issue meets the qualifications spelled out here:. test_string.diff looks good, except that it should probably only test the exception type, not the message (they are not a guaranteed part of the Python language and may change arbitrarily between versions or implementations (e.g. PyPy), so better not to add tests that depend on exact words). I don’t have anything specific to say about issue13598.diff; if it makes the test pass, then it’s good. “if manual == True” should just be replaced by “if manual”. If you’d like to, you can make one patch with fix + tests that addresses my comments and remove the older diffs. One potential problem with the simple approach to fixing this is that up until now, string.Formatter has been thread safe. Because all the formatting state was held in local variables and passed around as method arguments, there was no state on the instance object to protect. Now, this only applies if you start using the new feature, but it should be noted in the documentation and What's New that you need to limit yourself to accessing each formatter instance from a single thread. It's also enough for me to say "no, not in a maintenance release". Adding two attributes also seems unnecessary, and the pre-increment looks strange. Why not: In __init__: auto_field_count = 0 Then as the auto numbering checking, something like: auto_field_count = self.auto_field_count if field_name: if auto_field_count > 0: # Can't switch auto -> manual auto_field_count = -1 elif auto_field_count < 0: # Can't switch manual -> auto else: field_name = str(auto_field_count) self.auto_field_count += 1 (Alternatively, I'd ask the question: why do we prevent mixing manual numbering and explicit numbering anyway? It's not like it's ambiguous at all) @Nick I don't understand why should my patch make Formatter thread-unsafe - the auto_field_count and manual variables are local variables just like the variables in the other functions in Formatter. I have submitted a new patch, I have moved the increment to the end of if loop. What is the status of the bug? Could you upload just one patch with fix and test, addressing my previous comments, and remove the old patches? It will make it easier for Eric to review when he gets some time. Please also keep lines under 80 characters. Thanks in advance. It seems like the patch doesn't consider mixing of positional and keyword arguments: if you have the format string "{foo} {} {bar}", then manual will be set to True when "foo" is seen as the field_name, and fail soon after when "" is seen as the field_name the next time around. So, the test should include something which shows that fmt.format("{foo} {} {bar}", 2, foo='fooval', bar='barval') returns "fooval 2 barval", whereas with a format string like "{foo} {0} {} {bar}" or "{foo} {} {0} {bar}" you get a ValueError. Also, why "automatic field numbering" vs. "manual field specification"? Why not "numbering" for both? Added a new patch which addresses Éric's comments. Is there a reason "manual" is None, True, or False? Wouldn't just True or False suffice? > Is there a reason "manual" is None, True, or False? Wouldn't just True or False suffice? I suppose before we see the first bracketed form ({} or {\d+}) we don't know which it is. Yes, I guess that's so. I'll have to add a comment, as at first glance it just looks like a bug. Thanks! Its not a bug though it has maintenance problems because if you change "manual is False" to not manual it no longer works correctly. > it has maintenance problems because if you change "manual is False" > to not manual it no longer works correctly. So you should probably comment the initialisation appropriately. One brief comment on the wording of the error message: the inconsistent naming is actually copied from the str.format code. >>> "{foo} {} {bar}".format(2, foo='fooval', bar='barval') 'fooval 2 barval' >>> "{foo} {0} {} {bar}".format(2, foo='fooval', bar='barval') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot switch from manual field specification to automatic field numbering The current patch fails to catch the fact that auto vs manual numbering has been used in following corner case: from string import Formatter print(Formatter().format("{0:{}}", 'foo', 5)) To fix this, without adding state to the formatter instance, some more information is going to need to be passed to the _vformat method. Ramchandra's fix looks fairly good, although there is at least one remaining issue (see my last comment). I have attached a patch which addresses (and tests) this. I'd be happy to pick this up if there are any remaining issues that need to be addressed, otherwise: I hope this helps. Thanks, Buump. Looking at Phil Elson's patch: I didn't see a test case relating to the example in his comment, namely f.format("{0:{}}", 'foo', 5) Did I miss it? The documentation also needs to be updated. > I didn't see a test case relating to the example in his comment, namely > > f.format("{0:{}}", 'foo', 5) > > Did I miss it? The example should fail, which it wouldn't have done with the patch previously proposed. I believe the case is covered by the block: with self.assertRaises(ValueError): fmt.format("foo{1}{}", "bar", 6) Though there is no harm in adding another test along the lines of: with self.assertRaises(ValueError): fmt.format("{0:{}}", "bar", 6) If you think it is worthwhile? I'm uncertain which documentation to update since the method which has had its signature updated is private and is called solely by Formatter.vformat . Cheers, > I believe the case is covered by the block: [snip] Ah, right. I wasn't sure that was the exact same code path that was being exercised. But I didn't look very closely. > If you think it is worthwhile? Only if it exercises a different code path. New changeset ad74229a6fba by Eric V. Smith in branch '3.4': Issue #13598: Add auto-numbering of replacement fields to string.Formatter. New changeset 50fe497983fd by Eric V. Smith in branch '3.4': Issue #13598: Added acknowledgements to Misc/NEWS. Is there any chance this will be fixed for 2.7 as well?
https://bugs.python.org/issue13598
CC-MAIN-2021-39
refinedweb
1,402
67.65
In an earlier post we were looking at how to calculate an average using JavaScript’s array method. And in that article we ran into a dilemma. On the one hand, we could build our solution out of small, simple functions. But that meant doing many passes over the one array. On the other hand, we could do everything in a single pass. But that meant creating a hideously complex reducer. We were forced to choose between elegance and efficiency. In the same article though, I hinted at another way. A solution that would give us the elegance of using small, simple functions. But also the efficiency of doing our processing in a single pass through the array. What is this magical solution? It’s a concept called a transducer. Transducers are very cool. They give us a lot of power. But they are also a bit abstract. And that makes them hard to explain. So I could write an epic post explaining where transducers came from and how they work…. But someone else has already done it. Eric Elliott has written a lengthy article that explains transducers in depth. So rather than repeat his work, I’m going to encourage you to read that. So what’s the point of this article then? If Mr Elliott explains transducers so well, what else is left to say? Well, two things: - Even after reading Mr Elliott’s article twice, I still found it tricky to get my head around. So I thought I’d have a go at explaining how I understand them; and - I thought it might be instructive to apply transducers to a specific problem. That way, we can see them in action and make things concrete. So, in this article, I’ll solve the same problem from my previous article. Transducers are hard. It may take a couple of attempts to get your head around them. So if you’re still confused after reading Mr Elliott’s article, maybe this one might help you along the way. A practical application of transducers So, let’s refresh our memory on the problem we’re trying to solve. We have some data about Victorian-era slang terms:, }, ]; We’d like to find the average of all the entries that have a popularity score. Now, one way to solve the problem is using .filter(), .map() and .reduce(). It might look something like this: //); The problem with this approach is that we have to traverse the array three times: - Once to filter out the un-found items; - Again to extract the popularity scores; - And once more to calculate the total. This isn’t so bad, except that we’re creating at least two intermediate arrays. These could potentially take up a lot of memory (if we had a larger data set). But the good thing about this approach is that it breaks the task down into three easy sub-tasks. Another way to think about transducers Now, how do we get from our problem to transducers? To make the transition easier, let’s try a thought experiment. Imagine that someone with a lot of power outlawed the use of .filter(), .map() and .flatMap() in JavaScript. It’s a silly thought experiment, I know, but humour me. Imagine you couldn’t use the built in .filter() or .map() method. And neither could you write your own versions using for-loops. What would we do? This situation wouldn’t phase us too much, because we know that we can use .reduce() to do the job of both .filter() and .map(). Here’s how that might look: // Helper functions // --------------------------------------------------------------------------------- function isFound(item) { return item.found; }; function getPopularity(item) { return item.popularity; } function filterFoundReducer(foundItems, item) { return isFound(item) ? foundItems.concat([item]) : foundItems; } function mapPopularityReducer(scores, item) { return scores.concat([getPopularity(item)]); } //.reduce(filterFoundReducer, []) .reduce(mapPopularityReducer, []) .reduce(addScores, initialInfo); // Calculate the average and display. const {totalPopularity, itemCount} = popularityInfo; const averagePopularity = totalPopularity / itemCount; console.log("Average popularity:", averagePopularity); Notice how we chain .reduce() three times there. We’ve converted our main calculation so that it uses only .reduce(). The imaginary ban on .filter() and .map() hasn’t stopped us. But if this ban were to continue, we might want to make life easier on ourselves. We could save some effort by creating functions for building reducers. For example, we could create one for making filter-style reducers. And we could build another for creating map-style reducers: function makeFilterReducer(predicate) { return (acc, item) => predicate(item) ? acc.concat([item]) : acc; } function makeMapReducer(fn) { return (acc, item) => acc.concat([fn(item)]); } Nice and simple, aren’t they? If we were to use them on our average calculation problem, it might look like this: const filterFoundReducer = makeFilterReducer(isFound); const mapPopularityReducer = makeMapReducer(getPopularity); But, so what? We’re not any closer to solving the average problem more efficiently. When do we get to the transducers? Well, as Mr Elliott says in his article, transducers are tools for modifying reducers. To put it another way, we can think of a transducer as a function that takes a reducer and returns another reducer. If we were to describe that with Haskell types, it might look something like this: 1 type Reducer = (a, b) => a transducer :: Reducer -> Reducer What that means is: A transducer takes a reducer function as input, and transforms it in some way. We give it a reducer, and it gives us another reducer function back. Now, we’ve just modified our average-calculating code so that it only uses reducers. No more .filter() and .map(). Instead, we have three separate reducers. So, we’re still traversing the array three times. But what if, instead of three reducers, we used transducers to combine them into one? So we could, for example, take a reducer and modify it so that some items were filtered out. The first reducer still runs, but it just never sees some values. Or, we could modify a reducer so that every item passed to it was transformed or mapped to a different value. That is, every item is transformed before the reducer sees it. In our case, that might look something like this: // Make a function that takes a reducer and returns a // new reducer that filters out some items so that the // original reducer never sees them. function makeFilterTransducer(predicate) { return nextReducer => (acc, item) => predicate(item) ? nextReducer(acc, item) : acc; } // Make a function that takes a reducer and returns a new // reducer that transforms every time before the original // reducer gets to see it. function makeMapTransducer(fn) { return nextReducer => (acc, item) => nextReducer(acc, fn(item)); } Earlier, we made convenience functions for creating reducers. Now, instead, we’ve created convenience functions for changing reducers. Our makeFilterTransducer() function takes a reducer and sticks a filter in front of it. Our makeMapTransducer() function takes a reducer and modifies every value going into it. In our average calculation problem, we have a reducer function at the end, addScores(). We can use our new transducer functions to map and filter the values going into it. We would end up with a new reducer that does all our filtering, mapping, and adding in one step. It might look like this: const foundFilterTransducer = makeFilterTransducer(isFound); const scoreMappingTransducer = makeMapTransducer(getPopularity); const allInOneReducer = foundFilterTransducer(scoreMappingTransducer(addScores)); const initialInfo = {totalPopularity: 0, itemCount: 0}; const popularityInfo = victorianSlang.reduce(allInOneReducer, initialInfo); // Calculate the average and display. const {totalPopularity, itemCount} = popularityInfo; const averagePopularity = totalPopularity / itemCount; console.log("Average popularity:", averagePopularity); And now, we’ve managed to calculate our average in a single pass. We’ve achieved our goal. We are still building our solution out of tiny, simple functions. (They don’t get much simpler than isFound() and getPopularity().) But we do everything in a single pass. And notice that we we were able to compose our transducers together. If we wanted, we could even string a bunch of them together with compose(). This is why smart people like Mr Elliott and Rich Hickey think they’re so interesting. There’s a lot more to explore with transducers though. This is just one specific application. If you want to dive in and start using them in your projects, please take note of a few things first: - I’ve used non-standard function names in this article to try and make their purpose clear. For example, I use the argument name nextReducer, where Mr Elliott uses step. As a result, the solution here looks a bit uglier because of the long names. If you read Mr Elliott’s article, he uses more standard names and everything looks a bit more elegant. - As Mr. Elliott suggests in his article, it’s (usually) best to use someone else’s transducer library. This is because the version written here has been simplified to help make the concepts clear. In practice, there’s several edge cases and rules to handle. A well written implementation will take care of that for you. Transducers in Ramda Speaking of well written implementations, Ramda has one built-in for processing arrays. I thought I’d show how our problem works because Ramda’s way of doing it is a little bit magical. So magical, in fact, that it’s hard to see what’s going on. But once you get it, it’s brilliant. So, the thing that stumped me for quite a while is that with Ramda, you don’t need to make transducer factories. We don’t need makeFilterTransducer() or makeMapTransducer(). The reason is, Ramda expects you to use its plain ol’ filter() and map() functions. It does some magic behind the scenes and converts them into a transducer for us. And it does all the work of complying with the reducer rules for us as well. So, how would we solve the sample problem with Ramda? Well, we would start by using the transduce() function. It takes four parameters: - The first is a ‘transducer’. But, as we mentioned, we just compose plain old Ramda utilities. - Then, we pass a final reducer to transform. - And then an initial value. - And finally, the array to process. Here’s how our solution might look: import {compose, filter, map, transduce} from 'ramda'; // Our utility functions… function isFound(item) { return item.found; }; function getPopularity(item) { return item.popularity; } function addScores({totalPopularity, itemCount}, popularity) { return { totalPopularity: totalPopularity + popularity, itemCount: itemCount + 1, }; } // Set up our 'transducer' and our initial value. const filterAndExtract = compose(filter(isFound), map(getPopularity)); const initVal = {totalPopularity: 0, itemCount: 0}; // Here's where the magic happens. const {totalPopularity, itemCount} = transduce( filterAndExtract, // Transducer function (Ramda magically converts it) addScores, // The final reducer initVal, // Initial value victorianSlang // The array we want to process ); // And spit out the average at the end. const averagePopularity = totalPopularity / itemCount; console.log("Average popularity:", averagePopularity); One thing to note here is that in compose(), I’ve written filter() first, then map(). This isn’t a mistake. It’s a quirk of how transducers work. The order you compose is reversed from the usual. So filter() is applied before map(). And this isn’t a Ramda thing either. It’s all transducers. You can see how it happens if you read the examples above (not the Ramda ones). One final thing to point out: Transducers are not just limited to processing arrays. They can work with trees, observables (think RxJS) or streams (see Highland.js). Anything that has some concept of reduce(), really. And that’s kind of the dream of functional programming. We write tiny, simple functions like isFound() and getPopularity(). Then we piece them together with things like transduce() and reduce(). And we end up with powerful, performant programs. So, to sum up, Transducers are great. But they can also be confusing. So if anything I’ve written here confused you, please send me a tweet and let me know. I’d love to hear about it so I and try and improve the explanation. And of course, if you found it useful/helpful, I’d love to hear about that too.
https://jrsinclair.com/articles/2019/magical-mystical-js-transducers/
CC-MAIN-2021-31
refinedweb
1,997
58.79
aws-ses module Amazon Simple Email Service Construct LibraryAmazon Simple Email Service. Create a receipt rule set with rules and actions (actions can be found in the @aws-cdk/aws-ses-actions package): import s3 = require('@aws-cdk/aws-s3'); import ses = require('@aws-cdk/aws-ses'); import actions = require('@aws-cdk/aws-ses-actions'); import sns = require('@aws-cdk/aws-sns'); const bucket = new s3.Bucket(stack, 'Bucket'); const topic = new sns.Topic(stack, 'Topic'); new ses.ReceiptRuleSet(stack, 'RuleSet', { rules: [ { recipients: ['hello@aws.com'], actions: [ new actions.AddHeader({ name: 'X-Special-Header', value: 'aws' }), new actions.S3({ bucket, objectKeyPrefix: 'emails/', topic }) ], }, { recipients: ['aws.com'], actions: [ new actions.Sns({ topic }) ] } ] }); (Example not in your language? Click here.) Alternatively, rules can be added to a rule set: const ruleSet = new ses.ReceiptRuleSet(this, 'RuleSet'): const awsRule = ruleSet.addRule('Aws', { recipients: ['aws.com'] }); (Example not in your language? Click here.) And actions to rules: awsRule.addAction(new actions.Sns({ topic })); (Example not in your language? Click here.) When using addRule, the new rule is added after the last added rule unless after is specified. Drop spamsDrop spams A rule to drop spam can be added by setting dropSpam to true: new ses.ReceiptRuleSet(this, 'RuleSet', { dropSpam: true }); (Example not in your language? Click here.) This will add a rule at the top of the rule set with a Lambda action that stops processing messages that have at least one spam indicator. See Lambda Function Examples. Receipt filterReceipt filter Create a receipt filter: new ses.ReceiptFilter(this, 'Filter', { ip: '1.2.3.4/16' // Will be blocked }) (Example not in your language? Click here.) A white list filter is also available: new ses.WhiteListReceiptFilter(this, 'WhiteList', { ips: [ '10.0.0.0/16', '1.2.3.4/16', ] }); (Example not in your language? Click here.) This will first create a block all filter and then create allow filters for the listed ip addresses.
https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ses-readme.html
CC-MAIN-2020-05
refinedweb
320
53.68
Up to [DragonFly] / src / sys / dev / disk / fd Request diff between arbitrary revisions Keyword substitution: kv Default branch: MAIN Handle disklabels with the disk management layer instead of rolling our own in the floppy driver. Retain the floppy driver's format switching features via special fd0.<size> devices. Also fix a bug in FD_SOPTS where the floppy type table was being permanently overwritten. floppy device numbering has changed, update MAKEDEV appropriately. Remove PC98 support. timeout/untimeout ==> callout_* Split off the PCCARD specific driver parts of fd and sio and remove last uses of NCARD and use_card.h. The header will go with the NEWCARD merge. Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most ids have been removed from !lint sections and moved into comment sections. import from FreeBSD RELENG_4 1.20.2.3
http://www.dragonflybsd.org/cvsweb/src/sys/dev/disk/fd/fdc.h?f=h
CC-MAIN-2014-42
refinedweb
140
59.4
leap motion java sdk – max closes when running mxj Hello. I’m trying to write a Java External that can work with the Leap Motion device. in max.java.config.txt I configured the following: max.system.jar.dir /Volumes/2g-storage/projects/java-projects/jar/ this points to LeapJava.jar libLeap.dylib libLeapJava.dylib and I configured max.dynamic.class.dir /Volumes/2g-storage/projects/java-projects/leapmotion/piano/bin/ which points to the compiled classes now when I fire up max and try ‘mxj MaxLeapMotion’ the program just quits. it doesn’t show any segmentation fault error to report, it just closes. about support information: { "version" : "Version 6.1.3 (ac9dafd)", "platform" : "mac", "arch" : "x64", "osversion" : "Mac OS X Version 10.8.4 x86_64", "samplerate" : 44100, "iovs" : 64, "sigvs" : 64, "scheduler_in_audio_interrupt" : "off", "audio_drivername" : "Live", "audio_driver_subname" : "", "eventinterval" : 2, "overdrive" : "off", "mixerparallel" : "off", "mixercrossfade" : 0, "mixerlatency" : 30.0, "mixerramptime" : 10.0 } using max for live with ableton 9.0.5 and max 6.1.3 the problem occurs when I try to create a new leap motion Listener even if the Listener class is empty: ————- import com.leapmotion.leap.Listener public class TestListener extends Listener { } ———– when I try to instance the class the results are the same, max just closes right away with no pre-warning of any kind. ———————— import com.cycling74.max.DataTypes; import com.cycling74.max.MaxObject; import com.leapmotion.leap.Controller; public class MaxLeapMotion extends MaxObject { public void bang() { outlet(0, "congradulations!"); } public MaxLeapMotion() { declareOutlets(new int[]{DataTypes.LIST}); TestListener listener = new TestListener(); //new SampleListener(null); } } ————————– any ideas how to debug this issue further ? Anything in the OS X Console? Next step is to attach a Java debugger such as Eclipse and step through the code. I suspect something somewhere is calling System.exit(0). I actually wrote a mxj for Leap SDK myself. The problem is, that the Leap Java SDK includes a native dynamic library (dll on Win, dylib on Mac), to communicate with the Leap hardware. So to use this on a platform-agnostic java virtual machine, Java uses a mechanism called JNI (Java Native Interface). If the Java VM does not find the dll somewhere, the whole VM crashes. So this boils down to identify a place, where you can put leapjava.dylib. I did some research myself and you can view the readme of my leapjava mxj By the way: Do not confuse the leapjava.dylib/dll with leapjava.jar. The latter is the Java-side of the SDK so you got a control flow like: MaxMSP JavaVM / Your MXJ Leapjava.jar Leapjava.dylib The more to the right, the more nasty it gets. Hello Christoph, I am attempting to use your mxj in Windows 7 and I don’t have an issue loading java in Max but I do have this error: "could not load class semmd.leapmotion" I followed your instructions in the readme to copy your classes and help file as well as the LeapJava.rar, LeapJava.dll, and Leap.dll to the respective Max folders. However, the only item named semmd.leapmotion was the Max help file and I placed it in the Java/Help folder, so I’m not sure how to solve my problem. Any advice? Thanks There is a folder named "semdd", which contains the java file "leapmotion.class". Move the whole folder to cycling74/java/classes and the class should load without complaint. Regards, Christoph Hello Christoph, I tried to use your mxj in Windows 8.1 and it works on Max5 but not Max6. It seems to be a java problem. I get a message that reads: mxj: could not find Java 2 Runtime Environment. Error loading: (mxj) mxj_platform_init failed. Could not initialize the Java Runtime Environment. Please check your Java installation. Unable to create JVM I have a thread about the issue if you have time to go through and see if something is not working properly: Thanks!
https://cycling74.com/forums/topic/leap-motion-java-sdk-max-closes-when-running-mxj/
CC-MAIN-2015-11
refinedweb
656
59.3
Scout/HowTo/3.7/Add an icon Contents Add the icon file to the project In the client Plug-In (e.g. tutorialMiniCrm.client.tutorialMiniCrm) add the icon file to the resources/icons folder. Scout supports many different picture formats. You can use a PNG file that has a size of 16*16 pixels. Link your file to your application Open the Icons class in the shared (e.g. tutorialMiniCrm.shared.tutorialMiniCrm.Icons) and add a new line like this: public static final String UserHome ="home_red"; - Name of the constant is the name that you will use in your application. (e.g. UserHome) - Value is the name of your file without the extension. (e.g. home_red.png) Use your icon When you need to provide an Icon you can now use the Icons class. For example: @Override protected String getConfiguredIconId(){ return Icons.UserHome; } With the appropriate import: import tutorialMiniCrm.shared.tutorialMiniCrm.Icons; Of course the new icon is listed in the icon editor in the Scout SDK (Explorer View: Project > Shared > Icons, Object Properties View: Open icons editor). It is also available in the icon chooser field in order to configure quickly your GUI..
http://wiki.eclipse.org/Scout/HowTo/3.7/Add_an_icon
CC-MAIN-2015-32
refinedweb
194
65.32
Graphics.UI.Gtk.Gdk.EventM Contents Description Types and accessors to examine information in events. This module is not exposed by default and therefore has to be imported explicitly using: import Graphics.UI.Gtk.Gdk.EventM Word16 -. Event monad and type tags data EVisibility Source A tag for Visibility events. data EConfigure Source A tag for Configure events. data EProximity Source A tag for Proximity events. Instances data EWindowState Source A tag for WindowState event. data EOwnerChange Source A tag for OwnerChange events. Instances data EGrabBroken Source A tag for GrabBroken events. Accessor functions for event information eventWindow :: EventM any DrawWindowSource Retrieve the Graphics.UI.Gtk.Gdk.DrawWind Word16SourceArea :: EventM EExpose RectangleSource Query a bounding box of the region that needs to be updated. eventRegion :: EventM EExpose RegionSource Query the region that needs to be updated.Source The time (in milliseconds) when an event happened. This is used mostly for ordering events and responses to events. currentTime :: TimeStampSource Represents the current time, and can be used anywhere a time is expected. tryEvent :: EventM any () -> EventM any BoolSource Execute an event handler and assume it handled the event unless it threw a pattern match exception.
http://hackage.haskell.org/package/gtk-0.11.0/docs/Graphics-UI-Gtk-Gdk-EventM.html
CC-MAIN-2017-30
refinedweb
194
50.73
I am trying to read one input file of below format. Where Col[1] is x axis and Col[2] is y axis and col[3] is some name. I need to plot multiple line graphs for separate names of col[3]. Eg: Name sd with x,y values will have one line graph and name gg with relative x,y values will have another line graph. All in one output image but separate graphs. Is it possible with Python Matplotlib ? Pls do redirect me to any example. I have already checked couldn't find any. akdj 12:00 34515 sd sgqv 13:00 34626 sd dfbb 13:00 14215 gg ajdf 13:30 14224 gg dsfb 13:45 25672 FW sfhh 14:00 85597 ad Thanks for valuable suggestions You can use the condition z=='some tag' to index the x and y array Here's an example (based on the code in your previous question) that should do it. Use a set to automate the creation of tags: import csv import datetime as dt import numpy as np import matplotlib.pyplot as plt threshold = 30000 x,y,z = [],[],[] csv_reader = csv.reader(open('input.csv')) for line in csv_reader: y.append(int(line[2])) x.append(dt.datetime.strptime(line[1],'%H:%M')) z.append(line[3]) x=np.array(x) y=np.array(y) tags = list(set(z)) z=np.array(z) fig=plt.figure() for tag in tags: plt.plot(x[z==tag],y[z==tag],'o-',label=tag) fig.autofmt_xdate() plt.legend(loc=2) plt.savefig('test.png')
http://databasefaq.com/index.php/answer/3748/python-numpy-matplotlib-graph-plot-read-one-input-file-and-plot-multiple
CC-MAIN-2019-04
refinedweb
262
65.83
[DefaultMember("Item")] public class TriDiagonalMatrixF This is based on the wikipedia article: The entries in the matrix on a particular row are A[i], B[i], and C[i] where i is the row index. B is the main diagonal, and so for an NxN matrix B is length N and all elements are used. So for row 0, the first two values are B[0] and C[0]. And for row N-1, the last two values are A[N-1] and B[N-1]. That means that A[0] is not actually on the matrix and is therefore never used, and same with C[N-1]. System.Object SciChart.Charting.Model.Filters.SplineInterpolationFilter.TriDiagonalMatrixF Target Platforms: Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
https://www.scichart.com/documentation/v5.x/SciChart.Charting~SciChart.Charting.Model.Filters.SplineInterpolationFilter.TriDiagonalMatrixF.html
CC-MAIN-2018-47
refinedweb
150
57.91
Note: The blogger is not a Python professional programmer. He is 12 years old and Python is less than 1 year old. 😃 Hope to help some Python novices through this column! Hi~ Hello everyone! As we said in the last blog post, if there are some functions that can only be implemented with tens of thousands of lines without a library, you can only write them yourself, then how to simplify the process of copying and pasting tens of thousands of lines? What is a function? Well, don't worry, the function is actually we go to the restaurant to eat and ask the waiter to pack. No no no, that's it, at least in Python. Let's illustrate with an example. How to define a function Well, let’s talk about how to define a function first. def blablabla(): print('I am the content of the function! Oye!') a = True while a: print('Follow me now!') a = False A few points to note 1. Naming conventions for functions same as variable - To be understood. - The function name must be a combination of English letters, numbers and underscores. Numbers cannot be the first character of variable names. - Variable names also cannot have the same names as Python built-ins (that is, built-in functions). Otherwise, Python students should be confused again. 2. Punctuation The following format must be followed when defining a function: def functionname(): And the code inside the function must be indented. If you forget to indent or delete the indent, just press the Tab key before that line. How to run a function very simple~ After defining the function name, enter it directly Function name() For example mine: blablabla() The result of running is: Remember: there is one and only this way to run a function! ! At this point, you may find a problem. Yes, so how to solve this problem? Yes, we can put things inside parentheses that are "things" like variables, but not variables. What is this like? When you go to pack, you tell the waiter: So, how to define such a function? let's go~ How to define a function with parameters def blablabla(name): print('I am the content of the function! Oye!') a = True while a: print('Follow me now!',name) a = False Just put the name of the variable element in parentheses, and it works the same: How to run a function with parameters blablabla('Tool man 001 A') Running it will get: I am the content of the function! Oye! Follow me now! Tool man 001A Pay attention to several common bugs 1. Where you give parameters, but not at runtime Negative example: def blablabla(name): print('I am the content of the function! Oye!') a = True while a: print('Follow me now!',name) blablabla() Error message: Note: "Variable elements" are informally called "parameters". 2. Conversely, you have given the parameters, but not the place where the parameters are given Negative example: def blablabla(): print('I am the content of the function! Oye!') a = True while a: print('Follow me now!',name) a = False blablabla('hhh') Error message: Note: "Variable elements" are informally called "parameters". How to define and run a function with multiple arguments Hey this is interesting. In fact, it is separated by commas. def all_about_you(name,sex,age,hobby): print('wow, your name is',name,'and your sex is',sex,'and you are',age,'years old and you like',hobby) all_about_you('xiaocao162020','boy',12,'writing Python') Running this will get: wow, your name is xiaocao162020 and your sex is boy and you are 12 years old and you like writing Python Ah, don't worry about the problem of no punctuation, it's just for fun, this one also has several bug s, for example, if you give 3 variable elements, only 2 variable elements are entered at runtime, or vice versa. will report errors. Let me show you another BUG, to be precise, it is not a BUG: def all_about_you(name,sex,age,hobby): print('wow, your name is',name,'and your sex is',sex,'and you are',age,'years old and you like',hobby) all_about_you('writing Python','12','boy','xiaocao162020') Run, no error, but display: wow, your name is writing Python and your sex is 12 and you are boy years old and you like xiaocao162020 The translation will definitely kill you with laughter: To make sure this doesn't happen, we can enter in order or like this: def all_about_you(name,sex,age,hobby): print('wow, your name is',name,'and your sex is',sex,'and you are',age,'years old and you like',hobby) all_about_you(hobby='writing Python',age='12',sex='boy',name='xiaocao162020') Do you have a very intimate feeling? yes! we Manipulating files with Python The code for opening the file in that article is exactly: file1 = open('blablabla.txt',encoding='utf-8',mode='r') That's right, exactly what you think it is! open is actually a built-in function of Python! Built-in functions and custom functions work exactly the same way! Well, this seems to be the end, if you have any questions, please contact me~
https://algorithm.zone/blogs/explain-the-custom-functions-in-python-with-the-story-of-restaurant-packaging.html
CC-MAIN-2022-27
refinedweb
860
63.29
BBC micro:bit First MicroPython Program Introduction If you have taken the trouble to download the Mu software and have installed the driver, you need a quick way to test that everything works. We will start by displaying some information on the LED matrix. Programming Type the following into the editor and then press the Flash button. from microbit import * display.scroll("I am a micro:bit.") The first line of this program imports the library of micro:bit functions. The second line scrolls a message across the screen. This happens only once. This next program uses a while loop to repeatedly scroll the message across the screen. The sleep statement causes the micro:bit to pause for a set number of milliseconds. from microbit import * while True: display.scroll("I am a micro:bit.") sleep(5000) While loops repeat as long as the specified condition evaluates to true. In this case, we have said that the condition is true. That creates an infinite loop. The code that needs to be repeated is indented. You can use this technique for a game loop and as an equivalent to the loop() procedure that you write with an Arduino sketch. Python is case sensitive. You will need to write the code exactly as you see in the examples or you will get an error. We can use a break statement if there is a reason that we need to break out of the infinite loop. The following script does just that. from microbit import * while True: if button_a.is_pressed(): break display.scroll("I am a micro:bit.") sleep(5000) display.show(Image.HAPPY) If you hold down the A button, the program breaks out of the loop and displays a happy face on the LED matrix. Challenge Take your first steps and play around with the statements on this page. You need to check that the editor and COM port driver are working anyway.
http://multiwingspan.co.uk/micro.php?page=first
CC-MAIN-2017-22
refinedweb
322
76.93
Currently, when user iterates through various windows visible after start, it can "activate" a lot of different functionality just be watching. Most visible example of this phenomena is "Services" tab. It few nodes, each coming from different module, each doing something useless for majority of users, yet just clicking and making "Services" tab visible loads all these nodes (and many of associated classes) into memory. It is desirable to eliminate such lazy initialization and rather wait for the user to really choose which of available nodes he wants to use. This can be achieved by declarative registration of icon, name, and displayname and delaying loading of the rest of the node till the user expands it or invokes popup menu. I should also mention that the primary motivation for fixing the problem is issue 158765 - e.g. ergonomic IDE needs a way to analyse registered nodes and providing icon&co. declaratively with be of great help. Created attachment 78924 [details] API and its use throughout the IDE There is no impl of LazyNode visible in the patch. I presume it delegates to original upon addNotify of children, or getActions; and thereafter delegates all methods to original (e.g. getPasteTypes, ...). [JG01] Do not make people write this stuff in their layer; define an annotation. For example, I would like to see public class HudsonRootNode ... { ... @Node.Registration(location="UI/Services", name="hudson", displayName="org.netbeans.modules.hudson.ui.nodes.Bundle#LBL_HudsonNode", icon="org/netbeans/modules/hudson/ui/resources/hudson.png", position=488) public static Node getDefault() {...} ... } The processor would be trivial to implement. But consider instead defining a more specialized annotation in an appropriate module specifically for the Services tab. This would avoid the need to hardcode the UI/Runtime path and make code clearer. E.g. @ServicesNodeRegistration(name="hudson", displayName="org.netbeans.modules.hudson.ui.nodes.Bundle#LBL_HudsonNode", icon="org/netbeans/modules/hudson/ui/resources/hudson.png", position=488) public static Node getDefault() {...} Of course such an annotation would be less general, but we might want specialized annotations for other purposes anyway, and I don't know of any other place in the IDE where this kind of registration of singleton nodes (as opposed to node factories) would make sense. The NodeOp.factory method could stay where it is for possible future use - just the annotation would be in a different module. The only question is which module to put the annotation in. One possibility would be openide.windows. UI/Runtime/ is defined by core.ide, the TopComponent (NbMainExplorer.MainTab.createEnvironmentTab) is implemented by o.n.core, and it is registered in core.execution - i.e. a mess. Ideally the folder, TC, and annotation would all be defined in the same module. A new module could be created for the purpose, or as the most appropriate-seeming existing module, core.ide could be given a public API (with just the annotation) and the TC and its registration moved there. (AFAIK there is no other use of NbMainExplorer and it could probably be killed.) [JG02] Is there any purpose for having the public factory method? There is no situation where you would want to call this method overload (you have to instantiate the original node just to pass it in!), so better to remove it. Created attachment 78937 [details] Patch with new classes in API as well as change of implementation Re. JG01 - I happily provide annotation if there is sensible place to put it to. Creating new module however seems like overkill to me. Rather than that I prefer to keep just layer based registration. Re. JG02 - The factory method is the only place to put the documentation to (in absence of the annotation). It used to be good habit to have both methods one visible in JavaDoc with all docs including layer one, one callable from layer. If JG01 is resolved, I am OK with deleting the public method. JG01 - I suggest core.ide. Would that work? I could if necessary help with prep work - moving the current Services tab infra to that module - which would be desirable independently of this issue. JG02 - barring JG01, info could be in class Javadoc. [JG03] LazyNode should behave sensibly if optional attributes are missing. At least it seems that shortDescription is optional (e.g. HudsonRootNode does not set it currently). Not sure if setShortDescription(null) is legitimate. [JG04] switchToOriginal should handle the case that map.get("original") returns null, e.g. after a CNFE is thrown by XMLFS. [JG05] Careful with JUnit 4, it probably will not work correctly with NbTestCase, and we need to use NbTestCase so we can add @RandomlyFails etc. Re. core.ide - usually we want API to be in autoload module (although in case of compile time processor this may not be that important). core.ide can't be autoload. Moreover core.ide is in ideXY cluster, while the functionality is in platform. I don't think the module needs to be autoload. That is certainly appropriate for an API which is purely a bunch of Java classes you can use. But this deals with a major added GUI element, which you need to decide to enable. As to the cluster - NodeOp is indeed in the platform cluster, and that is fine. The Services tab is however defined, intentionally, in the ide cluster. And all potential users of the registration would also be in the ide cluster or higher; this GUI element is intended for use in an IDE. Putting the registration in a module in the platform cluster would be incorrect. Preparation: Services tab moved to core.ide. core-main #99eb1a5de1b6 Integrated into 'main-golden', will be available in build *200903281400* on (upload may still be in progress) Changeset: User: Jesse Glick <jglick@netbeans.org> Log: #161286 prep: move Services tab into core.ide module. Created attachment 79153 [details] New patch with @annotations I'd like to integrate the change soon. JG02 still unaddressed in attached patch, JG03-05 as well I think though less important. [JG06] Modules using the new annotation should have a <run-dependency>; they really expect the Services tab to be there. [JG07] Replace if (reg.position() != Integer.MAX_VALUE) { f.intvalue("position", reg.position()); } with f.position(reg.position()); [JG08] Do not use both instanceFile here, as that indicates that you want to bind the instance to the annotated element, which is not the case; use only instanceAttribute. (An RFE for a method to create a nicely named file in a given folder based on the element name would be accepted.) [JG09] displayName in db.explorer.node.RootNode is malformed; use . not / as sep. [JG10] The tab is called "Services", not "Service", so suggest "ServicesTabNodeRegistration". ^ [JG11] core.ide should dep on new openide.nodes. Integrated into 'main-golden', will be available in build *200903311400* on (upload may still be in progress) Changeset: User: Jesse Glick <jglick@netbeans.org> Log: #161286 prep addendum: set icon for Services tab. core-main#fcbe7ad3185b Re. JG03 - imho the node behaves sensibly. setSD(null) seems to be allowed. Report a bug if you find otherwise. Re. JG04 - the code handles such situation by reporting an exception and continuing. I am not sure what else you want it to do. Re. JG05 - I do not plan to have unstable tests in this area. Re. JG08 - You want me to not use an API that works and report you an issue to create another API that will work!? Sorry, I don't get the point. Feel free to do it yourself. Otherwise I think I addressed your comments. Integrated into 'main-golden', will be available in build *200904020200* on (upload may still be in progress) Changeset: User: Jaroslav Tulach <jtulach@netbeans.org> Log: #161286: Addressing JG06 and JG11. E.g. fixing runtime dependencies of those who use the new annotation core-main#0109f9b6fc77 - fixing broken javadoc links btw. Jesse: now when all modules using @ServicesTabNodeRegistration have runtime dependency on core.ide, the core.ide itself shall be autoload, shall it not? core.ide defines a couple of other assorted UI elements. No strong opinion. Integrated into 'main-golden', will be available in build *200904031400* on (upload may still be in progress) Changeset: User: Jesse Glick <jglick@netbeans.org> Log: Dependencies added in 757b11c277c1 (for #161286) were invalid acc. to schema. Correcting, and also making sure this mistake does not happen again.
https://netbeans.org/bugzilla/show_bug.cgi?id=161286
CC-MAIN-2017-26
refinedweb
1,390
58.48
Strategies for corporate and institutional banking Big, bigger, biggest Market concentration will force middle-ranking banks to merge, shrink or die UPHEAVALS and mergers among the top global banks will go on until four or five giant firms look something like Citigroup today. This is the horrible conclusion of a study on the future of European corporate and institutional banking by Oliver, Wyman, a New York firm of management consultants, and Morgan Stanley, an investment bank. Horrible, that is, for second-tier European banks, such as ABN Amro, Commerzbank and Société Générale, which may be champions in their own country (the Netherlands, Germany and France respectively), but which have tried in vain to break into the businesses offered worldwide by the top tier. These businesses provide a better return on capital than does plain lending. For example, transaction services (handling cash and securities accounts) earns a return on capital of 50%, equity derivatives a return of 45%, and mergers and acquisitions a 35% return (see chart). A handful of familiar names—Citigroup, J.P. Morgan Chase, Goldman Sachs, Merrill Lynch—dominates these businesses, either because it takes a huge investment to build them, or because only top names are trusted. Yet only Citigroup offers corporate and institutional clients the full range of services, from loans to mergers and acquisitions, that makes it a true global behemoth. J.P. Morgan Chase, for instance, is strong in the debt and derivatives markets but weaker in investment banking. Even without being a behemoth, there are five other strategies that larger banks and investment banks might usefully follow, says the report. They can: use their balance sheet to sell credit products (as do J.P. Morgan Chase and Barclays); specialise in equity and advisory work (Goldman, Merrill and Morgan Stanley); process transactions worldwide (State Street and Bank of New York); specialise in the transfer of risk; or aim to be an investment bank on a regional scale. Second division As for the second-tier banks that have tried to be global, they face a tougher task. Many have a home country, or a market share within it, that is too small to underwrite international success. To survive, they will need either to make cross-border mergers in Europe (which are not happening yet), or to get out of unprofitable businesses. Until this year investment banking's rewards looked so good—roughly a 20% annual return on capital—that European banks have continued to hurl themselves like moths at the flame. Two or three of them will have to go, says the report. On cue, ABN Amro announced last week that it would cut back its investment banking in America. It has made gallant efforts to compete, but has been unable to build enough volume in transaction banking, asset management and mergers and acquisitions—or sufficient quality in corporate lending—to make those businesses competitive on a worldwide scale. Sergio Rial, on the board of ABN Amro, says defiantly that the bank is still strong in European and Asian equities. He also argues that a nascent equity culture in Europe, and particularly in Germany, will change the dynamics, favouring the nimble. “The pursuit of scale and market share is being challenged. It is not clear that there is a winning model,” Mr Rial says. Other second-tier banks may be in a sadder position. For example, Commerzbank has spent three years looking for a buyer. Yet it continues to pursue an expensive adventure in equity markets, arguing that this is what its German clients expect. On April 2nd a group of Commerzbank shareholders, calling itself Cobra, ended two years of efforts to find the bank a foreign owner and disbanded. In Europe, the market in which investment banks sell their services consists of around 3,000 companies and 600 investment firms. Investment banks earned revenues of euro82 billion ($76 billion) from selling them services in 2000, and euro76 billion in 2001. But over half this business comes from the biggest 250 companies and 100 investors, which prefer relationships with the top banks. So corporate concentration forces concentration among banks. In the hope of winning more profitable business, the second-tier banks offer loans to these companies at below their cost of capital. That will achieve nothing, the report suggests. There is excess capacity for lending to big companies. The growing number of mutual funds which invest in loans, and which have no regulatory capital costs, are forcing prices down. And new international capital rules proposed for banks, if and when they come into force in 2006, are likely to free up even more capacity, making things worse. In this bleak landscape, mergers look attractive. Tomorrow's potential giants—Deutsche, J.P. Morgan Chase, Credit Suisse, and UBS, also of Switzerland—were built by mergers; so was Citigroup. Yet are their shareholders getting a fair deal? In 2001, corporate and institutional banking brought a risk-adjusted return to shareholders of around 21% of total revenues, the report says. That was dwarfed by the 40% of revenues paid out in bankers' salaries and bonuses. Top staff, who can easily move to a rival firm, will continue to enjoy fat rewards. Whereas Credit Suisse laid off 300 investment bankers this week, to cut high staffing costs, Deutsche Bank said only two weeks ago that it would ask shareholders' consent to award euro1.8 billion-worth of stock options to its senior bankers. Shareholders in these banks must wonder: do I back an investment bank that could reach the top five? Do I hunt for merger prospects among the second tier? Or do I dump my shares? From the print edition: Finance and economics Excerpts from the print edition & blogs » Editor's Highlights, The World This Week, and more »
http://www.economist.com/node/1067052
CC-MAIN-2013-48
refinedweb
960
60.55
Back to: C#.NET Tutorials For Beginners and Professionals Garbage Collector in .NET Framework In this article, I am going to discuss the Garbage Collector in .NET Framework with Examples. Please read our previous article where we discussed Managed and Unmanaged Code in .NET Application. At the end of this article, you will understand what is Garbage Collector in .NET Framework and how does it work? As part of this article, we are going to discuss the following pointers in detail. - What is Garbage Collector in .NET? - What are the different Generations of Garbage collectors? - How using a destructor in a class we end up in a double garbage collector loop? - How we can solve the double loop problems using finalize dispose patterns? What is Garbage Collector in .NET Application? When a dot net application runs, lots of objects are created. At a given point in time, it is possible that some of those objects are not used by the application. Garbage Collector in .NET Framework is nothing but is a Small Routine or you can say it’s a Background Process Thread that runs periodically and try to identify what objects are not being used currently by the application and de-allocates the memory of those objects. So, Garbage Collector is nothing but, it is a feature provided by CLR which helps us to clean or destroy unused managed objects. By cleaning or destroying those unused managed objects, basically reclaims the memory. Note: The Garbage Collector will destroy only the unused managed objects. It does not clean unmanaged objects. If you want to learn what exactly is managed and unmanaged objects, please read our previous article. Garbage Collector Generations in .NET: Let us understand what Garbage Collector Generations are and how does it affect Garbage Collector performance? There are three generations. They are Generation 0, Generation 1, and Generation 2. Understanding Generation 0, 1, and 2: Let say you have a simple application called App1. As soon as the application started it creates 5 managed objects. Whenever any new objects (fresh objects) are created, they are moved into a bucket called Generation 0. For better understanding please have a look at the following image. We know our hero Mr. Garbage Collector runs continuously as a background process thread to check whether there are any unused managed objects so that it reclaims the memory by cleaning those objects. Now, let say two objects (Object1 and Object2) are not needed by the application. So, Garbage Collector will destroy these two objects (Object1 and Object2) and reclaims the memory from Generation 0 bucket. But the remaining three objects (Object3, Object4, and Object5) are still needed by the application. So, the Garbage collector will not clean those three objects. What Garbage Collector will do is, he will move those three managed objects (Object3, Object4, and Object5) to Generation 1 bucket as shown in the below image. Now, let say your application creates two more fresh objects (Object6 and Object7). As fresh objects, they should be created in Generation 0 bucket as shown in the below image. Now, again Garbage Collector runs and it comes to Generation 0 bucket and checks which objects are used. Let say both objects (Object6 and Object7) are unused by the application, so it will remove both the objects and reclaims the memory. Now, it goes to the Generation 1 bucket, and checks which object are unused. Let say Object4 and Object5 are still needed by the application while object3 is not needed. So, what Garbage Collector will do is, it will destroy Object3 and reclaims the memory as well as it will move Objec4 and Object5 to Generation 2 bucket which is shown in the below image. What are Generations? Generations are nothing but, will define how long the objects are staying in the memory. Now the question that should come to your mind is why do we need Generations? Why do we need Generations? Normally, when we are working with big applications, they can create thousands of objects. So, for each of these objects, if the garbage collector goes and checks if they are needed or not, it’s really pain or it’s a bulky process. By creating such generations what it means if an object in Generation 2 buckets it means the Garbage Collector will do fewer visits to this bucket. The reason is, if an object move to Generation 2, it means it will stay more time in the memory. It’s no point going and checking them again and again. So, in simple words, we can say that Generations 0, 1, and 2 will helps to increase the performance of the Garbage Collector. The more the objects in Gen 0, the better the performance and the more the memory will be utilized in an optimal manner. How using a destructor in a class we end up in a double garbage collector loop? As we already discussed garbage collectors will only clean up the managed code. In other words, for any kind of unmanaged code, for those codes to clean up has to be provided by unmanaged code, the garbage collector does not have any control over them to clean up the memory. For example, let say you have a class called MyClass in VB6, then you have to expose some function let say CLeanUp() and in that function, you have to write the logic to clean up the unmanaged code. From your dot net code, you simply need to call that method (CLeanUp()) to initiate the clean-up. The point, or the section from where you would like to call the Clean-Up is the destructor of a class. This looks to be the best place to write the clean-up code. But, there is a big problem associated with it when you write clean-up in a destructor. Let us understand what the problem is? When you define a destructor in your class, the Garbage Collector before destroying the object, will go and ask the question to the class, do you have a destructor, if you have a destructor, then move the object to the next generation bucket. In other words, it will not clean up the object having a destructor at that moment itself even though it is not used. So, it will wait for the destructor to run, and then it will go and clean up the object. Because of this, you will find more objects in generation 1 and Generation 2 as compared to Generation 0. Example: Using Destructor Please create a console application and then copy and paste the following code in it in the Program class. using System; namespace GCDemo { class Program { static void Main(string[] args) { for(int i = 0; i <= 1000000; i++) { MyClass obj = new MyClass(); } Console.Read(); } } public class MyClass { ~MyClass() { //Unmanaged code clean up } } } So, if you writing the clean-up code in your destructor, then you will end up creating more objects in Generation 1 and Generation 2 which means you are not utilizing the memory properly. How to Overcome the above Problem? This problem can be overcome by using something called finalize dispose pattern. In order to implement this, your class should implement the IDisposable interface and provide the implementation for the Dispose method. Within the Dispose method, you need to write the clean-up code for unmanaged objects and in the end, you need to call GC.SuppressFinalize(true) method by passing true as the input value. This method tells suppress any kind of destructor and just go and clean up the objects. For better understanding, please have a look at the following image. Once you have used to object, then you need to call the Dispose method so that the double garbage collector loop will not happen as shown below. The complete code is given below. using System; namespace GCDemo { class Program { static void Main(string[] args) { for(int i = 0; i <= 1000000; i++) { MyClass obj = new MyClass(); obj.Dispose(); } Console.Read(); } } public class MyClass : IDisposable { ~MyClass() { } public void Dispose() { //Unmanaged code clean up GC.SuppressFinalize(true); } } } Now, the question that should come to your mind is why the destructor is there? The reason is as a developer you may forget to call the Dispose method once you use the object. In that case, the destructor will invoke and it will go and clean up the object. In the next article, I am going to discuss Assembly, EXE, and DLL in detail. Here, in this article, I try to explain the Garbage Collector in the C#.NET Application with examples. I hope you enjoy this Garbage Collector in C# article and I also hope that now you understood how the garbage collector works in C#. 2 thoughts on “Garbage Collector in .NET Framework” Good , thank you …… Very good explanation with simple words. Thank you so much 🤝
https://dotnettutorials.net/lesson/garbage-collector/
CC-MAIN-2022-21
refinedweb
1,477
63.9
This is how to use Codesmith professional version 5.1 without visual studio with Postgresql to generate nhibernate templates. - First download the Npgsql (version Npgsql2.0.2-bin-ms.net.zip). Extract and copy the "Npgsql.dll" and Mono.Security.dll" files to GAC (c:\windows\assembly). Note: This version of npgsql was determined from the dll not found error emitted when your test connection in Codesmith add data source dialog. - Now open "CodeSmith Studio". - In the "Schema Explorer" docking window click "Manage Data Sources". Next click "Add". - Name your datasource whatever you want. (hence referred to as "yourdatasource") - Select PostgreSQLSchemaProvider. - Put in the connection string. - Your database connection is setup. - In the "template explorer" click on "create template folder shortcut" icon in the toolbar to create a shortcut to the folder you want to create the Codesmith project in. - right click the newly created "template folder shortcut" and select "New->Codesmith Project". - Right click the newly create project and select "Add Output". Browsed and added the following template "C:\Users\Basiee\Documents\CodeSmith\Samples\v5.1\Templates\Frameworks\NHibernate\CSharp". Of course your username / version of codesmith / version of operating system come into play for this address. - Select your "Source Database" to be "yourdatasource" whatever you called it. - Modify your "assembly name" (required ... for your ease) as well as the namespaces (optional) to keep them consistent with the assembly name. - Now right click the project (in Template Explorer) and select "Generate Outputs". Enjoy!
http://basaratali.blogspot.com/2010/08/using-codesmith-51-with-postgresql-for.html
CC-MAIN-2017-34
refinedweb
244
61.73
#include <qvaluestack.h> Inherits QValueList<T>. Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient. See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes, and Non-GUI Classes. See also top() and push(). This function is equivalent to append(). See also pop() and top(). This function is equivalent to last(). See also pop(), push(), and QValueList::fromLast(). Returns a reference to the top item of the stack or the item referenced by end() if no such item exists. This function is equivalent to last(). See also pop(), push(), and QValueList::fromLast().
http://man.linuxmanpages.com/man3/QValueStack.3qt.php
crawl-003
refinedweb
109
62.85
Here are program instructions. IT SAYS "segmentation fault" WHEN RAN. Specifications You must create a Ship class: The Ship class maintains the position data for each ship/vessel and its distance from another Ship. It has a default constructor, which sets all of the member data to zero, and a non-default constructor that has three parameters, one for each coordinate. It contains methods to calculate the distance to another Ship and to retrieve that distance later. You must also overload a relational operator, such as < or >, for use in a sorting routine. Thus, a Ship object can report whether or not its distance is less than or greater than that of another Ship object. When you input the position data for your warship, you must use that data to create a Ship object dynamically. After reading in the number of enemy vessels, you must dynamically create an array of Ship objects to hold the enemy vessel data. You must create a separate function for reading in the data for the enemy vessels. After you read in the data for each enemy vessel, you must use the non-default constructor to create a Ship object and then assign it to a slot in the array. You will then call the method to calculate the distance from the warship. After all of the data is read, you must sort the enemy vessels by their distances from the warship. You must write a separate function for sorting. You must output the distances in sorted order. You must write a separate function to output this data. Sample position data is available in a file named positions.txt. Each line in the file contains a single position, with each coordinate separated by a space. For example, the line of data: 10 30 85 represents the position (10,30,85) in x,y,z coordinates. The first line in the file contains the position of your warship, the next line contains the number of enemy vessels, and the remaining lines each contain the position of a single enemy vessel. You must deallocate all dynamically-allocated memory. Output Your output should look as follows: There are 7 enemy vessels Sorted distances: 47 55 76 85 100 198 425 main.cpp #include <iostream> #include "Ship.h" using namespace std; int main() { int x, y, z; int amount; cout << "Please enter your ship data" << endl; cin >> x; cin >> y; cin >> z; Ship * myLocation = new Ship(x, y, z); cout << "How many ships are there?" << endl; cin >> amount; Ship * ships = new Ship[amount]; for (int i = 0; i < amount; i++) { ships[i] = ships[i].getCoordinates(); } for (int j = 0; j < amount; j++) { ships[j].setDistance(*myLocation, ships[j]); } ships[amount].sortDistance(&ships[amount], amount); ships[amount].outputDistance(&ships[amount], amount); return 0; } ship.h class Ship { protected: int x, y, z; float distance; Ship * ships; public: Ship(); Ship(int, int, int); ~Ship(); Ship & getCoordinates(); void setDistance(Ship, Ship); float getDistance(); bool operator<(Ship &); void sortDistance(Ship *, int); void outputDistance(Ship *, int); }; ship.cpp Ship::Ship():x(0), y(0), z(0), distance(0) { } Ship::Ship(int init_x, int init_y, int init_z): x(init_x), y(init_y), z(init_z) { } Ship::~Ship() { delete [] ships; } Ship & Ship::getCoordinates() { cout << "Please eneter the coordinates of ship" << endl; cin >> x; cin >> y; cin >> z; Ship * s = new Ship(x, y, z); return *s; } void Ship::setDistance(Ship s1, Ship s2) { distance = sqrt(((float)(s1.x - s2.x)*(s1.x - s2.x)) + ((s1.y - s2.y)*(s1.y - s2.y)) + ((s1.z - s2.z)*(s1.z - s2.z))); } float Ship::getDistance() { return distance; } bool Ship::operator<(Ship & other) { if (distance < other.distance) return true; else return false; } void Ship::sortDistance(Ship * new_ships, int number) { for (int i = 0; i < number - 1; i++) { for (int j = 0; j < number; j++) { if (new_ships[i] < new_ships[j]) { Ship temp; temp = new_ships[i]; new_ships[i] = ships[j]; new_ships[j] = temp; } } } } void Ship::outputDistance(Ship * new_ships, int number) { for (int i = 0; i < number; i++) { cout << "This is what ship " << i << " should be" << endl; } } Edited 4 Years Ago by Adnan671: n/a
https://www.daniweb.com/programming/software-development/threads/412572/how-can-i-fix-this-program
CC-MAIN-2016-50
refinedweb
681
61.56
Mongoose native SPI driver for ADS7843/XPT2046 Touch Screen Controller ADS7843/XPT2046 is a chip that is connected to a resistive touchscreen. The touchscreen has resistance in the X and Y directions separately. When the user touches the touchscreen a resistance in both directions is detected by the touchscreen controller. The touchscreen controller records the X and Y resistance changes using an ADC that can measure the voltage from the resistance changes in the X an Y directions. A schematic of the test board used is included in this project. This driver initializes the chip and allows the user to register a callback, which will be called each time the driver senses a touch ( TOUCH_DOWN) or a release ( TOUCH_UP) event. The callback function will be given the X and Y coordinates where the user pressed the screen. The X and Y coordinates are passed in the mgos_ads7843_event_data structure. The x and y attributes are values in screen pixels. The SPI bus must be connected to the screen via 5 signals. These are MOSI, MISO, SCK, /CS and /IRQ. When the screen is touched by the user the /IRQ line goes low. In the microcontroller code this causes an interrupt to occur. The interrupt service routine then reads the X and Y ADC values from the ADS7843 device (using the MOSI, MISO, SCK, /CS signals). The interrupt service routine then converts these ADC values into screen pixel positions. Once this is done a callback function is called. A pointer to a structure that holds the above X and y values along with some other data is passed to the callback function. The driver uses the Mongoose native SPI driver. It is configured by setting up the MOSI, MISO, SCLK pins and assigning one of the three available CS positions, in this example we use CS1: config_schema: - ["spi.enable", true] - ["spi.mosi_gpio", 23] - ["spi.miso_gpio", 19] - ["spi.sclk_gpio", 18] - ["spi.cs1_gpio", 27 ] # This defines the ADS7843 SPI chip select pin - ["ads7843", "o", {title: "ADS7843/XPT2046 TouchScreen"}] - ["ads7843.cs_index", "i", 1, {title: "spi.cs*_gpio index, 0, 1 or 2"}] # This defines the SPI CS line to use (0, 1 or 2) - ["ads7843.irq_pin", "i", 25, {title: "IRQ pin (taken low when the display is touched.)"}] - ["ads7843.x_pixels", "i", 320, {title: "The display pixel count in the horizontal direction"}] - ["ads7843.y_pixels", "i", 240, {title: "The display pixel count in the vertical direction"}] - ["ads7843.flip_x", "i", 0, {title: "Flip the X direction (0/1, 0 = no flip). Use this if the x direction is reversed."}] - ["ads7843.flip_y", "i", 0, {title: "Flip the Y direction (0/1, 0 = no flip). Use this if the y direction is reversed."}] - ["ads7843.flip_x_y", "i", 0, {title: "Flip the X and Y directions (0/1, 0 = no flip). Use this is if the display is upside down."}] - ["ads7843.min_x_adc", "i", 12, {title: "The min X axis ADC calibration value. Enter the value from debug output (min adc x value at screen edge)."}] - ["ads7843.max_x_adc", "i", 121, {title: "The max X axis ADC calibration value. Enter the value from debug output (max adc x value at screen edge)."}] - ["ads7843.min_y_adc", "i", 7, {title: "The min Y axis ADC calibration value. Enter the value from debug output (min adc y value at screen edge)."}] - ["ads7843.max_y_adc", "i", 118, {title: "The max Y axis ADC calibration value. Enter the value from debug output (max adc y value at screen edge)."}] #include "mgos.h" #include "mgos_ads7843.h" static void touch_handler(struct mgos_ads7843_event_data *event_data) { if (!event_data) { return; } LOG(LL_INFO, ("orientation=%s", event_data->orientation ? "PORTRAIT" : "LANDSCAPE")); LOG(LL_INFO, ("Touch %s, down for %.1f seconds", event_data->direction==TOUCH_UP?"UP":"DOWN", event_data->down_seconds)); LOG(LL_INFO, ("pixels x/y = %d/%d, adc x/y = %d/%d", event_data->x, event_data->y, event_data->x_adc, event_data->y_adc)); } enum mgos_app_init_result mgos_app_init(void) { mgos_ads7843_set_handler(touch_handler); return MGOS_APP_INIT_SUCCESS; } The min_x_adc, max_x_adc, min_y_adc and max_y_adc should be set in the mos.yml file in order to calibrate the display. This allows the pixel positions returned to accurately represent the position the display was touched. In order to calibrate the display run the example program and touch each edge of the display. When running the example application debug data is sent out on the serial port when the display is touched. E.G [Jan 9 02:36:10.761] touch_handler orientation=PORTRAIT [Jan 9 02:36:10.766] touch_handler Touch DOWN, down for 0.0 seconds [Jan 9 02:36:10.772] touch_handler pixels x/y = 0/4, adc x/y = 10/9 The above shows the top left corner of the display being touched. The 'adc x/y = 10/9' text contains the min X and Y values. The min_x_adc and min_y_adc attributes in the example mos.yml should be set to the values found. This should be repeated for the bottom right corner of the display using the max_x_adc and max_y_adc values. E.G [Jan 9 02:36:15.110] touch_handler orientation=PORTRAIT [Jan 9 02:36:15.115] touch_handler Touch DOWN, down for 0.3 seconds [Jan 9 02:36:15.120] touch_handler pixels x/y = 317/233, adc x/y = 120/115 This driver has been tested with the following display in all four orientations using a modified version of the following project
https://mongoose-os.com/docs/mongoose-os/api/drivers/ads7843-spi.md
CC-MAIN-2022-05
refinedweb
871
67.96
#include <deal.II/base/logstream.h> A class that simplifies the process of execution logging. It does so by providing The usual usage of this class is through the pregenerated object deallog. Typical setup steps are: deallog.depth_console(n): restrict output on screen to outer loops. deallog.attach(std::ostream): write logging information into a file. deallog.depth_file(n): restrict output to file to outer loops. Before entering a new phase of your program, e.g. a new loop, a new prefix can be set via LogStream::Prefix p("loopname");. The destructor of the prefix will pop the prefix text from the stack. Write via the << operator, deallog << "This is a log notice"; will be buffered thread locally until a std::flush or std::endl is encountered, which will trigger a writeout to the console and, if set up, the log file. In the vicinity of concurrent threads, LogStream behaves in the following manner: <<(or with one of the special member functions) is buffered in a thread-local storage. std::flushor std::endlwill trigger a writeout to the console and (if attached) to the file stream. This writeout is sequentialized so that output from concurrent threads don't interleave. Definition at line 82 of file logstream.h. Standard constructor. The standard output stream to std::cout. Definition at line 75 of file logstream.cc. Destructor. Definition at line 89 of file logstream.cc. Enable output to a second stream o. Definition at line 219 of file logstream.cc. Disable output to the second stream. You may want to call close on the stream that was previously attached to this object. Definition at line 232 of file logstream.cc. Return the default stream ( std_out). Definition at line 240 of file logstream.cc. Return the file stream. Definition at line 271 of file logstream.cc. Return true if file stream has already been attached, false otherwise. Definition at line 282 of file logstream.cc. Return the prefix string. Definition at line 290 of file logstream.cc. Push another prefix on the stack. Prefixes are automatically separated by a colon and there is a double colon after the last prefix. A simpler way to add a prefix (without the manual need to add the corresponding pop()) is to use the LogStream::Prefix class. Using that class has the advantage that the corresponding pop() call is issued whenever the Prefix object goes out of scope – either at the end of the code block, at the nearest return statement, or because an intermediate function call results in an exception that is not immediately caught. Definition at line 303 of file logstream.cc. Remove the last prefix added with push(). Definition at line 317 of file logstream.cc. Maximum number of levels to be printed on the console. The default is 0, which will not generate any output. This function allows one to restrict console output to the highest levels of iterations. Only output with less than n prefixes is printed. By calling this function with n=0, no console output will be written. See step-3 for an example usage of this method. The previous value of this parameter is returned. Definition at line 350 of file logstream.cc. Maximum number of levels to be written to the log file. The functionality is the same as depth_console, nevertheless, this function should be used with care, since it may spoil the value of a log file. The previous value of this parameter is returned. Definition at line 361 of file logstream.cc. Log the thread id. Definition at line 372 of file logstream.cc. set the precision for the underlying stream and returns the previous stream precision. This function mimics Definition at line 334 of file logstream.cc. set the width for the underlying stream and returns the previous stream width. This function mimics Definition at line 342 of file logstream.cc. set the flags for the underlying stream and returns the previous stream flags. This function mimics Definition at line 326 of file logstream.cc. Treat ostream manipulators. This passes on the whole thing to the template function with the exception of the std::endl manipulator, for which special action is performed: write the temporary stream buffer including a header to the file and std::cout and empty the buffer. An overload of this function is needed anyway, since the compiler can't bind manipulators like std::endl directly to template arguments T like in the previous general template. This is due to the fact that std::endl is actually an overloaded set of functions for std::ostream, std::wostream, and potentially more of this kind. This function is therefore necessary to pick one element from this overload set. Definition at line 126 of file logstream.cc. Return an estimate for the memory consumption, in bytes, of this object. This is not exact (but will usually be close) because calculating the memory usage of trees (e.g., std::map) is difficult. Internal wrapper around thread-local prefixes. This private function will return the correct internal prefix stack. More important, a new thread- local stack will be copied from the current stack of the "blessed" thread that created this LogStream instance (usually, in the case of deallog, the "main" thread). Definition at line 383 of file logstream.cc. Print head of line. Definition at line 403 of file logstream.cc. Internal wrapper around "thread local" outstreams. This private function will return the correct internal ostringstream buffer for operator<<. Definition at line 248 of file logstream.cc. Output a constant something through LogStream: Definition at line 406 of file logstream.h. Stack of strings which are printed at the beginning of each line to allow identification where the output was generated. Definition at line 321 of file logstream.h. We record the thread id of the thread creating this object. We need this information to "steal" the current prefix from this "parent" thread on first use of deallog on a new thread. Definition at line 328 of file logstream.h. Default stream, where the output is to go to. This stream defaults to std::cout, but can be set to another stream through the constructor. Definition at line 335 of file logstream.h. Pointer to a stream, where a copy of the output is to go to. Usually, this will be a file stream. You can set and reset this stream by the attach function. Definition at line 343 of file logstream.h. Value denoting the number of prefixes to be printed to the standard output. If more than this number of prefixes is pushed to the stack, then no output will be generated until the number of prefixes shrinks back below this number. Definition at line 351 of file logstream.h. Same for the maximum depth of prefixes for output to a file. Definition at line 356 of file logstream.h. Flag for printing thread id. Definition at line 361 of file logstream.h. A flag indicating whether output is currently at a new line Definition at line 366 of file logstream.h. We use our thread local storage facility to generate a stringstream for every thread that sends log messages. Definition at line 385 of file logstream.h.
https://www.dealii.org/developer/doxygen/deal.II/classLogStream.html
CC-MAIN-2020-34
refinedweb
1,203
68.16
On Sat, May 09, 2009 at 11:13:17AM +0200, martin f krafft wrote: > also sprach Stefano Zacchiroli <z...@debian.org> [2009.05.07.1902 +0200]: > > When I, as a newcomer of a given repo, do "git tag" I know I'm > > looking at a lot of "not current" information. On the contrary, > > when I do "git branch" I start trying figure out what each branch > > means. Having around a lot of no longer used branches is very > > annoying in that respect. > > Keep in mind that the branches accumulate remotely, so you'd have to > pass -r or -a to git-branch to be exposed to them. > > Obviously, any curious newcomer will do that, but then, a sane > convention like Manoj hinted at will help, because you'd have to be > amazingly curious to realy wonder about branches in the obsolete/* > namespace. > > Anyway, unfortunately, published branches cannot be renamed with > Git, or retired, or anything of that sort, so the concern is valid: > you'd have to start a new feature branch as obsolete/new-feature to > be able to declare it obsolete later on, at which point we might > just as well not use the namespace. :) > > I see two required steps to solve this: > > a. teach TopGit how to retire branches, as per debbug#505303 > > b. teach Git how to retire/rename published branches > > I'll think about (b) for a bit and see if this wouldn't make sense > to be raised with the Git people. Comments welcome, of course. You can do `git remote prune` to get rid of branches that disappeared upstream. Hypothetical `tg retire` (a stupid name, of course) would do git branch -d branch and git push origin :branch :refs/bases/branch. `tg update` or some other command would then have to do the `git remote prune` part and have some fancy logic to retire the branches locally too if there are no changes in them. The case when there are local changes in the retired branches is left as an exercise for the reader. ;-) -- Petr "Pasky" Baudis The lyf so short, the craft so long to lerne. -- Chaucer _______________________________________________ vcs-pkg-discuss mailing list vcs-pkg-discuss@lists.alioth.debian.org
https://www.mail-archive.com/vcs-pkg-discuss@lists.alioth.debian.org/msg00420.html
CC-MAIN-2018-30
refinedweb
368
68.1
Previous: struct that contains the data fields required by the class, and then call the class function to indicate that an object is to be created from the struct. Creating a child of an existing object is done by creating an object of the parent class and providing that object as the third argument of the class function. This is easily demonstrated by example. Suppose the programmer needs an FIR filter, i.e., a filter with a numerator polynomial but a unity denominator polynomial. In traditional octave programming, this would be performed as follows. octave:1> x = [some data vector]; octave:2> n = [some coefficient vector]; octave:3> y = filter (n, 1, x); The equivalent class could be implemented in a class directory @FIRfilter that is on the octave path. The constructor is a file FIRfilter.m in the class directory. ## -*- texinfo -*- ## @deftypefn {Function File} {} FIRfilter () ## @deftypefnx {Function File} {} FIRfilter (@var{p}) ## Create a FIR filter with polynomial @var{p} as coefficient vector. ## @end deftypefn function f = FIRfilter (p) f.polynomial = []; if (nargin == 0) p = @polynomial ([1]); elseif (nargin == 1) if (!isa (p, "polynomial")) error ("FIRfilter: expecting polynomial as input argument"); endif else print_usage (); endif f = class (f, "FIRfilter", p); endfunction As before, the leading comments provide command-line documentation for the class constructor. This constructor is very similar to the polynomial class constructor, except that we pass a polynomial object as the third argument to the class function, telling octave that the FIRfilter class will be derived from the polynomial class. Our FIR filter does not have any data fields, but we must provide a struct to the class function. The class function will add an element named polynomial to the object struct, so we simply add a dummy element named polynomial as the first line of the constructor. This dummy element will be overwritten by the class function. Note further that all our examples provide for the case in which no arguments are supplied. This is important since octave will call the constructor with no arguments when loading objects from save files to determine the inheritance structure. A class may be a child of more than one class (see the documentation for the class function), and inheritance may be nested. There is no limitation to the number of parents or the level of nesting other than memory or other physical issues. As before, we need a display method. A simple example might be function display (f) display (f.polynomial); endfunction Note that we have used the polynomial field of the struct to display the filter coefficients. Once we have the class constructor and display method, we may create an object by calling the class constructor. We may also check the class type and examine the underlying structure. octave:1> f = FIRfilter (polynomial ([1 1 1]/3)) f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2 octave:2> class (f) ans = FIRfilter octave:3> isa (f,"FIRfilter") ans = 1 octave:4> isa (f,"polynomial") ans = 1 octave:5> struct (f) ans = { polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2 } We only need to define a method to actually process data with our filter and our class is usable. It is also useful to provide a means of changing the data stored in the class. Since the fields in the underlying struct are private by default, we could provide a mechanism to access the fields. The subsref method may be used for both. function out = subsref (f, x) switch (x.type) case "()" n = f.polynomial; out = filter (n.poly, 1, x.subs{1}); case "." fld = x.subs; if (strcmp (fld, "polynomial")) out = f.polynomial; else error ("@FIRfilter/subsref: invalid property \"%s\"", fld); endif333 + 0.333333 * X + 0.333333 * X ^ 2 In order to change the contents of the object, we need to define a subsasgn method. For example, we may make the polynomial field publicly writable. function out = subsasgn (f, index, val) switch (index.type) case "." fld = index.subs; if (strcmp (fld, "polynomial")) out = f; out.polynomial = val; else error ("@FIRfilter/subsref: invalid property \"%s\"", fld); endif otherwise error ("FIRfilter/subsagn: Invalid index type") endswitch endfunction So that octave:6> f = FIRfilter (); octave:7> f.polynomial = polynomial ([1 2 3]); f.polynomial = 1 + 2 * X + 3 * X ^ 2 Defining the FIRfilter class as a child of the polynomial class implies that and FIRfilter object may be used any place that a polynomial may be used. This is not a normal use of a filter, so that aggregation may be a more sensible design approach. In this case, the polynomial is simply a field in the class structure. A class constructor for this case might be ## -*- texinfo -*- ## @deftypefn {Function File} {} FIRfilter () ## @deftypefnx {Function File} {} FIRfilter (@var{p}) ## Create a FIR filter with polynomial @var{p} as coefficient vector. ## @end deftypefn function f = FIRfilter (p) if (nargin == 0) f.polynomial = @polynomial ([1]); elseif (nargin == 1) if (isa (p, "polynomial")) f.polynomial = p; else error ("FIRfilter: expecting polynomial as input argument"); endif else print_usage (); endif f = class (f, "FIRfilter"); endfunction For our example, the remaining class methods remain unchanged. Previous: Overloading Objects, Up: Object Oriented Programming [Contents][Index]
https://octave.org/doc/v4.0.1/Inheritance-and-Aggregation.html
CC-MAIN-2020-10
refinedweb
859
56.55
by Mark Ellis Table of contents Created 27 February 2014 A lot goes into creating a DPS magazine when you create it with AEM. Out of the box you have everything you need to get up and running, but if you want to push it further there are a few things you’ll need to know. This article will cover some more advanced concepts such as AEM content sync and using HTMLResources, clear up some confusion with terms, and explore what actually happens when Folios and .folios are created with AEM. You’ll gain insight into advanced magazine creation that I learned from using AEM to publish the CMO.com app, a digital magazine for marketing professionals. I’m going to cover a few of the common terms, how they relate to each other, and the high level layout of a magazine issue. ‘Folios’, which I call ‘capital F folios,’ can be described as the issue of the magazine. ‘Folios’ contain one or more ‘Articles’ and an HTMLResources.zip file. However, in order to have an ‘Article’ ready to be included in a ‘Folio’, it needs to be packaged up, which results in a package with a ‘.folio’ extension for that ‘Article.’ This does not come up often, but you may find yourself occasionally trying to debug ‘Articles’ and they will have a ‘.folio’ extension after being packaged. This distinction will be handy later on in this article. The Content Sync Framework is a service in AEM. Media Publisher for AEM provides the Content Sync configurations that are required for packaging your Articles. Out of the box these will work for most cases, and they are responsible for packaging each individual ‘Article’ into a .folio package, complete with metadata and assets as well as the HTMLResources.zip. Clientlibs – also known as Client-Side Libraries – are the JS/CSS libraries that you’ll want included in your page. There are some additional properties you’ll have to specify if you’re using component level Clienlibs (covered in the next section) and in the Content Sync configuration. HTMLResourcesis an additional .zip package that gets uploaded and packaged with the ‘Folio’ that all ‘Articles’ have access to. Of the provided Content Sync configurations, there are two that are important for customizing: the .folio packaging configuration and the HTMLResources packaging configuration. Media Publisher for AEM will use the template specified on the ‘dps-Issue’, in the sample code this would be ‘ /apps/aaa/dps-sample/templates/issue’ and the property is ‘ dps-exportTemplate’ If you look under the /etc/contentsync/templates/aem-dps-sample/you’ll notice a dps-HTMLResourcesnode and some child nodes after this with a set of properties. When AEM creates the HTMLResources .zip it looks to this node to get the required files to include. Each sub node under the dps-HTMLResourcesnode represents a Content Sync configuration, this configuration is passed to a Content Sync framework which executes the appropriate handler based on the ‘type’ property of that node. The handler then specifies what to add to the HTMLResourcespackage. There are two main ones that we need to worry about – ‘clientlib’ and ‘copy’ (in the next section I’ll go over how to create your own). ‘copy’ is straightforward. You specify the path and optionally the extension, and everything in that path will be copied – with the full path – to HTMLResources.zip. If you specified the path as ‘ /content/dam/magazinestuff/’ then everything under that path would be copied with the destination as ‘ /HTMLResources/content/dam/magazinestuff/’ ‘clientlib’ works a little differently. You specify the clientlib that you want to include and the section (JS or CSS) of that clientlib that you want. For example, if articles in my magazine used the jQuery clientlibs, then I would add in two sub nodes: <foundation-jquery-js jcr: <foundation-jquery-css jcr: This will tell the content sync framework to include the jQeury clientlib in the HTMLResourcespackage. Note: I’m fairly certain an enhancement that will let you leave out the extension property for the clientlib type is in the works, but for the meantime you need to specify two clientlib nodes: one for JS, and one for CSS, if you want both to be included. I like to use component level clientlibs to help keep code organized and keep components contained to aid reuseability. Each component has their own clientlib, usually following the naming convention of aaa.projectName.components.componentName. If I wanted to use this convention, I would have to add in two content sync configurations for each separate component that I wanted to include in each article. To eliviate this, I add in an additional common category to each of my component clientlibs. For example, I would add the additional category of ‘aaa.projectName.mag.components’ resulting in ‘ aaa.projectName.components.componentName,aaa.projectName.mag.components’ on each component clientlibs I create. This allows me to create a global clientlib, which I stick in the design path for organization purposes, and to have that global clientlib, called ‘ aaa.projectName.mag.components-all’ embed the ‘ aaa.projectName.mag.components’ clientlib. This way I just need to maintain one pair of entries in the content sync configuration: <aaa-projectName-mag-components-all-js jcr: <aaa-projectName-mag-components-all-css jcr: This might seem a little confusing, but there is a practical example of this in the sample code. Also, this will combine all your component clientlibs together, so as a best practice you might want to namespace your component styles so they don’t accidentally get overwritten. When these content sync configuration nodes are passed to the content sync framework, it will resolve any additional embed clientlibs that are specified on the ‘ clientlibs-all’. In this case, the ‘ clientlibs-all’ has the category for ‘ aaa.projectName.mag.components’ specified as an ‘ embed’ property, which results in any clientlibs that have the category of ‘ aaa.projectName.mag.components’ to be resolved and embed in the ‘ clientlibs-all’. Therefore all of the component clientlibs will be merged together and included in HTMLResources.zip. Folio configuration There is also another node on the same level as the dps-HTMLResourcesnode named ‘ dps-folio’. This is the node that gets executed whenever a Article is packaged into a .folio. The vast majority of the time you won’t have to touch anything in here, and to be honest I am not 100% sure what all of the content sync update handlers do under the covers, but I can describe what I consider to be the important thing to know in this step: It rewrites the src attributes for <script>tags and <img>tags to point to the new destinations. As I touched on earlier, JavaScript and CSS included in the clientlibs get packaged into HTMLResources.zip. The packager rewrites all of the includes in the .html from absolute paths on the server – for example /etc/content/designs/clientlibs.css– to their new path which would be ../HTMLResources/etc/content/designs/clientlibs.css. Images are included inside the .folio package and rewritten in a similar manner, making them relative to the article rather then to the server. For example an image referencing ‘ /content/publications/magazine/article1/_jcr_content/article-image.img.png/1391657615025.png’ would be rewritten to ‘ ./article1/_jcr_content/article-image.img.png/1391797849453.png’. It then packages the image into the .folio with the same folder structure. This is an important thing to note if you’re creating paths programmatically in JavaScript to load or reference an image. Or if you’re referencing images in CSS inside of component clientlibs. I recommend against this: if you’re going to reference images inside of CSS, stick the styles/images inside your main ‘Design’ path. When we were developing the components for our CMO.com app we considered using the out of the box video component. However, I wanted a video component where I could configure the ‘poster image’. In reality this could have been easily done out of the box, but I also was looking for an opportunity to write my own Content Sync Update Handler and it seemed like an easy place to start. In the sample code, there is a ‘ CustomAEMDPSSampleContentSyncHandler’ Java class that shows how this is done. I grabbed this from one of the ‘Geometrixx’ example applications and configured a few lines to handle what I wanted it to do. I’ll touch on some of the inner workings, what happens, and where this is configured on the content sync template for the sample magazine. The content sync for mobile documentation covers the general idea of content sync and I’ll try to fill in any gaps where it differs specifically for DPS. Content Sync Handler Type At the top of the class, you’ll see the following: @Component( metatype = true, factory = "com.day.cq.contentsync.handler.ContentUpdateHandler/aem-dps-sample-video-update-handler", inherit = true ) The important part to note here is the bolded section of ‘ aem-dps-sample-video-update-handler’. This is the ‘type’ of content sync handler it is: the value specified in the configuration subnodes are matched against this value and handled appropriately. In the sample code under /etc/contentsync/templates/aem-dps-example/dps-folio/.content.xml, the following subnode: <custom jcr: would trigger our custom handler. Determine package contents Here is a general sequence of steps for what happens next as it runs through the custom content sync update handler. Since this is an add-on to the out-of-the-box handlers that already take care of most stuff, we really only need to worry if the article has a component of type ‘ aaa/dps-sample/components/content/video’ – which is the resourceTypeof the custom video component I made – and then package the content in from there. You’ll notice this is specified in a static variable at the top of the class. There are other important properties as also defined here, namely ‘ posterSource’, which is the property that the ‘poster image’ is referencing. These variables are basically the setup for what to package and when to package it. The ‘ updateCacheEntry’ method is the entry point into the handler and there are a few DPS helper methods in here to determine if the path being passed in from the ‘ configEntry’ is the overall DPSFolioobject or if it’s a DPSArticle; in our case, its going to be a DPSArticle. From there it will look at the components included on the page and compare the resourceTypesof the components to what we specified in our static variable at the top. If it finds a match, it downloads the source asset (the movie in this case) then it moves to the ‘ addToExportCache’ function which resolves the original rendition (for the movie) and copies it with the full path to the current cache of assets waiting to be packaged (as identified by the ‘ configCacheRoot’ property that got passed in back in the beginning. Finally, if the ‘ posterSource’ path is not blank, it passes it on to the inherited function ‘ renderResource’ – I don’t know exactly what happens here, but I expect it renders the resource and copies it into the asset cache as well – since that is what ends up in the cache. This just scratches the surface of what you can do using AEM to publish to DPS. There are a lot of moving pieces when you package a magazine. For the most part, this article is meant to give you a peek under the covers and to give you an understanding of why things may not be working as you might expect in your implementation. Comments are currently closed as we migrate to a new commenting system. In the interim, please provide any feedback using our feedback form. Thank you for your patience.
https://www.adobe.com/devnet/digitalpublishingsuite/articles/aem-dps-advanced-topics.html
CC-MAIN-2019-04
refinedweb
1,967
52.29
We are about to begin a series where we analyze large corpora of English words. In particular, we will use a probabilistic analysis of Google’s ngrams to solve various tasks such as spelling correction, word segmentation, on-line typing prediction, and decoding substitution ciphers. This will hopefully take us on a wonderful journey through elementary probability, dynamic programming algorithms, and optimization. As usual, the code implemented in this post is available from this blog’s Github page, and we encourage the reader to use the code to implement our suggested exercises. But before we get there, we should investigate some properties of our domain: the set of all finite strings of letters. Words, Words, Words. If we consider a fixed alphabet (any set, really, but for our purposes a finite one), we may consider the set of all finite strings of elements from , also called words. For example, given , we have the word . Also, we allow the empty word to be a string of length zero. The formal name for the “star” operation is the Kleene star. Most of our work here will be done over the English alphabet of letters . As usual, we are looking for some sort of underlying structure. Here the structure is that two words can be concatenated to make a larger string. In the parlance of abstract algebra, is a monoid with respect to the concatenation operation. If we denote the operation by (pretending it is) multiplication, we write , and the monoid structure just means two things. First, the operation is associative, so that any three words satisfy . Second, it has an identity element (here the empty word), so that for all words . For computer scientists, these are just natural properties of functions like C’s strcat(), but in mathematics they define the structure of the space of all words. To be completely clear, these two properties (a set with an associative binary operation and an identity element) define a monoid. We make a few abuses of notation here. In every monoid the operation is a pretend multiplication, so in general we will call it multiplication. We will also write strings (abusively, “products”) as , which would formally be . We lose nothing by the abuses, but gain brevity. The Kleene starred monoid has an additional property; it is the free monoid generated by . This won’t mean anything to the reader who isn’t familiar with universal properties, but it essentially tells us that any word is uniquely written as a product of letters in . Now, the structure we’ve described here is not particularly rich. In fact, free objects are the algebraic objects which are usually “completely understood.” For our purposes the language of abstract algebra is just a mature setting for our discussion, but the concepts we introduce will give an extra perspective on the topic. In other words, as we don’t plan to use any monoids more complicated than the English alphabet free monoid described above, we have no interesting (general) theorems to apply to our activities. Before we turn to a more concrete setting, we have one more definition. A monoid homomorphism between two monoids is a function which respects the multiplication operations and preserves the identity element. Rigorously, we have that all words satisfy , where the operation on the left side of the equality (before the application of ) is multiplication in , and the one on the right hand side is multiplication in . One easy example of a monoid homomorphism from our English alphabet free monoid is the length homomorphism. Rigorously, the set of natural numbers is a monoid under addition, and the function which assigns to each word its length is a homomorphism of monoids. This is intuitively clear: the length of a concatenation of two words is the sum of the lengths of the pieces. A more complex example which shows up in functional programming has to do with lists. Let be two classes of objects of some fixed types, then we may consider as the set of all lists of objects in . This is again a free monoid over with the operation of list appending and the empty list as the identity. Note that sits inside in a natural way: each element of can be considered a list of length one. With this understanding, we may be sloppy in calling the “product” of the list (note, itself need not have any operations). Now for any fixed operation , we may form the map homomorphism inductively as follows: This is precisely the map operation defined in our primer on functional programming. We encourage the reader to investigate how to phrase the other two functions (filter and fold) as monoid homomorphisms, or prove it cannot be done (thanks to Matt for pointing out this author’s mistake with regards to that). Metrics, and String Comparisons Since our goal is to do things like spelling correction, we are quite interested in strings of letters which are not actually words. We want to be able to tell someone that the word “beleive” is probably a misspelling of the word “believe.” So let us fix our alphabet and consider the free monoid . As we have noted, this is the set of all words one could type with the lowercase English alphabet, so it includes all of our egregious typos. It is a simplistic model, since we ignore punctuation, capitalization, and stylistic marks that convey meaning. But it is as good a place as any to start our investigation. To mathematically describe what it means for a misspelled word to be “almost” the intended word, we need to bring in the concept of a metric. In other words, we want to view our set as a metric space in which we can measure the distance between any two words (when viewed as a metric space, we will call them points). Then the set of all valid English words is a subspace. To correct a misspelled word , we can simply use the closest point in with respect to the metric. Of course, the hard part is describing the right metric. But before we get there, we must define a metric so we know what properties to aim for in constructing a metric on words. Definition: A metric is a function on a set which has the following three properties for all , and if and only if . (the triangle inequality) A space equipped with a fixed metric is said to be a metric space. There are plenty of interesting examples of metrics, and we refer the interested reader to Wikipedia, or to any introductory topology text (or the end of a real analysis text). We will focus on the Levenshtein metric. If we think for a minute we can come up with a list of ways that people make typing mistakes. Sometimes we omit letters (as in diferent), sometimes we add too many letters (e.g., committment), and sometimes we substitute one letter for another (missussippi could be a phonetic error, or a slip of the finger on a qwerty keyboard). Furthermore, we can traverse from one word to another by a sequence of such operations (at worst, delete all letters and then insert the right letters). So it would make sense to take the distance between two words to be the smallest number of such transformations required to turn one word into another. More rigorously, let be the unique way to write as a product of letters, and let be the same for . An elementary edit of is one of the following: - a deletion: the transformation for some , where the hat omits omission in the -th spot. - an insertion: the transformation for some , and some letter . - a substitution: the transformation for some and some letter . Then an edit from to is a sequence of elementary edits which begins with and ends in . The length of an edit is the number of elementary edits in the sequence. Finally, we define the edit distance between and , denoted , as the length of the shortest edit from to . To verify this is a metric, we note that all edits have non-negative length, and the only edit of length zero is the edit which does nothing, so if it follows that . Second, we note that edits are symmetric inherently, in that if we have an edit from to , we may simply reverse the sequence and we have a valid edit from to . Clearly, the property of being the shortest edit is not altered by reversal. Last, we must verify the triangle inequality. Let be words; we want to show . Take two shortest edits between and , and note that their composition is a valid edit from to . Following our definition, by “compose” we mean combine the two sequences of operations into one sequence in the obvious way. Since this is an edit, its length can be no smaller than the shortest edit from to , proving the claim. So is in fact a metric, and historically it is called Levenshtein’s metric. A Topological Aside Before we get to implementing this metric, we have a few observations to make. First, we note that the shortest edit between two words is far from unique. In particular, the needed substitutions, insertions, and deletions often commute (i.e. the order of operations is irrelevant). Furthermore, instead of simply counting the number of operations required, we could assign each operation a cost, and call the total cost of an edit the sum of the costs of each elementary edit. This yields a large class of different metrics, and one could conceivably think of new operations (combinations of elementary operations) to assign lower costs. Indeed, we will do just that soon enough. Second, and more interestingly, this metric provides quite a bit of structure on our space. It is a well known fact that every metric induces a topology. In other words, there is a topology generated by the open balls for all possible radii and all centers . We can also characterize the topology from another viewpoint: consider the infinite graph where each vertex is a word in and two words have a connecting edge if there exists an elementary edit between them. Then edit distance in is just the length of a shortest path in , and so the spaces are isometric, and hence homeomorphic (they have identical topologies). Indeed, this is often generalized to the word metric on a group, which is beyond the scope of this post (indeed, we haven’t gotten anywhere close to group theory yet on this blog!). For those of us unfamiliar with topology or graph theory, we can still imagine geometric notions that get to the intuitive heart of what “induced topology” means for words. For example, we can describe a circle of radius centered at a word quite easily: it is just the set of all words whose edit distance from is exactly . As a concrete example, the circle of radius 1 centered at the word is In fact, any geometric construction that can be phrased entirely in terms of distance has an interpretation in this setting. We encourage the reader to think of more. Python Implementation, and a Peek at Dynamic Programming Of course, what use are these theoretical concerns to us if we can’t use it to write a spell-checker? To actually implement the damn thing, we need a nontrivial algorithm. So now let’s turn to Python. Our first observation is that we don’t actually care what the edits are, we just care about the number of edits. Since the edits only operate on single characters, we can define the behavior recursively. Specifically, suppose we have two words and . If , we can leave the last characters the same and inductively work with the remaining letters. If not, we find the shortest edit between and , as if our last operation were a deletion of . Similarly, we can inductively find the shortest distance between and , as if our last move were an insertion of to the end of . Finally, we could find the shortest distance between and , as if our last move were a substitution of for . For the base case, if any word is empty, then the only possible edit is inserting/deleting all the letters in the other word. Here is precisely that algorithm, written in Python: def dist(word1, word2): if not word1 or not word2: return max(len(word1), len(word2)) elif word1[-1] == word2[-1]: return dist(word1[:-1], word2[:-1]) else: return 1 + min(dist(word1[:-1], word2), dist(word1, word2[:-1]), dist(word1[:-1], word2[:-1])) Here the [:-1] syntax indicates a slice of the first characters of an character string. Note again that as we don’t actually care what the operations are, we can simply assume we’re doing the correct transformation, and just add 1 to our recursive calls. For a proof of correctness, we refer the reader to Wikipedia (Sorry! It’s just a ton of case-checking). We also note that recursion in Python can be extremely slow for large inputs. There is of course a method of building up a cost matrix from scratch which would perform better, but we feel this code is more legible, and leave the performance tuning as an exercise to the reader. For more information on dynamic programming, see this blog’s primer on the subject. The cautious programmer will note the above algorithm is terribly wasteful! For instance, suppose we’re investigating the distance between and . Through our recursive calls, we’ll first investigate the distance between and , during which we recursively investigate versus . Once that’s finished, we go ahead and investigate the other branch, versus , during which we look at versus once more, even though we already computed it in the first branch! What’s worse, is that we have a third branch that computes versus again! Doing a bit of algorithm analysis, we realize that this algorithm is , where are the lengths of the two compared words. Unacceptable! To fix this, we need to keep track of prior computations. The technical term is memoized recursion, and essentially we want to save old computations in a lookup table for later reference. In mostly-Python: cache = {} def memoizedFunction(args): if args not in cache: cache[args] = doTheComputation(args) return cache[args] To actually implement this, it turns out we don’t need to change the above code at all. Instead, we will use a decorator to modify the function as we wish. Here’s the code, which is essentially an extra layer of indirection applied to the above pseudocode. def memoize(f): cache = {} def memoizedFunction(*args): if args not in cache: cache[args] = f(*args) return cache[args] memoizedFunction.cache = cache return memoizedFunction Here the function memoize() will accept our distance function, and return a new function which encapsulates the memo behavior. To use it, we simply use def f(x): ... equivalentButMemoizedFunction = memoize(f) But luckily, Python gives a nice preprocessor macro to avoid writing this for every function we wish to memoize. Instead, we may simply write @memoize def f(x): ... And Python will make the appropriate replacements of calls to f with the appropriate calls to the memoized function. Convenient! For further discussion, see our post on this technique in the program gallery. Applying this to our Levenshtein metric, we see an impressive speedup, and a quick analysis shows the algorithm takes , where are the lengths of the two words being compared. Indeed, we are comparing (at worst) all possible prefixes of the two words, and for each of the prefixes of one word, we compute a distance to all prefixes of the other word. The memoization prevents us from doing any computation twice. To this author, this approach is the most natural implementation, but there are other approaches worth investigating. In particular, Python limits the recursion depth to a few hundred. If we try to compare, say, two DNA sequences, this algorithm will quickly overflow. There are a number of ways to fix this, the most appropriate of which would be tail call optimization (in this author’s humble opinion). Unfortunately, we’d need to tweak the algorithm a bit to put the recursive call in tail position, Python does not support tail call optimization, and manually putting things in continuation-passing style is annoying, obfuscating, and quite ugly. If we decide in the future to do DNA sequence analysis, we will return to this problem. In the future, we plan to provide another Python primer, with a focus on dynamic algorithms. Other methods for solving this problem will arise there. Indeed, I’m teaching an introductory Python programming course next semester, so this will be a good refresher. Transpositions, and Other Enhancements One other significant kind of typo is a transposition. Often times we type the correct letters in a word, but jumble the order of two words. In a spell checker, we want the word to be closer to the word than it is to the word , but with the Levenshtein metric the two pairs have equal distance (two substitutions each). We can enhance the metric by making transpositions have a cost of 1. Historically, this extended metric is called the Damerau-Levenshtein metric. Indeed, Damerau himself gave evidence that transpositions, along with the other three elementary edits, account for over 85% of human typing errors. Then again, that was back in the sixties, and typing has changed in many ways since then (not the least of which is a change in a typist’s vocabulary). Adding transpositions to the algorithm above seems straightforward, but there are some nontrivial details to consider. For instance, we may first transpose two letters and then insert a new letter between them, as in the transformation from to . If we are not careful, we might prohibit such legal transformations in our algorithm. Here is an implementation, which again uses the memoization decorator. @memoize def dist2(word1, word2): if not word1 or not word2: return max(len(word1), len(word2)) elif word1[-1] == word2[-1]: return dist2(word1[:-1], word2[:-1]) else: minDist = 1 + min(dist2(word1[:-1], word2), dist2(word1, word2[:-1]), dist2(word1[:-1], word2[:-1])) # transpositions if len(word1) > 1 and len(word2) > 1: if word1[-2] == word2[-1]: transposedWord1 = word1[:-2] + word1[-1] + word1[-2] minDist = min(minDist, dist2(transposedWord1[:-1], word2)) if word2[-2] == word1[-1]: transposedWord2 = word2[:-2] + word2[-1] + word2[-2] minDist = min(minDist, dist2(word1, transposedWord2[:-1])) return minDist Indeed, we must inspect both possible transpositions, and the symmetry of the example above shows the need for both branches. The proof that this extended metric is still a metric and the proof of algorithmic correctness are nearly identical to the plain Levenshtein metric. So that was fun. Here are some other ideas we leave as exercises to the reader. First, if we allow ourselves to fix a keyboard layout (for many languages with Latin-based alphabets, the standard is qwerty with minor substitutions), we could factor that in to our analysis of letter substitutions and incorrect insertions. For instance, the word is just as close to as it is to , but it is less likely the user meant to type the first word, since is physically closer to than is. To implement this, we can modify the above algorithm to accept a look-up table of physical distances (approximations) between keys. Instead of adding 1 in the relevant branches, we can add a cost according to the look-up table. At the coarsest, we could construct a graph with vertices representing letters, edges representing physical adjacencies, and use the shortest graph path in place of physical key distance. We also note (from our mature vantage point) that this algorithm is not restricted to strings, but can be performed on any free monoid. This includes the example we mentioned earlier of lists. So we could generalize the algorithm to operate on any piece of data which has such an identity element and binary operation, and satisfies the freedom condition. My knowledge of Python is still somewhat limited, but the method for achieving this generalization comes in many names in many languages: in Java it’s interfaces, in C++ it’s templating, in Haskell it’s a typeclass. In Python, there is a fancy thing called duck-typing, and we leave this for our next Python primer. Next time, we’ll crack open some data files with actual English dictionaries in them, and see what we can do about solving interesting problems with them. Until then! Interesting article. I’m not sure your functions would translate correctly to other languages however. In particular languages where character combinations can be used to express a single letter. For example, in german “oe” is equivalent to “ö”. So the length must also be the same. But if you take your identity you say that length(“o”) + length(“e”) = length( “oe” ), which in this case it clearly shouldn’t. I’m not sure this would cause any significant problems for the overall technique. It probably just adds complications. Wonderful comment! You’re very right, and actually I speak German so I’m familiar with the rules you mention (additionally, the now-considered-archaic ß replaces ss). So one way around it would be some preprocessor function which replaces all instances of “oe” with “ö”, etc. Though I’m sure there are some obscure words (or at least, strings one might wish to type, whether or not they are standard words) which use “oe” in a nontrivially different way. One could make a conceivable metric out of it one way or another, but it does throw a stick in our assumptions about what kinds of typos are possible if we start changing what the user originally typed. I wonder offhand how much of a difference that makes on real-world data, and to what extent companies compensate for it in their applications. You could introduce “composition typos” — to borrow Unicode’s term. I wonder however if it might not be better to “decompose” the strings for comparison. That is, every combined character is split into its parts, so “ö” becomes “oe” instead of the other way around. Consider an example where the user types just “o” instead of “ö”. One would expect the spell checker to give a pretty close distance between those characters: if comparing against “oe” it would indeed be just 1 away. Decomposition would also make it possible that dropping/adding accents just becomes part of the cost — rather than having a large table of related accented/combined characters. Actually, in german oe is not the same as ö. I mean, you CAN replace ö with oe, for example, when you can’t enter ö. Some might replace ü it with u (like in Diane Kruger) and others replace ö with oe (like Chad Kroeger). Anyways, there is only one right way to write a german word, so writing “daß” for example, is just wrong, cause its “dass”, same goes for Umlauts. So with Chad Kroeger you could actually MEAN Chad Kroeger, and not Chad Kröger. The only problem there is is with people who can not enter Umlauts, but they are corrected then, so that’s OK. You might want to think about making it “cheaper” to transfer from oe to ö or sth.. Excellent! I’ve been curious about this sort of thing for a while now, so I’m eager to see how you explore this area. As an interesting side note, the use of a finite set for the fixed alphabet is rather well-founded, notwithstanding the scores of languages with potentially unique character sets! In Turing’s 1936 paper, for a footnote he considers a metric on the space of symbols, and asserts that this space is conditionally compact — meaning that unless we claim to be able to distinguish between two symbols s,r with d(s,r)<epsilon for any epsilon, there are really only finitely many symbols! There is a different method to deal with mistakes in ‘ words’ . Apart from mistypings, there are a lot of word mistakes caused by less optimal knowledge of the language. You could try and find the thesis of Martin Reynaart from the university of Tilburg. He used a very different approach: every letter is a value, it is raise to the fifth power, then summed. This is a very quick lookup for letter-swaps. Using precalculated common mistakes (drop a letter, change l for 1, ph for f etc) getting alternatives is quick and easy. Adding levehnstein to this helps discarding too big edits. A note about probability of mistakes: it is very helpful to identify the natural word frequency in suggesting the most likely alternative. A note about the assumption of words, why not focus on any string, including spaces and interpunction? Then sentence boundaries incorrec twordsplitups could be detected as well. Might also want to have a look al, a Dutch initiative, maybe a bit like this. That is an interesting question. Is someone just as likely to type the word “lefa” as they are “fale” when they mean to type the word “leaf”? What you’re suggesting is a sort of “weak” hashing method where two words have equal hashes if and only if they contain the same letters (another example of that: the letters could be assigned distinct primes, and the product of the letter values is the hash). I suppose I do sometimes type words completely jumbled when I’m rushing… I also wonder how much we as humans should allow ourselves to expect of a spell-checker. While checking bigram word frequencies is a great method (and actually, what I’m doing in the next post in this series for a related problem), if we want to check the spelling of a large (hundred page) document in real time, we do have to worry about performance. I think you’re right that either most times a human doesn’t know how to spell a word, or it’s a mistake that the human can correct far faster than the spell-checker. But it’s very difficult to make accommodations for people who don’t understand the language, because there will always be more and more ridiculous spellings of things. For instance, how can a spell checker guess what you mean when you type “ackwire”? Even word frequency tables won’t help there (at least, not the one we plan to use from Google), because AckWire is a product/company/username that probably has a nontrivial frequency! Great article! It’s not terribly important, but I’m not sure I understand the “left-fold homomorphism”. Is it required that the operation in the monoid Y has some relationship to the function g? I can’t see how in general the map is homomorphic. You’re right, and thanks for the comment. There are a number of reasons why my construction is gibberish and it’s not very constructive to go through them all. Here’s a simple reason why it doesn’t work: monoid homomorphisms must preserve the identity. Another is that Y would need to be a monoid itself, which is not true of most data types. I’ll keep this in the back of my mind and if I come up with a more appropriate construction I’ll post it here. In the second paragraph, starting with: As usual, this blog’s Github page, and we … There is a mixup with the html, so the link doesn’t work, and some of the text got caught in the garbled tag. I had to look at it for a few moments because it didn’t make any sense before I realized the issue, Anyway, awesome blog. I am absolutely loving it. Thanks! The links is fixed now.
https://jeremykun.com/2011/12/19/metrics-on-words/
CC-MAIN-2017-04
refinedweb
4,646
60.14
I learn Kivy. I have Django app with CRUD function (Books Library) and API for this (Tastypie). How can look "algorithm" building applications with a list of all my book? What component to use to list and how to retrieve data from the API and to display them? mysite.com/api/books/?format=json json: {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 8}, "objects": [{"title": "Kivy book", "description": "Cool book", "id": 1, "page_count": 155}]} Can anyone provide the code for this simple example? Here is an example from my understanding you are trying to achieve. It is based on the simplest ListView example. Please notice that I created an extended JSON version from the example you provided. Also, when you want to use the url, you have to substitute the 2 commented lines. The method for loading the json is load (for io input) and not loads (for string input). from kivy.uix.listview import ListView from kivy.uix.gridlayout import GridLayout import json import urllib2 class MainView(GridLayout): def __init__(self, **kwargs): kwargs['cols'] = 2 super(MainView, self).__init__(**kwargs) the_string_json = '{"meta": {"previous": null, "total_count": 8, "offset": 0, "limit": 20, "next": null}, "objects": [{"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 1"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 2"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 3"}]}' the_dict = json.loads(the_string_json) # Substitute the previous two lines for this ones: # the_io_json = urllib2.urlopen('mysite.com/api/books/?format=json') # the_dict = json.load(the_io_json) list_view = ListView( item_strings=[book['title'] for book in the_dict['objects']]) self.add_widget(list_view) if __name__ == '__main__': from kivy.base import runTouchApp runTouchApp(MainView(width=800)) Similar Questions
http://ebanshi.cc/questions/5025966/list-all-books-from-book-library-django-app-with-tastypie-in-kivy-app
CC-MAIN-2017-09
refinedweb
282
57.57
I'm sure someone has had the below need, what is a quick way of splitting a huge .gz file by line? The underlying text file has 120million rows. I don't have enough disk space to gunzip the entire file at once so I was wondering if someone knows of a bash/perl script or tool that could split the file (either the .gz or inner .txt) into 3x 40mn line files. ie calling it like: bash splitter.sh hugefile.txt.gz 4000000 1 would get lines 1 to 40 mn bash splitter.sh hugefile.txt.gz 4000000 2 would get lines 40mn to 80 mn bash splitter.sh hugefile.txt.gz 4000000 3 would get lines 80mn to 120 mn Is perhaps doing a series of these a solution or would the gunzip -c require enough space for the entire file to be unzipped(ie the original problem): gunzip -c hugefile.txt.gz | head 4000000 Note: I can't get extra disk. Thanks! This question came from our site for professional and enthusiast programmers.: head tail gunzip -c hugefile.txt.gz | head -n 8000000 |tail -n 4000000 to get the second block. Is perhaps doing a series of these a solution or would the gunzip -c require enough space for the entire file to be unzipped Is perhaps doing a series of these a solution or would the gunzip -c require enough space for the entire file to be unzipped No, the gunzip -c does not require any disk space - it does everything in memory, then streams it out to stdout. gunzip -c gzip pipe to split use either gunzip -c or zcat to open the file gunzip -c bigfile.gz | split -l 400000 Add output specifications to the split command. I'd consider using split. split a file into pieces split a file into pieces Here's a perl program that can be used to read stdin, and split the lines, piping each clump to a separate command that can use a shell variable $SPLIT to route it to a different destination. For your case, it would be invoked with zcat hugefile.txt.gz | perl xsplit.pl 40000000 'cat > tmp$SPLIT.txt; do_something tmp$SPLIT.txt; rm tmp$SPLIT.txt' Sorry the command-line processing is a little kludgy but you get the idea. #!/usr/bin/perl -w ##### # xsplit.pl: like xargs but instead of clumping input into each command's args, clumps it into each command's input. # Usage: perl xsplit.pl LINES 'COMMAND' # where: 'COMMAND' can include shell variable expansions and can use $SPLIT, e.g. # 'cat > tmp$SPLIT.txt' # or: # 'gzip > tmp$SPLIT.gz' ##### use strict; sub pipeHandler { my $sig = shift @_; print " Caught SIGPIPE: $sig\n"; exit(1); } $SIG{PIPE} = \&pipeHandler; my $LINES = shift; die "LINES must be a positive number\n" if ($LINES <= 0); my $COMMAND = shift || die "second argument should be COMMAND\n"; my $line_number = 0; while (<STDIN>) { if ($line_number%$LINES == 0) { close OUTFILE; my $split = $ENV{SPLIT} = sprintf("%05d", $line_number/$LINES+1); print "$split\n"; my $command = $COMMAND; open (OUTFILE, "| $command") or die "failed to write to command '$command'\n"; } print OUTFILE $_; $line_number++; } exit 0; Here's a python script to open a globbed set of files from a directory, gunzip them if necessary, and read through them line by line. It only uses the space necessary in memory for holding the filenames, and the current line, plus a little overhead. #!/usr/bin/env python import gzip, bz2 import os import fnmatch def gen_find(filepat,top): for path, dirlist, filelist in os.walk(top): for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name) def gen_open(filenames): for name in filenames: if name.endswith(".gz"): yield gzip.open(name) elif name.endswith(".bz2"): yield bz2.BZ2File(name) else: yield open(name) def gen_cat(sources): for s in sources: for item in s: yield item def main(regex, searchDir): fileNames = gen_find(regex,searchDir) fileHandles = gen_open(fileNames) fileLines = gen_cat(fileHandles) for line in fileLines: print line if __name__ == '__main__': parser = argparse.ArgumentParser(description='Search globbed files line by line', version='%(prog)s 1.0') parser.add_argument('regex', type=str, default='*', help='Regular expression') parser.add_argument('searchDir', , type=str, default='.', help='list of input files') args = parser.parse_args() main(args.regex, args.searchDir) The print line command will send every line to std out, so you can redirect to a file. Alternatively, if you let us know what you want done with the lines, I can add it to the python script and you won't need to leave chunks of the file laying around. asked 4 years ago viewed 9744 times active 3 years ago
http://superuser.com/questions/381394/unix-split-a-huge-gz-file-by-line/381591
CC-MAIN-2016-30
refinedweb
777
73.88
RPSL::Parser - Router Policy Specification Language (RFC2622) Parser # The new interface doesn't requires the creation of # a parser object anymore: use RPSL::Parser; my $data_structure = RPSL::Parser->parse( $data ); ########### # Alternativelly, use the old and deprecated interface: use RPSL::Parser; # Create a parser my $parser = new RPSL::Parser; # Use it my $data_structure = $parser->parse($data); This is a rather simplistic lexer and tokenizer for the RPSL language. It currently does not validate the object in any way, it just tries (rather hard) to grab the biggest ammount of information it can from the text presented and place it in a Parse Tree (that can be passed to other objects from the RPSL namespace for validation and more RFC2622 related functionality). new()deprecated Constructor. Handles the accessor creation and returns a new RPSL::Parser object. This method is deprecated, under request of some users. The RPSL::Parser interface will change, and there will be no need to create a "parser" object anymore. parse( [ $rpsl_source | IO::Handle | GLOB ] ) Parses one RPSL object for each call, uses the parser internal fields to store the data gathered. This is the method you need to call to transform your RPSL text into a Perl data structure. It accepts a list or a scalar containing the strings representing the RPSL source code you want to parse, and can read it directly from any IO::Handle or GLOB representing an open file handle. This is a mixture between a class and a object method at this moment, due to the deprecation of the new() method. It can detect whenever it was called with a class as the first parameter, and will try to instantiate and use that class as the parser implementation. comment() Stores an array reference containing all the inline comments found in the RPSL text. object Stores a hash reference containing all the RPSL attributes found in the RPSL text. omit_key Stores an array reference containing all the position of the keys we must omit from the original RPSL text. order Stores an array reference containing an ordered list of RPSL attribute names, to enable the RPSL to be rebuilt from the parsed data version. key Stores the value found in the first RPSL attribute parsed. This is sometimes refered as the RPSL object key. text Stores an scalar containing the RPSL text to be parsed. tokens Stores an array reference containing an ordered list of tokens and token values produced by the tokenize method. type Stores a string representing the name of the first RPSL attribute found in the RPSL text parsed. The RFC 2622 requires that the first attribute declares the "data type" of the RPSL object declared. _read_text( @input ) Checks if the first element from @input is a IO::Handle or a GLOB, and reads from it. If the first element is not any type of file handle, assumes it's an array of scalars containing the text for the RPSL object to be parsed, join() it all toghether and feed it to the parser. _tokenize() This method breaks down the RPSL source code read by read_text() into tokens, and store them internally. For commodity, it returs a reference to the object itself, so you can chain up method calls. _cleanup_attribute( $value ) Returns a cleaned-up version of the attribute passed in: no trailling or leading whitespace or newlines. _store_attribute( $attribute_name, $attribute_value ) Auxiliary method. It clean up the value and store the attribute in the data structure being built, and does the necessary storage upkeep. _store_comment( $comment_position_index, $attribute_and_comment_text ) This method extracts inline comments from the inline part of an object and store those comments into the parse tree being built. It returns the attribute passed in with the comments stripped, so it can be stored into the appropriated place afterwards. _build_parse_tree() This method consumes the tokens produced by _tokenize() and builds a data structure containing all the information needed to re-build the RPSL object back. It returns a reference to the parser object itself, making easy to chain method calls again. _parse_tree() This method assembles all the information gathered during the RPSL source code tokenization and parsing into a hash reference containing the following keys: Holds a hash reference whose keys are the RPSL attributes found, and the values are the string passed in as values to the respective attributes in the RPSL text. Multi-valued attributes are represented by array references. As this parser doesn't enforces all the RPSL business rules, you must take care when fiddling with this structure, as any value could be an array reference. Holds an array reference containing the key names from the data hash, in the order they where found in the RPSL text. This is stored here because the RFC 2622 commands that the order of the attributes in a RPSL object is important. Holds a string containing the name of the first RPSL attribute found in the RPSL text. RFC 2622 commands that the first attribute must be the type of the object declared. Knowing the type of object can allow proper manipulation of the different RPSL object types by other RPSL namespace modules. Holds the value contained by the first attribute of an RPSL object. This is sometimes the "primary key" of a RPSL object, but not always. Comment is a hash structure where the keys are index positions in the order array, and values are the inline comments extracted during the parsing stage. Preserving inline comments is not a requirement from RFC 2622, just a nice thing to have. RFC 2622 allows some attribute names to contain multiple values. For every new value, a new line must be inserted into the RPSL object. For brevity, and to allow humans to read and write RPSL, the RFC 2622 allows the attribute name to be omited and replaced by whitespace. It also dictates that lines begining with a "+" sign must be considered as being part of a multi-line RPSL attribute. This array reference stores integers representing index positions in the order array signaling attribute positions that must be omited when generating RPSL text back from this parse tree. As RFC 2622 doesn't request that attributes omited by starting a line with whitespace or "+" must preserve this characteristic, this is only a nice-to-have feature. =back Suppose you retrieve a RPSL Person object from the RIPE NCC WHOIS Database, like the one below. It's a simple query and I will not explain how you could do it here, because it's a bit out of scope for this module. Anyway, you have the following text as a result: person: I. M. A. Fool address: F.A.K.E Corporation address: 226 Nowhere st address: 10DD10 Nevercity Neverland phone: +99-99-999-9999 fax-no: +99-99-999-9999 e-mail: xxx@somewhere.com nic-hdl: XXX007-RIPE # Look, ma, I'm 007! ;) mnt-by: NICE-GUY-MNT changed: xxx@somewhere.com 20001016 source: RIPE Let's assume you need to send an email (for example, to report routing problems) to Mr Fool. It means that you need to retrieve the e-mail field value from this RPSL object. Let's assume you have the previous text in the $text variable. In order to parse the contents of the text into a nice Perl data structure, all you need to do is instanciate a parser, with use RPSL::Parser; my $parser = new RPSL::Parser; And then pass it the contents of the $text variable, and collect the resulting data structure back: my $data_structure = $parser->parse( $text ); It will give you something that will look more or less like this (dumped by Data::Dumper): $data_strucutre = { __META => { 'omit_key' => [4], 'comment' => { 8 => q{Look, ma, I'm 007! ;)} }, 'order' => [ 'person', 'address', 'address', 'address', 'address', 'phone', 'fax-no', 'e-mail', 'nic-hdl', 'mnt-by', 'changed', 'source' ], 'type' => 'person', 'data' => { 'source' => 'RIPE', 'mnt-by' => 'NICE-GUY-MNT', 'phone' => '+99-99-999-9999', 'nic-hdl' => 'XXX007-RIPE', 'fax-no' => '+99-99-999-9999', 'e-mail' => 'xxx@somewhere.com', 'changed' => 'xxx@somewhere.com 20001016', 'person' => 'I. M. A. Fool', 'address' => [ 'F.A.K.E Corporation', '226 Nowhere st', '10DD10 Nevercity', 'Neverland' ] }, 'key' => 'I. M. A. Fool' }, }; In a near future, there will be other objects that will know how to interpret this as the specific RPSL object declared, and to write the corresponding RPSL representation of a given data structure, simmilar to this one. RFC2622, for the full RPSL specification. Luis Motta Campos, <lmc@cpan.org> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.
http://search.cpan.org/dist/RPSL-Parser/lib/RPSL/Parser.pm
CC-MAIN-2016-30
refinedweb
1,450
60.14
OpenShift Table of Contents Introduction OpenShift is an Open Hybrid Cloud Application Platform / PaaS by Red Hat.It has a free plan as well as enterprise pricing options. Here is a good post comparing Heroku and OpenShift Deployment Steps Install RHC The first step is to create an account on OpenShift - it's free and easy. The next step is to intstall RHC.RHC is the OpenShift client tool. The simplest way to install it is to do sudo gem install rhc If the above command doesn't work install Ruby first and then Ruby Gems Deploy the template Web2py app . Now we create a blank web2py app and get it running on OpenShift. For this we use the following repo. You can follow the instructions given in the readme except change the Python version to 2.7 instead of 2.6 The basic steps are- Create a python-2.7 application rhc app create -a YOUR_APP_NAME -t python-2.7 Add this upstream repo cd YOUR_APP_NAME git remote add upstream -m master git://github.com/prelegalwonder/openshift_web2py.git git pull -s recursive -X theirs upstream master Note: If you want a specific release and not the latest snapshot, replace "master" with the branch name in the above lines (ie. 2.3.2). Then push the repo upstream git push That's it, you can now checkout your application at: # you'll be prompted for your namespace while creating your account, you needn't worry about it. Once your app is up you'll need administrative access to continue.For the admin app to work you need to put your password hash in parameters_8080.py in wsgi/web2py/. If you are using Ubuntu, you can find in your laptop, in "/home/YOUR_APP_NAME/wsgi/web2py/" a file called Parameters_*.py. there is a possibility that you can find more than one, with different numbers at the end. remove all of this file. then: $web2py.py -p 8080 -a YOUR_PASSWORD OR $web2py -p 8080 -a YOUR_PASSWORD it will create a file called 'Parameters_8080.py' in directory /home/YOUR_APP_NAME/wsgi/web2py/ then do these: $ln -s parameters_8080.py parameters_443.py $ln -s parameters_8080.py parameters_80.py $ln -s parameters_8080.py parameters_8000.py $git add . $git commit $git push Your parameters_*.py files will be sent to openshift. And then you can open via your web browser, and use your password you just created. if it is not working, try to enable your browser to accept cookies. Package and deploy Eden Now locally create package your local Eden setup via the administrative interface. Then create a new application on your OpenShift by uploading the package. To be able to do this, first you need to install Sahana Eden in your laptop. If you are using Ubuntu, the easiest possibility is to install the windows version using virtual machine such as Oracle Virtual Box. There is a file called 'Web2py.py' somewhere in your windows system. Find this using the windows explorer search facility. Probably it is located in C:\Users\Public\SahanaEden. Then double click to run this file. Wait until it shows a small window, choose server IP= Local (127.0.0.1), enter a Password and press the 'Start Server' button. Your Web browser will directly trying to connect to that ip address. Stop it, and Go to: Your browser will show the web2py admin page. enter your password and press Login. Now, on the left side, you will see many button, one of them, under Eden dir is called "Pack all". Press this button, and wait until its done (will take some time). The result is a file called "web2py.app.eden.w2p", this is the package that needs to be uploaded into Openshift. Use your browser, and go to: enter the administrative interface, enter your password, and press Login. Now, you are at the Openshift Web2py admin page. On the right side, you can see: "Upload and install packed application" section, fill in the Application name, and choose your "web2py.app.eden.w2p" file, and then press Install. It will take some time to finish the uploading process, if it is interrupted, just repeat the process. When it is installed, you will see your Application name on the left side. Phew. If using 'web2py.app.eden.w2p' is only producing frustrating error message, use the 'Or Get from URL' option, and copy this and then press Install. The next step is to install postgresql. From Ubuntu, use the terminal, and type: $rhc cartridge add postgresql-8.4 -a YOUR_APP_NAME Once Eden is installed you will need OpenShift to install a lot of the required packages and libraries for it to work.For that edit the setup.py file in the following way- Edit the install_requires line to install_requires=['newrelic','GitPython','xlrd','lxml','shapely','python-dateutil','xlwt','pyserial','tweepy','pil'], Note that these are only some of the libraries - please add them as needed. You can find the setup.py file in your own laptop. if you use Ubuntu, you can find it in /home/YOUR_APP_NAME. After you change the file content, do: $git add . $git commit # make sure you see file 'setup.py' is included in the list. $git push Now, Access your openshift web2py admin page through Enter your password, find a folder named 'models' and find a file named '000_config.py. Edit and save the file. In order to edit this file, you will need basic information of your postgresql. In your terminal, type: $rhs ssh $env | grep OPENSHIFT you will see lots of lines, containing your postgresql info. Use this to edit the 000_config.py If you are lucky, you can access Sahan Eden from Openshifht now. If not, pray for help might help you. Probably you will receive an error message saying something about "No such file or directory: 'applications/sahana/models/0000_update_check.py'". Before you start praying, try to access your application at openshift server, using $rhc ssh then go to your sahana eden directory, and find a directory named 'models'. Inside 'models' directory, type $nano 0000_update_check.py then write: CANARY_UPDATE_CHECK_ID = 4 followed by CTRL-O, ENTER, and CTRL-X So, you have created the file yourself. You can find your openshift Sahana eden web address from Web2py administrative page, folder 'your application name' (the one that you uploaded), move your mouse cursor above it, and you can see the web address. If it still doesn't work, you can start praying now. Updates To deploy updates simply package Eden locally and re-deploy it on OpenShift via the admin interface ( check the overwrite installed app option) ToDo - Have the admin interface directly fetch Eden from a Git repo.
https://eden.sahanafoundation.org/wiki/InstallationGuidelines/OpenShift?version=24
CC-MAIN-2022-21
refinedweb
1,114
67.04
Replaces the value or values of an attribute in an entry with a specified unsigned integer data type value. #include "slapi-plugin.h" void slapi_entry_attr_set_uint(Slapi_Entry* e, const char *type, unsigned int l); This function takes the following parameters: Entry in which you want to set the value. Attribute type in which you want to set the value. Unsigned integer value that you want assigned to the attribute. This function will replace the value or values of an attribute with the unsigned integer value that you specify. If the attribute does not exist, it is created with the unsigned integer value you specify.
http://docs.oracle.com/cd/E19693-01/819-0996/aaigk/index.html
CC-MAIN-2015-40
refinedweb
103
54.52
Security Sensor Tutorial Using PIR Sensor and ESP8266 Security Sensor Tutorial Using PIR Sensor and ESP8266 This tutorial demonstrates how to create a security sensor, using a PIR sensor, ESP8266, and the Arduino IDE, to indicate both high and low movement. Join the DZone community and get the full member experience.Join For Free This tutorial will walk you through the steps of using an ESP8266 and a PIR Sensor (Passive Infrared Sensor) to detect motion and send you notifications using a Wia F What You Will Need - PIR Sensor (HC-SR501) - ESP8266 - Female to Male Jumper Wires - USB Cable Before You Begin If you haven't done so already, visit our tutorial on getting started with the ESP8266. It details the correct environment to complete this tutorial. Connecting the Hardware Connect your wires according to the chart: | PIR Sensor | ESP8266 | | :-------------: |:-------------:/| | GND | GND | | OUT | D7 | | VCC | 3.3V | The PIR sensor runs on an operating voltage range — DC 4.5-20V. But, there is a way to power the sensor from a 3.3V source. The H pin on the side of the sensor is denoted by VCC in the illustration above and is connected to a voltage regulator that converts the 3.3V source. Install Libraries In the Arduino IDE, go to Sketch > Include Libraries > Manage Libraries. Install each of the following libraries by searching for their name in the search bar within the modal. A button will appear in the bottom right of the box that will allow you to install the library. - ArduinoJson - ESP8266WiFi - ArduinoHttpClient Due to recent changes in the library, be sure to install ArduinoJson 6.0 so that you are up to date. If a library doesn't show up in the results when you search it, you may need to update your Arduino IDE version. You can download the latest version here. Code In the Arduino IDE, copy and paste the following code: #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <ArduinoHttpClient.h> #include <Arduino.h> const char* ssid = "wifi-ssid"; // Your WiFi ssid const char* password = "wifi-password"; //Your Wifi password /* Get this secret key from the wia dashboard, in the `configuration` tab for your device. It should start with `d_sk` */ const char* device_secret_key = "your-device-secret-key"; // Wia API parameters char server[] = "api.wia.io"; char path[] = "/v1/events"; char statePath[] = "/v1/devices/me"; int port = 80; WiFiClient client; int status = WL_IDLE_STATUS; StaticJsonDocument<200> jsonBuffer; HttpClient httpClient = HttpClient(client, server, port); JsonObject& root = jsonBuffer.to<JsonObject>(); String response; int statusCode = 0; int BUTTON = 0; int SENSOR = 13; boolean buttonState = HIGH; boolean buttonDown = false; boolean stateAlarm = LOW; long motion = LOW; String dataStr = ""; String stateStr = ""; void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(BUTTON, INPUT); pinMode(SENSOR, INPUT); digitalWrite(LED_BUILTIN, HIGH); //"); } // Thing function runs continiously void loop() { buttonState = digitalRead(BUTTON); if (buttonState == LOW && stateAlarm == LOW) { if (buttonDown == false) { buttonDown = true; Serial.println("Alarm on!"); stateAlarm = HIGH; digitalWrite(LED_BUILTIN, LOW); updateStateWia(stateAlarm); delay(750); } } else if (buttonState == LOW && stateAlarm == HIGH) { if (buttonDown == false) { buttonDown = true; stateAlarm = LOW; digitalWrite(LED_BUILTIN, HIGH); Serial.println("Alarm off!"); updateStateWia(stateAlarm); delay(750); } } else { buttonDown = false; } if (stateAlarm == HIGH) { motion = digitalRead(SENSOR); //Serial.println(String(motion)); if (motion == HIGH) { Serial.println("Motion Detected!"); root["name"] = "motion"; root["data"] = String(motion); sendToWia(root); delay(2000); } } } void updateStateWia(boolean& state) { if (state == HIGH) { stateStr = "{\"state\": {\"enabled\": true}}"; } else { stateStr = "{\"state\": {\"enabled\": false}}"; } Serial.println(stateStr); httpClient.beginRequest(); httpClient.put(statePath); httpClient.sendHeader("Content-Type", "application/json"); httpClient.sendHeader("Content-Length", stateStr.length()); httpClient.sendHeader("Authorization", "Bearer " + String(device_secret_key)); httpClient.beginBody(); httpClient.print(stateStr); httpClient.endRequest(); } // Adds the correct headers for HTTP and sends Data to Wia void sendToWia(JsonObject& data) { following values in the code by placing your own values in between the quotation marks. your-WiFi-ssid(This is the name of your WiFi network) your-WiFi-password(Your WiFi network password) your-device-secret-key(Navigate to the Wia Dashboard > Devices and choose your device. The device_secret_key will be in the Configuration tab) The code above publishes an Event to Wia every time it detects motion, with a name value of motion (you'll need this later on, when building your Flow) and a data value equal to the reading from the motion sensor. Make sure the correct board is selected. Go to tools > board and select NodeMCU 1.0 (ESP-12E Module). Make sure the correct port is selected: tools > port. Turning on the Alarm To turn on your alarm, press the flash button on the Esp 8266. The blue LED should turn on. To turn off the alarm, press and hold the flash button for at least 2 seconds, the blue LED will turn off. Setting Up Your Flow Create the Flow Lets set up a flow that will send a notification to your phone when motion is detected by the PIR Motion Sensor. Go to your Wia Dashboard and click Flows in the left hand side menu. Create a new Flow with any name you like. Add an Event Trigger Node In Flow Studio, drag an Event node from the Trigger section, and: - Enter motionas the event name - Add your device Add a State Logic Node Now, add a Check State node from the Logic section - Enter enabledas the key - Select 'Equal to` from the Condition drop-down - Enter trueas the Value Add a Notification Node Next, drag over a Notification node from the Action section. - Enter "Motion Detected" as the Message. Now, Wia can send you a message to the Wia mobile app when your Security Sensor detects a motion. Add a Widget Next, head over to your Device's 'Overview' tab. Click 'Add a Widget'. Give the Widget a name Motion Detected, choose Widget type 'text', and enter the name of the Event i.e. motion. PIR Sensor Sensitivity Measures The PIR Sensor allows you to change the delay time and the sensitivity level. The PIR Sensor is a digital device. This means that it reads two values: HIGH and LOW. When the sensor detects movement, it reads HIGH. Otherwise, it reads LOW. The delay setting determines how long the PIR Sensor will read HIGH after it has detected a motion. The sensitivity sensor determines the proximity at which the PIR Sensor will register a movement. This sensor is more accurate when it is set to a lower proximity level. You can control these settings using the orange panels located directly across from the pins you used to wire your device. Trouble Shooting If you are having trouble finding the correct board, refer back to our getting started with the ESP8266 tutorial. If your port is not showing the USB option, try switching the USB cable and checking that the cable isn't "charge only." If this doesn't help, you may need to install a driver. This tutorial contains a section that will walk you through those steps. If you are receiving the error StaticJsonDocument does not name a type, its due to a breaking change introduced into the ArduinoJson library. Go to sketch > include library and manage libraries to update to version 6+. Published at DZone with permission of Austin Spivey . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/security-sensor-tutorial-using-pir-sensor-and-esp8
CC-MAIN-2020-40
refinedweb
1,211
54.42
:t3-core/t3-core-python.git # Choose where the clone lives git clone ssh://git@gitlab.t-3.com:t3-core/t3-core-python.git pip install -e ./t3-python-core Testing & Linting Test & Coverage Report pytest Lint pylama T3 Events In t3-core, we’ve a sub-module which is an event queue system used to connect microservices together, in an asynchronous manner, with built-in fault tolerance. It uses RabbitMQ as a messaging bus to accomplish this. Event queue system consists of 2 main parts, consumer, and publisher. A Consumer, as the name suggests, consumes the messages, by invoking a callback upon receiving the specified message, which is published by the Publisher. Separately running processes, commonly known as workers can consume messages, whereas, any process including web process can publish messages. If any process is unable to finish consuming the message, it gets requed in the system and is sent to a different consumer or stored until the consumer is available again. In T3 Events. T3 Events, is configured by setting up 2 key environment variables, T3_EVENTS, and T3_EVENTS_AMQP_URL, the first one is a boolean value of true or false on whether to use events or not, and the second one is a connection string for rabbit-mq. This env vars can be inserted into any system, and as long as different systems have same value for those env vars, they are part of the same message queue system. There are two main types of consumers and publishers, details below: Task Task consumer/publisher are dedicated to consuming or publishing Tasks, which by definition are consumed one at a time, for a given task, which means, the first available consumer will pick up the task and process it, then the next task in the list will go to the next available consumer, and so on. Below is an example of a sample task. Consumer: from t3.events.consumers imoprt TaskConsumer def message_callback(payload): print(f'message callback task consumer: payload: {payload}') # Start consumer test = TaskConsumer() test.set_task_name('test_task') test.set_callback(message_callback) test.run() Publisher: from t3.events.publisher import TaskPublisher # Use publisher test = TaskPublisher() test.set_task_name('test_task') test.set_message('test message, could be in json too') test.run() For the above example, the given example task name is test_task, which is the same for a consumer and a publisher, which connects them together. Since this is a TaskConsumer, and a TaskPublisher, if you run more than 1 Consumer, and Publish several times, it’ll be processed in a round-robin manner with the running Consumers, one at a time. Once 1 message is processed, then the system moves on to the next one, and so on. Topic Topic consumer/publisher are dedicated to consuming or publishing Topics, which by definition are broadcasted to all subscribed Consumers, for a given Topic, which means, when a topic is published, all consumers signed up for this topic will receive the message. Below is an example of a sample topic. Consumer: from t3.events.consumers import TopicConsumer def message_callback(payload): print(f'message callback topic consumer: payload: {payload}') # Start consumer test = TopicConsumer() test.set_topic_name('test_topic') test.set_callback(message_callback) test.run() Publisher: from t3.events.publishers import TopicPublisher import json # Use publisher test = TopicPublisher() test.set_topic_name('test_topic') test.set_message(json.dumps({'json': 'object'})) test.run() For the above example, the given topic name is test_topic, which is the same for a consumer and a publisher, which connects them together. Since this is a TopicConsumer, and a TopicPublisher, if you run more than 1 Consumer, and Publish, it’ll be processed by all running Consumers, at once. Running T3 Events T3 events is composed of Consumers, and Publishers. Consumers must be run in a separate process, as they are independent of anything else that is going on in the system, for local development, you can run python name_of_consumer_file.py, however in production environments, use nohup python name_of_consumer_file.py, for fault tolerance purposes. Pubishers on the other hand, can be run as part of a process, as their main job is to publish an event to the message queue system. To use a Publisher, you can run the lines below # Use publisher from the above examples, provided the 2 required environment variables are present. Project details Release history Release notifications 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/t3-core/0.9.1/
CC-MAIN-2020-16
refinedweb
736
53.61
Writing your first Django app, part 3¶ This tutorial begins where Tutorial 2 left off. We’re continuing the Web-poll application and will focus on creating the public interface – “views.” Where to get help: If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ. Overview.htm?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B. You will be pleased to know that Django allows us much more elegant URL patterns than that. A URL pattern is. path() calls: from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>.([q.question_text for q best %} Note To make the tutorial shorter, all template examples use incomplete HTML. In your own projects you should use complete HTML documents. Now let’s update our index view in polls/views.py to use the template: path() path('>/', URLconf. In the polls/urls.py file, go ahead and add an app_name to set the application namespace: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] the basics about form processing and generic views.
https://docs.djangoproject.com/en/3.1/intro/tutorial03/
CC-MAIN-2020-40
refinedweb
242
63.25
L is a rather sluttish guy. He almost never clean up his surroundings or regulate his personal goods, and often can’t find them at need. What’s worse, due to his power of impact in his dorm, not only is he himself sluttish, but he also spreads the habit of sluttery to his roommates. Even those who were originally pretty well-regulated, such as Song, has been affected by him, and seldom do any cleaning. As a result, L often can’t find his book before class, and thus has to suffer from an out-of-book class, during which he often sleeps and wastes time. After this has happend hundreds of times, L finally made a great effort to decide to tidy up his bookshelf. He collected all his books from everywhere in his dorm —- under the beds, on the windowsill, inside the desks……, put them in a huge box, and began to place the books onto his bookshelf. To make his bookshelf look more smart, L decided to arrange his books such that their height on the bookshelf increases(at least not decrease) from left to right. (i.e.the shortest book is on the left,and as one moves towards the right end of the bookshelf the books’ heights either remain the same as the previous book or increase, until the rightmost book is reached which is the tallest on the shelf). This seems a very easy, albeit time-consuming, task. Unfortunately, L has a strange way of putting his books on the shelf. As he takes a book out of the box, he wants to put it on the shelf without moving any of his other books(he is too lazy to do that), and the books should still be arranged in an acceptable way. For each book, he can either put it on the shelf, or put it aside (i.e.not put it on the shelf): if he puts it aside,then he will never put that book on the shelf. In other words, for every book, L may only put the book on the left side, or on the right side of the bookshelf. He may also throw this book away and not put it on the shelf. Here is an example Suppose L’s box contains 5 books, with the following heights: 2 5 1 3 4 Books are drawn strictly from left to right,then the best number of books that L can fit on the shelf is 4. There are two possible ways of doing this: 2 3 4 5 1 3 4 5 In the first case, L puts the book with height 2 on the left side of the shelf. The book with height 5 goes to the right side. The book with height 1 can’t be placed on the shelf (since it would be shorter than the book with height 2, and so would ruin the arrangement).The book with height 3 goes to the left side,and then the book with height 4 can go either to the left or right side. In the second case, L could put the book with height 2 aside.Then he places the book with height 5 on the right side, the book with height 1 on the left side, the book with height 3 on the left side, and the book with height 4 on either the left or right side. Input Input consists of a series of data sets, followed by a negative integer, which implies the end of input and should not be processed. Each data set begins with a line containing an integer N, denoting the number of books in L’s box. The following line consists of N positive integers denoting the height of each book in the box. The order in which these heights are given is the order in which L takes books from the box. You may assume that 1 ≤ N ≤ 100 and the height of each book will be in the range [1,100]. Output For each data set in the input, output a single line containing the sentence “At most X books can be put onto the bookshelf.”, where X is the maximum number of books L can put onto his bookshelf. Sample Input 5 2 5 1 3 4 8 1 8 3 6 5 4 7 2 -1 Sample Output At most 4 book(s) can be put onto the bookshelf. At most 6 book(s) can be put onto the bookshelf. 我解法是在求给定的序列中最长下降子序列中,还要回朔求倒着的最长下降子序列,再把正着的和倒着的加上一起。举个例子 2 5 1 3 4 正着的下降子序列 5 3,5 4,2 1; 相应的倒着的 3 1,4 3 2,3 2或者3 1,明显5 4和4 3 2 组合最长4是重复的,所以答案就是2+3-1; 这个解法时间是0.03秒,算是效率高的吧 大家注意,n==-1的时候break是错的,n<0才可以,我因为看错题目w了10几发 #include <iostream> #include <string.h> #include <stdlib.h> #include <math.h> #include <algorithm> using namespace std; int a[105]; int dp[105]; int bp[105]; int s[105]; int tag[105]; int n; int ans; int main() { while(scanf("%d",&n)!=EOF) { if(n<0) break; for(int i=1;i<=n;i++) {scanf("%d",&a[i]);s[i]=i;} memset(dp,0,sizeof(dp)); ans=0; for(int i=1;i<=n;i++) { int num=0; for(int j=i-1;j>=1;j--) { if(a[i]<=a[j]) { if(num<dp[j]) {num=dp[j];s[i]=j;} } } dp[i]=num+1; memset(tag,0,sizeof(tag)); int cnt=s[i]; while(s[cnt]!=cnt) { tag[cnt]=1; cnt=s[cnt]; } tag[cnt]=1; memset(bp,0,sizeof(bp)); int sum=0; for(int j=i-1;j>=1;j--) { if(a[j]>a[i]||tag[j]) continue; int num=0; for(int k=j+1;k<i;k++) { if(a[j]<=a[k]) num=max(num,bp[k]); } bp[j]=(num+1); sum=max(sum,bp[j]); } ans=max(ans,dp[i]+sum); } printf("At most %d book(s) can be put onto the bookshelf.\n",ans); } return。 Paulo和TC一直在收集整理关于敏捷回顾的任何想法和活动。在这篇内容里面,他们分享了7步法来帮助你组织你的下一次回顾。 Agenda structure:
https://cloud.tencent.com/developer/article/1109298
CC-MAIN-2020-50
refinedweb
1,004
75.54
a path is found. Calculate a path to a specified point and store the resulting path. This function can be used to plan a path ahead of time to avoid a delay in gameplay when the path is needed. Another use is to check if a target position is reachable before moving the agent. using UnityEngine; using UnityEngine.AI; using System.Collections; public class ExampleClass : MonoBehaviour { public Transform target; private NavMeshAgent agent; void Start() { agent = GetComponent<NavMeshAgent>(); NavMeshPath path = new NavMeshPath(); agent.CalculatePath(target.position, path); if (path.status == NavMeshPathStatus.PathPartial) { } } } Did you find this page useful? Please give it a rating:
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent.CalculatePath.html
CC-MAIN-2019-43
refinedweb
102
53.47
- Advertisement Jakob KrarupMember Content Count14 Joined Last visited Community Reputation159 Neutral About Jakob Krarup - RankMember Personal Information - Website spriteBatch.Draw slow? Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingDo you only have a single SpriteBatch.Begin before and a single SpriteBatch.End after your drawing? Having many separate spritebatches with the begin/end will slow your drawing down a lot. - Hi Shippou You could fiddle a bit with the chunk sizes, to ensure that you would only read/dump files from and to disk every so often. If your maps are pretty simple, the amount of data in memory shouldn't be a problem. To my knowledge this is the same way Minecraft does it. You could also cache a bigger amount of chunks, say two concentric circles worth around the one the player is currently in. I can't see this becoming a problem on modern computers. Try the sample that's for download on my Blog - I haven't experienced any problems, and the chunks there are very small, to illustrate the concept. If you make 255x255 chunks you would load a lot less and the files would still be fast to read and not too much of a strain on memory. Kind regards - Jakob - Hi Mellkor A similar question popped up on the Microsoft XNA forums a while back, and I posted some graphics to visualize the theory and a code sample with class diagram. (scroll down to "I found some time yesterday, and coded a framework for making infinite worlds.") I hope it will prove useful to you Kind regards - Jakob - Yup - they are now :) Nice game! The gfx for the menu and introscreen is very nice. I like the concept, but I don't get the feeling that what I do changes very much in the game. If I move in a different direction all the small enemies quickly catch up to me, and the big enemy is very hard to outmaneuver. I would like small explosions as well when I hit or when I am hit, so I get the reward (feedback) for aiming well. A little sound for each shot being fired would be nice too. Overall a very good first game! :) Kind regards - Jakob Rotate sprites around a point in 2D Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingGlad to hear it! :) Cudos on coming back with your solution for future reference :) /Jake - The links are down. Maybe it has to do with DropBox having trouble, but otherwise, if you could upload again? :) Rotate sprites around a point in 2D Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingHi: Find the current rotation of and distance to the child object change the rotation by the wanted amount calculate the new position using cos and sin (you may want to read up on these) basically cos(angle) gives you the X coordinate of where to position something, and sin(angle) gives you the Y coordinate. Getting the rotation of a Vector2 is possible using the Atan2 function: private float Vector2ToRadian(Vector2 direction) { return (float)Math.Atan2(direction.X, -direction.Y); } XNA - Tile Engine With Collision Jakob Krarup replied to QuackTheDuck's topic in Graphics and GPU ProgrammingHi :) Here you can download codesamples for reading a map from a textfile. This code uses numeric values, but you can change what you do with the characters read to a SWITCH statement like you are mentioning in your question. Kind regards - Jakob Jakob Krarup replied to Daniel Costa's topic in Graphics and GPU ProgrammingHere's a code framework for infinite worlds implemented in XNA: You would have to make an implementation of IPermanentMapStorage which gets maps from a webservice. You can probably use the rest of the code as is /Jake P.S. in case you are interested in seeing the newest version, which uses Perlin noise for map generation (not a requirement for the framework), it is attached to this post. Static Creations and upcoming XNA Game Jakob Krarup replied to Rustystatic's topic in Your AnnouncementsCool :) Good luck! /Jake Problem displaying correct portion of a scene Jakob Krarup replied to tmccolgan88's topic in For Beginners's ForumHi tmccolgan88 What you need is a "camera". And I put "camera" in quotation marks, because it is merely a way of thinking about the concept. Whenever you are drawing the background, you are using the absolute coordinates, which makes them stay where they are, and your player move, as you point out. What you are looking for is a way to "translate the coordinates of the world into the screen, based on the player's position". This can be done by storing a Vector2 (yes - you may call it "_camera", to keep up the illusion that there *is* a real camera ;)), and updating the value of that vector based on the player's movements. Whenever you want to draw the background (world), you subtract the position of the camera from the position of the tiles/map-pieces/whatever, to make it the new origin for coordinates (it will be the top-left corner of the screen). Does that make sense? Otherwise Google "2D camera" or ask again Kind regards - Jakob Setting coordinates in map editor Jakob Krarup replied to ChristianFrantz's topic in For Beginners's ForumHi Burnt_casadilla You can change the line: builder.Append(separator + (map[x, y] > oceanLevel ? "X" : " ")); to builder.Append(separator + map[x, y]); This will look up the value in the double array at position x,y and add that to the StringBuilders buffer for later retrieval. EDIT: I added an extended version of the editor to the blogpost (at the bottom), which supports saving the heightmap (and you can look at the code for loading from the file as well, though the application doesn't support it). as for adding a border - you can do this with a for-loop, iterating through zero to max on both the Y and X axis, and setting the value there to 50 if either the X or the Y value is either zero or max. If that doesn't make sense, ask again Kind regards - Jakob Krarup ;-) Help with Worm Clone Draw() method Jakob Krarup replied to Manhattanisgr8's topic in For Beginners's ForumHi :) Kind regards - Jakob - Advertisement
https://www.gamedev.net/profile/210703-xnafan/
CC-MAIN-2019-22
refinedweb
1,061
66.07
In this article, I’ll show you: 💬 How to check the version of the Python module (package, library) abc? And how to check if abc is installed anyways? These are the eight best ways to check the installed version of the Python module abc: - Method 1: pip show abc - Method 2: pip list - Method 3: pip list | findstr abc - Method 4: library.__version__ - Method 5: importlib.metadata.version - Method 6: conda list - Method 7: pip freeze - Method 8: pip freeze | grep abc Before we go into these ways to check your abc abc in your current Python environment? Method 1: pip show To check which version of the Python library abc is installed, run pip show abc or pip3 show abc abc Name: abc Version: a.b.c Summary: ... Home-page: ... Author: ... Author-email: ... License: ... Location: ... Requires: ... Required-by: ... In some instances, this will not work—depending on your environment. In this case, try those commands before giving up: python -m pip show abc python3 -m pip show abc py -m pip show abc pip3 show abc Next, we’ll dive into more ways to check your abc abc ... abc abc using the CMD or Powershell command: pip3 list | findstr abc to locate the version of abc in the output list of package versions automatically. Here’s an example for abc: pip3 list | findstr abc('abc') for library abc. This returns a string representation of the specific version such as 1.2.3 depending on the concrete version in your environment. Here’s the code: import importlib.metadata print(importlib.metadata.version('abc')) # 'abc'? conda list '^abc' Method 7: pip freeze The pip freeze command without any option lists all installed Python packages in your environment in alphabetically order (ignoring UPPERCASE or lowercase). You can spot your specific package abc if it is installed in the environment. pip freeze Output example (depending on your concrete environment/installation): PS C:\Users\xcent> pip freeze aaa==1.2.3 ... abc= abc using the CMD or Powershell command: pip freeze | grep abc to programmatically locate the version of your particular package abc in the output list of package versions. Here’s an example for abc: pip freeze | grep abc abc==1.2.3 Related Questions Check abc Installed Python How to check if abc is installed in your Python script? To check if abc is installed in your Python script, you can run import abc in your Python shell and surround it by a try/except to catch a potential ModuleNotFoundError. try: import abc print("Module abc installed") except ModuleNotFoundError: print("Module abc not installed") Check abc Version Python How to check the package version of abc in Python? To check which version of abc is installed, use pip show abc or pip3 show abc in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu) to obtain the output major.minor.patch. pip show abc # or pip3 show abc # 1.2.3 Check abc Version Linux How to check my abc version in Linux? To check which version of abc is installed, use pip show abc or pip3 show abc in your Linux terminal. pip show abc # or pip3 show abc # 1.2.3 Check abc Version Ubuntu How to check my abc version in Ubuntu? To check which version of abc is installed, use pip show abc or pip3 show abc in your Ubuntu terminal. pip show abc # or pip3 show abc # 1.2.3 Check abc Version Windows How to check my abc version on Windows? To check which version of abc is installed, use pip show abc or pip3 show abc in your Windows CMD, command line, or PowerShell. pip show abc # or pip3 show abc # 1.2.3 Check abc Version Mac How to check my abc version on macOS? To check which version of abc is installed, use pip show abc or pip3 show abc in your macOS terminal. pip show abc # or pip3 show abc # 1.2.3 Check abc Version Jupyter Notebook How to check my abc version in my Jupyter Notebook? To check which version of abc is installed, add the line !pip show abc to your notebook cell where you want to check. Notice the exclamation mark prefix ! that allows you to run commands in your Python script cell. !pip show abc Output: The following is an example on how this looks for abc in a Jupyter Notebook cell: Package Version ------------- – – ------- aaa 1.2.3 ... abc 1.2.3 ... zzz 1.2.3 Check abc Version Conda/Anaconda How to check the abc version in my conda installation? Use conda list 'abc' to list version information about the specific package installed in your (virtual) environment. conda list 'abc' Check abc Version with PIP How to check the abc version with pip? You can use multiple commands to check the abc version with PIP such as pip show abc, pip list, pip freeze, and pip list. pip show abc pip list pip freeze pip list The former will output the specific version of abc. The remaining will output the version information of all installed packages and you have to locate abc first. Check Package Version in VSCode or PyCharm How to check the abc version in VSCode or PyCharm? Integrated Development Environments (IDEs) such as VSCode or PyCharm provide a built-in terminal where you can run pip show abc to check the current version of abc in the specific environment you’re running the command in. pip show abc pip3 show abc pip list pip3 list pip freeze pip3 freeze You can type any of those commands in your IDE terminal like so: Summary In this article, you’ve learned those best ways to check a Python package version: - Method 1: pip show abc - Method 2: pip list - Method 3: pip list | findstr abc - Method 4: library.__version__ - Method 5: importlib.metadata.version - Method 6: conda list - Method 7: pip freeze - Method 8: pip freeze | grep abc.
https://blog.finxter.com/how-to-check-abc-package-version-in-python/
CC-MAIN-2022-33
refinedweb
993
70.23
#include <perfmon/pfmlib.h> int pfm_find_event(const char *str, unsigned int *desc); int pfm_find_full_event(const char *str, pfmlib_event_t *e); int pfm_find_event_bycode(int code, unsigned int *desc); int pfm_find_event_bycode_next(unsigned int desc1, int code, unsigned int *desc); int pfm_find_event_mask(unsigned int *idx, const char *str, unsigned int *mask_idx); The library does not directly expose the event code, nor unit mask code, to user applications because it is not necessary. Instead applications use names to query the library for particular information about events. Given an event name, the library returns an opaque descriptor. Each descriptor is unique and has no relationship to the event code. The set of functions described here can be used to get an event descriptor given either the name of the event or its code. Several events may share the same code. An event name is a string structured as: event_name[:unit_mask1[:unit_mask2]]. The pfm_find_event function is a general purpose search routine. Given an event name in str, it returns the descriptor for the corresponding event. If unit masks are provided, they are not taken into account. This function is being deprecated in favor of pfm_find_full_event_name. The pfm_find_full_event function is a general purpose search routine. Given an event name, it returns in ev, the full event descriptor that includes the event descriptor in ev->event and the unit mask descriptors in ev->unit_masks. The number of unit masks descriptors returned is indicated in ev->num_masks. This function is the preferred search function. The pfm_find_event_bycode searches for an event given its code represented as an integer. It returns in desc, the event code. Unit masks are ignored. Because there can be several events with the same code, the library provides the pfm_find_event_bycode_next to search for other events with the same code. Given an event desc1 and a code, this function will look for the next event with the same code. If such an event exists, its descriptor will be stored into desc. It is not necessary to have called pfm_find_event_bycode prior to calling this function. This function is fully threadsafe as it does not maintain any state between calls. The pfm_find_event_mask function is used to find the unit mask descriptor based on its name passed in str for the event specified in idx. Some events do not have unit masks, in which case this function returns an error.
http://www.makelinux.net/man/3/P/pfm_find_event_bycode
CC-MAIN-2015-14
refinedweb
389
64.61
Yes, atom-workspace is valid for keymaps, though it would appear not for that one. It looks like everything for Tab is just atom-text-editor:not([mini]): So you should probably just use that and leave out the atom-workspace. Yes, atom-workspace is valid for keymaps, though it would appear not for that one. It looks like everything for Tab is just atom-text-editor:not([mini]): So you should probably just use that and leave out the atom-workspace. Thanks for the response, but I was doing something wrong. My settings got reset and I had to add php and erb to the package’s settings. Why is this so hard ? All I want this to do seems incredibly simple in most Mac apps (hell the OS provides for it even if it is a menu item) I want to set the Script plugin to run my current Python script file with Command R This is pretty common on a Mac. Command I should be “info” normally. This Angular JS directive or whatever it is, pretty much the ONLY deal breaker. This is the same crap that keeps me from using Sublime. I like to use the keyboard shortcuts I know by convention that are similar across lots of Mac apps. Back to TextMate. There is a reason it is easy to use. What do you have in your keymap.cson and what does the Keybinding Resolver tell you when you try to use those keybindings? If we know this, we can help you figure out why your keybindings aren’t working. You can disable the default set of package keybindings by going to the package config/info page within Atom ( Settings -> Packages and click on the grey box around the package info) and scrolling down to the keybindings. There’s a checkbox there that will disable the package’s keybindings, and you can define your own in keymap.cson. This Angular JS directive or whatever it is, pretty much the ONLY deal breaker. I’m not sure what this is referring to. Thanks, I’ll look into it more. The “selectors” as they are are pretty dense and poorly (not centrally) documented or discoverable. I don’t have a lot of time to spend on it today. Nice thing is Atom has come along way since last I tried it out about 6 months ago. You can see the selector for a language on its settings page. They’re not centrally located, no, and it would probably be useful to have scope names displayed on the grammar selector (in the spot where the keybindings are displayed in the Command Palette). It would make sense to be able to see all (optionally) Then search/filter them. Inevitably conflicts or bugs or just unexpected behavior arise that can be difficult to trace. I’ve seen this with every polyglot editor. Context / scope isn’t quite enough as those can be many and when the clash can be quite unpredictable. There shouldn’t ever be a scope clash. Each TextBuffer is styled by only one grammar. That grammar may have other scopes embedded inside it, but as long as each grammar you have installed uses a unique name, you’re always going to know which scope you’re working with. So I made that happen. I have a fork of the grammar-selector package that shows scopeName in the modal: There is currently a pull request open, but it won’t be included in Atom for a few release cycles. If you would like to use it, you can go to the command line and run apm install damnedscholar/grammar-selector, then reload Atom. It will download the package to your .atom/packages directory and automatically override the built-in package until you delete it. Be aware that installing a separate version of a built-in core package in the ~/.atom/packages directory is something for advanced users. Because this kind of thing has caused immense support headaches in the past, I’m working on building a system to warn people that this can cause problems in the near future. I will probably disable that package immediately (I’ve had one or more core packages overridden for months) and feel briefly sad that I had to kill the dalek, but it seems like a very useful thing for when people come here asking questions. I like this plan. Well, my dalek package won’t complain if you launch Atom in Dev Mode because it assumes that in Dev Mode you know what you’re doing Very cool!!! (sorry for the exceptionally late reply) All we need now is that + shortcuts. Hello! I’m facing similar problems and tried out all the solutions here, but it’s not working. Every time I’m trying to save the keymap.cson file, I’m getting a… Failed to load /home/svub/.var/app/io.atom.Atom/data/keymap.cson Duplicate key ‘atom-text-editor’. I tried unset! on different namespaces, no success. My goal: to map Ctrl-H to jump to the left pane and Ctrl-L for the other direction - like I’m used to from VIM. First I installed vim mode plus but they use a very strange shortcuts: Ctrl-w l and Ctrl-w h which are both quite difficult to reach for using them all the time. This is my keymap.cson with all the things I tried so far: `#’.vim-mode.command-mode:not(.mini)’: #’.vim-mode.command-mode:not(.mini)’: #‘body .native-key-bindings’: #‘atom-workspace atom-text-editor’: #‘atom-workspace atom-text-editor:not([mini])’: #‘atom-workspace atom-text-editor:not([mini])’: #‘atom-text-editor.vim-mode-plus:not(.insert-mode)’: #‘atom-text-editor.vim-mode-plus:not(.insert-mode)’: ‘atom-text-editor’: ‘ctrl-h’: ‘unset!’ ‘atom-text-editor’: ‘ctrl-l’: ‘unset!’ #‘atom-workspace atom-text-editor:not([mini])’: ‘atom-text-editor’: ‘ctrl-h’: ‘window:focus-pane-on-left’ #‘atom-workspace atom-text-editor:not([mini])’: ‘atom-text-editor’: ‘ctrl-l’: ‘window:focus-pane-on-right’ ` How can it be done? Hope somebody can help. When posting code you need to make sure to highlight it and press the </> button above the editor in order to format it as code. The error message is pretty self-explanatory. You have two atom-text-editor keys when you should only have one. This is a CSON file, so you can have as many entries as you want under a single key, but you can’t have multiple keys with the same name at the same level. Each key is a folder and every entry is a file, so how are you going to find which folder your file is in if you have a bunch of folders with identical names? Yes, it works, thank you! I read the error “duplicate key” like “the key binding is already defined somewhere” so I was trying to unset it in any way I could imagine… it didn’t cross my mind that it’s referring to the format of the config file. But that might be only me. Thank you very much for your quick answer!
https://discuss.atom.io/t/how-to-replace-a-keymap-binding/16834?page=2
CC-MAIN-2018-13
refinedweb
1,196
73.07
Here at t-bot we scrunitize every line of code. Here’s one from the Rails' world. Ok, pretend we have a site where each registered user has their own blog. Naturally we’d have the ability for you to view someone’s blog. Following a design where each model has its own controller that handles all its CRUD, we put this feature in the #show action like so: user.rb class User < ActiveRecord::Base has_one :blog end blog.rb class Blog < ActiveRecord::Base belongs_to :user end blogs_controller.rb class BlogsController < ApplicationController def show @blog = Blog.find params[:id] end end The URL of that action would look something like ‘/blogs/show/1’. But wait. That URL is just not pretty enough. The client asks it to be changed to ‘/blogs/show/chad’, ‘chad’ being the username of the user that the blog belongs to. When users register we also validatesuniquenessof :username, to ensure its unique. Alright thats not that hard. Our first try: routes.rb ActionController::Routing::Routes.draw do |map| map.show_blog 'blogs/show/:username', :controller => 'blogs', :action => 'show' end blogs_controller.rb class BlogsController < ApplicationController def show @user = User.find :first, :conditions => ['username = ?', params[:username]] @blog = @user.blog end end Ugly. I don’t like setting instance variables to objects that I can navigate to from other instance variables I’ve already set. I already found the User object with the given username, I can then just ask it for its blog. I like keeping the actions short and the instance variables to the absolute minimum that I need. How about making user a local variable? Nah, I don’t like local variables in actions. Let’s try again. blogs_controller.rb class BlogsController < ApplicationController def show @user = User.find :first, :conditions => ['username = ?', params[:username]] end end Nope, still don’t like it. Like I said earlier, I like to let each model have its own controller that handles all its CRUD e.g. Blog model, BlogsController. I expect the model’s controller to be only working with objects of that type e.g. the BlogsController should only be dealing with Blog objects but now the #show action find’s a User object. That doesn’t seem right to me. Here we go again. blogs_controller.rb class BlogsController < ApplicationController def show @blog = Blog.find :first, :joins => 'inner join users on users.id = blogs.user_id', :conditions => ['users.username = ?', params[:username]] end end Oooo. No more User object, I like that. The BlogsController is now only working with Blog objects, another plus. But…the ‘joins’ keyword parameter. From the Rails doc :joins: An SQL fragment for additional joins like LEFT JOIN comments ON comments.post_id = id. (Rarely needed). Rarely needed….hmmm. Some of you might think I’m doing this for performance. After all, if I loaded just the User object that would be 1 query, then when I navigated to the user’s blog that would be another query. 2 queries comparied to 1. I also could get the same performance as the query using ‘joins’ by using the ‘include’ keyword parameter in my #find to eagerly fetch the user object’s associated blog, but nah I don’t feel like doing that because I’d still be loading a User object in the BlogsController and that feels wrong. I’m not doing this for performance reasons, its purely for clarity. The bottom line is: don’t trade pretty URLs for ugly code even if that means you have to bust out ‘joins’.
http://robots.thoughtbot.com/bustin-out-joins
CC-MAIN-2014-49
refinedweb
583
68.97
This is a recipe is often use for the mainline of my Python scripts. With this recipe your Python script will: - gracefully handle Ctrl+C(i.e. KeyboardInterrupt) - log an error (using the loggingmodule) for uncaught exceptions, importantly with the file and line number in your Python code where the exception was raised - gracefully ignore a closed output pipe (common when the user pipes your script through lessand terminates that) - if your script logger is enabled for DEBUGlevel logging, a full traceback will be shown for an uncaught exception Presumptions: you have a global logvariable a la: import logging log = logging.setLevel("scriptname") your script's entry point is a function def main(argv): ... Python, 31 lines You have 1/0 which always produces an exception, by definition. What is the point of this? Nine years old recipe looks more solid and prints stack trace along with variables values: @chris: stupidity. I had put that in for testing. I'll remove it. @denis: thanks for the link. I'll probably try to incorporate that for a future rev.
https://code.activestate.com/recipes/577258-python-script-main-line-for-graceful-exception-han/
CC-MAIN-2022-05
refinedweb
178
72.87
Hi all, As I search through the mail list my problem appears to be a pretty known problem. Once I was able to get ivy cache updated using solution suggested here: ml Although that looks rather like workaround, since I have to apply either latest.integration or some version with + at the end to the dependency to get cache updated. Thus, I cannot use the same ivy.xml file for both "snapshot" and "release" builds as I would expect passing version to the dependency element through the ant property like rev="${build.version}". Unfortunately, I cannot reproduce successful cache update any more even with latest.integration as dependency version. Shouldn't changing="true" on dependency work without requiring rev=" latest.integration"? It appears also that the problem is not [directly] connected with the "classifier" attribute I use. It persists for projects/artifacts without "classifier" too. Best Regards, Sergey Shcherbakov. -----Original Message----- From: Sergey Shcherbakov [mailto:sshcherbakov@echelon.de] Sent: Friday, June 26, 2009 3:40 PM To: ivy-user@ant.apache.org Subject: RE: Publication of the artifacts with classifiers to the maven repository My problem is actually the same as described here: 8229.html It is not solved though. Best Regards, Sergey Shcherbakov. -----Original Message----- From: Sergey Shcherbakov [mailto:sshcherbakov@echelon.de] Sent: Friday, June 26, 2009 1:41 PM To: ivy-user@ant.apache.org Subject: Publication of the artifacts with classifiers to the maven repository Hi all, Understanding advantages of the Ivy vs. Maven I am using Ivy as dependency managing tool for our non-Java projects. But we have also some Java maven projects that cannot be migrated to Ivy now. So I am trying to use homogenous dependency environment where Ivy projects sometimes depend on the Maven artifacts in the maven repository. Recently I found a problem. An Ivy project A publishes it's "snapshot" artifact to the maven repository so that it can be used by other maven projects. There is another Ivy project B that among others depends on artifacts generated by project A. In case of snapshot build the artifact gets changed without changing its version number. The project A overwrites the artifact in the repository with each snapshot build properly. The project B finds this artifact for the first time, downloads it to the ivy cache and uses OK. The problem is that the project B doesn't notice that the artifact gets changed in the maven repo and doesn't update the cache although changing="true" is specified for that dependency. Thus outdated version of the A comes into the project B build. The resolution in debug mode shows : [ivy:resolve] A is changing, but has not changed: will trust cached artifacts if any There was though some problem with ivy repo file parsing (shown only in debug mode): [ivy:resolve] problem while parsing cached ivy file for: com.echelon.es#LnsNative;4.03.000-SNAPSHOT: [xml parsing: ivy-4.03.000- SNAPSHOT.xml:15:85: cvc-complex-type.3.2.2: Attribute 'classifier' is not allowed to appear in element 'artifact'. in file:/C:/Doc uments%20and%20Settings/ss/.ivy2/cache/A/ivy-4.03.000-SNAPSHOT.xml The cached ivy file do really contains classifier attribute but doesn't have namespace prefix and no xmlns declaration, although the initial project A ivy.xml file had that definitions. Obviously, when Ivy published artifacts (or when the cache ivy file was generated) the namespace prefixes were removed by Ivy. Can that be a reason of not updating snapshot artifacts in cache? Best Regards, Sergey Shcherbakov.
http://mail-archives.apache.org/mod_mbox/ant-ivy-user/200906.mbox/%3CC7F5B1CB032FB2439B59D288A08F7C8FFE1F85@hopi.emea.echcorp.com%3E
CC-MAIN-2016-40
refinedweb
595
57.77
<scribe> ScribeNick: dorchard <scribe> Scribe: DaveO <Stuart> Date: 05-Feb-2007 <Vincent> zakim +33.9.51.75.aabb is Vincent approved minutes of last week [09:08] <DanC> RESOLVED: to approve as a true record RESOLUTION: approved minutes of Jan 30 approved dan: openID and SAML are interesting topics for future agenda [09:09] noah: paper submitted and accepted for enterprise of web services workshop [09:10] ... invited to present so I'll prep slides stuart: regrets for Feb 12th [09:11] next week scribe: Noah stuart: transition of TAG, things to think about [09:13] vincent: working on some of my open action items [09:14] <noah> +1 to what Dan said. [09:15] dan: if stuart has any questions, I suggest bringing them up. ... but I'm against going through the whole list <noah> I might be a bit more willing to have group skim, but would be opposed to detailed review of all issues as a use of our shared group time. Norm: namespace-8, let's finish stuart: versioning dan: keep versioning high priority [09:18] <DanC> (I took an action re urns and registries too; apologies, no progress) dave: also URNsRegistries [09:19] raman: how long is transition period? stuart: while we have them around, we keep flogging them. [09:20] <DanC> (mez's text ) [09:21] <timbl> .me notes today was booked out for me many weeks ago. noah: if this is going to go on for a long time, give somebody else some ownership timbl: validation seen as a repository of truth [09:30] ... w3c has controlled specs via validation ... validator needs to be revisited ... validation could be what w3c, or even TAG, of what is acceptable or recommended [09:31] <DanC> (I agree the validator is a big part of the story; I'm coming up with more and more justification for budgeting validator work against the TAG... yeah... what tim's saying.hmm.) timbl: do you say "no quotes, die, reload", vs advisory [09:32] stuart: what does TAG vs WG do? [09:33] timbl: two philosophies: 1) stick things in a some stuff may become stds; 2) stick with using namespaces ... how to cleanly develop these things, probs in either case <noah> I think CDF adds an extensibility story to XHTML, no? <raman> interesting ... the only thing the tagsoup and xhtml folks would agree on is probably "we dont need RDF:-)" [09:34] <DanC> maybe, noah, but if they [CDF] have, I haven't seen it. timbl: TAG crosses many different groups, how do you take all these things and evolve them. <Zakim> DanC, you wanted to think out loud about encouraging validator dev dan: validator is close to TAG's work. [09:35] ... don't want html and css validators, want just a validator. ... shorten feedback loop between authors and validator developers [09:36] ... unicorn project.. <Zakim> noah, you wanted to talk about role of WG dan: maybe we just need some detailed time on this.. noah: help them to fish rather than do the fishing. ... TAG should set forth principles, ie self-description ... TAG should help w3c get WG's going. [09:39] <Zakim> Norm, you wanted to point out that I don't see how the validator helps by itself. I need to be able to read something that tells me the right answers, norm: answers need to be written down. raman: tag shouldn't maintain validator ... today people point their browser at something and see if it works [09:40] <noah> I think rather than getting credibility by having a fraction of users go to our validators, it's far more effective to get the sort of credibility that will cause the browser vendors to implement the "right" answers. raman: biggest success would be to have browser do validation. <noah> That means the answers we advocate have to be practical. <Zakim> timbl, you wanted to say that the browser could fix it in View Source timbl: actually, I think that people when they do the, they also do view source ... whenever you do a save as or view source, it offers the cleaned up version <noah> Suggest one would need to separate: view source from "view corrected source". I think there are a bunch of drawbacks to making it hard to see the "real" source when that's what you want. <noah> Tim's answer of highlighting diffs is fine, as long as you can reconstruct the original too. [09:43] <noah> I do view source :-) timbl: imagine if you did view source and it colour coded. whenever you copied the source, you'll get the cleaned up raman: people don't do view source anymore because it's too complicated timbl: my son does it, and I think a lot of people still do this <noah> My son too. <Vincent> my sons too timbl: and if it's generated, then it's even less excusable that it doesn't validate dan: stick cases such as the forms and table nesting "documented hack" in the test suite raman: people do open table, insert data, close table [09:45] <Stuart> ack vincent [09:46] timbl: how about forms have id tags, and always refer to forms via ids rather than the tags vincent: many pages "near" him are out of his control and not valid. ... many of the content management tools, like blogs and wikis, etc. produce just garbage [09:47] <Norm> If only we had either a carrot or a stick... raman: chicken and egg ... some times content produces for old bugs and not necessary but sometimes the browser won't fix it. [09:48] <Stuart> ack dave [09:49] <DanC> DO: I hear TV pointing out problems with lots of suggestions, and wonder if TV has any suggestions going forward. [09:51] raman: you run into the browser issue right away, then you run into legacy issue. [09:52] <Stuart> ack DanC [09:53] <Zakim> DanC, you wanted to observe that TV clearly has more details swapped in than I do, and to ask if he has suggestions, and to re-raise the "free to a good home" possibility dave: was hoping to hear ideas for what we could do.. danc: thinks he hears TV say I don't hear the answer, but TAG should do more work. [09:54] raman: architecturally the TAG needs to answer the question: should tagsoupintegration exist on the web, and then how does it coexist with structured markup. <DanC> do, raman is re-iterating 3 options from HT's summary [09:55] raman: henry said it well, tagsoup exists and come up with strategy for migrating toward structured markup 2) structured good; 3) tagsoup /structured co-exists ... lean towards co-existence and a strategy for moving towards structured [09:56] timbl: there have been many extremes, step function for moving ... meet halfway on each one. ... for example people that want to omit quotes, and that's in xml. [09:58] ... we're looking at each thing separately, and looking at the benefits of moving in the direction we want ... question of which battles. eg, namespaces and microformats. [09:59] <noah> I have mixed feelings about calling a a format in which attributes need not be quoted "XML", because the major selling point of the "XML Brand" is that the expectations for interop with deployed parsers are very high. Don't want to break that. I do think having a sort of "nearly XML" with known, stable transform to and from is a fine idea. I just don't want to quite brand it as XML. timbl: namespaces very important imbl: microformats can't cope with scale of evolution that we should have [10:00] <noah> +1 The importance of namespaces for supporting self-description and as a basis for distributed innovation is the sort of principle the TAG itself should be driving. timbl: the battle for namespaces is different level than quoted attributes <DanC> TV: yes, (1) consistent tree, and (2) namespaces are my main things. quotes are in the noise. [10:01] <Zakim> noah, you wanted to say success is bringing the browsers along raman: problem is coupling these things, can't do namespaces unless you do xml and you can't do xml unless you have attributes noah: there was a tone to the discussion that "oh yeah there's the browsers" ... I think it should be the other way around [10:02] ... success is fostering discussion that happens in the browsers enefits noah: path forward has to include browsers [10:03] <Zakim> Norm, you wanted to ask if we really believe that fixing quotes on attributes would really help norm: every time this issue comes up, quotes on attributes ... I wonder that this level of syntactic fixup is really a big part of this issue. [10:04] ... we could write 10,15 rules on this [10:05] <DanC> (TV has given examples of how it's deeper than that, indeed.) <raman> Agree with Norm that fixing quotes on attrs is in the noise; I blieve myself and timbl were saying the same <noah> If Norm is right that the problems are really deeper browser dependencies, then I wonder how much mileage we get out of Tim's proposal for a self-correcting View Source? Seems like that would deal with the minor issues more successfully than the deep ones. [10:06] <noah> I could be wrong about that. <DanC> (the 10 or 15 rules evidently cost 1747 lines of python. 1/2 ;-) ht: I don't think that the xml syntax issues aren't the big deal. ... I think it's more the unclosed tags, if anything <noah> I suspect there's also a perceived convenience/DWIM issues. Not sure how big a deal that is. ht: in the examples that hixsie gave, what happens when you pollute your xml with bad html and plug that into good xhtml ... spent some time on formal languages in that area. ... there is some work out there, but there was nothing that covered all the cases we came up with <DanC> ( ) ht: john cowan's approach was the last thing standing that might get to some consensus [10:08] ... if you cannot live with "here is a large collection of semi-formal english", then i want to go back and look at john's tagsoup raman: at least it's in a ruleset for program use [10:09] <DanC> (I started looking at cowan's tables in discussion with #whatwg folks, but only scratched the surface. I should update ) raman: raggett's tidy used to have c code, which got migrated to java danc: talk to the folks who worked on Access [10:10] ... maybe at f2f noah: politics to who we invite.. [10:11] (some discussion about individuals) [10:12] stuart: any comm team in japan? [10:15] <noah> Maybe the right thing would be for someone (Rhys) to approach Tommy (name?) informally and ask what would be the most effective way to pursue such contacts. <noah> I would welcome some more formal contact with HTML 5. Not all of us take the trouble to participate directly with WHAT WG, etc. <Rhys> The person from Access is Tommy Kamada who is Access CTO and their AC Rep [10:18] <noah> I think it's appropriate to make the liaison with HTML 5 community at least more semi-formal, perhaps formal. stuart: we should have some metings with the various groups. ... and how about the chartering process? [10:19] ht: question is really, what is the architectural space the 1,2,* WGs are working in, and how can help [10:20] <noah> I think the TAG can help in commenting on the W3C WG structure insofar as our technical insight contributes to an artful decision as to whether this work seems to admit working in separate groups or one, for example. <ht> HST gives apologies for next week (sorry if that tips the balance) ht: I suggest adjourning this item for 2 weeks, as timbl sent regrets [10:22] meeting adjourned <noah> [10:26]
http://www.w3.org/2001/tag/2007/02/05-tagmem-minutes
CC-MAIN-2015-22
refinedweb
2,015
66.98
Name Of file !!! jay nair Greenhorn Joined: Sep 13, 2005 Posts: 28 posted Apr 19, 2006 08:00:00 0 public class stack { private int stck[]; private int tos; // initialize the stack stack( int i) { stck = new int[i]; tos = -1; } void push(int i) { if(tos >= stck.length) System.out.println(" Stack Overflow/stack is full "); else stck[++tos] = i; } int pop() { if(tos < 0) { System.out.println(" Stack underflow "); return 0; } else return stck[tos--]; } } class nstack { public static void main ( String args[]) { stack test = new stack(10); for( int i=0; i<10; i++) { test.push(i); } for( int i=0; i<10; i++) { System.out.println("stck["+test.pop()+"] :" + test.pop()); } } } I am confused about file names , in the above code , if i keep the class name as nstack.java , the compiler says that class stack is public should be declared in a file name called stack.java , now if i give the file name as stack.java then it compiles just fine but but when i try 2 run it it gives error " Exception in thread " man" java.langNoSuchMethodError: main also i wanted to know what does this statement mean ... * Files with no public classes have no naming restrictions. if the above is true then class bool1 { public static void main ( String args[]) { boolean b ; b = false; System.out.println( " b is " +b); b = true; System.out.println( " b is " +b); if (b)System.out.println( " this is executed "); b=false ; if (b)System.out.println( " this is not executed ha ha ha "); System.out.println ( " 10 < 9 is " +( 10<9) ); System.out.println( " this is test '\u0061' and another one\b \r and this line shld come in next line "); } } will the above code work if the File name is bool.java ???( i have noticed that when i compile it it gives out bool1.class which is normal , now if thats the case isnt the statemnet ( * files with no public classes have no naming restrictions) contradicted ? Help will be appreciated ... thanks in advance Preparing for SCJP 5 jay nair Greenhorn Joined: Sep 13, 2005 Posts: 28 posted Apr 19, 2006 08:04:00 0 I am confused about file names , in the above code , if i keep the class name as nstack.java , the compiler says that class stack is public should be declared in a file name called stack.java , wat i meant was if i keep the FILE NAME as nstack.java not class name ... sorry Ernest Friedman-Hill author and iconoclast Marshal Joined: Jul 08, 2003 Posts: 24189 34 I like... posted Apr 19, 2006 08:11:00 0 I'm not sure what you're confused about. I can tell you that there are three unrelated things going on here. 1) When you compile any Java source file (a *.java file is called a "source file"), a class file is created for each class in the file. Each class file is named X.class, where X is the name of a class as given in the source file. 2) There's a rule that there can be only one public class in a source file, and if there is a public class in a source file, the source file must have the same name as that class, plus ".java". 3) When you run a Java application, the argument to "java" is the name of a class which contains a "main()" method: this name has nothing to do with the name of any source file, but only to do with the name of a class. [Jess in Action] [AskingGoodQuestions] jay nair Greenhorn Joined: Sep 13, 2005 Posts: 28 posted Apr 19, 2006 09:16:00 0 thanks ernest , i guess i was not descriptive about my problem.... well in the stack program , there is one public class , so according to rule the name of the file must be the name of that class , now if i do that it compiles fine but since the class in which the main method is there has the name nstack so wen i try to Run the program it gives me error saying it did not find any MAIN method , so my question is , i s there anyway this program will run ... or the only possible way is to make another file and put the public class ( stack class) in that file and name the file as stack.java .... hope i was clear , thanks for ur reply , would really appreciate further clarifications , Ernest Friedman-Hill author and iconoclast Marshal Joined: Jul 08, 2003 Posts: 24189 34 I like... posted Apr 19, 2006 09:28:00 0 As I tried to point out, all of these things are really unrelated. You tell the compiler (javac.exe) the name of the source file, and it creates some number of class files. Then you tell the runtime (java.exe) the name of the class you want to run, the one with main() in it. So in your case, you'd say javac stack.java java nstack jay nair Greenhorn Joined: Sep 13, 2005 Posts: 28 posted Apr 19, 2006 09:32:00 0 thanks ernest , that makes sense , i guess i was seeing it in a complex way .... thanks again , I agree. Here's the link: subject: Name Of file !!! Similar Threads cannot resolve symbol Have problem in stack ! not able to get the output Could not find or load main class StDemo exception related Is this possible? All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/403211/java/java/file
CC-MAIN-2015-18
refinedweb
927
79.6
Difference between revisions of "Line drawing function" Revision as of 15:20, 1 November 2008 class line: "this class will creates a line after the user clicked 2 points on the screen" def __init__(self): self.view = FreeCADGui.ActiveDocument.ActiveView self.stack = [] self.callback = self.view.addEventCallback("SoMouseButtonEvent",self.getpoint) print "click the two points of the line" def getpoint(self,info): if info["State"] == "DOWN": pos = info["Position"] point = self.view.getPoint(pos[0],pos[1]) self.stack.append(point) if len(self.stack) == 2: l = Part.Line(self.stack[0],self.stack[1]) shape = l.toShape() Part.show(shape) self.view.removeEventCallback("SoMouseButtonEvent",self.callback) Detailed explanation import Part, FreeCADGui In python, when you want to use functions from another module, you need to import it. In our case, we will need functions from the Part Module, for creating the line, and from the Gui module (FreeCADGui), for accessing the 3D view. creates("SoMouseButtonEvent" everytime a mouse button is pressed or released, the getpoint function will be executed. print "click the two points of the line" It is always a good idea to think about what feedback you will give to the user. You must help him to understand what's going on... So let's print a message to help him to know what he must do next. Of course, our example is very basic. Maybe you can think of something better? def getpoint(self,info): Now we define the getpoint function, that will be executed when a mouse button is pressed in a 3D view. This function will receive an argument, that we will call info, which contains several pieces of information (mode info here). if info["State"] == "DOWN": The getpoint function will be called when a mouse button is pressed or released. But we want to pick a 3D point only when pressed (otherwise we would get two 3D points very close to each other). So we must check for that here. pos = info["Position"]("SoMouseButtonEvent" 2 files, Init.py and InitGui.py inside your MyScripts directory. The Init.py can be left empty, and themain interface. But this still won't work, because a FreeCAD command must be formatted in a certain way to work. So we will need to transform a bit our line() tool. Our new exercise.py script will now look like this:
https://wiki.freecadweb.org/index.php?title=Line_drawing_function&diff=prev&oldid=643
CC-MAIN-2020-16
refinedweb
392
66.74
The You could use cwd parameter, to run scriptB in its directory: import os from subprocess import check_call check_call([scriptB], cwd=os.path.dirname(scriptB))() I believe you can use a single properties file (e.g. build.py) that's read by Ant and Python. For example: build.xml <project default="build"> <property file="build.py"/> <target name="build"> <echo message="${src.webinf}"/> </target> </project> script.py #!/usr/bin/python import ConfigParser config = ConfigParser.ConfigParser() config.read("build.py") print config.get("properties", "src.webinf") build.py [properties] src.webinf = WEB-INF Example usage $ ant Buildfile: /Applications/MAMP/htdocs/clicks/test/build.xml build: [echo] WEB-INF BUILD SUCCESSFUL Total time: 0 seconds $ python script.py WEB-INF: The problem is probably your data. Verify that the CSV data is read correctly (debug the reader). When I run your script with the following input files: file1.csv foo,bar,baz 1,2,3 2,3,4 3,4,5 file2.csv 4,5,6 5,6,7 6,7,8 Then the result of your script is the following: $ python test.py [['4' '5'] ['5' '6'] ['6' '7'] ['foo' 'bar'] ['1' '2'] ['2' '3'] ['3' '4']] Therefore I think your bug must be about reading the CSV files. Maybe the column separator isn't working correctly. :-) PHP session changes aren't written to the session storage by default until the end of the program; while the program is running, $_SESSION is just like any other variable; only accessible within its own program; it's only when the program ends and the session is written to disk that the next program can get at the changes you've made to the session data. So the short answer is that you won't be able to do this just by checking the session and expecting the latest updates to be there. You can force PHP to write to the session at any time during the program by using the session_write_close() function, but as you may gather from the function name, this will also close the session to that program, so that program can't make any further updates to it. I guess you could then re-open the sessio should change directory within the same command: cmd = "/path/to/executable/executable" outputdir = "/path/to/output/" subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True) This is a possible approach - using a condition that is set in the main program to decide whether to execute a particular line in the script. If your main program is for ii = 1:9 skipLine3 = (mod(ii,3)==0); runSub end And runSub.m looks like this: A = 1; B = 2; % modified lines to trap condition where 'skipLine3' doesn't exist: if ~exist('skipLine3', 'var') skipMe = false; else skipMe = skipLine3; end if ~skipMe, B=B*2; end fprintf(1, "for iteration %d B is %d ", ii, B) Then the output will be: for iteration 1 B is 4 for iteration 2 B is 4 for iteration 3 B is 2 for iteration 4 B is 4 for iteration 5 B is 4 for iteration 6 B is 2 for iteration 7 B is 4 for iteration 8 B is 4 for iteration 9 B is 2 As you can see - the skipLine3 parameter, which is set in the main loop (every forgot , in all subprocess.call([...]) ["i3-msg", "-t", "get_workspaces"] edit: if len(status_list) <=3: subprocess.check_output(["dzconky_for_3_workspaces.sh"]) else: subprocess.check_output(["dzconky.sh"]) dzconky_for_3_workspaces.sh #!/bin/sh exec conky -d -c "$HOME/bin/conkyrc_cli" | dzen2 -fg "#666666" -bg "#333333" -ta left -w 725 -x 54 -y 750 & exit 0 Ok I think this might be what you are looking for, client libraries to authenticate and yeah I believe appengine now recommends using the oauth2 for any kind of authentication: Then you get an auth token where you pass in headers on your restful request like: # Your authenticated request Authorization: Bearer TokenHere Then in your handler you get it like: try: user = oauth.get_current_user('') except NotAllowedError: user = None # then from the first link you should be able to access if user.is_current_user_admin() This is how I authenticate on android, but I only do this once and store it in session and just enable cookie jar on the httpclient. maybe you are looking for CSVfix, this is a tool for manipulating CSV data in the command shell. Take a look here: With it you can, among other things: Reorder, remove, split and merge fields Convert case, trim leading & trailing spaces Filter out duplicate data or data on exclusion lists Enrich with data from other sources Add sequence numbers and file source information Split large CSV files into smaller files based on field contents Perform arithmetic calculations on individual fields Validate CSV data against a collection of validation rules and convert between CSV and fixed format, XML, SQL and DSV I hope this helps you out, best regards, Jürgen Jester. you need to give it the full path to the script that you are trying to call, if you want to do this dynamically (and you're in the same directory), you can do: import os full_path = os.path.abspath('kvadrat.py')() You should take a look at the JMP automation guide. You can automate JMP from Python using the win32com interface, which is unfortunately quite buggy and incomplete. I've written a custom library of code to work around these issues, largely because my job requires me to work with JMP extensively and its built-in jsl programming language is awful at many things. WSGI requires that you return the output you want to send back to a browser as the return value of your function, not just print it out. So you'd need to use pprint.pformat() and return its result, rather than pprint.pprint (which just tries to print it out via print - not what you want here). def application(environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) aaa = ['a','b','c'] return pprint.pformat(aaa) Yes, it's a sed one-liner: sed -i -r '1{s/(^|$)/"/g;s/,/","/g}' file.csv This means: -i - edit files in place -r - use extended regular expressions 1{...} - perform the operations in {...} only on the first line of the file s/(^|$)/"/g - replace (s) either the beginning (^) or end ($) of the line with ", everywhere they occur (g), then s/,/","/g - replace (s) each instance of , with "," everywhere it occurs (g) try this: (save it to your main.sh): #!/bin/ksh awk -F: -v a="$1" -v i="$2" 'NR==1{n=$2;print $1":"a"-"i;next}{print $1":"n}' /VersionInfo.properties > /tmp/tmpVersion && mv /tmp/tmpVersion VersionInfo.properties try with main.sh "13.7.0" "4" You cannot treat a part of a file like you wish to. You can use heredoc syntax for now, like this : $data = <<<END ... END; Later you replace this code by : $data = file_get_contents ( $filename ); You can do something like this: var code = "javascript:go('', 'trials'); return false;" $('.Tips4').attr('onclick', code);
http://www.w3hello.com/questions/How-to-access-and-modify-the-contents-of-one-object-created-by-one-script-from-another-script-in-python-
CC-MAIN-2018-17
refinedweb
1,170
59.94
From the IBM WebSphere Developer Technical Journal. Introduction IBM DB2 Universal Database (UDB) Enterprise Server Edition V8.2 introduced a new high availability feature, called High Availability Disaster Recovery (HADR), that provides a failover capability to its client applications by replicating data from a primary database to a standby database. This enables client applications to easily recover from a partial or complete disaster. In addition, DB2 HADR is associated with an Automatic Client Reroute (ACR) capability to make the failover behavior virtually transparent to its client applications. IBM WebSphere Application Server Network Deployment (ND) V6.1, for example, uses DB2 to store its application persistent data. WebSphere Application Server applications need only to make connections to the primary database. To keep a synchronized copy of the database on the standby server, DB2 HADR log files are consistently sent from the primary to the standby to keep the two in sync. When the primary server goes offline for (planned or unplanned) downtime, the standby server is available to be brought online. When the Automatic Client Reroute feature has been enabled, the DB2 reroute logic will check whether or not the standby server can be found. If it is found, the reroute first retries the connection to the failed primary server, and if that fails again, the reroute will connect to the alternate standby server. At this time, the WebSphere Application Server connection is re-established with the alternate server, and the transaction is rolled back and then re-issued on the alternate server. The entire DB2 HADR failover process is transparent to the WebSphere Application Server ND applications. DB2 HADR plus the Automatic Client Reroute capability enable its client applications to recover from a failed database server with minimal interruption. This article describes the steps for building a highly available database environment by leveraging DB2 HADR and Automatic Client Reroute using WebSphere Application Server ND V6.1 as the client application. This article assumes familiarity with IBM WebSphere Application Server Network Deployment V6.x and DB2 Universal Database (UDB) Enterprise Server basic concepts and setup. DB2 HADR preparation DB2 HADR requirements Before enabling DB2 with HADR as the WebSphere Application Server application datastore, you need to be aware of these basic requirements for both the primary and standby DB2 servers: - Identical operating system and DB2 version are required. - Same container file system and installation path are necessary, such as /home/db2inst1/sqllib. - If using by reference, communication ports for HADR need to be specified in: - For UNIX® or Linux®: /etc/services - For Windows®: c:\windows\system32\drivers\etc\services - The standby server machine has to be reachable by TCP/IP from the primary server and by the client application. DB2 HADR setup Let's look at what is involved in setting up the DB2 HADR primary and standby servers: Install DB2 UDB Enterprise Server Edition on both the primary and standby machines. Start the DB2 servers on both machines, if they are not already running, then create your database and the required tables on the primary machine. For illustration purposes, we will use "Sample" as the database name. (See the DB2 Information Center for detailed installation information.) Next, identify the TCP/IP connection communication ports for each database on the primary and standby machines (as per normal client/server database connectivity). The port name is user-defined and the port numbers can be any numbers, provided there are no conflicts. It is not required that the ports on the primary and standby servers be identical; however, if you can keep the ports the same on both machines, the configuration will be much easier. For our Sample database, two ports (51012 and 51013) are used on the primary and standby servers: Listing 1. Two HADR ports used for the "Sample" database >more /etc/services # HADR ports assigned by user ha_sample 51012/tcp ha_sample_int 51013/tcp You need to edit the /etc/services file (UNIX/Linux) or c:\windows\system32\drivers\etc\services (Windows) to specify the ports. (Note that only the administrator account can edit these files.) Configure the HADR variables for each database on the primary machine. (The steps shown here are for the primary machine only.) This process must be repeated for each database. When setting up these variables, verify that the hard_local_hos" and hard_remote_host variables refer to the proper machines. Also, the hadr_local_svc and hadr_remote_svc variables must match the names defined in the /etc/services file described above. The "Sample" database is used here as an example: Listing 2. HADR variables for the Sample database >db2 update db cfg for Sample using hadr_local_host <primary machine IP address> >db2 update db cfg for Sample using hadr_remote_host <standby machine IP address> >db2 update db cfg for Sample using hadr_local_svc ha_sample >db2 update db cfg for Sample using hadr_remote_svc ha_sample_int >db2 update db cfg for Sample using hadr_remote_inst <DB2 instance name on the standby> >db2 update db cfg for Sample using hadr_timeout 120 >db2 update db cfg for Sample using hadr_syncmode nearsync >db2 update db cfg for Sample using logretain on >db2 update db cfg for Sample using LOGINDEXBUILD on >db2 update alternate server for database Sample using hostname <Standby IP address> port 60000 Above, NEARSYNC is selected as the sync mode. This mode provides less protection against transaction loss than SYNC, in exchange for a shorter transaction response time than SYNC mode. Notice that the last command in Listing 2 enables the Automatic Client Reroute capability for DB2 HADR and port 60000 is the DB2 instance port number on the standby machine. Verify your configuration values by entering this command, also shown in Listing 3: db2 get db cfg for <database_name> | grep HADR Listing 3. HADR configuration for our Sample database on the primary machine >db2 get db cfg for sample | grep HADR HADR database role = STANDARD HADR local host name (HADR_LOCAL_HOST) = svtlewis.rchland.ibm.com HADR local service name (HADR_LOCAL_SVC) = ha_sample HADR remote host name (HADR_REMOTE_HOST) = svtclark.rchland.ibm.com HADR remote service name (HADR_REMOTE_SVC) = ha_sample_int HADR instance name of remote server (HADR_REMOTE_INST) = db2inst1 HADR timeout value (HADR_TIMEOUT) = 120 HADR log write synchronization mode (HADR_SYNCMODE) = NEARSYNC Now, it is time to backup the database from your primary machine and restore it on the standby. The following commands will backup your databases on the primary machine (also shown in Listing 4). You need to repeat the command for each of your databases. Be aware that you cannot perform a backup on a database that has an existing connection with its client application. cd <temp_backup_directory> db2 backup db <database_name> The backup copy of each database will be stored in the <temp_backup_directory>. Listing 4. Backup database on the primary machine >cd tmpdir >db2 backup db sample Backup successful. The timestamp for this backup image is :20061101161943 Transfer the backup files generated on the primary machine to the standby machine. To restore the database to the standby machine, log on to the standby machine with your DB2 user ID. The command below will restore your database on the standby machine (Listing 5). You need to repeat this command for each of your databases: db2 restore db <database_name> from <temp_restore_directory> replace history file Listing 5. Restore database on the standby machine >cd tmpdir >db2 restore db sample replace history file DB20000I The RESTORE DATABASE command completed successfully. After restoring all databases on the standby machine, all the DB2 HADR variables shown in Listing 6 for each database must be copied from the primary DB2 server to the standby server. From the standby DB2 server perspective, the primary DB2 server is the remote host. Thus, you need to modify the hadr_local_host, hadr_remote_host, hadr_local_svc and hadr_remote_svc values on the standby machine. In addition, the Automatic Client Reroute must be updated to point to the primary machine. Notice that the port 60000 is the DB2 instance port number on the primary machine. Listing 6. HADR variables of the Sample database on the standby machine >db2 update db cfg for Sample using hadr_local_host <standby machine IP address> >db2 update db cfg for Sample using hadr_remote_host <primary machine IP address> >db2 update db cfg for Sample using hadr_local_svc ha_sample_int >db2 update db cfg for Sample using hadr_remote_svc ha_sample >db2 update alternate server for database Sample using hostname <Primary machine IP address> port 60000 It is critical that all the HADR parameters be set with proper values prior to starting DB2 HADR on either the primary or standby machine. If any of these parameters are empty or misconfigured, DB2 HADR servers will not start properly. In addition, DB2 HADR needs to be started on the standby machine first, before it is started on the primary machine. On the standby machine, first deactivate the database and then issue the start hadrcommand to start it as the standby database (Listing 7). db2 deactivate db <database_name> db2 start hadr on db <database_name> as standby Listing 7. Deactivate and start the Sample as the standby database >db2 deactivate db sample >db2 start hadr on db sample as standby DB20000I The START HADR ON DATABASE command completed successfully >db2 get snapshot for db on sample | grep Role Role = Standby On the primary machine, first activate the database and then issue the start hadr command to start it as the primary database (Listing 8). db2 activate db <database_name> db2 start hadr on db <database_name> as primary Listing 8. Activate and start the Sample as the primary database > db2 activate db sample > db2 start hadr on db sample as primary DB20000I The START HADR ON DATABASE command completed successfully > db2 get snapshot for db on sample | grep Role Role = Primary When starting DB2 HADR servers, you should receive a message indicating that the "START HADR ON DATABASE command completed successfully" message. To ensure that HADR servers are running on the primary and standby machines with the proper roles, you can issue this command on the primary and standby machine to verify: db2 get snapshot for db on <database_name> | grep Role Under the HADR status role, you will see "Standby" for the standby machine and "Primary" for the primary machine. If you can't get the proper indicator for each database, you need to review all previous steps. After the databases on the standby and primary machines are started successfully, you need to ensure that both databases are in sync. If they are not, the failover will not work successfully, which makes it possible to get undesirable results, such as data loss. Issue this command to check the state for both databases on the primary and standby database machines: db2 get snapshot for database on <database_name> | grep State You will need to wait until the standby database makes a connection with the primary database to get both databases in peer mode. Once the databases are in peer mode, the DB2 HADR servers on the primary and standby machines are ready for use. DB2 Universal JDBC Driver behavior when running DB2 HADR Although DB2 JDBC Universal Driver will transparently connect to the appropriate database server (that is, the primary versus the alternate), there are differences when comparing the DB2 Universal JDBC Driver Type2 and Driver Type4: DB2 Universal Driver Type2 After the first successful connect to the DB2 database, DB2 will update the JDBC driver with the alternate server information. The alternate server information then gets stored on the JDBC driver side, in memory as well as in a DB2 database directory (persistent on disk). When the connection to the primary DB2 server fails, DB2 will retrieve the alternate server information from memory (or from the DB2 persistent copy, if the alternate server information is not found in memory). The DB2 driver will then use the alternate server information to connect to the right DB2 server. The entire process is transparent to the user. DB2 Universal Driver Type4 After the first successful connect to the DB2 database, DB2 will also update the JDBC driver with the alternate server information. However, the alternate server information will only be stored in memory on the JDBC driver side. When the connection to the primary DB2 server fails, DB2 will retrieve the alternate server information from memory and will use that alternate server information to connect to the right DB2 server. The entire process is transparent to the user. The fact that Type4 only updates the information in memory and does not persist it in the DB2 persistent copy (as is the case with Type2) causes the alternate server information to be lost if the client side JVM (for example, WebSphere Application Server) is shutdown (normally or abnormally). The information is, of course, restored when the connection is established again; however, an issue could arise if the client side JVM is restarted after the DB2 primary failed-over to a standby. In this case, the client will not know about the alternate server information, and instead will continue to connect to the primary (which is down). See the Appendix for more details on how to persist the HADR alternate server information when using the DB2 Universal JDBC Driver Type4. Configuring WebSphere Application Server Defining your data source in WebSphere Application Server ND should be straightforward, since there is no special requirement for setting up a connection with an HADR-enabled DB2 server. You can configure your DB2 data source to be of Type2 or Type4 to connect to DB2. For the DB2 server name, you need only enter the primary DB2 server machine. WebSphere Application Server doesn't need to know anything about the standby machine, since the high availability and client reroute features are supported on the DB2 server side. Hence, you will define your DB2 datasource in the same manner as if you were not using HADR. Here is an example of configuring a DB2 HADR connection on WebSphere Application Server ND: - Create DB2 Universal JDBC Driver provider. - Create a new data_source by selecting JDBC providers => DB2 Universal JDBC Driver Provider => Data sources => <DataSource_Name>. Create the data source with all the information of the primary DB2 machine only (Figure 1). Before testing the DB2 HADR takeover behavior, you need to verify that the connection between WebSphere Application Server and the DB2 HADR primary machine works well. Figure 1. Data source configuration on the WebSphere Application Server console By default, the DB2 Automatic Client Reroute feature retries to establish a connection to the database repeatedly for up to 10 minutes. It is, however, possible to configure the exact retry behavior. Users of Type4 connectivity with the DB2 Universal JDBC Driver can use the following JDBC custom properties to do so: - maxRetriesForClientReroute: Use this property to limit the number of retries, if the primary connection to the server fails. This property is only used if the retryIntervalClientReroute property is also set. - retryIntervalForClientReroute: Use this property to specify the amount of time (in seconds) to sleep before retrying again. This property is only used if the maxRetriesForClientReroute property is also set. These properties can have an effect of better turnaround time by limiting the duration in which an automatic reroute is attempted and returning an error quicker to the application, if a reroute is not possible. From the WebSphere Application Server administrative console: - To configure resources, navigate to JDBC providers => DB2 Universal JDBC Driver Provider => Data sources => <DataSource_Name> => Custom properties. - Select New and add these custom properties: - maxRetriesForClientReroute: 2 - retryIntervalForClientReroute: 15 - Apply and save your configuration. The above example has the effect of limiting reroute to 2 attempts with a 15 second sleep time between attempts. Figure 2 shows how to set these properties. The actual values you set will depend on the hardware and topology in your environment. Figure 2. Add custom properties for Data source configuration Refer to the DB2 documentation on Automatic Client Reroute configuration for the equivalent DB2 Registry variables and additional details. HADR takeover When the WebSphere Application Server application is connected to the DB2 HADR primary machine, you can start verifying the HADR failover behavior. Issue the following commands on the standby server for a DB2 HADR takeover to occur (Listing 9). db2 takeover hadr on db <database_name> It is a good practice to check that your database on the standby machine has the "primary role" after the takeover. db2 get snapshot for db on <database name> | grep Role Listing 9. Database takeover on the standby machine > db2 takeover hadr on db sample DB20000I The TAKEOVER HADR ON DATABASE command completed successfully. After the takeover, WebSphere Application Server needs to get a new connection to access the database on the standby machine. You will see the following messages logged in the SystemOut.log files (Listing 10) indicating that the application first tried to connect to the primary machine and then re-attempted to connect to the standby machine. Once the application retries, it should obtain a new connection to the standby database. Listing 10. WebSphere Application Server SystemOut.log [11/1/06 17:15:39:298 CST] 00000039 ServletWrappe E SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: /dbview.jsp. Exceptionthrown : javax.servlet.ServletEx.O37F.061101231714 There are other types of failure situations in which database takeover must be performed by force for the connection between WebSphere Application Server and DB2 HADR to work. Below are some sample situations so you can examine the differences. Case 1 The primary is unavailable from the network. The state on the standby machine becomes "Remote catchup pending" (Listing 11), meaning that the standby has lost the connection to the primary. Listing 11. Remote catchup pending state on the standby > db2 get snapshot for database on sample | grep State State = Remote catchup pending In this case, WebSphere Application Server connections with DB2 UDB will timeout. Failover does not occur automatically, since WebSphere Application Server still has a connection with the primary database. Therefore, a "takeover by force" command, shown below, must be performed on the standby machine. Once the takeover takes place, WebSphere Application Server will establish new connections to the standby database. db2 takeover hard on db <database name> by force The state will be changed to "Disconnected" for a while, since the primary is not available from the network at the time of takeover (Listing 12). Listing 12. Database takeover by force on the standby > db2 takeover hadr on db Sample by force DB20000I The TAKEOVER HADR ON DATABASE command completed successfully. > db2 get snapshot for database on sample | grep Role Role = Primary > db2 get snapshot for database on sample | grep State State = Disconnected Case 2 A regular DB2 database is used as the WebSphere Application Server application datastore. A JDBC provider is configured to connect to the database from the applications. Later, it is decided to switch the database to HADR-enabled DB2. After setting up HADR and starting the database server, the first time the application tries to connect to the primary HADR database, it will log the following message in SystemOut.log: Listing 13. WebSphere Application Sever SystemOut.log [10/27/06 0:26:27:796 CDT] 0000002b WebApp E [Servlet Error]-[/dbview.j sp]: com.ibm.websphere.ce.cm.StaleConnectionEx.A7AD.061027052803...) Once the application reattempts to connect to the database, it will get the connection successfully. Case 3 During the time that the primary machine is off-line, requests keep coming through WebSphere Application Server to access the standby database. The data on the standby database might be modified based on client requests. Therefore, when the primary is back online again, the databases on the primary and standby might be out of sync. In this situation, you need to start the database on the primary machine as the standby to get the two databases back in sync again. Since the two databases are out of sync, HADR will automatically sync both databases by changing the state from S-RemoteCatchup to S-NearlyPeer, and finally to S-Peer. The following messages logged in the db2diag.log file show the state changes during the database sync operation. Listing 14. State changes logged in the db2diag.log file 2006-11-01-17.06.15.113214-360 I383930C400 LEVEL: Warning PID : 4021 TID : 4160127008 PROC : db2agent (SAMPLE) 0 INSTANCE: db2inst1 NODE : 000 DB : SAMPLE APPHDL : 0-8 APPID: *LOCAL.db2inst1.061101230614 FUNCTION: DB2 UDB, High Availability Disaster Recovery, hdrEduStartup, probe:211 52 MESSAGE : Info: HADR Startup has completed. 2006-11-01-17.06.15.669454-360 E384331C363-RemoteCatchup (was S-RemoteCatchupPending) 2006-11-01-17.06.16.145289-360 E385032C-NearlyPeer (was S-RemoteCatchup) 2006-11-01-17.06.16.240636-360 E385386C-Peer (was S-NearlyPeer) Case 4 To avoid transaction failures for a planned takeover when WebSphere Application Server is not actively serving clients, or to reduce transaction failures for a planned takeover while WebSphere Application Server is actively serving clients, you can first purge the connection pools, then issue the takeover command and purge the pool again (in the case of the application server actively serving clients). For example, suppose the plan is to shut down the primary machine overnight. The next day, starting client requests without purging the connection pool first (even if takeover was done on the database side from the primary to alternate) will result in the client requests using bad connections from the WebSphere Application Server connection pool (assuming they haven't aged out). Hence, the requests will fail until the pool cleans itself of the bad connections. Therefore, it is best to purge the pool manually to avoid this situation. To purge the connection pool of WebSphere Application Server, go to the deployment manager bin directory and issue the following commands for each application server (see WebSphere connection pool can be purged using MBeans Technote for details): ./wsadmin.sh set ds [$AdminControl queryNames type=DataSource, name=<ds_name>] $AdminControl invoke $ds purgePoolContents Listing 15. Purge the database connection pool for server2 >./wsadmin.sh >set ds [$AdminControl queryNames type=DataSource,name=myDS,process=server2,*] >$AdminControl invoke $ds purgePoolContents You can also purge all the pools in WebSphere Application Server with one command: Listing 16. Purge all pools >./wsadmin.sh >set mbeans [$AdminControl queryNames type=DataSource,*] foreach mbean $mbeans { >$AdminControl invoke $mbean purgePoolContents } You can then issue the takeover command on the standby machine. Since the connection pool on the primary has been purged and the takeover command has been issued, all client requests will be automatically directed to the standby without getting lots of failure messages logged in the SystemOut.log (Listing 13). Know if the takeover occurs while WebSphere Application Server is actively serving clients, there is still a small window in which some connections will be opened after the pool is purged and before the takeover is complete. Fallback to the primary machine Prior to fallback to the primary machine, you need to ensure that the DB2 UDB server has been started successfully on the primary, then issue the command below on the primary machine to take over the database from the standby machine. db2 takeover hadr on db <database name> Double check that the database on the primary machine has the proper role: db2 get snapshot for database on <database name> | grep Role It should return with "Primary." Also, the state now for both databases on the standby and primary should be in the "Peer" state. Troubleshooting For your reference, here is a collection of causes and solutions for some of the possible problems that you might encounter using DB2 HADR: SQL1768N Unable to start HADR. Reason code = "7" when starting the primary or standby database. The possible cause of this problem is that the primary database failed to establish a connection to its standby within the HADR timeout interval. You can adjust the interval to fit with your environment. SQL1768N Unable to start HADR. Reason code = "8" when starting the primary or standby database. Check the required HADR variables below (see Listing 3). They must be correct and cannot be empty: - HADR database role - HADR local host name - HADR remote host name - HADR remote service name - HADR instance name of remote server - HADR timeout value - HADR log write synchronization mode SQL1768N Unable to start HADR. Reason code = "99" when starting the primary or standby database. Examine the HADR ports and names used for each database in the /etc/services file. They should have identical hadr_remote_svc and hard_local_svc settings, as described above. SQL1769N Stop HADR cannot complete. Reason code = "2" when stopping the primary or standby database. In this case, you can deactivate the database prior to stopping the HADR: db2 deactivate db <database_name> db2 stop hadr on db <database_name> SQL30081N A communication error has been detected when starting HADR on the primary or standby machine. Check key parameters to make sure they are configured correctly on all DB2 UDB server machines. Login in to the database machine with the DB2 UDB user account (for example: db2inst1), then type these commands at the user prompt: db2start (if DB2 is not running) db2set DB2COMM=TCPIP db2set DB2AUTOSTART=YES db2 update dbm cfg using SVCENAME DB2_db2inst1 db2stop db2start (The SVCENAME is the TCP/IP service name on your configuration is in the /etc/services file.) SQL2406N The BACKUP cannot be performed because the data base needs to be rolled forward. SQLSTATE=57019 when backing up the database. You need to roll forward your database by using this command (also in Listing 17). db2 rollforward db <database_name> to end of logs and stop Listing 17. Database rollfoward >db2 rollforward db sample to end of logs and stop Rollforward Status Input database alias = sample Number of nodes have returned status = 1 Node number = 0 Rollforward status = not pending Next log file to be read = Log files processed = S0000000.LOG - S0000006.LOG Last committed transaction = 2006-10-06-16.22.35.000000 DB20000I The ROLLFORWARD command completed successfully Takeover doesn't work on the primary or standby machine. You can issue the takeover command by force: db2 takeover hard on db <database_name> by force Conclusion DB2 Universal Database (UDB) High Availability Disaster Recovery (HADR) provides a high availability solution for its client application. As a client application, WebSphere Application Server has the capability to distinguish between a database failure verses a takeover situation. When a DB2 HADR takeover occurs, WebSphere Application Server re-establishes its connection, leveraging the DB2 Automated Client Reroute feature automatically to the standby HADR server. This article used WebSphere Application Server Network Deployment V6.1 and DB2 UDB HADR to demonstrate how the takeover happens between these two products. You have gone through the steps to enable DB2 with HADR and to configure WebSphere Application Server ND to connect to DB2 HADR. You also learned about the takeover behavior and the expected messages logged in the WebSphere Application Server log files during the takeover. In addition, you received some troubleshooting tips and techniques for several common error situations. There is no extra configuration step required on WebSphere Application Server to make the HADR failover to work successfully. WebSphere Application Server takes the advantage of the technologies provided by DB2 UDB HADR and the Automatic Client Reroute feature to provide a highly available environment for your applications. Part 2 of this series will look at attaining high availability databases using Oracle® Real Application Cluster with WebSphere Process Server. Appendix To persist HADR alternate server information when using DB2 Universal JDBC Driver Type4: Add a new DataSource custom property in the WebSphere Application Server administrative console with these values: - Name: clientRerouteServerListJNDIName - Type: java.lang.String - Value: cell/persistent/alSrvlist(here, "cell" should be used as is; this is NOT the cell name) The value of the clientRerouteServerListJNDIName must have the cell/persistent/in front of it. Otherwise, the JNDI object will not be persisted in WebSphere Application Server. The value here should match the JNDI name passed in the T4CRBind.java file (see the registry.bind and regirstry.unbind lines in Listing 18). Save and sync your entire cell. Copy the program in Listing 18, and compile it with the db2jcc.jar file. From the WAS_HOME/bin directory, execute the compile command below, then put the T4CRBind.class in WAS_HOME/bin directory: javac -classpath /home/db2inst1/sqllib/java/db2jcc.jar:$CLASSPATH T4CRBind.java Be sure "java" is in your path (that is, set PATH=$JAVA_HOME/bin). If the db2jcc.jar file is located in a different path, then adjust as required. Create a launcher program that can launch the T4CRBind class as shown in Listing 19. Restart the WebSphere Application Server that is running your application and start the launcher program from the WAS_HOME/bin directory. You can launch the program by executing: launchT4CRBind.sh T4CRBind Prior to running this command, make sure that your entire cell is running. This includes the deployment manager, node agents, and application servers. Be aware that the program below will not work when WebSphere Application Server global security is enabled. Furthermore, if you are running with global security enabled and want the persistence of alternate server information to work at run time, you will need APAR PK48854 (available for 6.1.0.15 and later). Listing 18. T4CRBind.java import javax.naming.InitialContext; import com.ibm.db2.jcc.DB2ClientRerouteServerList; public class T4CRBind { public static void main(String[] args) { try { InitialContext registry = new InitialContext(); DB2ClientRerouteServerList address = new DB2ClientRerouteServerList(); int[] alternateServerPorts = { 60000 }; String[] alternateServerHosts = { "svtclark.rchland.ibm.com" }; address.setPrimaryPortNumber(60000); address.setPrimaryServerName("svtlewis.rchland.ibm.com"); address.setAlternatePortNumber(alternateServerPorts); address.setAlternateServerName(alternateServerHosts); registry.unbind("cell/persistent/alSrvlist"); registry.rebind("cell/persistent/alSrvlist", address); System.out.println("JNDI Registration done...."); } catch (Exception e) { e.printStackTrace(); } } } Listing 19. launchT4CRBind.sh #!/bin/sh binDir=`dirname $0` . "$binDir/setupCmdLine.sh" CMD_NAME=`basename $0` if [ -f ${JAVA_HOME}/bin/java ]; then JAVA_EXE="${JAVA_HOME}/bin/java" else JAVA_EXE="${JAVA_HOME}/jre/bin/java" fi DB2JCC_HOME="/home/db2inst1/sqllib/java/db2jcc.jar" export DB2JCC_HOME CLASSPATH=".:$DB2JCC_HOME:$WAS_CLASSPATH" export CLASSPATH # In the case where more than one application server is installed, you will need to run # the synch to make sure that the name space of the entire cell is updated. Also, if the # port for the naming space is not the default, then you will need to specify the # –Djava.naming.provider.url= <specify the url here> "$JAVA_HOME/bin/java" \ "-Dwas.install.root=$WAS_HOME" \ "-Djava.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory" \ * -classpath "$CLASSPATH" com.ibm.ws.bootstrap.WSLauncher "$@" exit 0 Resources - WebSphere Application Server V6.1 Information Center - DB2 Information Center - DB2 High Availability Disaster Recovery.
http://www.ibm.com/developerworks/websphere/techjournal/0705_lee/0705_lee.html
CC-MAIN-2014-41
refinedweb
5,045
51.28
C++ virtual function is a member function that is declared in the base class and redefined by a derived class. The virtual function is used to tell the compiler to perform dynamic linkage or late binding (means, the compiler determines the type of object it is having and then it binds the function call) on the function. We have to create a pointer to the base class, and then that pointer refers to the object of the derived class. Virtual Function in C++ Polymorphism refers to a property by which objects belonging to a different class can respond to the same message but in various forms. When there are C++ functions with the same name in both superclass as well as a subclass, virtual functions gives programmer capability to call a member function of a different class by the same function call based upon different context. Virtual functions ensure that a correct function is called for the object, regardless of an expression used to make a function call. Suppose the base class contains the function declared as a virtual, and the derived class defines the same function. The function from a derived class is invoked for the objects of a derived class, even if it is called using the pointer or reference to the base class. They are mainly used to achieve the Runtime polymorphism. Functions are declared with the virtual keyword in the base class. The resolving of a function call is done at the Run-time. If we want to declare a virtual function, the virtual keyword is used. #Concept non-virtual function Before knowing the virtual function, we first have to know what happens when we don’t use the virtual function. First, refer to the below function. #include<iostream> using namespace std; //Bank is Base Class class Bank { public: //declaring non-virtual function here. In the above example, we can see that *ptr is the pointer of the base class. This pointer can only be accessed by the based class, not the members of the derived class members. #Virtual Function Concept If you want to overcome the above situation, we virtual function. Using the virtual function, we can access the members of the derived class. See the below example to understand the concept. #include<iostream> using namespace std; //Bank is Base Class class Bank { public: //declaring virtual function here virtual. So from the above example, we can see that the compiler determines the type of an object at run time and then it is calling the appropriate function. #Rules of virtual function - This function cannot be static and can not be a friend function of another class. - It must be a member of some other class. - This function can be accessed through object pointers. - The virtual function must be declared in base class only. - This function should be accessed using pointer or reference of base class type to achieve runtime polymorphism. - We cannot have a virtual constructor, but we can have a virtual destructor. - The prototype of this type of function should be the same in the base as well as derived class. #Concept of Pure Virtual Function A virtual function, which is not used to perform any task, only serves as a placeholder, is called Pure Virtual Function. Declaration of Pure Virtual Function ends with = 0 only. See the following code. class Student { public: virtual void details()=0; }; This function is also called doing nothing function because although it is declared in the base class, it has no definition. In this function, the main objective of a base class is to provide the traits to derived classes and to create a base pointer used for achieving a runtime polymorphism. Important note on the pure virtual function that you always should override the pure virtual function of the base class in the derived class, if you forget to override the derived class will become an abstract class. Now, we will see one example of a pure virtual function. See the following program. #include<iostream> using namespace std; //Declaring Base Class class student { public: //creating pure virtual function virtual void details()=0; }; //declaring Derived class class Info:public student { public: void details() { cout<<"\nName: Debasis\nRoll: 14"; } }; int main() { student *s; Info i; s=&i; s->details(); return 0; } See the following output. So in the example, we can see that in the base class student we have declared one pure virtual function details() and then in the derived class we have used it. So, here we end the concept of virtual function. Finally, Virtual Function in C++ Example is over.
https://appdividend.com/2019/07/02/virtual-function-in-c-example-c-virtual-function-tutorial/
CC-MAIN-2020-29
refinedweb
764
61.36
Details Description importtsv support importing into a life table or to generate HFiles for bulk load. import should allow the same. Could even consider merging these tools into one (in principle the only difference is the parsing part - although that is maybe for a different jira). 152.coprocessor.TestClassLoading. Ran the failed tests locally. They all pass. Would review board help? This is actually a pretty simple change: import can optionally import into HFiles. In that case a new mapper and an additional reducer are used (similar to what importtsv does). Most of the changes are just so that code can be shared between KeyValueImporter and the existing Importer mapper classes. LGTM. Whats missing is better documentation in the usage for Import. This new option will be under a rock unless its better surfaced. +1 on commit after beefing up usage. Add some lines under here: - System.err.println("Usage: Import <tablename> <inputdir>"); + System.err.println("Usage: Import [-D" + BULK_OUTPUT_CONF_KEY + + "=/path/for/output] <tablename> <inputdir>"); ... going on about what the -D thingy does. Good stuff. Yeah, you're right of course Will do and a post a new patch soon. How about this. Same patch, just different message. Note that I manually tested this. I have not managed to create a test for this. Might think about a good test more in a separate jira. Committed to trunk. Thanks for reviewing stack! Integrated in HBase-TRUNK-security #122 (See) HBASE-5440 Allow Import to optionally use HFileOutputFormat (Revision 1293101) Result = FAILURE larsh : Files : - /hbase/trunk/src/main/java/org/apache/hadoop/hbase/mapreduce/Import.java Integrated in HBase-TRUNK #2669 (See) HBASE-5440 Allow Import to optionally use HFileOutputFormat (Revision 1293101) Result = SUCCESS larsh : Files : - /hbase/trunk/src/main/java/org/apache/hadoop/hbase/mapreduce/Import.java Thanks Lars and Stack. I actually had a chance to play around with this a bit over the weekend and it certainly suited my purposes of being able to restore in a reasonable timeframe should disaster strike. We are actually still on 0.90.4 so I backported the relevant portions of the changes to that version of Import. Happy to create a patch if folks think that might be interesting. Hey Paul, I am glad this is useful for you. Reducing the timeframe for recovery is exactly what I had in mind with this. @Stack and @Ram: Are we doing more 0.90 releases? Should we add this? First cut. Only used when -Dimport.bulk.output=<path/to/output> is set. I did experiment with a Reducer that accepts Mutation (common super class of Put and Delete), but that caused more problems than it solved, hence the KeyValueImporter.
https://issues.apache.org/jira/browse/HBASE-5440?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
CC-MAIN-2014-10
refinedweb
446
60.82
Random nextGaussian() method in Java In this tutorial, we are going to learn about the nextGaussian() method which is present in the Random class in Java. It is used to generate the next pseudorandom Gaussian double value with a mean of 0.0 and standard deviation of 1.0 from this random value generator’s sequence. Let’s see some points… - This method is present in java.util package. - It does not throw an exception at the time of returning a value. - The method does not accept any parameter. - The return type of the method is double, it returns the random Gaussian distributed double value with mean and standard deviation from this Random Generator. There are various applications of the method: - It is used in mathematics. - It is also used in modelling and simulation. - It also can be used for sampling the packets as it generates clusters of values with mean and standard deviation. Random nextGaussian() method in Java Following are the steps we need to follow to achieve our goal: - Import java.util package. - Create an object of Random class. Random random=new Random(); - Create one double variable to store the number generated from the nextGaussian() method. double value=random.nextGaussian(); - Finally, print the number. Following is the code for our task: Example 1: //import package import java.util.Random; public class nextGaussian { public static void main(String[] args) { //create object of random class Random random=new Random(); //return pseudorandom Gaussian value double value=random.nextGaussian(); //print the value System.out.println("Random Gaussian value: "+value); } } Output 1: Random Gaussian value: -0.09891103710685835 Output 2: Random Gaussian value: 0.6904242633193539 Example 2: import java.util.Random; public class nextGaussian { public static void main(String[] args) { Random random=new Random(); for(int i=0;i<5;i++) { double value=random.nextGaussian(); System.out.println("Random Gaussian value: "+value); } } } Output: Random Gaussian value: -2.270553436367474 Random Gaussian value: 0.06981849943114561 Random Gaussian value: -0.9181225040401672 Random Gaussian value: 0.3383560104821811 Random Gaussian value: -1.1352213899667787 This is how we can implement nextGaussian method in Java. I hope you find this tutorial useful. Also, read: Find the second-highest number in an ArrayList in Java
https://www.codespeedy.com/random-nextgaussian-method-in-java/
CC-MAIN-2021-43
refinedweb
363
52.05
Frequency aliasing is a physical effect whereby the sampling frequency of a disturbance masks the actual frequency of the disturbance. For example, imagine the electrical system in Europe where AC frequency is 50Hz. A system that samples the AC frequency at 53Hz will not measure the AC frequency as 50Hz, but rather as 3Hz. This effect is aliasing. Aliasing shows up often in engineering, where it is important to understand that measured frequencies do not always represent frequencies of anything fundamental to the system. However, with information about the measured frequency and the sampling frequency, the actual frequency of a disturbance (or its harmonics) are known. The interactive plotter below demonstrates the aliasing effect. By default, it is meant to represent sampling of a 50Hz signal at 53Hz, which because of the aliasing effect is measured as a 3Hz signal. The 3Hz signal can be seen in the time domain in the top figure and in the frequency domain in the bottom figure. Use the green buttons to interact with what you see below - the sliders also work. Increase the sample frequency until the original 50Hz signal appears. Or reduce the signal frequency until the aliasing effect disappears. Play around with it! The fundamental frequency of a signal cannot be measured when it is sampled at a frequency lower than twice (2x) the signal frequency (half of the sample frequency is the Nyquist Frequency). In this scenario, the signal frequency has been aliased to a different frequency. Another visual representation of this effect is included here, where a 12Hz signal has been sampled at 9Hz which has created a 3Hz signal under measurement. As an engineer who has measured a 3Hz signal by sampling a system at 9Hz, it is impossible to know for sure if there is really a 3Hz disturbance or if the 3Hz measurement indicates a 12Hz disturbance is present - another possibility is the 2nd harmonic of a 6Hz disturbance is responsible! An understanding of the aliasing effect must be paired with system knowledge in this scenario. The aliased frequency can be determined from the signal frequency and the sample frequency in a Python function. All possible aliased frequencies also usually include harmonics of the signal frequency. The function below can be used to generate a table of aliased frequencies given a sampling frequency, a signal frequency, and N harmonics of interest of the signal frequency. def get_aliased_freq(f, fs): """ return aliased frequency of f sampled at fs """ import numpy as np fn = fs / 2 if np.int(f / fn) % 2 == 0: return f % fn else: return fn - (f % fn)
https://rbtechblog.com/blog/freq_alias
CC-MAIN-2020-10
refinedweb
433
52.49
. A full adder Let’s start with an adder for two one-bit numbers. Because of the possibility of overflow, the result will be two bits, which I’ll call “sum” and “carry”. So that we can chain these one-bit adders, we’ll also add a carry input. addB ∷ (Bool,Bool) → Bool → (Bool,Bool) In the result, the first Bool will be the sum, and the second will be the carry. I’ve curried the carry input to make it stand out from the (other) addends. There are a few ways to define addB in terms of logic operations. I like the following definition, as it shares a little work between sum & carry: addB (a,b) cin = (axb ≠ cin, anb ∨ (cin ∧ axb)) where axb = a ≠ b anb = a ∧ b I’m using (≠) on Bool for exclusive or. A ripple carry adder Now suppose we have not just two bits, but two sequences of bits, interpreted as binary numbers arranged from least to most significant bit. For simplicity, I’d like to assume that these sequences to have the same length, so rather than taking a pair of bit lists, let’s take a list of bit pairs: add ∷ [(Bool,Bool)] → Bool → ([Bool],Bool) To implement add, traverse the list of bit pairs, threading the carries: add [] c = ([] , c) add (p:ps) c = (s:ss, c'') where (s ,c' ) = addB p c (ss,c'') = add ps c' State This add definition contains a familiar pattern. The carry values act as a sort of state that gets updated in a linear (non-branching) way. The State monad captures this pattern of computation: newtype State s a = State (s → (a,s)) By using State and its Monad instance, we can shorten our add definition. First we’ll need a new full adder definition, tweaked for State: addB ∷ (Bool,Bool) → State Bool Bool addB (a,b) = do cin ← get put (anb ∨ cin ∧ axb) return (axb ≠ cin) where anb = a ∧ b axb = a ≠ b And then the multi-bit adder: add ∷ [(Bool,Bool)] → State Bool [Bool] add [] = return [] add (p:ps) = do s ← addB p ss ← add ps return (s:ss) We don’t really need the Monad interface to define add. The simpler and more general Applicative interface suffices: add [] = pure [] add (p:ps) = liftA2 (:) (addB p) (add ps) This pattern also looks familiar. Oh — the Traversable instance for lists makes for a very compact definition: add = traverse addB Wow. The definition is now so simple that it doesn’t depend on the specific choice of lists. To find out the most general type add can have (with this definition), remove the type signature, turn off the monomorphism restriction, and see what GHCi has to say: add ∷ Traversable t ⇒ t (Bool,Bool) → State Bool (t Bool) This constraint is very lenient. Traversable can be derived automatically for all algebraic data types, including nested/non-regular ones. For instance, data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving (Functor,Foldable,Traversable) We can now specialize this general add back to lists: addLS ∷ [(Bool,Bool)] → State Bool [Bool] addLS = add We can also specialize for trees: addTS ∷ Tree (Bool,Bool) → State Bool (Tree Bool) addTS = add Or for depth-typed perfect trees (e.g., as described in From tries to trees): addTnS ∷ IsNat n ⇒ T n (Bool,Bool) → State Bool (T n Bool) addTnS = add Binary trees are often better than lists for parallelism, because they allow quick recursive splitting and joining. In the case of ripple adders, we don’t really get parallelism, however, because of the single-threaded (linear) nature of State. Can we get around this unfortunate linearization? Speculation The linearity of carry propagation interferes with parallel execution even when using a tree representation. The problem is that each addB (full adder) invocation must access the carry out from the previous (immediately less significant) bit position and so must wait for that carry to be computed. Since each bit addition must wait for the previous one to finish, we get linear running time, even with unlimited parallel processing available. If we didn’t have to wait for carries, we could instead get logarithmic running time using the tree representation, since subtrees could be added in parallel. A way out of this dilemma is to speculatively compute the bit sums for both possibilities, i.e., for carry and no carry. We’ll do more work, but much less waiting. State memoization Recall the State definition: newtype State s a = State (s → (a,s)) Rather than using a function of s, let’s use a table indexed by s. Since s is Bool in our use, a table is simply a uniform pair, so we could replace State Bool a with the following: newtype BoolStateTable a = BST ((a,Bool), (a,Bool)) Exercise: define Functor, Applicative, and Monad instances for BoolStateTable. Rather than defining such a specialized type, let’s stand back and consider what’s going on. We’re replacing a function by an isomorphic data type. This replacement is exactly what memoization is about. So let’s define a general memoizing state monad: newtype StateTrie s a = StateTrie (s ⇰ (a,s)) Note that the definition of memoizing state is nearly identical to State. I’ve simply replaced “ →” by “ ⇰”, i.e., memo tries. For the (simple) source code of StateTrie, see the github project. (Poking around on Hackage, I just found monad-memo, which looks related.) The full-adder function addB is restricted to State, but unnecessarily so. The most general type is inferred as addB ∷ MonadState Bool m ⇒ (Bool,Bool) → m Bool where the MonadState class comes from the mtl package. With the type-generalized addB, we get a more general type for add as well: add ∷ (Traversable t, Applicative m, MonadState Bool m) ⇒ t (Bool,Bool) → m (t Bool) add = traverse addB Now we can specialize add to work with memoized state: addLM ∷ [(Bool,Bool)] → StateTrie Bool [Bool] addLM = add addTM ∷ Tree (Bool,Bool) → StateTrie Bool (Tree Bool) addTM = add What have we done? The essential tricks in this post are to (a) boost parallelism by speculative evaluation (an old idea) and (b) express speculation as memoization (new, to me at least). The technique wins for binary addition thanks to the small number of possible states, which then makes memoization (full speculation) affordable. I’m not suggesting that the code above has impressive parallel execution when compiled under GHC. Perhaps it could with some par and pseq annotations. I haven’t tried. This exploration helps me understand a little of the space of hardware-oriented algorithms. The conditional sum adder looks quite similar to the development above. It has the twist, however, of speculating carries on blocks of a few bits rather than single bits. It’s astonishingly easy to adapt the development above for such a hybrid scheme, forming traversable structures of sequences of bits: addH ∷ Tree [(Bool,Bool)] → StateTrie Bool (Tree [Bool]) addH = traverse (fromState ∘ add) I’m using the adapter fromState so that the inner list additions will use State while the outer tree additions will use StateTrie, thanks to type inference. This adapter memoizes and rewraps the state transition function: fromState ∷ HasTrie s ⇒ State s a → StateTrie s a fromState = StateTrie ∘ trie ∘ runState Geoffrey Irving: It’s probably worth mentioning the way addition (and similar associative operations) are normally parallelized, namely parallel prefix circuits.27 November 2012, 9:25 pm conal: Hi Geoffrey. I’m glad you brought up parallel prefix sum, and more generally scans, which I wrote about here recently. As I understand them, parallel prefix (aka “prefix scan”) circuits add many numbers and produce sums of all prefixes (and more generally, associative operations, as you mentioned). The tricky bit is efficiently calculating all of the prefix sums, maximizing parallelism (to reduce time) and minimizing redundant computation (to reduce work). If one wants just a single result, then a balanced tree fold is much simpler and faster. In contrast, the problem I’m considering here is to add just a pair of numbers operating on the multiple bits in parallel, producing a single, multi-bit sum. I don’t know whether there are any interesting connections between pair addition and either scan or fold.28 November 2012, 11:02 am GrahamHutton: Hi Conal – have you looked at ‘carry save addition’, which uses an alternative representation of binary numbers to avoid the rippling carry in addition? Many moons ago myself and Erik Meijer wrote a paper about this:. It would be nice to see how this could be expressed using more modern FP ideas.28 November 2012, 2:17 pm augustss: Conal, I think Geoffrey is referring to one of the standard multibit adders which works by parallel prefix, but replacing the full adder by an associative operator.28 November 2012, 2:25 pm conal: Geoffrey & Lennart: Thanks! I’ll dig into these parallel prefix approaches.28 November 2012, 7:45 pm conal: Graham: thanks for the pointer to your paper and to carry save addition.28 November 2012, 7:46 pm
http://conal.net/blog/posts/parallel-speculative-addition-via-memoization
CC-MAIN-2016-07
refinedweb
1,507
57.71
Introduction to e-Commerce. A Little History. Dr. Michael D. Featherstone Fall 2009. Intro to the Internet and Dr. Michael D. Featherstone Fall 2009 The Web has no geography, no landscape. It has no distance. It has nothing natural in it. It has few rules of behaviour and fewer lines of authority. Common sense doesn’t hold there, and uncommon sense hasn’t yet emerged. No wonder we’re having trouble figuring out how to build businesses in this new land (Weinberger “Small Pieces Loosely Joined” 2002, p. 8). It grew like a weed without the shaping impact of a consciously defined social contract to determine what the medium should be delivering, for what purpose, and with what value. Perhaps it happened too fast, too unexpectedly for constructive reflection; so that the technology shaped us before we could shape it. Donnelly “The Confetti Generation: How the new communications technology is fragmenting America”, 1986, p. 21 The Web presents a new paradigm for business It represents a punctuated equilibrium in the business environment The Internet evolved. It was developed in the 1960’s in response the perceived threat of a nuclear attack during the ‘Cold War’ between the USA and the (former) USSR. It was built through the combined efforts of the Military, Industry, and Academe. Originally it was under the auspices of ARPANET, the Advanced Research Projects Agency. The Wizards: Vint Cerf and Robert KahnCerf and Kahn teamed up in the early 1970s to devise the TCP and IP protocols—the basic linking structure of the Internet. Before being anointed “chief Internet evangelist” by his current employer, Google, Cerf served as a senior vice president at MCI; he had begun his distinguished career as a student of Leonard Kleinrock’s at U.C.L.A. Kahn helped design the original Interface Message Processor for the Arpanet at Bolt, Beranek & Newman, in 1969, before heading the computer-research arm of ARPA. In 2005 the two men were awarded the Presidential Medal of Freedom. Factoid: Nobody knows who first used the word Internet - it just became a shortcut around this time for "internetworking". The earliest written use of the word appears to be by Vint Cerf in 1974 . Tracking the Internet into the 21st Century At some point in your careers, you will have the opportunity to introduce a boss or a manager or executive or colleague. It may be at a company conference or a national conference or merely a local or team meeting. Such an opportunity can provide tremendous exposure for you. You may or may not know the Web was invented by a single individual. Tim Berners-Lee invented the World Wide Web while at CERN in Switzerland. He also developed HTML – the hyper text markup language. (see view source) That means that the very first browser was his invention as well. He has since been ‘Knighted’ by Queen Elizabeth of England, so it’s “Sir Tim Berners-Lee now. <html> <head> <title>MensBowTies dot-com everything about bow ties</title> <meta name="description" content="shopping, everything about bow ties, mens fashion,"> <meta name="keywords" content="bow ties, bow tie, necktie, mens fashion"> <style> <!-- .welcome { font-size: 12pt; font-family: geneva,arial; color: ffffff } .small { font-size: 8pt; font-family: geneva,arial } td { font-family: geneva,arial; font-size: 10pt } .bold { font-weight: bold; font-family: geneva,arial; font-size: 10pt } .large { font-size: 12pt; } --> </style> <STYLE type="text/css"> <!-- Marc Andreesen developed the first commercial browser while at the University of Illinois. Originally referred to as the Mosaic browser, it became the Netscape browser. BROWSERS ARE JUST CODE aximp c:\windows\system\shdocvw.dll tlbimp mshtml.tlb namespace ND.WebBrowser { using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using Microsoft.Win32; using AxSHDocVw; using MSHTML; // etc..); } protected void mnuFileOpen_Click(object sender, EventArgs e) { OpenForm frmOpen = new OpenForm(); frmOpen.ShowDialog(this); if(frmOpen.DialogResult == DialogResult.OK) { Object o =AxWebBrowser.Navigate(frmOpen.Address, ref o, ref o, ref o, ref o); } } “The Internet ('Net) is a network of networks. Basically it is made from computers and cables. What Vint Cerf and Bob Kahn did was to figure out how this. … The Web is an abstract (imaginary) space of information. On the Net, you find computers -- on the Web, you find document,.” Quoted from Sir Tim Berners-Lee The dot-com bust of 2000-2002 And then everything changed. Fast-forward to the dot-com crash of 2000-2002. Venture capital investments started dropping immediately, borrowers defaulted, bond-market froze, and stock market started to tumble first slowly, and then, after September 11, it dropped down very fast, just like the falling comet. Companies started disappearing left and right, and the party quickly came to an end. Prospects disappeared, analysts changed their tune, and internet became a commodity. Note that this chart shows growth in EXPONENTIAL TERMS. Thank you for your attention
https://www.slideserve.com/Jimmy/introduction-to-e-commerce
CC-MAIN-2018-30
refinedweb
815
58.79
Tutorial: Integrate Amazon Business with Azure Active Directory In this tutorial, you'll learn how to integrate Amazon Business with Azure Active Directory (Azure AD). When you integrate Amazon Business with Azure AD, you can: - Control in Azure AD who has access to Amazon Business. - Enable your users to be automatically signed-in to Amazon. - An Amazon Business single sign-on (SSO) enabled subscription. Go to the Amazon Business page to create an Amazon Business account. Scenario description In this tutorial, you configure and test Azure AD SSO in an existing Amazon Business account. - Amazon Business supports SP and IDP initiated SSO - Amazon Business supports Just In Time user provisioning Adding Amazon Business from the gallery To configure the integration of Amazon Business into Azure AD, you need to add Amazon Amazon Business in the search box. - Select Amazon Business from results panel and then add the app. Wait a few seconds while the app is added to your tenant. Configure and test Azure AD single sign-on Configure and test Azure AD SSO with Amazon Business using a test user called B.Simon. To configure and test Azure AD SSO with Amazon Business, complete the following building steps: - Configure Azure AD SSO - to enable your users to use this feature. - Configure Amazon Business Amazon Business test user - to have a counterpart of B.Simon in Amazon Business that is linked to the Azure AD representation of user. - Test SSO - to verify whether the configuration works. Configure Azure AD SSO Follow these steps to enable Azure AD SSO in the Azure portal. In the Azure portal, on the Amazon in IDP initiated mode, perform the following steps: In the Identifier (Entity ID) text box, type a URL using one of the following patterns: In the Reply URL text box, type a URL using one of the following patterns: Note The Reply URL value is not real. Update this value with the actual Reply URL. You will get the <idpid>value from the Amazon Business SSO configuration section, which is explained later in the tutorial. You can also refer to the patterns shown in the Basic SAML Configuration section in the Azure portal. Click Set additional URLs and perform the following step if you wish to configure the application in SP initiated mode: In the Sign-on URL text box, type a URL: The following screenshot shows the list of default attributes. Edit the attributes by clicking on the Edit icon in the User Attributes & Claims section. Edit Attributes and copy Namespace value of these attributes into the Notepad. In addition to above, Amazon Business application expects few more attributes to be passed back in SAML response. In the User Attributes & Claims section on the Group Claims dialog, perform the following steps: a. Click the pen next to Groups returned in claim. b. Select All Groups from the radio list. c. Select Group ID as Source attribute. d. Check Customize the name of the group claim checkbox and enter the group name according to your Organization requirement. e. Click Save. On the Set up Single Sign-On with SAML page, in the SAML Signing Certificate section, find Metadata XML and select Download to download the certificate and save it on your computer. On the Set up Amazon Business section, copy the appropriate URL(s) based on your requirement. Configure Amazon Business SSO In a different web browser window, sign in to your Amazon Business company site as an administrator. Click on the User Profile and select Business Settings. On the System integrations wizard, select Single Sign-On (SSO). On the Set up SSO wizard, select the provider according to your Organizational requirements and click Next. On the New user account defaults wizard, select the Default Group and then select Default Buying Role according to user role in your Organization and click Next. On the Upload your metadata file wizard, click Browse to upload the Metadata XML file, which you have downloaded from the Azure portal and click Upload. After uploading the downloaded metadata file, the fields in the Connection data section will populate automatically. After that click Next. On the Upload your Attribute statement wizard, click Skip. On the Attribute mapping wizard, add the requirement fields by clicking the + Add a field option. Add the attribute values including the namespace, which you have copied from the User Attributes & Claims section of Azure portal into the SAML AttributeName field, and click Next. On the Amazon connection data wizard, click Next. Please check the Status of the steps which have been configured and click Start testing. On the Test SSO Connection wizard, click Test. On the IDP initiated URL wizard, before you click Activate, copy the value which is assigned to idpid and paste into the idpid parameter in the Reply URL in the Basic SAML Configuration section in the Azure portal. On the Are you ready to switch to active SSO? wizard, check I have fully tested SSO and am ready to go live checkbox and click on Switch to active. Finally in the SSO Connection details section the Status is shown as Active. Create an Azure AD test user In this section, you'll create a test user in the Azure portal called B.Simon. Note Adminstrators need to create the test users in their tenant if needed. Following steps show how to create a test user. -.. Assign the Azure AD test user In this section, you'll enable B.Simon to use Azure single sign-on by granting access to Amazon Business. In the Azure portal, select Enterprise Applications, and then select All applications. In the applications list, select Amazon Business.. Note If you do not assign the users in the Azure AD, you get the following error. Assign the Azure AD Security Group in the Azure portal In the Azure portal, select Enterprise Applications, select All applications, then select Amazon Business. In the applications list, type and select Amazon Business. Amazon Business test user In this section, a user called B.Simon is created in Amazon Business. Amazon Business supports just-in-time user provisioning, which is enabled by default. There is no action item for you in this section. If a user doesn't already exist in Amazon Business, a new one is created after authentication. Test SSO In this section, you test your Azure AD single sign-on configuration using the Access Panel. When you click the Amazon Business tile in the Access Panel, you should be automatically signed in to the Amazon Business for which you set up SSO. For more information about the Access Panel, see Introduction to the Access Panel. Additional Resources Feedback
https://docs.microsoft.com/en-us/azure/active-directory/saas-apps/amazon-business-tutorial
CC-MAIN-2019-39
refinedweb
1,109
63.49
[This is now documented here:] This is just an interesting little nugget I was asked to document today. Suppose you're writing some Outlook Object Model code (using Outlook 2007, of course) and are trying to classify the kinds of items you're working with. From the OOM, you'd start by looking at the type. Maybe it's Outlook.MailItem. or Outlook.Contact, etc. This article illustrates the concept. But what about Outlook.MeetingItem? It turns out there's a number of things this could be. It could be a compose form if the message hasn't yet been sent. It could be a regular meeting response. Or it could be a counter proposal. A counter proposal is when the recipient of the request has proposed a new time for the meeting. Detecting the compose case is easy - just check Item.Sent. But how do you tell if it's a counter proposal? That's not something we covered in the OOM. But there's a named property you can use to find out: dispidApptCounterProposal. Since I'm a C++ guy, here's the C++ definition: #define dispidApptCounterProposal 0x8257 The property is in the PSETID_Appointment namespace (see my blog entry on Outlook 2007 properties). It's type is PT_BOOLEAN. Here's some C# code that shows how you might use this property from the OOM:. We.
https://blogs.msdn.com/b/stephen_griffin/archive/2007/06.aspx?Redirected=true&PostSortBy=MostRecent&PageIndex=1
CC-MAIN-2015-18
refinedweb
227
76.52
Alrighty folks. I have another application for all you computer vision fans out there. This time, it’s an application that combines C#, OpenCV, and DirectX to produce kind of a virtual 3D environment. The application uses a standard webcam to track your head movements. As you move your head, the 3D environment will respond in return. The idea is based on the head tracking for desktop VR displays using the Wiimote by Johnny Lee as seen in the following YouTube video. Even though Johnny Lee’s application is extremely cool and is the starting point for my application, it isn’t as good as it could be. For example, Johnny’s application requires a Nintendo Wiimote and some goofy looking glasses with IR LEDs mounted on them. My application does away with all of this unnecessary equipment and replaces it all with a single webcam. Adding OpenCV into the mix allows you to do the head tracking without the need for the Wiimote. Checkout my video and be sure to download a copy of the source code along with a working version of the application from the link below the video. Also, be sure to let me know what you think of the application in the comments below. Download Virtual 3D using OpenCV and C# here. (7MB) PayPal will open in a new tab. PERFECT work Lucus Thanks! I’m getting ready to share an updated version of the app sometime over the weekend. The current version has 2 separate windows and defaults to the first camera it finds. The new version has both windows displayed in a single Windows Form. That way you don’t have to drag screens around. Plus, the new version includes a drop down menu that allows you to select which camera you want to use. I’m also adding in the ability to load 3D models into the environment which can be manipulated by moving your head or by voice commands. At some point I plan on adding support for an extra camera so that you can manipulate the 3D environment using your hands as well as your face and voice. Hi LuCus ,great tutorials man, I’m currently working on AR and i believe the tools i need are unity and C# (Which i have never done before). Can you please guide me to more tutorials on opencvsharp as well as how to go about and complete my project. areas i need to cover for my project: – Detect and track face and eyes (USB camera feed) – Save into database – Perform face recognition – Do calibration and projection(3D) – Determine the X, Y, Z, coordinates along with the angle and direct your 3D model in unity I haven’t done any work with Unity. The example in this article was all done using DirectX. As for other OpenCV articles, you can go to where you will find a list of other articles I have written. (Make sure you click the red “Previous Articles” link at the bottom of each list as the lists only show 5 results per page.) You can also checkout my other website at (Learn Computer Vision [dot] com). Within those lists, you will find a few articles that show how to detect and track faces as well as eyes. This article () also includes a ZIP download that can help get you started with Augmented Reality. That project shows how to layer a video feed over the top of markers that are within another video feed coming from a live webcam. And, for one more AR example using DirectX, you should take a look at. You can also use the link to see a better list of OpenCV articles. Hi LuCus , thx for your other website, now i believe i am getting there. I’v been trying the whole day to combine both face detection and eye detection but i keep on getting very funny results. at the end i did this, which is an empirical way of thinking about the human face, it also save some computation time. I add a little on your code to have this using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using OpenCvSharp; namespace Virtual3D { public class HeadTracker { #region Camera Variables private const double Scale = 2.0; private const double ScaleFactor = 2.5; private const int MinNeighbors = 1; private CvCapture cap; private CvHaarClassifierCascade cascade; private CvMemStorage storage; private int _posX; private int _posY; private Thread _cameraThread; #endregion public HeadTracker() { cap = CvCapture.FromCamera(1); cascade = CvHaarClassifierCascade.FromFile(“haarcascade_frontalface_alt2.xml”); //eyecascade = CvHaarClassifierCascade.FromFile(“haarcascade_eye.xml”); storage = new CvMemStorage(); _cameraThread = new Thread(new ThreadStart(Update)); _cameraThread.Start(); } public int PosX { get { return _posX; } } public int PosY { get { return _posY; } } public Thread CameraThread { get { return _cameraThread; } } public void Update() { CvWindow win = new CvWindow(“Virtual 3D”); while (CvWindow.WaitKey(10) < 0) { IplImage, cascade, storage, ScaleFactor, MinNeighbors, 0, new CvSize(30, 30)); for (int i = 0; i < faces.Total; i++) { CvRect r = faces[i].Value.Rect; CvPoint center = new CvPoint { X = Cv.Round((r.X + r.Width * 0.5) * Scale), Y = Cv.Round((r.Y + r.Height * 0.5) * Scale) }; CvPoint leftEye = new CvPoint { X = 40 + Cv.Round((r.X + r.Width * 0.1) * Scale), Y = 65 + Cv.Round((r.Y + r.Height * 0.1) * Scale) }; CvPoint rightEye = new CvPoint { X = 160 + Cv.Round((r.X + r.Width * 0.1) * Scale), Y = 65 + Cv.Round((r.Y + r.Height * 0.1) * Scale) }; int radius = Cv.Round((r.Width + r.Height) * 0.25 * Scale); int radius2 = (int)radius/4; img.Circle(center, radius, CvColor.Red, 3, LineType.AntiAlias, 0); img.Circle(leftEye, radius2, CvColor.Blue, 3, LineType.AntiAlias, 0); img.Circle(rightEye, radius2, CvColor.Blue, 3, LineType.AntiAlias, 0); _posX = center.X; _posY = center.Y; _posX = (img.Width / 2) – _posX; _posY = (img.Height / 2) – _posY; } // my own piece of code to track eyes // end of my code. win.Image = img; } } } } what do you think? Thx for your kind advices That’s one way you could handle it. A while back I wrote an app that guestimated the location of facial features such as the eyes, nose, and mouth using a similar technique. Here is another, simpler in my opinion approach. Unlike your code, this code takes into account head tilting. using System; using OpenCvSharp; namespace EyeDetect { class EyeDetect { public EyeDetect() { CvCapture cap = CvCapture.FromCamera(1); CvWindow w = new CvWindow("Eye Detection"); IplImage img; const double Scale = 2.0; CvHaarClassifierCascade face_cascade = CvHaarClassifierCascade.FromFile("haar/haarcascade_frontalface_alt2.xml"); CvHaarClassifierCascade eye_cascade = CvHaarClassifierCascade.FromFile("haar/haarcascade_eye.xml"); CvMemStorage storage = new CvMemStorage(); while (CvWindow.WaitKey(10) < 0) {, face_cascade, storage, 2.5, 1, 0, new CvSize(30, 30)); if (faces.Total > 0) { CvRect face = faces[0].Value.Rect; CvPoint center = new CvPoint { X = Cv.Round((face.X + face.Width * 0.5) * Scale), Y = Cv.Round((face.Y + face.Height * 0.5) * Scale) }; int radius = Cv.Round((face.Width + face.Height) * 0.25 * Scale); CvRect r = faces[0].Value.Rect; r.X = center.X - radius; r.Y = center.Y - radius; r.Width = radius * 2; r.Height = radius * 2; img.Rectangle(r, CvColor.Red, 1); storage.Clear(); // Consider swapping out img with smallImg for faster processing img.SetROI(r); CvSeq eyes = Cv.HaarDetectObjects(img, eye_cascade, storage, 1.15, 3, 0, new CvSize(25, 15)); for (int i = 0; i < eyes.Total; i++) { CvRect eye = eyes[i].Value.Rect; if(i < 2) img.Rectangle( eye.X, eye.Y, eye.X + eye.Width, eye.Y + eye.Height, CvColor.Red, 1); } Cv.ResetImageROI(img); storage.Clear(); } w.Image = img; Cv.ReleaseImage(img); } } } }
http://www.prodigyproductionsllc.com/articles/programming/virtual-3d-with-opencv-and-c/
CC-MAIN-2017-04
refinedweb
1,262
60.61
WebAssembly: Using Emscripten to Create a Bare-Bones Module WebAssembly: Using Emscripten to Create a Bare-Bones Module This article is the result of some research/experimentation to see if it’s possible to build a WebAssembly module using Emscripten but not have any of the plumbing code. Join the DZone community and get the full member experience.Join For Free In my last article, An Introduction to WebAssembly, I showed you some of the basics of working with a WebAssembly module by using Emscripten. This article is the result of some research and experiments to see if it’s possible to build a WebAssembly module using Emscripten but not have any of the plumbing code. For example, if we were to build the following C file using the following command line, the result would be an HTML file that is 101 KB, a JS file that is 80.2 KB, and a wasm file that is 9.4 KB! #include <stdio.h> #include "../emscripten/emscripten.h" int main() { return 0; } int EMSCRIPTEN_KEEPALIVE add(int x, int y) { return x + y; } emcc test.c -s WASM=1 -s NO_EXIT_RUNTIME=1 -O1 -o hello.html Having all of that plumbing is very convenient because it lets you start playing around with WebAssembly modules right away but what if we want just the bare minimum and will handle the HTML and JavaScript ourselves? Fortunately, there is a way to tell Emscripten to output just the bare bones wasm file. Let's first strip the C file down to just the bare minimum. In this case, we only want the add method: int add(int x, int y) { return x + y; } If we use the following command line, we will get just the wasm file and it’s only 202 bytes! emcc test.c -s WASM=1 -s SIDE_MODULE=1 -O1 -o test.wasm The SIDE_MODULE flag tells Emscripten to compile only our methods and nothing else which means you will also not have access to things like printf or malloc. If not specified, the default optimization flag used is -O0 (capital letter o and the number 0) but that results in the following error being thrown when you try to load the module: LinkError: import object field 'DYNAMICTOP_PTR' is not a Number Adding any optimization flag other than -O0 will fix the issue so we went with -O1 (capital letter o and the number 1) for this example. One thing to note, however, is that the O appears to be case sensitive. The various optimization flags that are available can be found here. We also need to specify the name of the output file in the command line because, if we don't, Emscripten will output the file with the name a.out.wasm. Because we've decided not to use Emscripten's plumbing code, we need to write our own HTML and JavaScript. The following is some example HTML and JavaScript to load in the module: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <input type="button" value="test" onclick="javascript:OnClickTest();" /> <script type="text/javascript"> var gModule = null; var importObject = { 'env': { 'memoryBase': 0, 'tableBase': 0, 'memory': new WebAssembly.Memory({initial: 256}), 'table': new WebAssembly.Table({initial: 0, element: 'anyfunc'}) } }; fetch('test.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, importObject) ).then(results => { gModule = results.instance; // Hold onto the module's instance so that we can reuse it }); function OnClickTest(){ alert(gModule.exports._add(1, 2)); } </script> </body> </html> One thing that you may have noticed that is different with our call to the C method, as compared to what we did in the previous blog post, is that we're not using Module.ccall or Module.cwrap. Those are Emscripten helper methods. Here, we're calling the C method directly. Something else to be aware of here is that your JavaScript will need to include an underscore character before the method name. For example, in our case, our method is called add. When you call the add method in JavaScript you would use _add(1, 2); rather than add(1, 2); Although this approach might not be a solution that will work in every situation, given that you don't have access to things like malloc, it might be a useful way of creating a helper library if you're doing things like number crunching and don't need all of the overhead that comes with Emscripten's plumbing. Published at DZone with permission of Gerard Gallant , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/webassembly-emscripten-side-module
CC-MAIN-2019-26
refinedweb
778
59.43
10 More C# Extension Methods for the Holiday Season 10 More C# Extension Methods for the Holiday Season C#'s extension methods are pretty cool, so here's a gift of ten such methods that could help you out! Join the DZone community and get the full member experience.Join For Free Ahhh, it's that time of year again when we stuff the C# stocking with some Extension Methods! Notice: This post was written for the Second Annual C# Advent Calendar (#csadvent). <commercial-voice> For the entire month of December, you can receive more than 60 articles geared towards C# for the very low price of $0.00!</commercial-voice> Thanks a lot to Matt Groves (@mgroves) for putting this together again! Awesome job, Matt! Have I mentioned how much I love extension methods? Ok, maybe once or twice, but they are soooo useful. I know I wrote about them last year for the First Annual C# Advent Calendar, so I thought why not do it again since everyone loves small, little morsels of C# code to make their lives better? Here are some more of my favorite Extension Methods for C#. IEnumerable<T>.ForEach Ever need a simple one-liner that sets something in your list? A simple extension, I know, but it does the trick. public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> action) { foreach (T item in collection) { action(item); } return collection; } Usage: customers.ForEach<Customer>(t=> t.Enabled = true); String.IsValidIp() As you write networking utilities, you most likely need an IP validator of some kind. public static Boolean IsValidIp(this string ip) { if (!Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")) return false; var ips = ip.Split('.'); if (ips.Length == 4 || ips.Length == 6) { return Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256; } return false; } Usage: "255.255.15.22".IsValidIp() // returns true; DateTime.ToFormattedDateTime(bool includeTime) I've been using this on my blog for as long as I can remember. This formats the DateTime of a blog post to make it a little prettier under the post's primary image. public static string ToFormattedDateTime(this DateTime dateAndTime, bool includeTime) { // Format: January 26th, 2006 at 2:19pm string dateSuffix = "<sup>th</sup>"; switch (dateAndTime.Day) { case 1: case 21: case 31: dateSuffix = "<sup>st</sup>"; break; case 2: case 22: dateSuffix = "<sup>nd</sup>"; break; case 3: case 23: dateSuffix = "<sup>rd</sup>"; break; } var dateFmt = String.Format("{0:MMMM} {1:%d}{2}, {3:yyyy} at {4:%h}:{5:mm}{6}", dateAndTime, dateAndTime, dateSuffix, dateAndTime, dateAndTime, dateAndTime, dateAndTime.ToString("tt").ToLower()); if (!includeTime) { dateFmt = String.Format("{0:MMMM} {1:%d}{2}, {3:yyyy}", dateAndTime, dateAndTime, dateSuffix, dateAndTime); } return dateFmt; } Usage: DateTime.Now.ToFormattedDateTime(false) // Returns: December 19th, 2018 DateTime.Now.ToFormattedDateTime(true) // Returns: December 19th, 2018 at 9:00a DateTime.ToW3CDate() At one time, I wrote an application for a client where the date/time HAD to be in the W3C date (ISO 8601) standard when reporting (yes...the long one). This is one of those extensions that's nice to have around instead of fiddling with a formatting string and it makes it simple enough to remember. public static string ToW3CDate(this DateTime dt) { return dt.ToUniversalTime().ToString("s") + "Z"; } Usage: DateTime.Now.ToW3CDate(); // Returns: 1997-07-16T19:20:30.45Z DateTime.GetQuarter() Trying to figure out how to generate a report by quarter? public static int GetQuarter(this DateTime fromDate) { return ((fromDate.Month - 1) / 3) + 1; } Usage: DateTime.Now.GetQuarter(); // Returns: 4 DirectoryInfo.Empty() Ok, BIG WARNING here! Yes, this will erase files and subdirectories. You have been warned! public static void Empty(this System.IO.DirectoryInfo directory) { foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete(); foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); } Usage: DirectoryInfo di = new DirectoryInfo(@"c:\MyDir"); di.Empty(); // Files and Subdirectories wiped out...DOGS and CATS Living Together! Object.ToDictionaryProperties(BindingFlags flags) There are times when you just want a list of members and their values. public static Dictionary<string, object> ToDictionaryProperties(this object atype, BindingFlags flags) { if (atype == null) return new Dictionary<string, object>(); var t = atype.GetType(); var props = t.GetProperties(flags); var dict = new Dictionary<string, object>(); foreach (PropertyInfo prp in props) { object value = prp.GetValue(atype, new object[] { }); dict.Add(prp.Name, value); } return dict; } Usage: var customerValues = customer.ToDictionaryProperties(BindingFlags.Public); // Returns: a list of public properties with their values in a Dictionary<string,object>() DateTime.ToDaysTil(DateTime endDateTime) Since we are coming up on Christmas, why not have a countdown version of the ToReadableTime() extension method and have it focus on the future instead of telling us how long it's been since a date has passed? This could also be used for a product launch ("15 days until the product launch"). public static string ToDaysTil(this DateTime value, DateTime endDateTime) { var ts = new TimeSpan(endDateTime.Ticks - value.Ticks); var delta = ts.TotalSeconds; if (delta < 60) { return ts.Seconds == 1 ? "one second" : ts.Seconds + " seconds"; } if (delta < 120) { return "a minute"; } if (delta < 2700) // 45 * 60 { return ts.Minutes + " minutes"; } if (delta < 5400) // 90 * 60 { return "an hour"; } if (delta < 86400) // 24 * 60 * 60 { return ts.Hours + " hours"; } if (delta < 172800) // 48 * 60 * 60 { return "yesterday"; } if (delta < 2592000) // 30 * 24 * 60 * 60 { return ts.Days + " days"; } if (delta < 31104000) // 12 * 30 * 24 * 60 * 60 { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "one month" : months + " months"; } var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "one year" : years + " years"; } Usage: var christmas = new DateTime(2018, 12, 25); var almost = DateTime.Now.ToDaysTil(christmas); // returns: "5 days" (you add what you want after it). Object.IsNullOrDbNull() This is great to test if objects are null or DBNull comes back from the database. Again, it's about simplifying the code and making it readable. public static bool IsNullOrDbNull(this object obj) { return obj == null || obj.GetType() == typeof(DBNull); } Usage: var notValid = obj.IsNullOrDbNull(); String.IsValidUrl() This extension method was created to validate what a user was typing into a textbox. How do you know whether a user entered a valid URL or not? Of course, this doesn't hit the URL, it merely uses Regular Expressions to validate it. public static bool IsValidUrl(this string text) { var rx = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); return rx.IsMatch(text); } Usage: "".IsValidUrl(); // returns: true Conclusion The whole idea behind extension methods is three-fold: - Extend a class where you don't have access to the source code. - Make your life easier when working with complex classes by using simple method calls. - Allows the syntax to become readable for other developers. I hope these extension methods make your holiday a little happier. Merry Christmas, everyone and I'll see you next year (some I'll see at Codemash!). Do you have a favorite extension method? Which class needs the most "extension?" }}
https://dzone.com/articles/10-more-c-extension-methods-for-the-holiday-season?fromrel=true
CC-MAIN-2019-51
refinedweb
1,181
52.26
The QSqlError class provides SQL database error information. More... #include <QSqlError> The QSqlError class provides SQL database error information. A QSqlError object can provide database-specific error data, including the driverText() and databaseText() messages (or both concatenated together as text()), and the error number() and type(). The functions all have setters so that you can create and return QSqlError objects from your own classes, for example from your own SQL drivers. See also QSqlDatabase::lastError() and QSqlQuery::lastError(). This enum type describes the context in which the error occurred, e.g., a connection error, a statement error, etc. Constructs an error containing the driver error text driverText, the database-specific error text databaseText, the type type and the optional error number number. Creates a copy of other. Destroys the object and frees any allocated resources. Returns the text of the error as reported by the database. This may contain database-specific descriptions; it may be empty. See also setDatabaseText(), driverText(), and text(). Returns the text of the error as reported by the driver. This may contain database-specific descriptions. It may also be empty. See also setDriverText(), databaseText(), and text(). Returns true if an error is set, otherwise false. Example: QSqlQueryModel model; model.setQuery("select * from myTable"); if (model.lastError().isValid()) qDebug() << model.lastError(); Returns the database-specific error number, or -1 if it cannot be determined. Sets the database error text to the value of databaseText. See also databaseText(), setDriverText(), and text(). Sets the driver error text to the value of driverText. See also driverText(), setDatabaseText(), and text(). Sets the database-specific error number to number. Sets the error type to the value of type. This is a convenience function that returns databaseText() and driverText() concatenated into a single string. See also driverText() and databaseText(). Returns the error type, or -1 if the type cannot be determined. Assigns the other error's values to this error.
http://idlebox.net/2010/apidocs/qt-everywhere-opensource-4.7.0.zip/qsqlerror.html
CC-MAIN-2014-15
refinedweb
317
53.47
Python Bindings to Interact with BESS GRPC Daemon Project description pybess pybess is a Python library which lets you interact with BESS using gRPC. Installation You can install the library directly using pip/pip3: pip3 install pybess_grpc Usage As mentioned above pybess can be used to communicate with BESS over gRPC. An example of usage of this library is to list all BESS ports remotely: import sys from google.protobuf.json_format import MessageToDict from pybess_grpc.bess import BESS bess = BESS() try: bess.connect(grpc_url="%s:10514" % sys.argv[1]) ports = bess.list_ports() print(MessageToDict(ports)["ports"]) finally: bess.disconnect() 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/pybess-grpc/
CC-MAIN-2021-31
refinedweb
128
50.43
- Packages and the import Statement Up until now, you have been using the fully qualified name of the class java.util.ArrayList. The fully qualified name of a class includes its package name (java.util in this example) followed by the class name (ArrayList). Packages provide a way for developers to group related classes. They can serve several needs: First, grouping classes into packages can make it considerably easier on developers, saving them from having to navigate dozens, hundreds, or even thousands of classes at a time. Second, classes can be grouped into packages for distribution purposes, perhaps to allow easier reuse of modules or subsystems of code. Third, packages provide namespaces in Java. Suppose you have built a class called Student and you purchase a third-party API to handle billing students for tuition. If the third-party software contains a class also named Student, any references to Student will be ambiguous. Packages provide a way to give a class a more unique name, minimizing the potential for class name conflicts. Your class might have a fully qualified name of com.mycompany.studentinfosystem.Student, and the third-party API might use the name com.thirdpartyco.expensivepackage.Student. I will usually refer to the Java system classes without the package name unless the package is not clear from the class name. For example, I will use ArrayList in place of java.util.ArrayList, and Object instead of java.lang.Object. Typing java.util.ArrayList throughout code can begin to get tedious, and it clutters the code as well. Java provides a keyword—import—that allows identification of fully qualified class names and/or packages at the source file level. Use of import statements allows you to specify simple class names throughout the remainder of the source file. Update CourseSessionTest to include import statements as the very first lines in the source file. You can now shorten the phrase extends junit.framework.TestCase to extends TestCase. You can change the reference defined as java.util.ArrayList<Student> to ArrayList<Student>. import junit.framework.TestCase; import java.util.ArrayList; public class CourseSessionTest extends TestCase { ... public void testEnrollStudents() { CourseSession session = new CourseSession("ENGL", "101"); Student student1 = new Student("Cain DiVoe"); session.enroll(student1); assertEquals(1, session.getNumberOfStudents()); ArrayList<Student> allStudents = session.getAllStudents(); ... } } (Make sure your tests still run! I'll keep reminding you for a while.) Update AllTests, StudentTest, and CourseSession to use import statements. Your code will look so much cleaner!
https://www.informit.com/articles/article.aspx?p=406343&seqNum=11
CC-MAIN-2021-43
refinedweb
409
51.34
Entity Framework, LINQ and Model-First for the Oracle Database Overview Purpose This tutorial covers how to use Entity Framework 5 or 6, Language Integrated Query (LINQ), and generate Data Definition Language (DDL) scripts using Model-First for Oracle database. Time to Complete Approximately 30 mins. Introduction: - LINQ query - LINQ query with a lambda expression and calling a stored procedure to perform an update against the results - Entity SQL Next, you will call a stored procedure added to the EDM via a function import. The stored procedure will modify the database data and return the results with an implicit resultset. To return the resultset, you will run a Oracle wizard that provides the resultset parameter information in a .NET config file. You will then see how to run a stored procedure returning a scalar parameter value. Then, you will see how to insert and delete data to the database without using a stored procedure. Lastly, you will use Model-First with Oracle database. In a Model-First scenario, a developer first creates an Entity Framework object-relational data model. From that data model, the developer can automatically generate an Oracle relational database model in the form of DDL scripts. Prerequisites Before starting this tutorial, you should: Install Microsoft Visual Studio 2013 or later with .NET Framework 4.5 or later. Install Oracle Database 11g Release 2 or later. Install Oracle Data Access Components (ODAC) 12c Release 3 (12.1.0.2.1) or later from OTN. The ODAC download includes Oracle Developer Tools for Visual Studio and ODP.NET that will be used in this lab. Extract these files into your working directory. Note: If you have installed ODAC 12c Release 3 configured on a machine-wide level, you will see an error when trying to generate database scripts using Entity Framework Model-First. To resolve this issue, use an ODAC version later than this release or reinstall ODAC 12c Release 3 with the "Configure ODP.NET at a machine-wide level" box UNchecked. Creating a new Project in Visual Studio To create a new .NET console application to run Entity Framework and LINQ application from, open Visual Studio. Click File. Select New > Project. Select Visual C#:Windows > Console Application. Rename the project as EntityFramework. Click OK. The project EntityFramework opens up. Creating an Oracle Connection Before creating the Entity Data Model, you need an Oracle database connection that uses ODP.NET. To create an Oracle Connection: Select View > Server Explorer. In the Server Explorer window, if you already have a HR schema connection, expand it to connect to the database. As an example, the screen shot below identifies the HR schema as HR.ORCL. Enter HR for both the User name and Password and click OK. Skip to Step 6. If you do not have a HR connection, then right-click on Data Connections in Server Explorer. Choose Add Connection. Enter HR for both the User name and Password. Check Save password. Select Data source name with the HR schema, such as ORCL. Click Test Connection. Click OK in the "Test connection succeeded" dialog box. Click OK in the Add Connection dialog box. The connection has been created. Expand HR.ORCL You will now create the stored procedures that will be used later in this lab to perform updates and data retrieval. To add the stored procedures into the HR.ORCL data connection, right-click HR.ORCL and select Query Window. Open the working directory to where you extracted the files.zip. Find the INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM stored procedures. Copy the code for INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM into the SQL Query Window and click Execute Query ( )for each of the stored procedures. Make sure that the newly added stored procedures appear beneath the HR.ORCL > Procedures node after refreshing. Creating an Entity Data Model using the Entity Data Model Wizard You will now create an Entity Data Model based on HR's DEPARTMENTS and EMPLOYEES table and the three new stored procedures that you just added. To do so, you will add an EDM to our project. The EDM will be automatically generated using the Entity Data Model Wizard. Note: If you wish to use the Entity Framework 6 version, perform the following steps first: Perform the steps mentioned in the NuGet ODP.NET Installation and Configuration section of the Using NuGet to Install and Configure Oracle Data Provider for .NET OBE. Select Build > Rebuild Solution from the Visual Studio menu, which will allow this project to start using Entity Framework 6. In the Solution Explorer window, right-click the EntityFramework project and select Add > New Item. In the Add New Item window, choose ADO.NET Entity Data Model and rename it to HRModel.edmx and click Add. In the Entity Data Model Wizard, select Generate from database and click Next. Select HR.ORCL as the data connection. Select Yes, include the sensitive data in the connection string and name it as HREntities and click Next. Select Entity Framework 5.0 version and click Next. Note: You will not receive this window if you are using the Entity Framework 6 version and have performed the Using NuGet to Install and Configure Oracle Data Provider for .NET OBE. You will automatically be redirected to the next step. Select DEPARTMENTS and EMPLOYEES from Tables and INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM from Stored Procedures and Functions. Rename the Model Namespace to HRModel and click Finish. Note: If these stored procedures do not appear, make sure that you added them earlier in the OBE - INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM to the HR schema under Procedures. If you are using Entity Framework 6 version, you may receive a Security Warning popup on clicking Finish. Click Ok and continue. The HRModel EDM has been created and is displayed. Entity Framework Data Retrieval There are a number of ways to query the EDM, which then retrieves data from the database. This section will demonstrate three common EDM querying methods: LINQ, LINQ with lambda expressions, and Entity SQL. Executing a LINQ query To execute a LINQ query against an Oracle database, you will create the code to execute a LINQ query and return the results to the console window. Type the namespace references highlighted in the graphic below (applicable only for Entity Framework 5 version). Alternatively, you can copy and paste this information. Open the files folder containing Programcs.txt from your working directory. Then, copy the code including the namespace references and paste them at the top of the Program.cs. These directives allow access to the ADO.NET, Entity Framework and Object Services namespaces. It is not necessary to reference ODP.NET namespaces in this tutorial as ODP.NET is being used indirectly via Entity Framework. However, if you are using Entity Framework 6 version, change the namespace references to reflect the graphic highlighted below. Type in the .NET code below. The code executes a LINQ query against the EDM you just created. It then accesses the result and outputs it to the screen. The LINQ query retrieves all employee information with EMPLOYEE_ID less than the max_id variable. Alternatively, you can copy the code from Programcs.txt for the LINQ query and paste it on Program.cs after the Main statement. Make sure you include an end curly brace to terminate the USING scope. Click (Start). The output of the LINQ query appears, thereby successfully executing a LINQ query against the Oracle database. Executing a LINQ query using a lambda expression and Entity Framework stored procedure mapping LINQ queries can include lambda expressions. Lambdas are used as LINQ arguments to standard query operator methods. Updates, inserts, and deletes can be executed on an entity by mapping Oracle stored procedures to these operations in the EDM. In the below mentioned steps, you will execute a LINQ query with a lambda expression against the EMPLOYEE entity, then map a stored procedure to execute an update against all rows selected. You will use one of the stored procedures you imported earlier into the EDM. First, you will create a stored procedure mapping for updating the data. When .NET tries to update the data, the mapped stored procedure will execute for every row selected by LINQ. In the Solution Explorer window, double click HRModel.edmx. In the HRModel.edmx, right-click on EMPLOYEE entity and select Stored Procedure Mapping. In the Mapping Details - EMPLOYEE, select ,<Select Update Function> and select the stored procedure, INCREASE_SALARY_BY_10. Parameter data types must now be mapped between the entity and Oracle database. Select EMPLOYEE_ID for ID and SALARY for SAL from the drop down lists. Type in the highlighted code below or copy the code from the Programcs.txt from the section labeled "LINQ using lambda expressions --" and paste it in Program.cs after the previous code statements. Click (Start) Note: Press Enter to continue after viewing the first resultset. LINQ retrieves the two rows of data and updates each row by executing the stored procedure. You should see text that indicates the salaries have been updated. Executing an Entity SQL query In this section, you will query the same rows as in the previous section to show that the stored procedure successfully updated the selected rows. You will use another query method available in Entity Framework called Entity SQL. Type the highlighted code below or copy code from Programcs.txt from the section labeled "Entity SQL -- "and paste it in Program.cs after the previous code statements. Click (Start) to view the updated results with the salaries increased by 10. Note: Press Enter twice to continue while viewing the output. Function Imports and Retrieving Implicit Resultsets | Inserting and Updating Data Directly. Oracle has introduced a wizard to automatically generate the resultset metadata. This section shows you how to modify Oracle database data programmatically in Entity Framework. You will perform an insert and a delete on the DEPARTMENTS table. You will use Visual Studio's Function Import tool to map the stored procedure to a user-defined .NET method. Since the stored procedure returns an implicit resultset, you need to use a wizard to generate the resultset metadata in the .NET config file before using the tool. In the Server Explorer window, expand Procedures in the HR.ORCL connection. Right-click on UPDATE_AND_RETURN_SALARY and choose Run. Note: Please use the exact same connection you started off this OBE with. Do not use an ODP.NET, Managed Driver connection if you began with an ODP.NET, Unmanaged Driver connection and vice versa. The Run Procedure dialog opens up. Since we're not interested in the stored procedure's result running outside the application, we can just leave the input parameters unchanged and click OK. The procedure runs successfully. In the Out Parameters section of the window, select the Select For Config option for the NEW_SALARY parameter. Click the Show Config button. It displays the resultset and column metadata that will be added to the App.config file. Then, click the Add Config to Project button to add the metadata to the App.config file. The App.config file opens with the added REF CURSOR information. Note: A window might pop up asking if you want to reload the App.config file. Click Yes. Next, you will use the Function Import tool to map a .NET method to the Oracle stored procedure. Double-click HRModel.edmx in the Solution Explorer. Right-click anywhere in the HRModel.edmx window, and select Model Browser. In the Model Browser, expand the HRModel, then expand the Function Imports node. Double click to open the UPDATE_AND_RETURN_SALARY procedure. Note: You imported this procedure earlier when you created the EDM. In the Edit Function Import window, select Complex in the Returns a Collection Of section. The stored procedure returns a result set with two columns, not a fully-defined entity nor a scalar value. Click Get Column Information. The column information will be retrieved from the .NET config file. Click Create New Complex Type in the Stored Procedure / Function Column Information section and click OK. To call the method from .NET, you will use the default UPDATE_AND_RETURN_SALARY Function Import name. In the Solution Explorer window, open the Program.cs file. Type or copy the following code from the Programcs.txt - "Update salary using a stored procedure function import" after the previous code statements. Notice that the entity context now has an UPDATE_AND_RETURN_SALARY method defined. This method will call the mapped stored procedure and return the implicit resultset. Click (Start). Note: Press Enter thrice to continue while viewing the resultset. The .NET method returns the employee name and updated salary. Retrieving Output Parameters from Stored Procedures This section demonstrates how to retrieve output parameters from stored procedures within Entity Framework. The output parameter needs only to be declared explicitly in .NET and map to an output parameter in the stored procedure. This is different from older Entity Framework versions when a function import was required for stored procedure output parameters. In the Solution Explorer window, open the Program.cs file. Type or copy the following code from the Programcs.txt - "Retrieving output parameters from stored procedures" after the previous code statements. Notice that the entity context has an OUTPARAM method defined. An ObjectParameter is bound to the OUTPARAM method to retrieve the output parameter. This method will call the mapped stored procedure that return the parameter. Click (Start). Note: Press Enter four times to continue while viewing the resultset. Insert and Delete Data Using LINQ This section demonstrates how LINQ can be used to insert and delete data programmatically. Type or copy the code that inserts and deletes the new department entry in your Program.cs file. You can copy from the Programcs.txt file and paste it to the Program.cs file after the previous code statements. The program comments describe what each code segment does.Click (Start). Note: Press Enter six times to continue while viewing the resultset. The console describes whether the department was successfully added and deleted. Model-First the HRModel.edmx, select the EMPLOYEE entity. To create a new property in EMPLOYEE entity, right-click on it and select Add New > Scalar Property. Name the property as ADDRESS. To generate the DDL scripts, right-click on the HRModel in the Model Browser and select Properties. Change the Database Schema Name to HR and select SSDLtoOracle.tt (VS) for the DDL Generation Template. Make sure that Generate Oracle via T4(TPT).xaml (VS) is selected in the Database Generation Workflow property to ensure table per type DDL will be generated. These selections ensure that Oracle DDL is created for the HR schema where each type represents a separate database table. Right-click HRModel.edmx and select Generate Database from Model. After you select Generate Database from Model, a Custom Workflow Security Warning will appear. Click OK. The Generate Database Wizard generates DDL scripts for Oracle database to execute. These scripts can be saved to a file to be run later, such as through the built-in SQL*Plus execution engine that is part of Oracle Developer Tools for Visual Studio. Note: The script creates and deletes database objects. By default, the deleted scripts are commented out. If you wish to use them, make sure to uncomment them before executing. Summary In this tutorial, you have learned how to: - Create a new Project in Visual Studio. - Create an Oracle connection. - Create an Entity Data Model using the Entity Data Model Wizard. - Execute queries for Entity Framework Data Retrieval. - Map stored procedures to EDMs. - Use Entity Framework Function Imports for creating user-defined methods mapped to stored procedures. - Retrieve Output Parameters from Stored Procedures. - Programmatically modify Entity Framework data. - Use Model-First to generate Oracle DDL scripts. Resources - You may visit the Oracle Technology Network Portal to know the latest developments in Oracle .NET. - To learn more about Oracle .NET with Visual Studio refer to additional OBEs in the Oracle Learning Library. Credits - Lead Curriculum Developer: Ashwin Agarwal - Other Contributors: Alex Keh, Christian Shay.
https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/EntityFrameworkOBE_2/EntityFrameworkOBE.html
CC-MAIN-2019-35
refinedweb
2,661
59.6
Inheritance syntax Posted on March 1st, 2001 public class invoked on the command line will be called. (And you can have only one public class per file.). Here, you can see that Detergent.main( ) calls Cleanser.main( ) explicitly. comes along for free, but that part isn’t the primary point.)( ). When inheriting you’re not restricted to using the methods of the base class. You can also add new methods to the derived class exactly the way you put any method in a class: just define it. The extends keyword suggests that you are going to add new methods to the base-class interface, and the method foam( ) is an example of this. In Detergent.main( ) you can see that for a Detergent object you can call all the methods that are available in Cleanser as well as in Detergent (i.e. foam( )). Initializing the base class. Even if you don’t create a constructor for Cartoon( ), the compiler will synthesize a default constructor for you that calls the base class constructor.Constructors with arguments.)Catching base constructor exceptions As just noted, the compiler forces you to place the base-class constructor call first in the body of the derived-class constructor. This means nothing else can appear before it. As you’ll see in Chapter 9, this also prevents a derived-class constructor from catching any exceptions that come from a base class. This can be inconvenient at times.
https://www.codeguru.com/java/tij/tij0065.shtml
CC-MAIN-2019-35
refinedweb
240
65.62