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
On Wed, 2006-02-15 at 11:17 -0500, Stephen Smalley wrote: > On Wed, 2006-02-15 at 09:49 -0600, Timothy R. Chavez wrote: > > This makes sense to me. I'll go ahead and make the change. I wouldn't > > even technically need the function or function call in my patch since > > selinux_available() simply returns ss_initialized. > > Well, I think we want to keep that variable private to the SELinux > "module". In the future, we'll likely add proper namespace prefixes to > all non-static SELinux symbols to avoid polluting the kernel namespace. > I think maybe I miscommunicated my intentions. If I move the check to determine whether or not SELinux is enabled into selinux_id_to_ctx(), then I can simply use ss_initialized directly rather then calling selinux_available(), as I'll be making the check within the SELinux "module" (selinux/exports.c). -tim
https://www.redhat.com/archives/linux-audit/2006-February/msg00074.html
CC-MAIN-2014-15
refinedweb
141
63.7
significant. If you don’t know where to start, then we particularly recommend Avro, which is also supported in the Confluent Platform. In the next section we briefly introduce Avro, and how it can be used to support typical schema evolution. Avro¶ Defining an Avro Schema"} ] } You can then use this Avro schema, for example, to serialize a Java object (POJO) into bytes, and deserialize these bytes back into the Java object.. Schema Evolution¶ in practice until you run into your first production issues. Without thinking through data management and schema evolution carefully, people often pay a much higher cost later on. There are three common patterns of schema evolution: Backward Compatibility¶ Backward compatibility means that data encoded with an older schema can be read with a newer schema. Consider the case where all the data in Kafka is also loaded into HDFS, and we want to run SQL queries (e.g., using Apache Hive) over all the data. Here, it is important that the same SQl queries continue to work even as the data is undergoing changes over time. To support this kind of use case, we can evolve the schemas in a backward compatible way. user schema from the previous section to the following by adding a new field favorite_color: {"namespace": "example.avro", "type": "record", "name": "user", "fields": [ {"name": "name", "type": "string"}, {"name": "favorite_number", "type": "int"}, {"name": "favorite_color", "type": "string", "default": "green"} ] } Note that the new field favorite_color has. Note Avro implementation details: Take a look at ResolvingDecoder in the Apache Avro project to understand how, for data that was encoded with an older schema, Avro decodes that data with a newer, backward-compatible schema. Forward Compatibility¶ Forward compatibility means that data encoded with a newer schema can be read with an older schema. Consider a use case where a consumer has application logic tied to a particular version of the schema. When the schema evolves, the application logic may not be updated immediately. Therefore, we need to be able to project data with newer schemas onto the (older) schema that the application understands. To support this use case, we can evolve the schemas in a forward compatible way: data encoded with the new schema can be read with the old schema. For example, the new user schema we looked at in the previous section on backward compatibility is also forward compatible with the old one. When projecting data written with the new schema to the old one, the new field is simply dropped. Had the new schema dropped the original field favorite_number (number, not color), it would not be forward compatible with the original user schema since we wouldn’t know how to fill in the value for favorite_number for the new data because the original schema did not specify a default value for that field. Full Compatibility¶ Full compatibility means schemas are backward and forward compatible. To support both previous use cases on the same data, we can evolve the schemas in a fully compatible way: old data can be read with the new schema, and new data can also be read with the old schema. Confluent Schema Registry¶ As you can see, when using Avro, one of the most important things is to manage its schemas and reason about how those schemas should evolve. Confluent Schema Registry is built for exactly that purpose. You can find out the details on how to use it to store Avro schemas and enforce certain compatibility rules during schema evolution by looking at the Schema Registry API Reference.
https://docs.confluent.io/current/avro.html
CC-MAIN-2018-47
refinedweb
589
57.1
C-ing a Flashing Light In my previous article, I showed how combining two instructions into one can speed up a very small countdown loop. In this article, I’ll demonstrate how a single non-optimizing compiler option can have an even greater impact on performance. C-ing It Using assembly language in low-level code isn’t required, except in circumstances unique to a platform. For the Raspberry Pi, the memory layout reserves bytes starting at 100h as ATAG’s (attribute tags) describing pre-OS configuration of the RPi. The catch is, the ATAG’s are stored to 100h after the kernel.img load, but before kernel execution. Several bytes loaded from kernel.img will be over-written with ATAG’s, so it’s important to avoid placing code in that space. To this end, in part 3 of the Baking Pi tutorial, the main code is moved to 8000h, and the sole instruction at address 0 is a jump to 8000h. Keeping the parts properly laid out is a task for the linker, which I will explain later. The main code consists of three parts: initializing the GPIO controller, turning the OK light on or off via the GPIO controller, and a delay loop that counts down from 3f0000h (4,128,768 in decimal). The assembly code version did this all in one source file; doing the same in C in a single source file is mostly trivial. The first step is to initialize the GPIO controller: #include <sys/types.h> ; The GPIO_* constants define the CPU-visible addresses of the GPIO controller, or at least the addresses used in this source file. The BCM2835 GPIO controller is a sophisticated interface that provides one of “raw,” loosely-timed, or closely-timed signals. Since the target is a single output line, these four GPIO_* constants are sufficient. Note that the variables are declared with the “register” storage qualifier. The flash() function in this case stands alone, calling no other functions, and returning no values. With no OS, no standard C library, and no setup code other than “jump immediately to flash(),” there is no program stack for temporary storage. Everything must be kept in ARM registers. The variable i is the counter for our delay loop, and status will keep track of whether the OK light should be turned on or off. The only reason to #include <sys/types.h> is to use the u_int32_t data type. We want to write values to the GPIO controller, without the compiler trying to re-interpret those values in secret. Casting a GPIO_* value to a “pointer to an unsigned 32-bit value” makes our intention clear to the compiler. So why stuff a single 1 bit into the GPIO_PIN_FUNC? Actually, GPIO_PIN_FUNC controls the function assignments of ten GPIO lines, in this case lines 10-19. GPIO line 10′s function is selected by bits 2-0, line 11′s function is selected by bits 5-3, and so on. Bits 20-18 control the function selection for GPIO line 16, in this case turning it into a raw output line (and the other 9 lines carelessly into inputs). All this is calculated “by hand” from Broadcom’s BCM2835 Peripherals reference. Such use of “magic values,” and not taking into account the current function assignments of the other pins, are definitely not good programming practices. The next step is to set up an infinite loop: while (1 == 1) { Followed by a very convoluted assignment: *((u_int32_t *)(status ? GPIO_PIN_ON : GPIO_PIN_OFF)) = 1 << 16; From the inside out, the status variable is the predicate in the conditional expression (status ? GPIO_PIN_ON : GPIO_PIN_OFF). Depending on its “true/false” value, the whole conditional expression will take either the GPIO_PIN_ON value, or the GPIO_PIN_OFF value. The selected value will then be cast to a pointer-to-unsigned-32, as we did above, and dereferenced for an assignment. The net description of this one assignment is that GPIO line 16 will be turned either on or off, depending on status being either True or False. Unlike the GPIO function assignment registers, the on/off registers act in isolation; bits that are 0 remain unaffected, while bits that are 1 are either turned on (when writing to GPIO_PIN_ON) or turned off (when writing to GPIO_PIN_OFF). This minimizes the time difference between two lines going high or low together. In digital circuit design, this time difference is called “propagation delay.” Next is the delay loop, counting down from the same starting value as before: // delay i = 0x3f0000; while (i--); Remember that i is a register variable, counting down from 4,128,768 in the empty while (i--); loop. Any GCC optimization level greater than zero, that is, -ON where N is greater than zero, will cause the empty while (i--); loop to be eliminated completely. This means that this C source file must include -O0, in order to make sure this delay loop is compiled “as-is”. It also means that the overall code will not be optimized at all. Finally, the one thing remaining to do is to switch the status variable to its logical opposite: status = !(status); } } And with that, the infinite loop starts over. Normally, part of the boot code would set up a stack, but not in this case. And, normally, the beginning of a function would save registers to the stack (in the “prologue”), so that they could be used in calculations and then restored before the function returns (in the “epilogue”), but again, not in this case. Without a stack, there is no capability to save registers. GCC calls a function without a prologue or epilogue “naked”: void flash(void) __attribute__((naked,noreturn)); These attribute declarations should appear right before the code to which it applies, as a courtesy to someone reading the code. So, here is the entire code for light-flash.c: /* light-flash.c -- converting light-flash.s to C */ #include <sys/types.h> void flash(void) __attribute__((naked,noreturn)); ; while (1 == 1) { // forever *((u_int32_t *)(status?GPIO_PIN_ON:GPIO_PIN_OFF)) = 1 << 16; // delay i = 0x3f0000; while (i--); // toggle status status = !(status); } // should never get here } Building it There are two main components to the build process, beyond the source code: the makefile and the linker script. The makefile is concerned with keeping the build process orderly, while the linker script describes how the various pieces are to fit together. Typically, both make and the ld linker have built-in rules to take into account the requirements of a host operating system. However, this light-flashing program has no host OS, so the built-in rules are useless. The programmer is in complete control, but that means the programmer can make no assumptions about the build process: everything must be specified explictly. (note 1) The linker script defines how to lay things out in the object file: /****************************************************************************** * kernel.ld * by Alex Chadwick * modified by gus3 * * A linker script for generation of raspberry pi kernel images. ******************************************************************************/ SECTIONS { /* * First and formost we need the .init section, containing the Interrupt * Vector Table. When the ARM gets the reset signal, it jumps to address 0. * The Raspberry Pi's VideoCore hardware delivers this interrupt after loading * the kernel.img and initializing the ATAG's. * * (A complete OS would contain subsequent jump instructions for different * interrupt types. This project leaves these uninitialized.) */ .init 0x0000 : { *(.init) } /* We allow room for the ATAGs and then start our code at 0x8000. */ .text 0x8000 : { *(.text) } } It is up to the linker to create a file with all these sections laid out as specified. Since the output file is intended to be loaded “raw,” that means the margin between the .init and .text sections will be padded out with zeros. The result is an amazingly large file (>32K) for so few executed instructions. The makefile, derived from Alex Chadwick’s version, simplifies a few steps with generic replacements: ############################################################################### # makefile # by Alex Chadwick # modified by gus3 # # A makefile script for generation of raspberry pi kernel images. ############################################################################### # Used when cross-compiling. Unneeded when building on the RPi, so later # references to it are removed. # ARMGNU ?= arm-none-eabi # The intermediate directory for compiled object files. BUILD = build/ # The directory in which source files are stored. SOURCE = source/ # The name of the output file to generate. TARGET = kernel.img # The name of the assembler listing file to generate. LIST = kernel.list # The name of the map file to generate. MAP = kernel.map # The name of the linker script to use. LINKER = kernel.ld # The names of all object files that must be generated. Deduced from the # assembly code files in source. OBJECTS := build/light-flash.o build/light-flash-start.o # Rule to make everything. all: $(TARGET) $(LIST) # Rule to remake everything. Does not include clean. rebuild: all # Rule to make the listing file. $(LIST) : $(BUILD)output.elf objdump -d $(BUILD)output.elf > $(LIST) # Rule to make the image file. $(TARGET) : $(BUILD)output.elf objcopy $(BUILD)output.elf -O binary $(TARGET) # Rule to make the elf file. $(BUILD)output.elf : $(OBJECTS) $(LINKER) ld --no-undefined $(OBJECTS) -Map $(MAP) -o $(BUILD)output.elf -T $(LINKER) # Rule to make the object files. $(BUILD)%.o: $(SOURCE)%.c gcc -O0 -c -nostdlib -I $(SOURCE) -o $@ $< $(BUILD)%.o: $(SOURCE)%.s as -I $(SOURCE) $< -o $@ # Rule to clean files. clean : -rm -f $(BUILD)*.o -rm -f $(BUILD)output.elf -rm -f $(TARGET) -rm -f $(LIST) -rm -f $(MAP) So, with the *.c and *.s files in source/, and kernel.ld and makefile in the current directory, a simple invocation of make should do the following: - Compile/assemble the source files to object files, with no platform support included; - Link the object files into a single temporary file, and create a map of its symbols; - Create a listing file from the temporary file; - Convert the temporary file to a raw binary file, suitable for booting. The options passed to GCC bear some explanation. Avoiding optimization with -O0 makes sure the delay loop remains in place. GCC stops after compiling, with -c. Finally, the -nostdlib option omits all the platform support libraries, such as glibc and the C entry code that passes command-line arguments to main(). For your convenience, this link opens a .tar.gz archive containing all the source and build files for this project. (Edit 2012-10-08: I swapped the inline shell archive for hosted file; CAPTCHA and 30-second wait.) The makefile is configured for building on a Raspberry Pi; if you use a cross-compiler, you will need to adjust the gcc and as commands in the makefile to point to the proper toolchain. Note, however, that running the resulting kernel.img file will require a second computer, with an SD card reader. I suggest you also use a second SD card, with no critical data on it. This way, the kernel.img currently in the RPi will stay “safe” from these experiments. If you wish, you may use the SD card already in the RPi, but make a copy of the /boot/kernel.img file before over-writing it with the kernel.img in the c-arm/ directory. Once you have tested the light-flashing kernel.img, you will need to cut power to the RPi, remove the SD card, insert the card into a PC, and restore the original /boot/kernel.img to the card. Remember that the card’s /boot partition is mounted under another directory, probably /mnt, so the actual path would be /mnt/kernel.img. This sounds like a lot of work, and it is. This is the price of total control over the system. Seeing the flashing OK light is the reward of all this extra effort. But it isn’t your imagination that the light is flashing kind of slowly. In my testing, the flashing was approximately 0.9 Hz, or one flash every 1.1 seconds. Take a look at the listing in kernel.list to see that the main routine is 104 bytes (26 instructions) long, much heavier than Alex Chadwick’s version at 36 bytes (9 instructions) long. Is there anything we can do to compact the code, without letting the optimizer remove the delay loop? Yes, there is: we can build Thumb code instead of ARM code. What is Thumb code? For a long time, ARM processors have had a reduced-capability mode, called “Thumb mode,” in which the general register set is cut from 16 to 8 registers, still 32 bits each; only branch instructions may be conditional; and the instruction size is reduced from 4 bytes to 2. These simple changes in the character of the instruction set means that twice as many instructions can fit in the same space, whether in the processor cache, in RAM, or on disk. (note 2) Also, it’s usually faster to decode 16 bits instead of 32. To get GCC to build Thumb code, simply prepend “-mthumb” to the command’s parameter list. In line 55 of the makefile above, it’s simply a matter of changing “gcc -O0″ to “gcc -mthumb -O0″, and leaving the rest of the command intact. The compiler and linker will handle the rest. In this case, “the rest” includes a bad assumption in the code. The branch instruction in light-flash-start.s is a simple branch, executed in ARM mode, but the branch target is Thumb code. The build process inserts a “shim,” a short block of code to handle changing the CPU to Thumb mode where the programmer omitted it. Using the “-mthumb” option grew the size of the program text from 26 to 29 instructions, but the shorter instruction size means the actual byte count dropped from 104 to 58 bytes. The previous article showed where reducing two machine instructions to one caused a slight speed-up that was barely perceptible. In this case, switching from ARM to Thumb for the bulk of the code makes a visible difference of 32%, taking the flash time down from 1.1 to 0.75 seconds. All these “benefits” come from adding just one option to the GCC command line. Summary The switch from ARM to Thumb instructions changed these characteristics in the resulting code: For simple C code, compiling to the Thumb instruction set made a huge difference. Even though the actual number of instructions to be decoded, executed, and retired grew by 11.5%, the execution speed of the delay loop improved by 1/3! Both versions of the code fit easily into the 64K of cache, so the best explanation is the simplified Thumb instruction set. Notes (1) A printing-press geek made a useful distinction to me many years ago: Some systems are like cars with automatic transmission; some systems are like cars with a manual transmission; and some systems are like cars that let you open up the gear box and move the gears around by hand, hoping for the best. Which one most resembles this project is left as an exercise for the reader.^ (2) Except that the Raspberry Pi runs this code not from a disk, but rather as boot code from an SD card. The pedantic term is “non-volatile storage.”^ One CommentLeave a Comment Trackbacks
http://mindplusplus.wordpress.com/2012/10/02/c-ing-a-flashing-light/?like=1&_wpnonce=6484ab78b3
CC-MAIN-2013-48
refinedweb
2,528
64.41
16 May 2012 08:28 [Source: ICIS news] SINGAPORE (ICIS)--Prices of Asian acrylonitrile-butadiene-styrene (ABS) resin have fallen further this week to reach the trough for the year. Offers of prompt parcels were reduced by $30-40/tonne (€23.7-31.6/tonne) from the week ended 11 May to the $1,900-1,950/tonne CFR (cost & freight) ?xml:namespace> “Some trades have already been fixed at under $1,900/tonne this week,” said a trader in Spot prices are now at their lowest for the year as the previous low point was at $1,980/tonne CFR in early January and SM prices had peaked this year at above $2,200/tonne CFR in March, according to ICIS data. Traders believe prices have further downside potential, given the persistent lack of demand and falling feedstock prices. The weak economic conditions in the “The recent flare up in the eurozone crisis has again dampened sentiment and caused global markets to sell off,” said a Taiwanese ABS maker. The fall in commodities prices took crude futures down to $93/bbl at one point this week, putting downward pressure on prices of raw materials for ABS like styrene monomer (SM) and butadiene (BD). SM prices fell below $1,400/tonne CFR China this week while BD numbers $2,250/tonne CFR NE (northeast) Asia. “The decline in feedstock prices dragged ABS numbers lower again this week and lower resin offers could not interest buyers,” said a trader in southeast Asia. End-users of ABS have largely retreated to the sidelines this week, preferring to delay purchases in anticipation of further price decreases. Major ABS suppliers in Asia include Chimei Corp and FCFC of Taiwan, LG Chem, Kumho Petrochemical and Cheil Samsung of
http://www.icis.com/Articles/2012/05/16/9560075/asian-abs-prices-at-new-low-for-2012-after-losing-more-ground.html
CC-MAIN-2014-10
refinedweb
293
63.83
ZF Home Page Issue Tracker Code Browser Wiki Dashboard Contributors Wiki Developers Wiki Proposers Wiki Most Wanted Contributor License Agreement Mailing Lists Code Contributor Guide Documentation Contributor Guide Developer Notes Zend_OpenId is a set of components that allow anyone to create OpenID authentication servers and consumers According to an identity is the "collective aspect of the set of characteristics by which a thing is definitively recognizable or known". In many applications an Identity is necessary to authenticate entities, authorize access, maintain privacy and prevent disclosures In the current Internet world, we have a lot of different unconnected identity systems, and a lot of identities for the individual user. An end user needs to remember their names and passwords for each and every site or service they visit and use.. An OpenID identifier is typically a URL. It may be the URL of the user's personal page, blog or other resource that may provide additional information about him. Such URLs are aliases pointing to the OpenID Provider's local identifier for the user. If a user does not wish to support an alias, they may use the OpenID Proider's local identifier directly. End-users should be able to use this identity URL to register and authenticate themselves on any site that supports OpenID. No more need for many passwords and duplicate user names - just one identifier for Internet services. OpenID is an open, decentralized, and free user centric solution. A user may choose which OpenID provider to use, or even create their own personal identity server. No central authority must approve or register Relying Parties (OpenID Consumers or just Sites) or OpenID Providers (OpenID Servers). The protocols utilised by OpenID scale well. OpenID standards are community driven. Several implementations are freely available for C++, C#, Java, Perl, Python, Ruby and PHP. However there is no final stable release yet for a PHP library conforming to the OpenID 2.0 specification (currently draft 11). The difficulty of a PHP implementation is increased by the fact that the majority of PHP installations do not have sufficient cryptographic or efficient math functions to provide OpenID applications which perform well. This proposal includes a reference to a possible openssl extension patch which would improve the efficiency of such functions in PHP. At present, Identity 2.0 and OpenID are very popular and growing technologies and the Zend Framework's OpenID implementation may be a significant advantage in leading and supporting the development of web applications leveraging OpenID in PHP. This document describes proposals for the Zend Framework's OpenID implementation. It will allow the use of both OpenID Providers (Servers) and Consumers (Relying Parties/Applications) that will fully implement the draft OpenID 2.0 Authentication Specification and remain backwards compatible with the current OpenID 1.1 specification. Also proposed is support for OpenID Extensions (e.g. Simple Registration Extension) which may allow for Relying Parties and Providers exchange data concerning the authenticated user with that user's permission. The main purpose of Zend_OpenId components is implementing an OpenID authentication protocol described in the following diagram: The Zend_OpenId components will implement both Zend_OpenId_Consumer and Zend_OpenId_Provider. The consumer class will contain two main public methods login() and verify(). The first one should be called on user login (step 1), it will perform normalisation, discovery and redirection to provider (steps 2-4). The function verify() should be called after redirecting back from provider (step 9), it must perform final validation of received authentication data. The Provider will have just one main method handle() that should be called on any OpenID request. Both Provider and Consumer need external storage to store some data between requests. These storages will be implemented through abstract interface class, so it will be possible to use different kinds of storages without redesign. If a milestone is already done, begin the description with "[DONE]", like this: Zend_OpenId_Consumer usage Simplified OpenID server with external user interface I am very excited to see this proposal. Wouldn't this be a good thing to tie into Zend_Auth instead of reinventing the wheel? Zend_OpenId component implements both OpenID probvider and consumer. And provider is not related to Zend_Auth anyway. I was thinking about creating Zend_Auth_Adapter_OpenId in the future. Hey Dmitry, My comments on the proposal are below. Firstly the comment about there being no existing PHP OpenID 2.0 implementation should be deleted quickly. There is a PHP4 implementation written by JanRain called the PHP OpenID Library which is freely available under an open source license. It's the current defacto 2.0 standard in PHP. It is not a perfect 2.0 implementation but that's to be expected given we're currently at Draft 11 in the specification process for 2.0 (it was Draft 10 not so long ago) so a perfect implementation doesn't exist anywhere. The overview could be split into a few sections. e.g. What is OpenID, How the ZF will implement OpenID, and a few long term goals/objectives on why it's useful to be included in the framework. The truth is most people don't know what OpenID is, or why they should care. Giving them information is essential, esp. so the reviewers know what they're reviewing . The name of the component should probably be "Zend_Openid", small "i" in the name since that seems to follow the Zend Framework naming convention better. Nitpicking me . Some mention could be made of OpenID compatibility, e.g. Microsoft Vista, AOL implementing an OpenID 1.1 Provider for users, other integrated services. In the overview, this would grab the proposal more interest from other users. Should be careful about talking about the implementation of cryptographic algorithms. PHP's core extension BCMath is a living terror, but GMP or big_int are far faster. Not all PHP solutions are horribly inefficient. Also, the dependency on an openssl patch should be optional. I'm not even sure it needs mentioning. As far as I know such a patch (yours or Wez's) will not be implemented in the near future. The requirement to implement Simple Registration Extension 1.0 should be dropped. OpenID extensions require no specific internal handling - literally Extension support should be extremely generic so developers may define other Extensions at runtime (e.g. sreg 1.1 Draft 1) which immediately enables their support. This is possible since Extensions just add a "namespace" to the key-value list sent/returned from an OP server. Maybe "This component must implement support for OpenID Extensions" is generic enough for this. 2.0 will see a few new Extensions which could use such a generic interface. (I'll forward my Extension implementation so you can see what I mean). On the dependencies: Zend_Http_Client should be used - it's easy to implement where needed. Zend_Services_Yadis is effectively 95% complete for OpenID 2.0. It could do with a little API simplification but is otherwise functional. I would suggest come review time, we both press for Yadis to be reviewed since they are potentially dependent on each other. Zend_Uri has a static check() method for validating a normalised URI. I would suggest a subclass has more value since normalisation should be local to the OpenID classes. On a similar track, I think selfUrl() could be removed. Setting the Trust Root and Return To uris should be something a user can easily do themselves if they wish. Note that Zend_Uri does not currently have complete support for Internationalised Domain Names using Unicode characters in URIs. This is a requirement of the Yadis Specification (can't remember off hand whether the OpenID 2.0 implementors' draft itself mentions it). I'll leave comments on code to another day - In short the existing code needs to be refactored into more focused classes where it's easier to modify behaviour and apply the growing set of OpenID 2.0 rules. One of the final points is on design. As I elaborated last week when I was about to post my own OpenID proposal, I was pushing for a split between OpenID and it's components. I still believe there is a lot of merit in extracting common stuff like Diffie-Hellman, HMAC, and Math elements into their own classes. This would allow other components reuse these (e.g. HMAC for Zend_Mail) and cut out any future duplication of the same sort. If you want an example of an implementation, I've already proposed my existing code to PEAR and it's listed as a Proposal for comment. The rest of my code will find it's way to you very soon. I'll also update the referenced repository with the current Zend_Services_Yadis implementation (mainly a few bug fixes I found during testing over the weekend). I saw JanRain library version 1.2.2 at and it doesn't have support for OpenID 2.0. It also is not compatible with latest php versions (it supports php from 4.3.0 to 5.1). I agree that overview is too small and this proposal is good mainly for people that already know about OpenID. The name of the component should be "Zend_OpenId" (we already have Zend_Auth_Storage_NonPersistent). The component will be able to work without OpenSSL patch, but with bcmath it will work too slow. According to Simple Registration Extension 1.0 may be you are right. I would like to support your way if you show me what kind of API should be used for that. I agree to reuse Zend_Http_Client and Zend_Services_Yadis, however I don't see how Yadis may depend on OpenId. URI normalization is described in RFC3986 and it is not related to OpenID. It would be nice to have it implemented in Zend_URI. Also I don't see any reason to always require specification of trust root and return uri from user. Extracting reusable components is a good idea, but I have no idea how much time it will take. I would be glad to look into your OpenID proposal, and OpenID and Yadis code. Hi Dmitry, Yes, 1.2.2 implements OpenID 1.0, but a few months back JanRain released 2.0RC1 of the library which implements OpenID 2.0. Also, the myopenid.com service is run by JanRain and they certainly implement 2.0 for their server (I have one of my OpenID identities registered there and using 2.0 for authentication). I'd prefer (only a personal pref) either Openid or OpenID (if camel casing is allowable then might as well use the official spec title if possible). I used Openid in the proposal example code (my one) - I'm talking too much over a tidly point... Yes, but GMP is far faster than BCMath - possibly as fast as an openssl patch unless openssl gets an even better set of algorithms than gmp or PECL's big_int (though big_int is not as good as gmp). BCMath has some horrible algorithm in its source screwing it up. It would be nice to see that improve if possible given the mountain of code likely depending on it. Simple Registration is only of a few extensions. Once 2.0 is finalised don't be surprised to see something allowing Phishing protection querys to check if a Phishing-safe method was used - for example Microsoft will bundle a rebranded OpenID 2.0 protocol in Vista CardSpace once the 2.0 drafting is over. Here's an extract of my code. I use a "Request" object which lets the end user setup extra Extension parameters to piggy-back on the authentication requests. Part of my refactoring woes (I initially went by Draft 8 or something way back when) is refactoring this object into two separate classes - Authentication, and Extension Requests (Extensions can piggy back without there being defined authentication params). It's simple to add a piggy-backed parameter - just add the namespace for the extension, and append all params to the new authentication redirect's URI. I just start by building separate Argument and ExtensionArgument arrays - the rest is just making a http_build_query call. The response just comes back with a param like openid_sreg_email, which is then added to the openid_signed list. The value signature just needs to include it when computing the MAC. Yadis does not depend on OpenID - I should proofread my comments! OpenID 2.0 specifies some additional requirements - a Zend_Uri subclass might allow these more easily. Might not though. I'm thinking of rules disallowing URI fragments and such. Extracting classes isn't too difficult - it's small fry against implementing OpenID itself. The extracted code is quite small - see the PEAR proposals. Code coming soon - if I can't finish the refactoring quickly I'll just forward what I have. It's enough at least to make a 2.0 process so long as some edge cases (XRIs since Yadis code needs a small update) aren't met. Probably I'm just nitpicking over folding more code into Request/Response classes so the specification is more easily understandable with it. I didn't see 2.0RC1 before. Than you for pointing me. As I understood according to coding standard the name must be OpenId, however I would prefer OpenID too. You are right anout GMP. It gives near the same speed as OpenSSL, the bcmath problem in one algorithm, that should be changed to more efficient one. I like your solution for generic OpenID extensions support, however this time I don't see if it is enough for SREG. Yeah, the code extract is pretty vague without more of the code to put it in context. The use case is something like: I made the same in little bit different way: Dmitry, How familiar are you with Zend Framework? For example, in Zend_OpenId_Provider_User_Session you don't leverage Zend_Session. This proposal should also be integrated with Zend_Auth. After all, Zend Framework is a coherent whole, not a collection of unrelated classes. I don't know ZF well, so thank you for suggestion. BTW I thought here is a place to discuss proposal and prototype that you saw is just a quick implementation that I plan to finish after proposal approvement. I am not sure that this proposal must include Zend_Auth integration. It can be implemented later as an Zend_Auth adapter on top of Zend_OpenId_Consumer. I agree that Zend_Session should be leveraged and that the Zend_Auth adapter should be trivial to implement (provided there is not an impedance mismatch) after we have a viable OpenID component. Oh, and I believe the name should be as Dmitry already has it, "Zend_OpenId". This is because "Open" is one word, and "identifier" is another word. We do not capitalize all of the letters of acronyms and abbreviations (e.g., Zend_Config, Zend_Uri). I'm also excited to see this develop. Although I also prefer Zend_OpenID, I think the coding standard does indeed require that it must be Zend_OpenId ... "If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters are not allowed; e.g., a class "Zend_PDF" is not allowed, while "Zend_Pdf" is acceptable." -- I agree there should be a Zend_Auth_Adapter_OpenId, but also agree that doesn't belong in this proposal. It should be an Auth team proposal, and make use of Zend_OpenId_Consumer. I think it would be helpful to use Zend_Session in place of the session_* functions, but I know even less about OpenID provider-side implementation than I do about relying-party-side. I think Dmitry would agree that this is a proposal, not a review of complete code. It's something to be examined with the knowledge it will get serious attention over the coming few months. There will almost certainly be a Zend_Auth_Adapter_OpenId, however OpenID is itself a necessary standalone component given both its size and complexity. It's impossible to bundle an entire OpenID 2.0 library into an adapter, so library first, adapter second. The original code for this was developed outside the Zend Framework initially - hence the lack of component integration at the moment. I'm sure once the code is being refactored the current Zend Framework components will quickly find themselves co opted . Dmitry – I know that OpenID needs to redirect to the OpenID provider in order to login and/or retrieve identity details, and I see some methods relating to redirection. Please consider that this will likely be used in the MVC, and think about how it might integrate with Zend_Controller_Response_Http (which aggregates HTTP response headers and sends them); I don't want the two components to conflict in the end. Other than that, the API looks reasonable to me, and I think the dialog you and Padraic are having is leading to some good refinement of the code. I look forward to experimenting with this! It is not a problem. This won't effect design but just implementationt that is done only on "working-prototype" level. This proposal is approved for incubator development. Before the component would be promoted to core (i.e., the trunk), however, it should take advantage of Zend_Service_Yadis and Zend_Crypt, when they become available. Also, this component should integrate with Zend_Session (Darby Felton, Ralph Schindler) and Zend_Controller_Reponse_Http (Matthew Weier O'Phinney). Please also coordinate with Pádraic Brady, assisting with his proposed components (Crypt and Yadis) as possible. So is this component going to get a spot in the tracker? I'm new to OpenID, but after having looked at Provider, Provider_Storage, Provider_User, Provider_User_Session (incubator) DRY and I were thinking: delegating to the existing Zend_Auth package seems like the way to go. Implementing Zend_Auth_Adapter_Interface (either directly by your Provider_Storage class or by a seperate class Zend_Auth_Adapter_OpenId_Provider) brings in the Zend_Auth class' magic for free. Chances are that you could get rid of the Provider_User hierarchy... I've been working on some real world ZF use cases for Zend_OpenId_Provider, now. Obviously my initial comment wasn't based on any Here's my feedback on the authentication part, the persistent data part and the server part. 1. Maybe it's possible and a good idea as well to leverage the Zend_Server package for the server part of Zend_OpenId_Provider. 2. I want to reuse my existing auth/login/logout models (based on the Zend_Auth package). So I just want to pass a Zend_Auth_Result to the server component. 3. I'd like to be able to pass seperate Associations and Trusted Site models to the server component. The server would typehint abstract classes or interfaces from the library. Any update? Zend_OpenId has been moved to core on November. For further details you can have a look at Ups, time to checkout a new copy then. Thanks for the links Simone Do you know if there's an RSS feed of the changelog? It would be nice if I could add it to Eclipse and get notify every time the log changes. You can subscribe to SVN changelog from here If you want to subscribe a custom changelog simply apply the filter from then subscribe the page with your default aggregator. The feed URL will be extracted by your aggregator from the link tag. Powered by a free Atlassian Confluence Open Source Project License granted to Zend Framework. Evaluate Confluence today.
http://framework.zend.com/wiki/display/ZFPROP/Zend_OpenId
crawl-002
refinedweb
3,204
64.71
Android, you have several techniques available for implementing custom 2D graphics and animations in views. In addition to using drawables, you can create 2D drawings using the drawing methods of the Canvas class. The Canvas is a 2D drawing surface that provides methods for drawing. This is useful when your app needs to regularly redraw itself, because what the user sees changes over time. In this codelab, you learn how to create and draw on a canvas that is displayed in a View. The types of operations you can perform on a canvas include: - Fill the whole canvas with color. - Draw shapes, such as rectangles, arcs, and paths styled as defined in a Paintobject. The Paintobject holds the style and color information about how to draw geometries (such as line, rectangle, oval, and paths), or for example, the typeface of text. - Apply transformations, such as translation, scaling, or custom transformations. - Clip, that is, apply a shape or path to the canvas to define its visible portions. How you can think of Android drawing (super-simplified!) Drawing in Android or on any other modern system, is a complex process that includes layers of abstractions, and optimizations down to the hardware. How Android draws is a fascinating topic about which much has been written, and its details are beyond the scope of this codelab. In the context of this codelab, and its app that draws on a canvas for display in a full-screen view, you can think of it in the following way. - You need a view for displaying what you are drawing. This could be one of the views provided by the Android system. Or, In this codelab, you create a custom view that serves as the content view for your app ( MyCanvasView). - This view, as all views, comes with its own canvas ( canvas). - For the most basic way of drawing on the canvas of a view, you override its onDraw()method and draw on its canvas. - When building drawing, you need to cache what you have drawn before. There are several ways of caching your data, one is in a bitmap ( extraBitmap). Another is to save a history of what you drawn as coordinates and instructions. - To draw to your caching bitmap ( extraBitmap) using the canvas drawing API, you create a caching canvas ( extraCanvas) for your caching bitmap. - You then draw on your caching canvas ( extraCanvas), which draws onto your caching bitmap ( extraBitmap). - To display everything drawn on the screen, you tell the view's canvas ( canvas) to draw the caching bitmap ( extraBitmap). What you should already know - How to create an app with an Activity, a basic layout, and run it using Android Studio. - How to associate event handlers with views. - How to create a custom view. What you'll learn - How to create a Canvasand draw on it in response to user touch. What you'll do - Create an app that draws lines on the screen in response to the user touching the screen. - Capture motion events, and in response, draw lines on a canvas that is displayed in a fullscreen custom view on the screen. The MiniPaint app uses a custom view to display a line in response to user touches, as shown in the screenshot below. Step 1. Create the MiniPaint project - Create a new Kotlin project called MiniPaint that uses the Empty Activity template. - Open the app/res/values/colors.xmlfile and add the following two colors. <color name="colorBackground">#FFFF5500</color> <color name="colorPaint">#FFFFEB3B</color> - Open styles.xml - In the parent of the given AppThemestyle, replace DarkActionBarwith NoActionBar. This removes the action bar, so that you can draw fullscreen. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> Step 2. Create the MyCanvasView class In this step you create a custom view, MyCanvasView, for drawing. - In the app/java/com.example.android.minipaintpackage, create a New > Kotlin File/Class called MyCanvasView. - Make the MyCanvasViewclass extend the Viewclass and pass in the context: Context. Accept the suggested imports. import android.content.Context import android.view.View class MyCanvasView(context: Context) : View(context) { } Step 3. Set MyCanvasView as the content view To display what you will draw in MyCanvasView, you have to set it as the content view of the MainActivity. - Open strings.xmland define a string to use for the view's content description. <string name="canvasContentDescription">Mini Paint is a simple line drawing app. Drag your fingers to draw. Rotate the phone to clear.</string> - Open MainActivity.kt - In onCreate(), delete setContentView(R.layout.activity_main). - Create an instance of MyCanvasView. val myCanvasView = MyCanvasView(this) - Below that, request the full screen for the layout of myCanvasView. Do this by setting the SYSTEM_UI_FLAG_FULLSCREENflag on myCanvasView. In this way, the view completely fills the screen. myCanvasView.systemUiVisibility = SYSTEM_UI_FLAG_FULLSCREEN - Add a content description. myCanvasView.contentDescription = getString(R.string.canvasContentDescription) - Below that, set the content view to myCanvasView. setContentView(myCanvasView) - Run your app. You will see a completely white screen, because the canvas has no size and you have not drawn anything yet. Step 1. Override onSizeChanged() The onSizeChanged() method is called by the Android system whenever a view changes size. Because the view starts out with no size, the view's onSizeChanged() method is also called after the Activity first creates and inflates it. This onSizeChanged() method is therefore the ideal place to create and set up the view's canvas. - In MyCanvasView, at the class level, define variables for a canvas and a bitmap. Call them extraCanvasand extraBitmap. These are your bitmap and canvas for caching what has been drawn before. private lateinit var extraCanvas: Canvas private lateinit var extraBitmap: Bitmap - Define a class level variable backgroundColorfor the background color of the canvas and initialize it to the colorBackgroundyou defined earlier. private val backgroundColor = ResourcesCompat.getColor(resources, R.color.colorBackground, null) - In MyCanvasView, override the onSizeChanged()method. This callback method is called by the Android system with the changed screen dimensions, that is, with a new width and height (to change to) and the old width and height (to change from). override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { super.onSizeChanged(width, height, oldWidth, oldHeight) } - Inside onSizeChanged(), create an instance of Bitmapwith the new width and height, which are the screen size, and assign it to extraBitmap. The third argument is the bitmap color configuration. ARGB_8888stores each color in 4 bytes and is recommended. extraBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - Create a Canvasinstance from extraBitmapand assign it to extraCanvas. extraCanvas = Canvas(extraBitmap) - Specify the background color in which to fill extraCanvas. extraCanvas.drawColor(backgroundColor) - Looking at onSizeChanged(), a new bitmap and canvas are created every time the function executes. You need a new bitmap, because the size has changed. However, this is a memory leak, leaving the old bitmaps around. To fix this, recycle extraBitmapbefore creating the next one by adding this code right after the call to super. if (::extraBitmap.isInitialized) extraBitmap.recycle() Step 2. Override onDraw() All drawing work for MyCanvasView happens in onDraw(). To start, display the canvas, filling the screen with the background color that you set in onSizeChanged(). - Override onDraw()and draw the contents of the cached extraBitmapon the canvas associated with the view. The drawBitmap() Canvasmethod comes in several versions. In this code, you provide the bitmap, the x and y coordinates (in pixels) of the top left corner, and nullfor the Paint, as you'll set that later. override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawBitmap(extraBitmap, 0f, 0f, null) } Notice that the canvas that is passed to onDraw() and used by the system to display the bitmap is different than the one you created in the onSizeChanged() method and used by you to draw on the bitmap. - Run your app. You should see the whole screen filled with the specified background color. In order to draw, you need a Paint object that specifies how things are styled when drawn, and a Path that specifies what is being drawn. Step 1. Initialize a Paint object - In MyCanvasView.kt, at the top file level, define a constant for the stroke width. private const val STROKE_WIDTH = 12f // has to be float - At the class level of MyCanvasView, define a variable drawColorfor holding the color to draw with, and initialize it with the colorPaintresource you defined earlier. private val drawColor = ResourcesCompat.getColor(resources, R.color.colorPaint, null) - At the class level, below, add a variable paintfor a Paintobject and initialize it as follows. // Set up the paint with which to draw. private val paint = Paint().apply { color = drawColor // Smooths out edges of what is drawn without affecting shape. isAntiAlias = true // Dithering affects how colors with higher-precision than the device are down-sampled. isDither = true style = Paint.Style.STROKE // default: FILL strokeJoin = Paint.Join.ROUND // default: MITER strokeCap = Paint.Cap.ROUND // default: BUTT strokeWidth = STROKE_WIDTH // default: Hairline-width (really thin) } - The colorof the paintis the drawColoryou defined earlier. isAntiAliasdefines whether to apply edge smoothing. Setting isAntiAliasto true, smoothes out the edges of what is drawn without affecting the shape. isDither, when true, affects how colors with higher-precision than the device are down-sampled. For example, dithering is the most common means of reducing the color range of images down to the 256 (or fewer) colors. stylesets the type of painting to be done to a stroke, which is essentially a line. Paint.Stylespecifies if the primitive being drawn is filled, stroked, or both (in the same color). The default is to fill the object to which the paint is applied. ("Fill" colors the inside of shape, while "stroke" follows its outline.) strokeJoinof Paint.Joinspecifies how lines and curve segments join on a stroked path. The default is MITER. strokeCapsets the shape of the end of the line to be a cap. Paint.Capspecifies how the beginning and ending of stroked lines and paths. The default is BUTT. strokeWidthspecifies the width of the stroke in pixels. The default is hairline width, which is really thin, so it's set to the STROKE_WIDTHconstant you defined earlier. Step 2. Initialize a Path object The Path is the path of what the user is drawing. - In MyCanvasView, add a variable pathand initialize it with a Pathobject to store the path that is being drawn when following the user's touch on the screen. Import android.graphics.Pathfor the Path. private var path = Path() Step 1. Respond to motion on the display The onTouchEvent() method on a view is called whenever the user touches the display. - In MyCanvasView, override the onTouchEvent()method to cache the xand ycoordinates of the passed in event. Then use a whenexpression to handle motion events for touching down on the screen, moving on the screen, and releasing touch on the screen. These are the events of interest for drawing a line on the screen. For each event type, call a utility method, as shown in the code below. See the MotionEventclass documentation for a full list of touch events. override fun onTouchEvent(event: MotionEvent): Boolean { motionTouchEventX = event.x motionTouchEventY = event.y when (event.action) { MotionEvent.ACTION_DOWN -> touchStart() MotionEvent.ACTION_MOVE -> touchMove() MotionEvent.ACTION_UP -> touchUp() } return true } - At the class level, add the missing motionTouchEventXand motionTouchEventYvariables for caching the x and y coordinates of the current touch event (the MotionEventcoordinates). Initialize them to 0f. private var motionTouchEventX = 0f private var motionTouchEventY = 0f - Create stubs for the three functions touchStart(), touchMove(), and touchUp(). private fun touchStart() {} private fun touchMove() {} private fun touchUp() {} - Your code should build and run, but you won't see anything different from the colored background yet. Step 2. Implement touchStart() This method is called when the user first touches the screen. - At the class level, add variables to cache the latest x and y values. After the user stops moving and lifts their touch, these are the starting point for the next path (the next segment of the line to draw). private var currentX = 0f private var currentY = 0f - Implement the touchStart()method as follows. Reset the path, move to the x-y coordinates of the touch event ( motionTouchEventXand motionTouchEventY), and assign currentXand currentYto that value. private fun touchStart() { path.reset() path.moveTo(motionTouchEventX, motionTouchEventY) currentX = motionTouchEventX currentY = motionTouchEventY } Step 3. Implement touchMove() - At the class level, add a touchTolerancevariable and set it to ViewConfiguration.get(context).scaledTouchSlop. private val touchTolerance = ViewConfiguration.get(context).scaledTouchSlop Using a path, there is no need to draw every pixel and each time request a refresh of the display. Instead, you can (and will) interpolate a path between points for much better performance. - If the finger has barely moved, there is no need to draw. - If the finger has moved less than the touchTolerancedistance, don't draw. scaledTouchSlopreturns the distance in pixels a touch can wander before the system thinks the user is scrolling. - Define the touchMove()method. Calculate the traveled distance ( dx, dy), create a curve between the two points and store it in path, update the running currentXand currentYtally, and draw the path. Then call invalidate()to force redrawing of the screen with the updated path. private fun touchMove() { val dx = Math.abs(motionTouchEventX - currentX) val dy = Math.abs(motionTouchEventY - currentY) if (dx >= touchTolerance || dy >= touchTolerance) { // QuadTo() adds a quadratic bezier from the last point, // approaching control point (x1,y1), and ending at (x2,y2). path.quadTo(currentX, currentY, (motionTouchEventX + currentX) / 2, (motionTouchEventY + currentY) / 2) currentX = motionTouchEventX currentY = motionTouchEventY // Draw the path in the extra bitmap to cache it. extraCanvas.drawPath(path, paint) } invalidate() } This method in more detail: - Calculate the distance that has been moved ( dx, dy). - If the movement was further than the touch tolerance, add a segment to the path. - Set the starting point for the next segment to the endpoint of this segment. - Using quadTo()instead of lineTo()create a smoothly drawn line without corners. See Bezier Curves. - Call invalidate()to (eventually call onDraw()and) redraw the view. Step 4: Implement touchUp() When the user lifts their touch, all that is needed is to reset the path so it does not get drawn again. Nothing is drawn, so no invalidation is needed. - Implement the touchUp()method. private fun touchUp() { // Reset the path so it doesn't get drawn again. path.reset() } - Run your code and use your finger to draw on the screen. Notice that if you rotate the device, the screen is cleared, because the drawing state is not saved. For this sample app, this is by design, to give the user a simple way to clear the screen. Step 5: Draw a frame around the sketch As the user draws on the screen, your app constructs the path and saves it in the bitmap extraBitmap. The onDraw() method displays the extra bitmap in the view's canvas. You can do more drawing in onDraw(). For example, you could draw shapes after drawing the bitmap. In this step you draw a frame around the edge of the picture. - In MyCanvasView, add a variable called framethat holds a Rectobject. private lateinit var frame: Rect - At the end of onSizeChanged()define an inset, and add code to create the Rectthat will be used for the frame, using the new dimensions and the inset. // Calculate a rectangular frame around the picture. val inset = 40 frame = Rect(inset, inset, width - inset, height - inset) - In onDraw(), after drawing the bitmap, draw a rectangle. // Draw a frame around the canvas. canvas.drawRect(frame, paint) - Run your app. Notice the frame. Task (optional): Storing data in a Path In the current app, the drawing information is stored in a bitmap. While this is a good solution, it is not the only possible way for storing drawing information. How you store your drawing history depends on the app, and your various requirements. For example, if you are drawing shapes, you could save a list of shapes with their location and dimensions. For the MiniPaint app, you could save the path as a Path. Below is the general outline on how to do that, if you want to try it. - In MyCanvasView, remove all the code for extraCanvasand extraBitmap. - Add variables for the path so far, and the path being drawn currently. // Path representing the drawing so far private val drawing = Path() // Path representing what's currently being drawn private val curPath = Path() - In onDraw(), instead of drawing the bitmap, draw the stored and current paths. // Draw the drawing so far canvas.drawPath(drawing, paint) // Draw any current squiggle canvas.drawPath(curPath, paint) // Draw a frame around the canvas canvas.drawRect(frame, paint) - In touchUp(), add the current path to the previous path and reset the current path. // Add the current path to the drawing so far drawing.addPath(curPath) // Rewind the current path for the next touch curPath.reset() - Run your app, and yes, there should be no difference whatsoever. Download the code for the finished codelab. $ git clone Alternatively you can download the repository as a Zip file, unzip it, and open it in Android Studio. - A Canvasis a 2D drawing surface that provides methods for drawing. - The Canvascan be associated with a Viewinstance that displays it. - The Paintobject holds the style and color information about how to draw geometries (such as line, rectangle, oval, and paths) and text. - A common pattern for working with a canvas is to create a custom view and override the onDraw()and onSizeChanged()methods. - Override the onTouchEvent()method to capture user touches and respond to them by drawing things. - You can use an extra bitmap to cache information for drawings that change over time. Alternatively, you could store shapes, or a path. Udacity course: Android developer documentation: Canvasclass Bitmapclass Viewclass Paintclass Bitmap.configconfigurations Pathclass - Bezier curves Wikipedia page - Canvas and Drawables - Graphics Architecture series of articles (advanced) - drawables - onDraw() - onSizeChanged() MotionEvent ViewConfiguration.get(context).scaledTouchSl components are required for working with a Canvas? Select all that apply. ▢ Bitmap ▢ Paint ▢ Path ▢ View Question 2 What does a call to invalidate() do (in general terms)? ▢ Invalidates and restarts your app. ▢ Erases the drawing from the bitmap. ▢ Indicates that the previous code should not be run. ▢ Tells the system that it has to redraw the screen. Question 3 What is the function of the Canvas, Bitmap, and Paint objects? ▢ 2D drawing surface, bitmap displayed on the screen, styling information for drawing. ▢ 3D drawing surface, bitmap for caching the path, styling information for drawing. ▢ 2D drawing surface, bitmap displayed on the screen, styling for the view. ▢ Cache for drawing information, bitmap to draw on, styling information for drawing. For links to other codelabs in this course, see the Advanced Android in Kotlin codelabs landing page.
https://developer.android.com/codelabs/advanced-android-kotlin-training-canvas?hl=Es-419
CC-MAIN-2021-31
refinedweb
3,090
58.38
UFDC Home | Help | RSS TABLE OF CONTENTS HIDE Front Cover Front Matter Preface Frontispiece Science in Biblical Expression... What is a lost soul? Sabbath Lights Could we have forseen Concentrating the Spiritual Abyssinia On the Individuality of the... "Professional" Prophets Fable On the Higher Education of American... Sadducees and the Boethusians God desires the Heart (Prayer) Note on the Tahkemoni as a source... Maimonides as Halakist "Quest of the Ages" Concerning Hygiene Which fruit did Eve give? And Abraham said : Divine exhortation Inviolability of personality "Dante and Religious Liberalis... Cleaning Place of Nashim is the Order of... Judaism and the Sacredness... Seat of the Poor Fascination of Folklore Philosophy of History Home-made Parable Molokans Congregational Singing in... Battle of "Jeremiah" Rabbah Gamaliel II Haggai Jeremiah Chapters 50-51 Jerusalem as seen by the Jewish... Menorial tribute Need of a Scientific approach to... Function of Theology in Spiritual... Sanctions in Judaism "What Next for Jews?" Prayer for the Sick Advertisement Published Sept 1859... Re-discovery of Faith We Are Our Brother's Keeper Jewish Education in Ashkenazic... Plan of the Holy Temple Psychology of Dealing with... "And They Went Both of Them... Psalms in Worship History of Anti-Semitism in... "I Am Not Worthy of the Least of... Conception of Prophecy and Prophets... "Enemy" in Psalms Introduction to Book of Zechar... Index of Authors and Titles Back Cover Group Title: The Kallah. Yearbook. Title: Yearbook CITATION THUMBNAILS PAGE IMAGE ZOOMABLE Full Citation STANDARD VIEW MARC VIEW Permanent Link: Material Information Title: Yearbook Physical Description: Serial Language: English Conference: Kallah Convention of Texas Rabbis Publisher: s.n. Place of Publication: Houston etc Frequency: annualregular Subjects Subject: Jews -- Texas ( lcsh ) Notes Dates or Sequential Designation: v.1- 1927/28- General Note: Publication suspended 1931/32-1934/35. Record Information Bibliographic ID: UF00072065 - 19115074 Table of Contents Front Cover Front Cover Front Matter Front Matter Preface Preface Frontispiece Frontispiece Science in Biblical Expressions Page 1 Page 2 Page 3 What is a lost soul? Page 4 Sabbath Lights Page 5 Page 6 Could we have forseen Page 7 Concentrating the Spiritual Page 8 Page 9 Abyssinia Page 10 Page 11 On the Individuality of the Prophets Page 12 "Professional" Prophets Page 13 Fable Page 14 On the Higher Education of American Jewish Youth Page 15 Sadducees and the Boethusians Page 16 God desires the Heart (Prayer) Page 17 Note on the Tahkemoni as a source for Maimonides Page 18 Page 19 Maimonides as Halakist Page 20 Page 21 Page 22 Page 23 Page 24 Page 25 "Quest of the Ages" Page 26 Concerning Hygiene Page 27 Which fruit did Eve give? Page 28 And Abraham said : Page 29 Divine exhortation Page 30 Page 31 Inviolability of personality Page 32 "Dante and Religious Liberalism" Page 33 Cleaning Page 34 Place of Nashim is the Order of the Mishnah Page 35 Page 36 Judaism and the Sacredness of Life Page 37 Page 38 Seat of the Poor Page 39 Page 40 Fascination of Folklore Page 41 Philosophy of History Page 42 Home-made Parable Page 43 Molokans Page 44 Congregational Singing in the Bible Page 45 Page 46 Page 47 Page 48 Battle of "Jeremiah" Page 49 Page 50 Page 51 Page 52 Rabbah Gamaliel II Page 53 Page 54 Page 55 Page 56 Page 57 Page 58 Page 59 Page 60 Haggai Page 61 Page 62 Page 63 Page 64 Page 65 Jeremiah Chapters 50-51 Page 66 Page 67 Page 68 Jerusalem as seen by the Jewish Travelers during the Crusades Page 69 Page 70 Page 71 Page 72 Page 73 Page 74 Page 75 Page 76 Page 77 Page 78 Page 79 Page 80 Page 81 Menorial tribute Page 82 Need of a Scientific approach to the Study of Religion Page 83 Page 84 Function of Theology in Spiritual Judaism Page 85 Sanctions in Judaism Page 86 "What Next for Jews?" Page 87 Prayer for the Sick Page 88 Advertisement Published Sept 1859 - Feb 1860 Page 89 Re-discovery of Faith Page 90 We Are Our Brother's Keeper Page 91 Jewish Education in Ashkenazic Lands from 1600 - 1800 Page 92 Page 93 Page 94 Page 95 Page 96 Plan of the Holy Temple Page 97 Page 98 Psychology of Dealing with People Page 99 "And They Went Both of Them Together" Page 100 Psalms in Worship Page 101 Page 102 Page 103 History of Anti-Semitism in Germany Page 104 Page 105 Page 106 Page 107 Page 108 Page 109 Page 110 Page 111 Page 112 "I Am Not Worthy of the Least of all the Mercies and All the Truth" Page 113 Conception of Prophecy and Prophets in Rabbinic Literature Page 114 Page 115 Page 116 Page 117 Page 118 Page 119 "Enemy" in Psalms Page 120 Introduction to Book of Zechariah Page 121 Page 122 Page 123 Page 124 Index of Authors and Titles Page 125 Back Cover Page 127 Full Text !wj 4 5 . . . . . 4 ;* '. - ~44 4- ,., -,lip$ TBTH ANNIVERSARY -uXA OF si~bKuASms L -. :A H A n\IA Ji\~ fj^Vw iTr Ij; /nn) WHAT THE KALLAH IS March 28, 1927, in Houston, the Kallah of Texas Rabbis was first assembled at the call of Dr. Abraham I. Schechter. It has continued a unique union of all the rabbis of the state for the sake of scholarship and the love of learning. The name of the Kallah, and its ultimate origin, comes from the semi-annual assemblies of Babylonian scholars during the early centuries of the Christian era. These sessions, before the Rosh Hashonah and the Passover holidays, were attended by thousands of devoted disciples. Out of those lectures and intellectual debates, eventually grew the Babylonian Talmud (com- pleted circa 500). Even thereafter, the annual sessions of the Kallah continued for many hundred years. The name Kallah is itself of great interest. The word is identical with the Hebrew word for "Bride", an allusion to the divine teachings of the Torah given to Israel as "Bride of God". By remaining faithful to the letter and spirit of this bethrothal document of Torah, the children of Israel continue to merit the appellation of Bride of God. Another explanation sees in the name an abbreviation, an acrostic on the letters K'neseth Lom'de Ha-Torah, "an assembly of students of Torah". This derivation accordingly traces the English word "college" and the Hebrew "Kallah" to a common root. Here in this great state of Texas, there are nearly forty accredited and ordained rabbis in Israel. None is a professor in any Jewish theological seminary, and therefore none claims to be a specialist in Jewish scholarly research. We might perhaps be if we were in position to devote all our time to academic pursuits. But we have other duties to perform. WVe rabbis of Texas, far removed from the centers of higher Jewish learning in America, must look for our scholarly authority to the pro- fessors at the Hebroe Union College, the Jo.iish Theological Seminary, the Jev- ish Institute of Religion, the Rabbi Isaac Elchanan Yeshiva, and thu Hebrew Theological College. We may not be remarkable for our scholarship, but we are for our devotion to scholarship. In the midst of rabbinical duties and communal cares, the rabbis of Texas insist upon making time for study and research for its own sako, and in coming together for the purpose of reading and discussing with one another the original results of our o;n precious moments of blissful study. And we are content to call ourselves, Kallah, a name which describes us simply as an "Assembly of Students of Torah." Meetings of the Kallah have been held annually: 1927 in Houston; 1928 in Beaumont; 1929 in Dallas; 1950 in Fort Worth; 1951 in Waco; 1952 in San Antonio; 1935 in Austin; 1954 in Galveston; 1935 in Beaumont; 1956 in Tyler. Presidents of the Kallah have been: Dr. Abraham I. Schechter; Dr. David Lofkowitz; Rabbi Samuel Rosinger; Rabbi Harry A. Merfeld; Rabbi Samuel Halevi Baron; Rabbi David B. Alpert. Samuel Halevi Baron PREFACE mat. Th sixth in the series of Kallah Yearbooks appears in modest for- "t-.-.. I That has some advantages; for it makes possible a wider distribu- tion and a larger number of articles. Because this Book marks the Tenth Anniversary of the Kallah, brief one-page articles were invited from non-Texas colleagues. The longer papers are abstracts of papers prepared for, and delivered to, the Kallah sessions. The entire volume shows the sources of Jewish thinking among con- temporaries. It is useful as model of the sort of anthology which should be gathered.at frequent intervals, and which should prove of cumulative value in the years. Devotion to Jewish sources of inspiration is the thread of unity among these articles. The publication and the distribution of this volume was made possible by the following friends, to whom it is now dedicated; as patrons of Jewish learning: Tyler Jewish Community; Sam Dorfman: Sabine Royalty Corp; Estate of K. Marmar; Eugene M. Solow; Dr. Edwin G. Faber; B'nai Brith of Pine Bluff; E-Tex Paper Co; Meyer Nathan; Mr. and Mrs. Abraham Alpert. ...,., ,' TYLER, TEXAS, MARCH 30.31, 1936 TENTH KALLAH OF TEXAS RABBIS AND WIVES .I A % i iFi^^- ii ' S.i&r'^TZ~ -Ra~~&i & J">^^ A SCIENCE IN BIBLICAL EXPRESSIONS: A PHAPRACOLOGICAL APPRECIATION OF ISAIAH LIX,5, G. Many a Biblical passage is a source of interest and delight to the God-fearing scientist who studies the Wonders of creation as revealed not only in the book of nature but also in His expressed word, the Book of of Books. To me, as a scientific investigator specializing in pharmacology and toxicology, the fifty-ninth chapter of Isaiah presents at least one such interesting passage in verses 5 and 6. Basilisk's eggs do they hatch, and spider's webs do they weave; he that eatcth of their eggs must die, and if one be crushed, a viper will break forth. Their webs cannot serve for garments, and they cannot clothe themselves with their works; their works are works of wickedness, and the deed of violence is in their hands. From the pharmacological point of view, snakes and spiders are a topic of timely interest because the venom of various serpents is now being used medicinally in treatment of certain diseases while the poison of several spiders, particularly that of the black widow, has caused a number of serious illnesses and even death within the past few years. The Hebrew word ziphoni,rendered "basilisk" in this passage, de- notes a "poisonous serpent." The Hebrew term, derived according to some from a root which means "to hide," alludes to the insidious nature of the viper, which attacks its victim unaware. The special interest attaching to this passage, how- ever, lies in the reference to the viper's eggs. "He that eateth of their eggs must die". This passage prompted me to make an inquiry concerning certain pro- perties of snake venom. In the first place, is the venom of a poisonous reptile toxic when taken by stomach? In the second place, are eggs of reptiles poisonous? Although I personally endeavored to obtain the material requisite for such tests, I was able to secure only the eggs of the black snake, which is not a poisonous reptile. These eggs, which I fed to white mice in my laboratory, apparently pro- duced no harm. The question arises, Are the eggs of poisonous snakes dangerous or not? Not all reptiles are viviparous or lay t -'; which are hatched outside the body. The chief representative of this class of poisonous reptiles in the United States is the deadly coral snake. The North American rattlesnake is viviparous and hatches its eggs within the body. Irrespective of whether they are hatched inside the body or out, Flexner and Noguchil have found that the ovaries or eggs of poisonous reptiles are only a little less poisonous than the toxin found in their poison glands. This information is a positive answer to the first of the queries raised above. Similar data have been published by the French investigator, Phisalix.2 Noguchi also discovered that considerable quantities of snake venom administered by stomach, are deleterious and may produce death, 3a finding which supplies the answer to our second query. It appears therefore that the prophet's description of the snake is literally, as well as scientifically, in perfect agree- ment with modern scientific facts. PHARMACOLOGICAL APPRECIATION OF ISAIAH LIX, 5, 6. Page #2 Spiders are mentioned three times in the Bible: first, in the passage from Isaiah quoted above; then in Job (VIII 14), "Whose trust will be cut off, ond but a spider's web is which he confideth." and, finally, in Proverbs (XXX. 28), "The spider thou canst catch with hands, and yet she is in the palaces of a king." In the old versions of the passage from Proverbs, in the Talmud and also in the Hebrew commentaries the word used for spider is semanith. Some modern scholars think that semamith denotes not a spider but a lizzard because a similar root in Arabic refers to a lizzard and because many varieties of this animal are to be found in the Holy Land. From the zoological point of view, however, such an interpretation is very unlikely because an ordinary blizzard is an animal that moves about with lightning like rapidity and can- not be easily grasped with the hands. Even the gecko, which some Biblical scholars- think that this word refers to, is a swiftly moving animal. I am therefore inclined to believe that spider was the meaning intended to be con- veyed by the Hebrew semamith. Spiders are not only reckoned among the most useful and wonder- ful insects but are also classed with these that are most poisonous.4 The lactrodectus mactans Fabricius, or black widow spider, of the United States is a formidable insect, the poison of which, according to D'Amour,5 is about half as potent as that of the rattlesnake. The tarantula, also a member of the spider family, is very dangerous to man and beast. Isaiah's metaphorical use of the spider to describe the ungodly and wicked is very apt. He admirably compares them to the venomous spider, which not only weaves a web with which to ensnare its victims but also injects a poison into their helpless bodies when they are caught. In his commentary on Isaiah, Julius Hirsch states that the word spider in this passage is derived from two words forming a quadrilli- teral noun; namely, akab and kabash, akab meaning "to ensnare" and kabash,"to overcome" or "'to destroy." The venomous spider literally first entraps its victims and then paralyzes and kills them with its deadly poison. So do the enemies of the Lord to those caught in their evil meshes and unable to resist them. On the other hand, semamith, the ubiquitous house-spider, belong- ing, as Rashi states in his commentary, to the group of Araninae (of which there are many varieties, such as the TheridiumEpira and Argiope), is quite harmless and generally regarded by entomologists as very useful because it destroys other insects known to be positively harmful. Such spiders may be found in any habitation, be it the hovel of the beggar or the palace of the king, and may be grasped with impunity as Solomon states in the Proverbs. We may therefore appropriately conclude this comment with a quotation from the Psalmist, "How manifold are Thy works 0 LORD! is wisdom hast Thou made them all: the earth is full of Thy riches..........living creatures both small and great!" PHARMACOLOGICAL APPRECIATION OF ISAIAH LIX, 5, 6, Page #3 Biblography 1. Flexner and Noguchi: Jour. of Path. and Bact., 1903, VIII, 379. 2. Phisalix: C. R. Soc. Biol., 1905, LVII, 15. 3. Noguchi: Snake Venoms; Carnegie Institution of Washington, 1909, page 220. 4. Metclaf and Flint: Fundamentals of Insect Life; McGraw-Hill Book Co., 1932, page 177. 5. D'Amour: Amer. Jour. Physiol., 1955, CXIII, 32. Baltimore David I. Macht, M. D. PSALMS 1. Immortality Happy is the man that walked in the counsel of courage, And sat in the seat of the wise, Whose delight was in beauty and service, And the truth did he meditate day and night, Whose life was a mission, not a career, And love was the measure of his ripening years He is like a tree, planted by streams of water, That bringeth forth its fruit in its season, And whose leaf doth not wither Even when swallowed by the darkness that covers the night. 2. Humanity Why do the nations rage, and tribes meditate vanity? Why do provincial kings bestir themselves, and petty rulers take counsel together? Let us break their chains asunder, and cast away their cords from us! He that dwelleth in heaven laugheth at them he that is eternal derideth them He speaketh unto them in scorn, nd. affrighteth them in indignation. As for me, I anointed my king on Zion, I proclaimed my ruler on the hill of holiness. Let me tell of the right divine: The Eternal said to me, "Thou art my sonl All nations will be thine inheritance, and the ends of the earth thy possession. Thou shalt break the bands of clannishness with an iron rod, thou shalt dash tyrants in pieces like a potter's vessel." Joseph L. Baron Milwaukee WHAT IS A LOST SOUL? "Vherefore the Lord said, "foreasmuch as this people draw near unto ME with their mouth, and with their lips they do honor Me, but his heart is far from ME---------"(Isaiah 29.15) Our life is a process of conversation between ourselves and the whole of the world in which we live. It is possible for human beings to talk to one another with their lips, and be remote from one another in their hearts. Falsehood and selfishness create chasms between man and man; and the professions of friendship have ~ 1::'y. to be tested by the inner facts of sincerity and love. These principles of human intercourse are also valid for this continuous conversation between the individual and his world. A man may be at odds with his world and he may be in harmony with his world; but there is everything in human experience to give us, as we look at the facts of nature and at the facts of history, a sense of loneliness in the presence of the great unknown. There it is, in its immensity, operating according to natural laws, opaque, silent, inscrutable, frequently cruel, and apparently uninterested in the lot of us poor human beings. Then, too, in that group which we call humanity there is some- thing massive, something imimonse, something in the pre-occupation of individuals and of social wholes, which makes the individual person feel that he is alone and uncared for, and that his only possible policy is one of struggling with might and main to gain for himself by snatching from the whole what he can. Now in so far as a person maintains this picture of the universe, he is a lost soul. He cannot look at the world with confidence. He cannot see beyond that horizon which closes his life in nothingness and means the ulti- mate wiping out of the race. He cannot see any meaning in his life beyond what he can enforce by dint of his own self-assertion. In so far as we feel in our- selves this absence of confidence, this absence of certainty, this fear of cala- mity and of death, this servitude to chance, this rebellion, this poor guesswork of questions thrown into tho void and receiving no answers, we are lost. The only thing which could come to us to make it possible for us to deal in honor and trust with the world, and with each other, is some assurance that these appearances are not true; some assurance that out of the silence there is a voice which speaks, and in the callous machinery of the cos- mos there is a heart which cares, and a purpose which plans. "The Universe speaks to me." "God speaks to me." The veil of reality has been broken, and we can say to the universe, not "IT is there", but "THOU ART THERE AND THOU CAREST FOR ME." William E. Hocking New Haven THE SABBATH LIGHTS Of the many services which hallow the Jewish home and convert it into a sanctuary, none is richer in touching beauty and tender sentiments than the lighting and blessing of the Sabbath Candles. The beauty of holiness of this home-rite has inspired poets to weave it into song, and moved painters to envisage it on the canvas. The lighting of the Sabbath Candles is a simple ceremony, yet is not simplicity the basis and the crown of beauty? Light, especially the soft, subdued light of candles, has a compelling charm and fascination. Unlike any other fire which suggests pain and injury, the lambant flame of the candle im- presses one as a beneficent force, dispelling the instinctive fear of darkness and filling the heart with cheer. The light of a candle is like the light of a star. It is a benign element which looks down upon us with the affection that radiates from a mother's eye when it lingers on her child. And if any candle-light brings to one's mind the sublime concepts of star and Mother, how much the more the Sabbath Candles, which are the veritable symbols of these two shining lights of God. Any Jew or Jewess who has not enshrined in his or her heart the angelic figure of a mother lighting and blessing the Sabbath Candles, lacks one of the sublimest scenes in life and one of the most inspiring impres- sions that motherly piety and sanctity leave upon the child mind and heart. The ceremony is of a very ancient origin. The earliest teachers of the Talmud speak of it as a general and well established custom. As to its meaning, light is a symbol of joy and cheer, and therefore a most befitting thing to welcome the Sabbath with. Light is also the symbol of the soul, and the Sabbath Candles exhort us in flaming speech to dedicate the day of rest to the cultivation of the soul life of man. As to the number of the candles, the general custom was to light two. The twin lights stand for the double joy of life with which the Sabbath fills the heart of Isroal. It is indicative of the double wel- come with which we greet the Queen of Sabbath. It is also a symbol of the two lives which man shares, this world and the future bliss. In some homes, however, a candle was lit for each child, a custom which brought home on the Sabbath Eve, in vivid memory, the children who had florn from the nest of the paternal roof, aye, even those whose souls took Tings to the Heavenly Abode. It is this senti- ment that inspired Grace Aguilar to indite the stanza. "Shine Sabbath Lamp, and may thy waves of light Bring near the absent dear ones, far away; Shii us our loved one. in our dream to-night, Our dead who rest in Heaven's bright Sabbath Day!" But what lends this ceremony chief significance and what clothes it with beauty and poetry is the performer, the mother, wife and queen of the Jewish home. She who was cormrisioned by theLoid to kindle the torch of life in this world, has also been chosen to illumine the home with divine light. She who makes of the Jewish home a heaven and a haven of rest, has befittingly been chosen to welcome the Day of Rest. She who brings blessing into the lives of mankind, well merits the distinction to bless the Sabbath Light. The Sabbath Lights are the guardian angels that weekly visit the Jewish home. Their shining presence lends a charm of beauty to the poorest hovel, and enhances the lustre of the richest hone. Their radiance lit up Mother's beauteous face, when with the self-consciousness of a bride, she blushingly blessed them for the first time in her new home. They wove a halo around the new life with which the home was made happy, later. When the Sabbath Lights transfigure the babe, "The Hoaven which lies about us in our infancy", is visible to the naked eye. The Sabbath Lights witness the growth of the chil- dren, and behold Father's hair turn grey, and Mother's comeliness change into a beauty of holiness. And when the infirmities of ago fill man's heart with longing for rest and peace, the Guardian Angels of the Sabbath Lights illumine his dark paths and show him the road leading to Heaven. To eliminate a ceremony of such supernal beauty and sublime mean- ing from the Jewish home, is like tearing a master piece from its frame on the wall, and throwing it in the trash pile. It is both n act of vandalism as well as of vulgarity. Our homes may be adorned with artistic tapestry, elegant furni- ture, rich drapery and other embellishments, yet all this aesthetic finery will not lend beauty to the home. The beauty of the homu lies in its spirit, in its atmosphere, in its culture, in its customs, institutions and traditions. And search over the wide world as you may, you will not find a more beautiful home service than the lighting of tho Sabbath Candles. May the Lord open the eyes of Jewish womanhood and unable her to discern and appreciate the beauty of thu heritage that has fallen to her. Then, indeed, the Sabbath Lights vill shed their celestial radiance in every Jewish home, and fill with chaste joy and cheer every Jewish heart. Samuel Rosinger ORGANIZED JEWISH LIFE The value of organized Jewish life becomes more and more apparent as we come fade to face with the tragedies that seem to overwhelm world Jewry. It is an inherent characteristic of the Jew that he was never hap- hazard. He held to the saying of the Fathers "who is wise, he who foresees the future", and having this in mind prepared for the days that were not yet. At this moment I am thinking of American Jewry and the ,wisdom of the pioneers in creating institutions that are of so incalculable a benefit long after the pioneers passed into the Great Beyond. You take HIAS, the Hebrew Sheltering and Immigrant Aid Society, for instance. It is the story which commenced in 1884 of a handful of immi- grant Jews anxious to make things a little easier for those who followed them into the new and unknown world. They, themselves, derived no benefit from the institution they called into being but hundreds of thousands of others, first in the United States and now throughout the world, have been the recipients of its services. And this is equally true of other institutions of all types which dot the American Jewish scene. One can never tell what emergency will arise. It was Russia fifty years ago. It is Germany today. It is, well, therefore, that our institutions continue to exist and that American Jewry realized their absolute need. We look forward to happier days and may they come speedily. Jewish history, however, is unfortunately a book of dark chapters. Hence the necessity of strengthening organized Jewish life and make it responsive to the calls that come to it. New York City, N. Y. ISAAC L. ASOFSKY "COULD WE HAVE FORSEEN" The coming of Jews to America covers four chapters'. The first tells of "pioneers," the second of "settlers," the third oi "immigrants" and the fourth of selected "invitees." The marks distinguishing each group from the others are clear and deep, but they are not primarily differences in the people themselves. It is true that the earliest influx was predominantly Spanish and Portuguese, and second German, the third Eastern European and the fourth cosmopolitan. It is true the conditions they left behind them and the reasons for leaving then show clear differences. Yet the determining force has been right here in America. Frontier conditions produced pioneers. The growing up of a country made settlers of its men. The crowded cities of the end of the last century greeted newcomers through such portals as slums, ghettos and sweat-shops, and made what we call immigrants of them. The individual had little choice. Planning his life and that of his children was not his privilege. The pioneer typically lost himself. The settler struggled to save the past by transplanting it to his new environment. The immigrant spent his force in the cruel all-absorbing process of readjustment. For the first time we have an opportunity and a clear duty to look ahead and to make plans for the kind of Jewish community we think desirable in America. You ask, "Is prophecy possible in these days?" It has always been difficult and dangerous. Yet I believe we can sketch some highly probable lines for a blue print of American Jewry of the next generation. For example: on the basis of experience we know the sequence of the problems which are an aftermath of immi- gration even to the third generation. With a little study we can trace the rise, he peak, and the decline of the first generation problems of maladjustment, poverty and a dependent old age; we can discern the course of the typical second generation problems; educational, domestic, psychological and religious; for the third generation there is the largely unsolved difficulty of finding itself. At least, so far as this one example is concerned, it is clear that we have no excuse for crystalizing our community institutions as they happened to be formed in the days of intensive immigration. Nathan Isaac Boston CONCENTRATING THE SPIRITUAL Convenience has become one requirement in civilized life that previous ages never knew or demanded. With the aid of scientific investigation we are in possession of 'compact equipment', 'compressed quantities', and 'con- centrated forms'. Increased experience allows for the displacement of primi- tive methods by more convenient means of attaining the same objectives. In the spiritual sphere of human requirements we trace a contrary development. Philosophical elaboration on spiritual needs appear at an advanced stage of civilization. They proceeded by emblems, symbolic acts, imperative epigrams, and proverbial wisdom. The fetish, the totem, the tribal rite, con- cise commandments, saying of sages are contemporaneous with the most elementary acquisitions of civilization. The infantile human mind found abbreviated forms of thought more essential than convenient methods of providing for physical necessities. Centuries later. Man matures. His mind develops. Religion, philosophy, art, government, even become subject to controversial speculation. During lucid moments of leisurely contemplation he may articulate his intel- lectual and spiritual creations. He becomes expert in elaborating and record- ing systems of thought leading to the 'summum bonum' in life. Other indivi- duals may inspect them, criticize them, improve upon them, demolish then, or adopt them. But the need for a quintessence of spiritual persuasion has not been obviated even by the refined mind. Perhaps because of the complex and diversified life with which the blessings of civilization have endowed us, the spiritual in essense has become more than even a human necessity. Man's personality became an arena where two opposing trends are at combat. The syubolization of beliefs, opinions, ideals, by means of a flag, a slogan, a ritual degenerates into formalisms, empty phrases, meaning- less acts, ends in th selves. Representations of the sublime become petri- fied devoid of spiritual breath. Our Prophets were touched by the problem. Their utterances on the subject soar to the height of hyperbole. "Wherefore are the multitude of your sacrifices!" Too often has it been imputed to them that they urged the abolition of sacrifices. From a historical prospective such advance over their own age is utterly improbable. They decried the act of sacrifice with- out its spiritual counterpart. Yon Kippur presents a most pertinent instance of coordination between the most elusive, spiritual human attribute and conventionality in ritual. Man reunited with the source of All Spirit! The soul barod of callous layers that imprison its iridescence. Its brilliance replenished and its radiation restored. One day in the year man becomes thoroughly pervaded with human-ness. Godliness is roadmited into his boing. In the course of purification intellectual prowess plays a promi- nent part, yet not in its sublime, ephemeral, spiritual form alone. A house of worship, a prayerbook, a day of fasting are indcsponsable stimuli that urge and aid man to ascend the Mountain of the Lord. In Rabbinic lore we find a realistic solution to the philo- sophical speculation on the spiritual essence and its symbolic ritual. Here as in many another intricate problem the Rabbis succeeded in suggesting a possible compromise between irreconcilable thoughts by conceding a measure of reality to each. Expressed in their quaint idiom, it nevertheless conveys a fundamentally psychological analysis of our question. Homer besoir she'en beyom hakipurim, vehomer beyom hakipurim she'en baso'ir. (Tos.Yoma 4ernd)h a sense the atonining power of the Yom Kippur institution surpasses the ritual of the Scapegoat, and in another sense the latter convention is superior to the very idea of a Yom Kippur day. One may ac- quire atonement on Yom Kippur without the Scapegoat ritual and not vice versa. Yet the ceremony has its immediate effect on the participants; while the effi- caciousness of Yom Kippur as a day of atonement is attained only when the day has merged into darkness. Cryptic though this passage sounds, it nevertheless conveys a basic thought. A symbol or traditional ritual has value by its ability to evoke a response without the intricacies of the rather specialized mental pro- cess. It may degenerate into mere formalism and lose its justification, but the ideal that it represents remains unsullied. At the same time we cannot avoid observing that an ideal in the abstract must go through a painfully long metamorphosis before it is fructified by emotional zeal and applied practically. The idea and its symbolic embodiment are both spiritual realities. In spite of dangers and shortcomings, concentrated spirituality will continue motivating human lives. Houston Sanders A. Tofield PRAYER PSAL Athwart the tides of life's doep streams, Make mo, 0 Lord, a spark, A torch of hope for faltering dreams, A taper in the dark. A taper burning through the night For hearts that need a staff, A lamp of faith, a guiding light, To save hope's grain from chaff. Athwart man's sorrow-laden days, Make me, O Lord, a rod, To lead him through misfortune's maze To altar stjps of God. A rod to rouse his drooping soul, Scorched by the firs of pain, TTo seek again the higher goal That lies in Truth's domain. *Lot others, Lord, petition Thee For riches of the sod; Not I, 0 Lord; just lot me be A spark, a staff, a rod. Alexander Alan Steinbach Brooklyn, N. Y. #10 ABYSSINIA Ethiopia's dispute with Italy is very much to the fore. We cannot help admiring the unflinching courage which these valiant sons of the East in- variably display, and are led to esquire from which race do they spring? Are they of Semitic or Hamitic origin? This question is not very easy to solve. Under the name of Gush, we have a very early mention of Ethiopia (which included Nubia and the greater portion of Abyssinia) in Genesis 11, 15. Gush is in this passage quoted as one of the sons of Ham; together with Phut (Lybia) Mizraim (Egypt), and Canaan. It occurs again in Job xxviii, 19: Habakkuk iii, 7; 2 King xix, 9;Psalm Ixviii. 31; Isaiah xx.4, and in several other passages. In all these instances the Hamitic origin of Gush appears clear. By the Greeks the Cushite was called Aithiops burnt face, which corresponds to our negro- black. Likewise the huge monuments whose ruins may still be found in Abyssiania point more to a Hamitic than Semitic origin of the race, since, in no case have the Semites proved themselves great builders and architects. Their legal code and social institutions are also foreign to the Semitic spirit, being barbarous and bloodthirsty. On the other hand their language is an important Semitic dialect. I am referring to the Geez or Ethiopic which is still used in their official documents. But which ceased to be the spoken language at the end of the 15th century, although it remained the polite and official language. Towards 1,500 the Zageen family, an Auxumite dynasty, was replaced by another which came from Sewa where they spoke Amharic which became the court language and gradually ousted Geez. During the last few centuries Arabic has gained an important footing in Abyssinia, becoming the language of commerce and of foreign diplomacy, so that the official docu- ments in Geez are usually accompained by Arabic translations. At the present day, with a knowledge of Amharic, travellers can make themselves understood in all parts of Abyssinia; but there are at least a dozen other dialects spoken, most of which contain Semitic elements with a barbarous admixture of non- Semitic language. To address the Abyssinian tribes in their own dialects the traveller must indeed be a polyglot, since the languages vary from tribe to tribe and almost from village to village. But who are the Abyssinians? The discovery of the Himyaritic inscriptions proves the undoubted fact that we must look for the Origin of Geez in South Arabia, and in Geez we have the living remains of the old language which was spoken in Yemen. Abyssinia is inseparable from South Arabia in language and ethnography and we have only a glance at the map to observe that this is perfectly natural just as South Spain is influenced by Morocco and has been governed by a Moorish dynasty. Their language presents many variations from the remaining Se- mitic languages (Hebrew, Aramaic, and Arabic). The alphabet differs in the number, order, value, name, and form of the letters, in being written from left to right although Himyaritic reads from right to left-and in the vowel-signs being expressed neither by detached signs nor by vowel letters, but by appendages altering the shape of the consonants and thus rendering the alphabet more a syllabary of two hundred and two signs than a simple list of consonants, although the introduction of this complicated system of express- ing the vowels may be of comparatively modern origin, derived either from India or indigenous to Abyssinia. The Ethiopic literature though consisting of over two hundred works is strikingly unoriginal. It consists almost en- tirely of translations of tno Bible in the fourth century for which they seem to have used the Septuagint version, and also their Christianity points back to the Patriarchate of Alexandria. In the following centuries many translations from the Apocryphal books were made those of the apocalyptic books of Enoch and Jubilees being best known. The remainder of their literary work consists entirely of translations from the Greek, Arabic, and Coptic languages. The language in which this literature is preserved presents many Arabic character- istics, especially, in its grammatical forms, but the few traces of its poetry which are extant strongly remind us by their rhythm of the Mashal of Classical Hebrew; the frequent use of abstracts on the other hand recalls the later Rabbinic Hebrew and Aramaic. The number of Greek words in Geez proves the important role which the Byzantine Church played in Christian Abyssinia, and hence it is a polite and not a popular tongue. As we have pointed out above the present spoken language of Abyssinia is the Amharic, which presents many Geez characteristics in dictionary and grammar but also many non-Semitic elements, notably a barbarous pronunciation. It is probably an ancient, vulgar idiom not dervied from Geez but parallel with it. The subject will well repay painstaking study for its concerns a nation which was in a comparatively high state of civilization whilst the Britons were still painting their bodies blue. Houston Henry Barnston IS PERETZ WORTH IT? A Jewish scientist on seeing the page proofs of my latest volume Peretz, Psychologist of Literature and noting that the book runs into nearly 500 pages surprisingly asked "Is Peretz worth it?" It is a question that many Jews will ask who have heard about Peretz, the most expected question being, of course, "Who was Peretz, anyway?" And I have even had people asking "Is that the man who wrote a huge work on sociology?" (confusing Peretz with Pareto). What sort of people are we, ironically enough called "The People of the Book", if the name of our greatest modern writer means nothing to the vast majority? Is a thing of this sort thinkable of any other civilized nationality? Peretz's twentieth death anniversary was commemorated in all parts of the world by the ubiquitous Yiddish-speaking Jews, but the Engliah-speaking Jews in the land of educational opportunities still wonder whether Peretz is a writer or the name of a colony, and the comparative few who have heard of this versatile genius, who enriched the Hebrew as well as the Yiddish literature, know only his "Bontzye Shveig" and one or two other of his tales. They feed on mediocre stories in the magazines and ignore the "acres of diamonds" in their own fields. What a perversity runs through our spiritual fabric? Is it not high time that at least our communal leaders learnt something about this towering personality, even if he did not have the salesmanship of turn- ing his genius to account by making arrangements with American, British or German publishers to bring out translations of his works, A People this is acquainted with the exploits of its great scarcely deserves to possess any great figures. Cambridge A. A. Roback #12 ON THE INDIVIDUALITY OF THE PROPHETS Nothing is more untrue than the assertion that the great literary prophets were all alike. They were far nore differentiated, more salient as in- dividuals, each with his own character and reaction to the times in which he lived, than are their modern Rabbinical disciples. They differed in social origins, in outlook, in artistic power. True enough, they were the products of a unified and living tradition; they all worked within a certain complex of social ideas, in the same society. But no one of them -- the great literary prophets, not the in- significant cud-chewers of priestly cant -- was merely a breath of a Zeitgeist, or a prop of institutionalism. They were not moulded by their environment. They moulded the environment of others. They were, each in his time, members of a guild of artists who worked toward the same general goal and in the same creative milieu; but each was, in his own right, a creator and a moulder of ideas and goals of endeavor. The function of the prophets as artists, conscious literary artists, has not been sufficiently emphasized. It is said that Amos was a herd- man, and presumably not socially prominent in the fashionable world of his time; as a plebeian, he would not have been part of the polite world of scholars and of such belles-lettres as existed then; but all the same he was a gifted literary artist. Like Burns, he expressed in adequate, telling language his stinging rebuke--the rebuke of one wedded to the common people, their homely joys and honest toil--to the uncoo guid" of his time. His voice still persuasively rings in our ears, if we listen to it, telling us that "a man's a man for a' that", and a social poison or a moral disease is just as dangerous in the country-seats and palaces of ivory of rich landowners as it might be if found in the hovels of the poor. He was the first "citizen of the world", anticipating Geothe. Boundary lines meant nothing to the artist whose message had the universality of all true creative poetry, music or painting. His imagery is rich and varied; his pictures of the horrors of war, for instance, outrival anything in "All Quiet on the Western Front". The bones of the dead king of Edom burnt in lime, the ploughing up of cities, the ripping up of pregnant women, the selling into slavery of "cities-full" of captives; all these incidents of warfare, war upon the helpless - upon women and unborn babies and even upon corpses, are vividly portrayed. Con- cisely, in a few words, this great ancient poet brings into the minds of his readers all the fantastic devices of man preying on man, pictures prepared ages later by a modern Hebrew poet, Bialik, in his "al ha-Shechitah". The prophets, with Amos at their head, consciously labored to change the thought-world of those who would heed them. They conceived their work in the broadest terms. They were to be creators of the group ethos, of the vital myth. They were to do more than portray life; they were to endeavor to change it. With the impulsion that comes to every great artistic spirit, they desired so to fuse the experiences of the past and present of their own people and of the nations around then into works of true art, that the product of their genius might function as reagent, or at least as catalyst of social change. But with it all, how human they were! How bitterly scornful of the rotting rich! How lovingly breeding over Jerusalem, city of a dream, even when that city denied and scorned them! "Ariel, Ariel", cries Isaiah, in a burst of poetry, "City where David dwelt." Each prophet deserves extended study as an artist in words and images and a moulder of ideas. Wilmington, N. C. Benjamin Kelson #13 "PROFESSIONAL" PROPHETS Amos. 7. 10-17, the earliest autobiographical note written by one of our prophets and preserved in the Bible, draws a distinction between "prophets" on the one hand; and on the other, the writer. Amos, himself the type of man whom (despite his own denial) we are wont to regard as above all a "prophet." We solve the apparent difficulty by calling him a "literary" prophet and them "professional" prophets; and, adopting his attitude, we be- little the latter. But one thing is notable in this situation: Amos finds it necessary to deny that he is one of the class he deprecates. He knows himself to be enough like them that only his vehement denial can prevent his being classified as one of them. Amaziah has, in fact, called him a "seer", which neither for Amos nor for his hearers meant anything other than "prophet". Now, if the noble message of Amos could so easily be mistaken for that of a "professional" prophet, we are constrained to adopt an attitude somewhat more favorable than that which prevails, towards this popular class of godly men. Though there can be no doubt that many rungs in the ladder of the spirit di- vided him from them, and that Amos was proudly conscious of his advantage, yet were his predecessors and contemporaries among those who for pay announced the Word, not smooth-tongued assentators, nor wholly devoid of Divine ardor. Cincinnatti Sheldon H. Blank AESTHETICS AND THE GOD-CONCEPT According to an oft-quoted dichotomy the Jews made rightenous- ness focal in their view of the universe while the Greeks stressed the principle of order. The latter principle implies regulated sequence, natural law, balance, symmetry, harmony of the spheres and all that goes with a cosmos in contra- distinction to chaos. To view the world as a cosmos requires a measure of detachment and intellectual appreciation. Even more it requires aesthetic appreciation; hence the Greek emphasis on beauty: beauty in philosophic order as well as beauty in music and sculpture and literature. Is this general appre- ciation alien to the ancient Hebraic cosmic orientation? Does the dichotomy in terms of ethics as the Jewish contribution and aesthetics as the Greek con- tribution to civilization really hold? Like many other glib generalizations this one may also be a con- venient fiction. That Greek philosphers were not unmindful of ethical problems is too patent to require elaboration. But what about Jewish sensitivity to cosmic beauty? Is not the opening verse of the 19th Psalm indicative of a mind which envisaged God as more than an agency imploring man to be loyal to re- vealed codes? Much more specific in its delineation of this Hebraic sensitivity to the aesthetic component in the developed God-concept is the last verse of the 90th Psalm: "And may the beauty of the Lord our God be upon us". The con- text in which this verso occurs demonstrates quite clearly that the thought of beauty as related to God was an outgrowth of a primitive cosmic attitude--a foreshadowing, as it were, of that which is customarily regarded as a distinct- ively Greek contribution. In other words the ancient Hebrew concept of God :an not restricted to His ethical attributes, to the view of God as a God of Right- eousness or of Vengeance or of Love, but also took cognizance of aesthetic factor implicit in that concept when it transcends tribal restrictions. David Ballin Klein Austin #14 A FABLE "And let them make Me a Sanctuary that I may dwell among THEM." (Exodus 25.8) They were building an imposing structure. The edifice, for which the architect drew the plans, was to be an House of God. Skilled workmen, masons and carpenters, were busily engaged at their work. And when it was finished, ready to be dedicated for its noble purposes, all that had a share in its building came to the Lord, claiming the credit for it, demand- ing to be rewarded. Said the architect: "I drew the plans. Without these they could not have raised the building. To me, therefore, belongs the credit, and I expect the full reward." "What?" said the laborers, "without us, carpenters, masons and brick-layers, and plasterers, your plans would be nothing but a piece of paper. We claim credit for the building. Roeard belongs to us; with- out the skill of our hands there would b. no building." Now the 'foundation' spoke up: "I carry the building. Without foundation the structure would fall like cards before wind and storm." But said the walls: "What is the foundation good for if there are no walls? The four walls are virtually the 'building'. We there- fore, claim full credit for it. We demand to be rewarded." "How long could walls last without a roof? It's the roof that protects the building against rain and storm. Credit for the edi- fice belongs to the roof. I demand, therefore, the reward." "How silly you are, all of you", said the brick and the timber, the stones and the cement; You could not make walls, foundation or a roof, without the building material, could you? No! The credit for the House of God it is evident, belong to us, Therefore, we demand the entire reward." The Lord listened patiently to the insistent claims, and said He, smilingly: "You are rather conceited, all of you, my children. The House that you may build for Me? All these things My hands have made, and so all things came to be from me, timber, iron and steel, for I have created the All. How then can you claim credit? Moreover, "continued He, -neither bricks nor masonry, neither beams nor rafters make this building to be a "HOUSE OF GOD" any more than any other building. It is man, the people, that enter these gates with thanks- giving and sing praises to My name, the men and the women, they are the ones that make this house, any house, a House of God. To man alone belongs credit." Julius Rappaport Kenosha, Wis. #15 ON THE HIGHER EDUCATION OF AMiERICAN JEWISH YOUTH One of the most important tasks which Jewish teachers and rabbis can perform is to ensure the education of young people of college age in the history, literature and institutions of our people. Ve publicly express our pride in the cultural achievements of the Jews but we do very little to give our college students more than a vague idea of what these are. These young people would be ashamed to confess ignorance of the works of Homer, Plato, Dante and Goethe or of the groat events and social move- ments, let us say, of European history, but too many of them arc quite unabash- ed, perhaps even a little superior, in confessing ignorance of the works of Maimonides and Jehudah ha-Lovi, of the history of the synagogue, of the part played by Jews in the development of European science and commerce, in explor- ation and trade. Such knowledge, even a modest sum of it, can not be obtained mcruly by reading the few. available English translatijns of Hebrew classics or the brief general histories of the Jews rucommanded by hopeful rabbis and elders. It can only be obtained by having instruction given them in cAlleges and uni- versities where there is adequate provision for research and proper guidance furnished by trained teachers whD can be expected to keep their methods and re- quirements up to the standard of collegiate instruction. In a word, we need the endowment of more chairs of Jewish history and literature at large universities and of more Hillel Foundations at institut- ions where such chairs cannot be established. If the rabbis of Texas can under- take to interest the Jews of that state in so worthy a cause, they will not only make it possible for seminaries to prepare future rabbis more adequately, but they will be doing a groat and vital service to future generations of American Jews. Now York City Ralph Marcus God of our fathers, Blessed for aye, See'st thou the evil of our -.ay; Look down upon us, Weak and oppressed, Stricken, forsaken, sore distressed. Thou wilt be to us the cloud by day, Thou wilt be to us the fire by night. Lo, to the tabernacle of thy presence, Thou wilt lead us in thy might. God of our fathers, Thou who rul'st above, Save us, restore us, in thy love. Lead us in thy paths Of peace and right; Make us unblemished in thy sight. O thou God of truth and righteousness, Thou who scck'st to gird and guard and guide, Make us to know thee, trust thee, and serve thee, That with thee we may abide. *John Ha. es Holmes (ins-ired by Hatikvah) and set to its music) #16 THE SADDUCEES AND THE BOETHUSIANS The origin and causes of the Sadducean schism are matters of controversy among scholars, many of whom derive the name from "descendants of Zadok." The sect consisted of members of the priestly family who traced their descent to Zadok, High Priest in the time of David. According to the Talmud (Kiddushin 66a) and Josephus (Ant. XLLI.10) the sect began in the reign of John Hyrcanus who made common cause with the Sadducees. At the beginning of the second Temple, authority--ecclesia- tical, judicial, and some political--was vested in the High Priest of the Zadokite line. In Ezekiel's programme (Ez. 44.15ff), the Zadokites were the. rightful ..expounders of the Law. The increasing laxity and corruption in priestly ranks, aided by the degradation of the High Priesthood after Simon the Just when the office was usurped by Jason, made the scribes transfer religious authority to the newly-created "Nasi". This curtailed the prerogatives of the Zadokite family, especially of the High Priest. Such measures aroused the antagonism of the hitherto favored group. They frowned upon a Sanhedrin lacking a high priest as its head, and composed of laymen. The sadducees became bitter opponents of the scribes for introducing changes in the sanhedrin and disregarded the ordinances of the elders (Oral Law and Rabbinical Takanot). They clIng to the letter of scripture (Ant. XIII.10) for support of the exclusive rights of the priests and the legitimacy of the Zadokite family. When the Zadokite family was divested of its dignity, their opposition grew stronger particularly when the High Priesthood was conferred on the Hasmoneans. John Hyrcanus was originally a Pharisee, since the Sadducees disclaimed his right to that office. But when the sages raised question about his legitimacy, he was forced into the ranks of Sadducees. The Boethusians (related to the powerful priestly family of Boethus, Pesahim 57a) are of late origin. They are mentioned in Talmud (R. H. 22; Men. 65) in connection with the date of Shabuoth which they contended should come on Sunday. The Sadducees, it seemed, never raised that question: Shabuoth was always the 50th day from the second day of Passover. Josephus, Philo, and all Targumim (including the Syriac) are unanimous in translating the "morrow of the Sabbath" as the "morrow of the holiday". The insistence of the Beothusians upon a different date for Pentecost was due, I believe, to their jealousy of the true Nasi and his privi- leges in fixing the calendar. (San. lla). The high priest with his colleagues had that privilege in former days (Ezek. 44.27). After the destruction of the Temple and the abolishment of the High Priesthood, the priests lost all power in that matter and this greatly embittered the Boothusians. Plainfield, New Jersey Chaim Kaplan GOD DESIRES THE HEART (PRAYER) Kavvanah is a Hebrew term found frequently in Chasidic literature. It is difficult to convey in concise English the full equivalent of that expressive word. "Sincerity" or "direction of the heart" approximates the idea in some measure. A certain story told by Chasidim (reproduced in Hebrew in Kahana's Sefer ha-Chasiduth) perhaps best illustrates its meaning. There was a certain villager who used to come into torm for the high holidays to worship in the Synagogue of Israel Baal Shem, founder of Chasidism. He had a feebleminded son incapable of reading a mwrd of the Machzor, the book of holiday prayer. Not until the boy had attained Bar Mitzvah age did his father bring him along, and then only for Yom Kippur, in order to make sure that he should not unwittingly touch food on this solemn fast-day. Unobserved, the lad had hidden in his pocket a rude reed-pipe with which he used to while away the tranquil hours as he tended his father's flock. And so he sat in the Synagogue, unable to mumble a single word with the worshiping congregation. In the midst of the Mussaf prayers he burst out, "Father, I have my reed-pipe with me and I want to play on it." The father was shocked; and in threatening tones he replied, "Take care that you don't do--God forbid!---anything of the kind!" So the lad was forced to desist. During the Minchah service again he pleaded, "Father, let me play my shepherd pipe." Once more he was soundly berated and warned not to dare do such a thing. The afternoon service over, he renewed with growing intensity his demand. Seeing how overpowering was now this surging im- pulse to play, his father seized hold of the pocket on the boy's blouse to pre- vent him from pulling the instrument out. But in the middle of Ne'ilah,the con- cluding service, the poor lad could no longer restrain himself; and, mustering up what was for him an almost superhuman strength, he tore the pocket open, wrested from his father's hand the rustic flute, and putting it to his lips he gave out one long, loud note. The multitude was token aback and gasped at this desecration of the solemn Day of Atonement. Imagine, too, the mingled feelings of maddening shame and indignation that for a moment made everything grow black before his father's eyes. In the ominous hush that ensued, the Baal Shem Toy was observed cutting short his chanted prayers and saying: "This ignorant, half- witted shepherd-lad, by serving God in the only way ho know, has wrought far more than all our prayers and praises. That impassioned, plaintive note he sound- ed on his lowly reed-pipe, coming from the depths of his simple heart, has gone straight to God Himself. For after all, Rachmana libba ba'e, 'God desires the heart.'" SAMUEL HALEVI BARON Leavenworth, Kansas A NOTE ON THE TAHKEMONI AS A SOURCE FOR MAIMONIDES The recent eight-hundreth anniversary of the birth of Moses Maimonides celebrated throughout the civilized world adds intere to every item touching this immortal Jewish philosopher and his family. The limits imposed do not permit complete discussion of the! importance of the Tahkemoni of Judah Al-Harizi as a source fcr the attitude df Jewish contemporaries toward Moses Maimonides and his brilliant son, Abraham? I present here an important passage from the forty-sixth Ma~ama of the Tahkemoni and also a short'poem from the fiftieth Makama composed by/Al-Harizi in praise. of the Sefer Ha-mada, the justly famed opening section oP the great Code, the Mishneh-Torah. Judah Al-Harizi, distinguished Jwish poet, translator and satirist, lived during the last half of the twelfth century and the first quarter of the thirteenth. He was therefore a;younger contemporary of Moses Maimonides. Like the groat philosopher and codifier, he claimed Spain as his birthplace and was proud that he was a "Sefardi". In his masterpiece, the Tahkemoni, Al-Harizi gives us a vivid and unforgettable account of his far and fruitful vagabondage. Al-Harizi's wanderings bxig-' him to Cairo, Egypt where he met the young and accomplished son of Mos-o Maimonides, Abraham. This talented son was born in 1186 and died inl7>--i the year 1205, after his father's death, Abraham succeeded him g-' Nagid although he was then only nineteen years of age. Al-Harizil extolls Abraham Maimonides first and then passes on to high and sincere praise of his immortal father: Ex. 10:23 Amos. 8:12 Of. Gen. 47:12 Ps. 107:5 Ex. 2:17 Ex. 16:35 "Though young in years," he writes of Abraham Maimonides," He is great in attainments, Though a youth as far as days are concerned, he makes scholars look foolish. His father lifted up his light to those that wander in their thick darkness. He was a light for all the children of Israel in their habitations. For he saw that their multitude were athirst for the waters of the Torah. They wandered about seeking the word of God but they did not find it. There was no food for the little children. Hungry and thirsty, their soul fainted within them. And when he saw that Destiny had humbled their souls, Moses (Maimoni- des) arose and helped them. "He shook the whole Talmud as flour in a sieve and ex- tracted from it the pure, sifted fine flour. He pre- pared an arranged dish2 with all sweets and richness for those w.ho are preoccupied with the affairs of the world. And the children of Israel ate the Manna for which h they had not labored so that they should not stray in its path. For he removed from the Mishneh-Torah4 the names of the interpreters, the interpretations and sermons, the Hagga- doth and tho Novellae by uhlich one's thoughts are confused, thus rendering the whole Talmud into a raised path. He proclaimed through all the Diaspora: "Come into its gates (ofTalmud) with thanksgiving - Into its courts with praises," "Now it came about after the death of Moses (Maimonides) that every arrogant and harsh person took counsel, every simpleton gaped his mouth,-from Spain, France, Palestine and Babylon. They planned to assail the Mishneh-Torah with empty words but their arguments were thin and blanted. They broke the fence that the upright had built like little foxes that spoil the vineyard. But if they had spoken be- Of. Ps. 97:5 fore him, they would have melted like wax before the fire of his wrath. They would have fled from before him like Of. Ex. 15:10 lambs from lions or sparrows from eagles. They would have sunk like load in his mighty waters." Of the other references to Maimonides in the Tahkemoni, I give in conclusion a poem by Al-Harizi in praise of the Sefer He-mada: "I composed this," says Al-Harizi,7 about the Sefer Ha-mada when it was circulated and became known in Spain: "Oh Book! How like a tree, planted by streams of lore, From which each one desiring may pluc.k of wisdom's fruit; Though the books of our great scholars were to multiply still more, They would 6nly be the branches but it vould be the root!" ------ # ------# ------ # .----- (2) i.e. The Mishneh-Torah (5) i.e. The labyrinth of the Talmud fine metaphor. Of Yellin and Abrahams Maimonides U. P. S. 1903-p. 121 for com- parison by Greatz, (4) So is meant by Hibbur. (5) The Mishneh-Torah was severely criticized by many, the RaBaD, and others of J. E. IX-p. 85 article on Maimonides as Halakist by Dr. J. Z. Lauterbach (6) Seo The Tahkemoni Lagardo Edition, Mhk. 50:102 p. 196-7. (7) See Variant text Melochet Ha-Shir, A. Ncubauer-Frankfurt an Main 1865-p.51. Cincinnatti Victor E. Reichert THE MEANING OF A PARABLE In Berakoth 58b, we find the proverb "Let it suffice a servant to be as his master", i.e., let the servant be content to bear the misfortunes which his master also suffers. The sane proverb is found in Midrash Tanhuma (ed. Buber) on Genesis 17.2 with another meaning: "Lot the servant be content, if he enjoys privileges, equal to those of his master." A similar contract may be noted in the New Testament between Matthew 10.25 and Luke 6.40 where this proverb also occurs. (In Matthew, "It is enough for the disciple that he be as his master, and the servant as his Lord." In Luke, "The disciple is not above his master; but every one that is perfect shall be as his master.") Jewish Institute of Religion. Harry S. Lewis #20 MAIMONIDES AS HALAKIST In order to get an idea about Maimonides as a Halakist and his historical contribution in this field, and in order to appreciate the epoch- making value of his Mishneh-Torah it is necessary to acquaint ourselves with the general condition of Halakic literature previous to 1imoinides. Maimonides had at his disposal the Talmud, consisting of Mishnah, Tosepftah, Braitot and the so called Halakic Midrashim, as the Mechilta, Sifra, and Sifreh and the Jerusalem and Babylonian Gemara, in addition to the Gaonic literature consisting of various collections of Poskim, Responsa and commentaries on the Talmud. Among these codes ranks first a compilation by Rabbi Isaac Alphasi, (who owes this name to his native city, Alphas). All these conglomerations of laws, ideas, pilpuls, personal opinions, legends, sages and folks-tales lacked every kind of system and order, to say nothing of a legal-logical arrangement. The Mishneh claims for itself the rank of a code i. e. a. fixed system of laws and decisions for judges and laymen. Its form bears more resem- blance to a collection of differing opinions, views and discussions, usually without definite legal decisions. Tts characteristic form is like this and like this: "the words of Rabbi Meir", says Rabbi Meir; Rabbi Judah is of a different opinion; and the "sages" have still different views. Not unfrequently we find contradictions in one Mishnah itself. The Gemarah which really aims a harmonizing the conflicts of the Halakah by bas- ing its decision on the Mishnah does so in a number of instances; but, in general, it has complicated the Halakah by sanctioning the old Braitoth which were omitted by the Mishnah, and thus the latter was frequently completely divested of its authority of being the last word in the Halachic decision. Besides, the Amoriam, (i. e. the sages of the Gemarah) have sometimes completely reinterpreted the Mishnah and the Braitoth, correcting and changing from "not guilty" to "guilty" and from "kosher" to "treyfe" adding a multitude of new laws, amendments and decisions, as well as, paragraphs, opinions and pilpulim which even the greatest Talmud scholar finds difficult to separate and distinguish from the essence of the Halakah and its prupoce. Moreover, there is also added the legendary part of the Gemarah, interspersed with Halakah from which it is inseparable, since in the last analysis it is very difficult to decide what is Halakah and what Agadah. The Gaonim, the directors of the Academies in Babylonia and in Palestine of the post Talmudic period were great Talmudical scholars who mastered the secular knowledge of their times, as philosophy, astronomy, medi- cine, etc., and were very much concerned about the codification of the Talmud. They wished to collect the practical material of the Halakah which regulates Jewish religious and social life. The Gaonim, and the Reshe Galuta were politically independent in enforcing Jewish law in practical life. The Gaonim deserve credit for having reconciled the contradic- tions between the opinions of the Tanaim and Amoraim, and the many other talmudi- cal sources. In numerous instances they established the final legal decision. With regard to the inner organization of the Halakah they did not change much. Even-Alphasi, who lived after them, in utilizing their results outlined the Talmud by summarizing its Halakic content, was unable to c: 7.. its ori.i,,-'l form. The order (or, really its disorder) for its form of reasoning remained the nsme. #21 To better understand the difficulty of codifying the Halakah it is sufficient to state that if one wants to decide any case it is necessary to survey the entire talmudical literature from its beginning to its completion. For, although the Talmud is divided into various sections this division is, as a rule, not consistently followed. Even the Mishnah itself is not consistent in the distribution of its legal material. Half of the Masechta Ketubos, for example, which should deal with matters of family law, contains general civil law. Who would think to look for the law concerning the leper or the high priest in the tractate Megilah? or the laws regarding the slave in the tractate Kidushin, or the law applying to the murderer in the tractate Shevuoth, which deals with the Shmitah regulations? But how did this inconsistent arrangement of the laws come about? Probably because in the Mishnah assod.ations of form, style and name rank equally with those of ideas. Since the scholars had to teach everything by heart, they tried various methods of mnemo-technique in order to facilitate the handling over and the preservation of the Halachic formulas. For example, in the above mentioned case of Megilah, the Mishnah brings the legal decision in the formula of: en ben namely, what is the difference between the first and the second month of Adar, and after this there are enumerated a number of de- cisions which have nothing to do with this matter but which are also in the formula en ben. A similar assointion, one of the number, is the reason that the law concerning the slaves are found among the marriage laws (the number three). The tractate Edioth, for example, contains laws on various matters, classified according to the names of the Tanaim in whose names they are handed down. For example, "this and this one stated five laws", and they are enumerated even if there is not the least relationship between them; "this and this one told three stories", and the stories are told. Even more than the Mishnah, the Gemarah obliterates all distinctions between the legal parts. Through pilpulim, questions and expla- nations it connects a problem of ritual uncleanliness with Sabbath, and one of Nezikin with Kiddushin. The name of the Masechta is, therefore, not at all a key to its contents. in An illustration may serve. Maimonides tell one of his letters, that "in composing the Mishnah Torah this was my goal, since nobody is able to remember the Talmud Babli and Yerushalmi and the Braitoth -- the three which are the basis of the laws. And I wish to tell you what happened to me: there came to me a pious Dajan with the part of the Mishnah Torah containing the laws concerning the murderer (of the tractate Nezikin) in his hands, he showed me a certain Halakah and said; "read". When I read I told him; "what do you want; he replied; "where is this decision to be found" I answered; possibly in Sanhedrin among the laws concerning the murderer or in one of similar references. Said he; "I have already looked everywhere and could not find it, even not in Yerushalmi or in the Tosefta". I was very much surprised and I told him; "I roeomber that there and there in Gittin the matter is discussed". I took the tractate Gittin and I looked for it, but could not find it. I was very much puzzled and embarrassed and I said; "where can this law be found?" "Lot it go until I will remind myself". As soon as he had left I recalled it and I sent a messenger to bring him back. I showed him that it is an expressely stated law in Yebamoth where it is quoted in r22 connection with another matter. And so I am continuously worried when people come to ask where this and this law is to be found. Sometimes I tell them immediately there and there, and sometimes, not. In fact, I do not remember it myself until I look it up. And then I am very sad because I tell myself, if I the author, do not know where it is to be found how shall other people do"? Maimonides completely ignored the talmudical order with its chapters and tractates, and created a new logical order for the endless mass of the Halakah from its origin in the Torah till its final development. Nothing can be compared with it. The mass of the Halakah assumed a new shape in his hands, so that we face really a new creation. Form enlightens the contents and adds soul to it. The plan according to which the book was composed can be recognized in every single Halakah. Every chapter is a structure in itself, and every decision is in its logical place. Everywhere and in the minutest bit it is a masterpiece not only in style but also in construction and contents. It is sufficient to go through one paragraph in the Gemarah and to read it afterwards in "the Rambam" in order to appreciate Maimonides' accomplishment. It is simply a creation ex nihilo. Everything in its place according to the requirement of the subject matter. Sometimes that what is found in the Gemarah in a later place is quoted earlier and vice versa, whole chapters are turned around, and problems which are in the Gemarah amply discussed he reduces to a simple issue by means of one single word. It is really surprising that one man possessed sufficient strength to build such a grandiose structure from a mass of little pieces. In order to illustrate the greatness of the work it should suffice to remind of the fact that the chapter Birkat Kohanim is com- posed of twelve Gemarah Masechtoth; Hilchot Milah of fourteen; Hilchot Melachim of twenty four; and Hilchot Talmud Torah of thirty two Masechtoth. It is true that also in the Mishneh Torah certain laws which should really have been together are found in different places. But this is the result of the twofold principle, employed by Mainonides in the composition of this work. He approaehedSoahe work pedagogue, and as theologian. In the preface to the Sefer Hamitzvot he writes that he gave much thought to the order .. for the codification of the Halakah, resolving that in subject matters the principle de minorem ad majorem from the simple to the complicated, should be applied. But, on the other hand, "one should not assign one mitzvah to two subject matters", for in the Torah itself the order of the 615 mitzvot is given. Maimonides, was very particular about preserving the connection of the later Halakah (the oral law) with the written law and was, therefore, anxious to preserve the original order of the 613 mitzvoth by connecting with every mitzvah all the Halakot which had been developed during the course of time. This theological principle has, indeed, been victorious over the logical pedagogical one, for the division of the Mishneh Torah in 14 books (therefore the name Yad-Hachzakah) is based on the fourteen fold division of the mitzvoth, as defined in the "Guide for the Perplexed". Therefore certain Halakoth which really belong to a different section are connected by a verse or a word in the Torah applied to another mitzvah. Or, Halakoth, which are altogether different are united in one book or chapter because they seem to relate to one and the same mitzvah. The main characteristic of the Rambam's method is the construct- ion and arrangement of the Halakic material in uniting written with the oral law. The Talmud originally designed as a commentary and an inter probation of the #25 written law assumed such dimensions, outgrowing completely its original princi- ples, that it became almost completely divorced from its source, developing in- to a Torah for itself. Who, for example, can recognize in the complicated dietary laws with all their prohibitions and "fences" the original source of the simple sentence "you shall not boil a kid in its mother's milk", to say nothing of the original intention of this verse. Or, another example; the entire complex of laws and hundreds of cases of treyfeh which was appended to the short verse "the meat of an animal slain in the field you shall not eat", which means plainly the meat of an animal slain by a beast and not of a slaughtered animal in which there is found a symptom of a suspicion of a disease. And similarly there are more such laws which the Talmud itself calls "mountains appended to a hair". This distention of the original was really one of the main, if not the only motive, responsible for the rise of the Karaitic movement, which dis- carded entire Talmud by proclaiming the return to the Bible; "seek in the Torah". This movement flourished during Maimonides' lifetime in the communities of the East and seriously endangered the unity of world Judaism. The element of the Mishneh Torah which distinguished Maimonides from all his predecessors and followers consists in the systematical and logical connection of the written with the oral law. The generally accepted opinion that the Idishneh Torah represents the cofification of the Talmud is really erroneous. The Mishneh Torah is really built on the Torah, and makes the Talmud serve its original purpose of a commentary on the Torah (although it was simul- taneously considered as the only authentic criterion for its interpretation). As mentioned, the Mishneh Torah is arranged according to the order of the mitz- voth in the Torah; and each book and Halakot are preceded by the number of the mitzvoth of the Torah of which the Halakot are deduced. It is characteristic of Maimonides to begin the Halaka with the formula "the positive Torah command- ment reads..............." Whereevor it is possible to connect the Halakah, even the late one, with a Bible verse he does it. We read in one of his response "It befits an intelligent man to direct his heart upon truth and to consider whatever is clearly written in the Torah as a first principle and a basic statement....." If he finds a sentence in the Prophets or an opinion of our sages that contra- dicts this principle in this case he shall investigate vith his eyes and his heart until he understands the utterance of the prophet or the sage. Should it be proven that their opinion is in agreement with the one that is expressely stated in the Torah it is certainly good, but if not he shall say I do not under- stand the utterance of the Prophet or the sage and probably there is a hidden meaning and it should not be taken literally". In another responsum replying to a question as to why he decided in a certain case against a Sifre and a Gemarah, he answered that he himself was for a while puzzled, but with the help of common sense he realized that the Derash is opposed to the Pshat of the Bible verse, and, therefore, he accepted the latter. This, however, does not mean that he did not consider the Talmud as a legal authority, On the contrary, he acknowledged the historically proven development of the Halakah and the legal authority of the Masorah, i. e. the sages who are in every generation the bearers of religious legislation. He was, therefore, not concerned as some of his followers with forcing a connection of #24 oral with written law. The Halakah begins with the "positive commandments of the Torah" and ends with "from tradition we learn". He conceived Judaism in its historical entity, from the first religious revelation on Sinai through the period of the Prophets to the sages of the Talmud as being, intellectually, of equal rank. Maimonides accomplished much in cases where the Halakah con- flicts with science. Being himself a great philosopher and scientist and an ardent follower of Aristotle, (he proclaimed that whatever he taught concern- ing the heavenly spheres is absolutely true) he encountered difficulties not only with metaphysical problems in the "Guide for the Freplexed", but also with the scientific questions in the Halakah. The Talmud, as it is well known, sanctions popular belief as "heavenly voice", demons, witchcraft, etc. making them the basis for certain legal decisions. Maimonides was courageous enough to omit all those laws that are connected with superstition, excluding them from the realm of official religion by characterizing them as "lie, deception and suspicion of idolatry" (Hilchot, Avoda-Zarah ). The same method he followed in the exact sciences as mathematics and astronomy where- ever they contradict the results of the sages of the Talmud. However, the inferences from the empiric sciences as medicine (though being himself a physician) he did not accept as absolute truth, and, in general, he did not disown the Halakah on account of them, except for a few cases (see for example Hilchot Schechita and in his well known answer to the sages of Lunel in this matter). Maimonides used science as a helpmate of Halakah thus surprising not seldom his opponents and especially the Rebad who writes in one place:-- "Verily, were it not for his great accomplishment in collect- ing the laws of the Gemara, Yerushalmi, and Tosefta I should have called a protest meeting of the entire population together with their elders and scholars, because he has altered the expressions of the Talmud and changed the Halakot so that they have an altogether different meaning". About the same subject the Rosh (R. Asher Jechiel) to whom the Maimonides Rebad controversy was not quite clear, because he was not scientist, inquired from a certain Rabbi Israel, who was known as being well versed in the sciences and he replied that the Rambam excellently interpreted the Mishnah and "so it was handed over to Moses at Sinai" and those who oppose him are not worth while to be considered. Another element which distinguishes the Mishneh Torah from all other Halakic works is the important part the Agadah is assigned in the deter- mination of the Halakah. The Agadah, the creation of the people, expresses their relationships to life, God, the world, and men was neglected by the Halakists. One knew that the Halakah is law, and absolutely binding. The Agadah is a free creation of imagination, uncontrollable and, therefore, not to be relied upon, as the Gaonim stated it: "one does not rely upon the Agadah". The Halakah became thus completely dried up in being restricted to the scholastic sphere and being completely deprived of the breath of living religiousness. The Agadah, on the other hand, grow more and more undisciplined, being an open field for various superstitions and primitive beliefs. Maimonides through the Mishneh Torah was the first and last to create a synthesis between Halakah and Agadah, not only in the "Sefer Hamadah" and in the "Hilchot Melachim" where he dwells on the Agadic principle, but also in his other works which have really no relation whatsoever with Agadch he tries, by ame.ns of his marvellous style to freshen the dry Halakah with the Weltanschauung of the Agadch. #25 Sometimes, he even elevates a motive of the Agadah to a legal principle, by deriving from it a number of legal decisions. In this way he has completely abolished the separation which the Gaonim and Alphasi had intro- duced between the Halakah and the Agadah. He turned Agadah to Halakah and adorned the Halakah with the spirit of the Agadah. The former, thus, acquired form and stability, developing into the basis of religious and ethically pure conceptions. The latter became softer and more attractive, livelier and more spiritual. Despite the coolness with which the legal decisions are enumerated in the Mishneh Torah there is, nevertheless, a breath of life and even poetical beauty to be felt which starts with the philosophical-ethical introduction and ends with the Messianic epilogue. In contemplating the monumental work in its general aspect and in its specific characteristics one cannot help to concede that behind the general goal of supplying the people with a legal code to serve them as the final decision in whatever case it might be, there is also a hidden psychologi- cal reason, which might be termed the Messianic motive. It was surely not without purpose that Maimonides introduced into his Mishnah-Torah also the laws which do not refer to the time of the dispersion -- as the books of Seraim, Abodah, Korbanot, Shoftim and Hilchot Molachim. On every possible occasion the Ramham made it a point to refer to the royal past and the Messianic future. And the Rambam's idea of the Messianic era which is different from this world only in that the Jews will be politically free. The Messiah will be a king of the house of David who will study the Torah and comply with the Mitzvot as prescribed in the written, and in the oral law, and he will cause the en- tire nation to live according to the Tordh and firmly establish it in life (Hilchot Melachim IX, a). And it is for this future, which in Maimonides' time did not seem too far away that he composed his Mishneh-Torah -- a consti- tution for the future independent Jewish state upon their own soil. The Mishneh-Torah did not become as yet the constitution of the liberated Jewish people. It has, however, become the code of laws for the dispersed and scattered Jewish nation and it has more than any other work contributed to the preservation of the unity and integrity of historical Juda Judaism. New York City Chayim Tchernowitz WHY THE JEW CLINGS TO JUDAISM Judaism is the Jew's birthright and badge of honor, his spiritual patrimony and pride. By clinging to his ancient but ever-growing faith, a faith that has produced patriarchs and prophets, seers and psalmists, sages and saints, the Jew can best serve himself and the world. For Judaism is essentially a way of life. It is concerned not so much with a world to come as with this world in the process of becoming. It holds out to its adherents not so much the promise of individual salvation as the prospect of social re- demption. It glorifies faith, but only such as men can live by. It proclaims a God who created the world and all that is therein, but it protests that only by serving man, the image of God, can we pay homage to our Creator. It speaks to the heart of the Jew of the glories wrought by his fathers in the past, only that he may envisage all the more clearly the new heaven and earth to be fash-. ioned by his children in the future. It proscribes rites and creeds, but it reserves God's blessing and favor only for those who are clean of hand and pure of heart. It exalts piety, but it must be a piety that does not transgress the limits of sanity. With the Synagogue as its chief powerhouse, ;ith the home as its main laboratory, and with the marts of men as its extensive field of oper- ation, Judaism forever labors to breathe the breath of the divine into the man- `-fold relations of our common life, to lift man up out of the dust of the earth into the light and very presence of the Eternal. Cincinnatti Israel Bettan #26 "THE QUEST OF THE AGES" "Man is the only discontented creation of God and no doubt God in- tended to make him so. In the human breast there has been implanted what has rightly been called a "divine discontent". One poet has celebrated this quality of man's nature in the following lines: The thirst to know and understand, A large and liberal discontent; These are the goods in life's rich hand, The things that are more excellent. For "from the discontent of man the world's best progress springs," really this divine discontent "is the first step in the progress of a man or a nation" (Oscar Wilde). A similar thought is suggested in a beautiful legend found in the Midrash, the edifying stories of the Rabbis of old. They said that at dusk on the sixth day of creation, just when "by the Word" man was to be created, the angels to their consternation discovered that all the materials for the creation of man were ready except that by some mistake the materials for the heart of man has been over-looked. God ordered them to seek such material amongst the frag- ments left over from the other days of creation. When finally the angels brought to God their finds of the leftovers, it was discovered that they were the pride and pomp of the lion, the ferocity of the tiger, the cunning of the serpent, the meekness of the lamb, heat or fire and the cool of the glacier, the glow and warmth of the sunshine and the glint of the rivers. The mixture of these God looked at and felt its inadequacy for the heart of man. So he added Love and He poured in Hope and Desire and covered it all with Charity. This is the heart of man, and the hope and the desire for Joy and the Better-Life- the very soul of discontent at the things as they are--is the sustaining quality for human progress". Dallas David Lefkowitz YIGDAL IN NEW METRICAL TRANSLATION 1. Great God existent through eternity. No time can limit Him to whom we pray. 2. An all-embracing unity is He, Unique in oneness; words can not convey. 3. He is a spirit, holy, bodiless, No semblance or no image can portray. 4. Himself, First Cause, without ebginning, is Eternal ere creation's vast array. 5. The Lord of all is He. To all that is The universe reveals His might and sway. 6. The prophet's mystic gift He did inspire In Israel's chosen seers His truth to say. 7. Like Moses ne'er was seer in Israel To whom His glory God could clear display. 8. By means of Moses "faithful in His house" God gave us the Torah that we obey. 9. That Law shall ne'er be changed, not testament Shall substitute for it for e'er and aye. 10. God understands and knows our secret thoughts; Ere aught be formed, its end He can foresay. 11. A fit reward on virtue Ho bestows; Unscathed may none His teaching disobey. 12. Messiah He will send 0 be it soon! - To bring redemption on the judgment day. 15. The dead will He revive in healing love For ever blessed be He, our strength and stay. Newv York David DeSola Pool CONCERNING HYGIENE A popular notion exists that the Jewish dietary laws posses a hygienic intent and a hygienic efficacy. The question of hygienic efficacy being a medi- cal one can be decided only by medical research--not by popular fancy. What needs to be challenged here is the supposition that the dietary laws were ever intended to be hygienic. The Bible nowhere offers the slightest intimation of such a concept as that ot-hygiene. Food is classified not as healthful or unhealthful but as tahor or tame', ritually pure or impure; or as terefah or keshcrah prohibited because torn by a wild beast or not thus prohibited. While the Talmud does contain hygienic prescriptions, these are invariably connected with matters other than those of Kash- rut. Enlightening is this passage from Hullin III, 5: "An animal which has eaton something poisonous (to man) or which a serpent has bitten is permitted as food so far as Terefah is concerned; forbidden however because of jeopardy to human life." The Mishnah thus draws a clear cut distinction between the ritually forbidden on the one hand and the hygienically proscribed on the other. The traditional view is that God will reward with good health those who heed and punish with illness those who transgress His command, whatever sub- ject those commands may touch. Beyond this, neither Bible nor Talmud knows any- thing about the healthfulness of adhering to Kashrut or of fasting on the Day of Atonement. The same applies to all of the other supposedly hygienic provisions, such as the burying of filth or the segregation of persons with certain skin blemished or in certain sexual conditions. Staunch Jews have always observed the rules not in the belief that they are hygienic but in the belief that they are Divine. In fact, the hygienic plea usually appears as a last-stand argument when attachments begin to waver and the abandonment of those rituals impends. The popular theory that various Jewish rituals have a "moral" in- tent and even an esthetic intent needs a similar scrutiny for which, perhaps, the Kallah may offer the opportunity in some future publication. Cincinnatti Abraham Cronbach HOW FALSE WERE THE FALSE MESSIAHS? A study of the history of the Messianic idea in Israel will convince the fair-minded student that the false Messiahs were not all impostors. Many of them were sincere in their conviction that a God-given mission was theirs. This feeling may, in different cases, have arisen front varied causes and influences. In some it was intense patriotism, in others religious mysticism, while a few must be conceded to have suffered from the paranoiac insanity and delusions of grandeur that are to be observed in many men. For the most part, then, they were false Messiahs only objectively rather than subjectively--if I may make such a distinction. It is like the differ- ence between a revolution and a revolt. If you succeed, you are exalted as a revo- lutionary hero; if you fail, you are hanged as a rebel. In other words, they were false merely because they did not turn out to be the real Messiah. They were not so much the deceivers as the deceived or the self-deceived. A study of the history of Jewish sufferings will load one to wonder not so much that there were so many pseudo-Messiahs, as that there were so few. On an average, there were no more than about three known pseudo-Messiahs or Messianic movements for each century from the beginning of the Christian era to the end of the eighteenth century--including Jesus. There was certainly provocation enough for the appearance of more than the fifty or so would-be Saviors of Israel. Leavenworth, Kansas 3.llUJEL HALEVI BARON #28 WHICH FRUIT DID EVE GIVE? The Yale expedition to the Eastern Euphrates announces the discovery of a Christian chapel dating back to 232 on the wall of which was a painting of Adam and Eve standing by a tree on which were two pomegranates. This would indicate that as early as the third Christian century the tradition existed that it was a pomegranate which Eve gave Adam, not an apple as is the commonly received idea. The apple is not an ancient Oriental fruit, but the pomegranate is, and it is also the accepted symbol of fertility among all Orientals. The Adam and Eve story is a sex-story, so the pomegranate is the appropriate fruit. It will be remembered that rimon, or the pomegranate, appears in Scripture as one of the decorations on the garb of the high-priest, side by side with the bell, considered a phallic symbol. But how then did the idea arise that Eve gave an apple to Adam? The Latin for Pomegranate is pomum granatum, a seedy apple, and it is easy to see how the tradition of the pomum granatum may have given rise to the idea that it was pomum, an apple, which Eve had handed to her spouse. Some Hebrew commentators have suggested various fruits, such as the ethrog, as the Edenic fruit, but there is no reason for this suggestion, as there is for the pomegranate, with its numerous seeds, all typifying "Peru urevu." It may be added that the publication recording the finding of this painting merely cities that fact, and does not suggest what has occurred to me, that here we have the origin of the "Apple-idea". The Bible mentions no fruit, stating that it was the fruit of this specific forbidden tree, so the tradition of the pomegranate may be very ancient, and widespread. It is also a fact that in one or more ancient paint- ings of Madonnas they are shown holding a pomegranate, a plain reminscence of the first disobedience, which according to Christian theology was the rea- son for the sacrifice of Jesus. New York City Clifton Hacby Levy ON JEWISH EDUCATION Education has always been the pride and the cherished ideal of the Jewish people. In the words of the Rabbis, Torah is the first of the three pillars upon which the entire world is founded. It is natural that education would be of such prime importance because we know that logically knowledge must always precede practice if we want our actions to be meaningful and properly directed, Of course, of all education that of our children and youth is most important. The Talmud very interestingly asks in the tractate Shabbos, "Why do children die?" One answer is "because they neglect the study of the Torah," and another is "because they neglect to observe the Mezuzah." The Rabbis, in their keen vision, saw the two great educational agencies of which human life and society are functions: the school and the home. So they very pointedly ask: "Why do children die?" Why do so many of our children die a spiritual death? Why d) we see so many of our youth drifting away from the fold of Juda- ism and from the traditions of their fathers? The answer is concise and clear: because of the neglect of the study of the Torah and on account of the neglect of the Mezuzah. In other words, the Rabbis answer, because the education of 1he school and that of the home, (for which the Mezuzah is the proper symbol) has been sorrowfully neglected. Thus the indifference of our youth is traced entirely to their ignorance and lack of Jewish education. Baltimore, Md. Nathan Drazin Nathan Drazin #29 AND ABRAHAM SAID: "OH THAT ISHMAEL MIGHT LIVE BEFORE THEE." Gen. 17.18 The American scene is cluttered with saviors of Israel. Every Jewish private-in-the-ranks has, in his knapsack, a marshal's baton. Every Jewish organization is holding the last line against all the enemies of Israel. With all these defenders, Israel should be safe indeed, except for haunting reservation that somehow there seem to be too many roads to salvation. Some of these saviors are very appealing and spectacular. A Kingdom in Spain, Palestine or Uganda. Health for all the Jews through Jewish hospitals. A home for every Jewish child. Loving care for every aged Mother and Father in Israel. The kindling power of Jewish tradition the past re- lived in every Jewish child. And last of all, unfortunately, the Synagogue, the faithful mother of all the Jewish virtues -- forgotten like mothers some- times are in the recess of the home. We are forcibly reminded of the problem that confronted Abraham as he contemplated his two sons. Ishmael, the brilliant, spectacular, capti- vating, the son of the desert, brave and venturesome, a hunter and leader of men. And Isaac the Plain, simple plodder, who stayed at home, who yielded to his mother's calmer influences. Which of the two would represent the trunk line of development? We sympathize with Abraham when he prayed, "Oh that Ishmael might live before Thee". But it was not Ishmael the brilliant, the handsome, the spectacular, but the homely, Isaac who survived the centuries. And this points the moral to the modern story:---- On what highway shall we travel to safety, to fulfillment, aye, why not again to glory? Shall it be the highway of racial survival, racial literature, racial characteristics? Is it the shape of our noses or the curl in our hair that calls loudly for survival? Ishmael the brilliant and spectacularly Shall we achieve fulfillment by espousing the cause of national- ism and say to ourselves -- "Go to now -- let us be a nation -- with territory, with armies and with navies. Let us cultivate power and thus will we mako oppression bitter for our oppressors." Ishmale the hunter and leader of men! Or is our survival bound up with the cultivation of reli ion? Is not this our answer to the world's questioning? Is not this our .#F.ntee of perpetuity? Is n6t this the trunk line of Jewish development? Like Abraham, we too are tempted to exclaim "Oh that Ishmael might live before Thee." But Ishmael did not become the progenitor of the undy- ing people. It was Jacob, the man who lived in tents, the man who cultivated the finer graces of religion, the man who glorified -th Synagogue, the mother of all the Jewish virtues. Cincinnati Geortpin '4 / S#350 DIVINE EXHORTATION FY ---, 5.5 Of all recorded theophanies, I consider that of Aoges at the burning thorn-budsas the most stirring and of profoundest significance, because of the vital instruction that accompanies it. Confronted by the phenomenal sight of the thorn-bush burning with fire without bo'ing consumed, Mopes heard the voice of God calling to him, "Moses, draw not nigh nith-or; put off thy shoes from off thy feet; for the place whereon thou stan~ist 'i-hy;o ground." The average reader of the Bible is usually perplexed by this- command. He cannot see the connection between shod feet a#holy ground. So he passes it up without further investigation as one of thie passages of the Bible that may have a secret meaning, which lies beyond h/is grasp. But the Bible student finds no diffic.ty/in getting to the real meaning of this striking injunction, because he beholds in it a great truth ex- pressed in metaphorical language; a clever figure f speech which contains a most valuable lesson to anyone who assumes the serious responsibility of leader- ship of a great movement and a sacred cause. In the vernacular of the Ghetto the cemetery is known as "Der Heiliger Ort" the Holy Place. What causes/the eternal resting-place of mortal man to appear holy in the eyes of the Jew? In the cemetery he behold a true democracy, where there is no envy, maliceor hatred. Everyone is alike there; no rich and no poor, no master and no slave, no pride and no degradation, no joy and no heartaches......And, because it symbolizes the ideals of/a perfect democracy, the Jew regards it as holy ground. Any man who becomes interested in the promotion of high ideals for the living, truly stands on holy ground, and will act wisely if he will heed the Divine Exhortation, first heard by Moses:- "Shal n'olecho me-al raglecho."- Put off thy shoes from off thy feet.- Moses, who was called by a Divine Pro- vidence to emancipate an enslaved people, to teach them the laws of life, and to inspire them with a yearning for freedom, righteousness and peace, was sorely in need of a slogan to guide him in his far-reaching endeavor. That's why be- fore entering upon his great mission he hearkened to the counsel of God's voice,- "Put the muddy shoes of self-seeking and vainglory, of impatience, anger and jealousy, of haughtiness, conceit and unforgiveness, from thy heart!".- Every leader, in all walks of life, is inevitably confronted from time to time with trials and temptation, with hardship and unjust criticism. At such a time it is well to remember the wonderful slogan the great leader of old took as his own, which stood him in good stead when his patience was under trial, when an ungrateful rabble of ex-slaves challenged his authority and provoked his wrath. Moses, the meekest of men, was driven to despair, his very life was threatened, and yet he prayed to God to save his people. "Forgive them, 0 Lord," he pleaded, "blot me out from the book of life, rather than the multitude be destroyed." Even when his own sister turned against him and she was smitten with leprosy, he prayed for her recovery. In all his difficult moments, no matter how trying and exasperat- ing, Moses always stood his ground, because he stood upon Holy Ground, and did not forget'to put his shoes from off his feet'; he was ever mindful of the Divine Exhortation that came to him at the burning bush as he was commissioned to engage in the holy role of emancipator and lawgiver. Not only leaders but also laymen in Israel may profit by adopt- ing this ancient slogan in daily life. Man treads on holy ground whenever the question of uprightness, justice and truth comes up in his dealings with his dealings with his neighbor. If he would but remember to put off the "shoes of selfishness, dishonesty and desire for illicit gain,:' from his heart, all human transactions would become honorable, dignified and praiseworthy. The Psalmist reiterated this same warning in much simpler language when he exclaimed, "Who shall ascend the hill of the Lord, and who shall stand in His holy place? He that hath clean hands and a pure heat; who hath not inclined his soul to falsehood, and hath not sworn deceitfully." The leader as well as the layman in Israel, must have clean hands and a pure heart, in order to carry on the great work before them, to perpetuate Jewish teachings and promote the welfare of mankind; then every inch of the earth will become holy ground for man to stand upon, and there shall be no further need of removing the "muddy shoes from one's heart," because the spirit of God dwell in it, and it will become an everlasting Temple of holiness, of human kindness and love divine. Pine Bluff Morris Clark TEXT: PSALM 115, v.9, "WHO MAKETH THE BARREN WOMAN TO DWELL IN HER HOUSE AS A JOYFUL MOTHER OF CHILDREN" Biblical commentators have struggled with the interpretation of this verse. To me it seems very simple. The writer of the Psalm was evidently living in an age very much like the present. The women of that time were seem- ingly like those of today. They were interested in amusements. They would run to lectures, to movies, to bridge parties, or their equivalent in the early days. They did not want to stay home and rear families. The Psalmist was much exercised over this condition of affairs and, therefore, he made the pronouncement: You "barren woman", you do not want to stay at home and bring up a family, but you want to run about constantly from one thing to another. What will God do? "He maketh a barren woman to dwell in her house." Her punishment is to be that she will have to stay at home. But the mother of children", "she will have a good time." Louis I. Egelson Cincinnati #32 INVIOLABILITY OF PERSONALITY "He who preserves a life in Israel it is as if he preserved a whole world; and he who destroys a life in Israel, it is as if he destroyed a whole world." -Mishnah, Sanhedrin 37. "Just as people are unlike in their countenances, so also are they unlike in their ideas." Berakot 58. In Modern life and thought there is a positive trend of increas- ing respect for human personality. In social, economic and in international relationships, one may easily find this trend manifesting itself quite clearly. The cry of the thinking element in our population today is for economic de- mocracy by the side of the already acquired political democracy. This respect for the individual life and opinion is a healthy sign. The dawn of a better day depends upon it. God grant that it come speedily! To the Rabbis of the Talmud must go the credit of having pronounced this ethical principle in no uncertain terms. Godly men, they drew their ethi- cal guidance and judgments from the idea of God, the Father of all men, the Lover of all mankind. The statement in the Mishnah is, at first glance, rather astonishing. That the destruction of one human being should be comparable to the destruction of a whole world, sounds like an exaggeration. Is it possible that the loss of a life, insignificant in its expressions and accomplishments, is equal to cosmic catastrophy? On deeper reflection, the meaning of our Talmudic Philosophers becomes clear. These Rabbis evidently realized with remarkable insight, the rather modern discovery of the fact of individual differences a discovery which modern psychology has made in recent years. Individuals, they seem to say, differ in disposition, in thought, in desires and feelings no less than in ex- ternal appearance. And realizing this, observing this, the Rabbis stood in awe of the mystery. They could only marvel at the technique of the Supreme Artist who, having created billions of humans, made no two alike. Such is the creative power of God alone. According to Rabbinic thought and belief, God has a purpose with each and every human being. Bound up with every individual are potentialities and possibilities distinctly his. God has endowed his creatures with gifts which distinguish one from the other. Far from discouraging and suppressing individual traits and abilities, they regarded them as signs of God's greatness and mercy. Society, they held, is enriched by the variety of differences. The fact of variation in ideas and desires of man was another manifestation of God's wonders. Finding no two exactly alike in emotional and intellectual reactions, they regarded every single individual as a distinct, special and inviolable creation. His destruction was, therefore, a total loss of something precious, and irroplaccablo. A special relationship, mission and purpose has been blotted out, and hence the loss of a soul is indeed the loss of a world among many. To their high estimate of human personality the Rabbis taught that to preserve a life, is to preserve a world. Jonathan Abramovitz Dallas "DANTE AND RELIGIOUS LIBERALISM" #3 "What is it to be a liberal in religious thought? Might it not be beneficial for the clarification of our thought if we first set down what a liberal is not? It is not liberal in the religious life just to be on the other side. One or the other religions and sects has not appealed to the spiritual outlook and has not harmonized with the spiritual wave-lengths of this or that soul. It may be that all the existent churches and their doctrines have failed of appeal, for one reason or the other. That does not mean that the one thus left could stand on the outside and call names, or throw stones. A liberal is not merely opposed to this or that attitude, sect or credal statement. Such an attitude is negative, destructive and utterly uninspiring. Nor is a liberal in religion a materialists Many there are vho have become weary of the theories of life and duty and the spirit which have been woven out of the unsubstantial fancies of mystics and have been hardened into fixed church dogmas, and in protest they have cried odt, "only by my senses will I be led", and "only what is reported to me by them Vill I be- lieve". He is not a liberal, for he, too, begins to dogmatize as to essential reality. And the agnostic is not the religious liberal. There was a time when the agnostic was needed. In an age when rash assertion and mistaken tradition dominated thought too strongly and tied and manacled human spiritual and in- tellectual progress, the banner of the agnostic was a conquering and triumphant emblem. It humbly said to those sectarians who claimed to know all, even the composition of the pavement of the heavenly streets, "I do not know." It is right to confess ignorance and such confession ignorance and such confession is also a protest against outrageous claims of knowledge; but ignorance is never a thing to glory in, not to make a religion of. "To be a religious liberal is to swear eternal allegiance unto truth. It is to use every faculty, every little candle, every lamp that God has given us in a never-faltering search for truth. It is to sense the external world to its fullest extent and never to hesitate in the process of learning about it all that we possibly can. It is to set no limits to the thousand ventures of the soul for more and more knowledge, more and more truth. It is to hate all manner of sophistication, and all foolish and hypocritical harmonizing of an assured fact with a false dogma or creed. It is the courage to stand by the truth once it has been attained without the hope of reward or the fear of consequences. It is to revere our soul, our intellect, to respect our reason, and never to be treasonable to them by turning away from their dectation when we find it socially inconvenient. It is to be true to our own selves ever." Dallas David Lefkowitz THREE PROPHETS There were three types of prophets, said the ancients. The prophet, like Elijah, insisted upon the honor due God the Father, without insisting upon the honor due Israel the son. The second type, like Jonah, insisted upon the honor due Israel the son, without insisting upon the honor duo the Father. The third and noblest type, represented by Jeremiah, insisted upon the honor due the Father as well as the son. These approximate the groups in modern Jewish life. The denominationalists are indifferent to the people; the secular-nationalists are indifferent to the re- ligious and spiritual values of Jewish life; and the religious--nationalists who believe in the synthesis and unity of Jewish people and faith, of God and Israel: Salvation can come from this latter group alone! Hartford Abraham J. Feldman GLEANING The following is a translation of a section of an article by Kalman Schulman, entitled, "ha-Yehudim v'Torasam bain ha-Anin, "which appeared in a collection of essays by 19th century Jewish savants under the name of "Gan P'rachim" (Wilna, 1881). (Kalman Schulman was born in 1819, in Mohilev, Russia. Because of his wide secular knowledge and pure Hebrew style, Schulman was at one time the most widely read Jewish writer. Some of his better known works are: "Safah Berurah", a collection of proverbs and epigrams; "Dibre Yene ha-Yehudin", a trans- lation of the first part of Gratz's "Geschichte der Juden"; "Mistere Paris", a translation of Eugene Sue's novel "Les Mysteres de Paris"; and "Dibre Yene Olan", a universal history based on the works of Weber and Bocker. Schulman contributed many articles to the "ha-Maggid", "ha-Lebanon", ha-Karnel", and "ha-Melitz.") "Roman writers have erred grievously concerning the teachings of Judaism. Juvenal, the satirist, has this to say: 'Jews do not worship One God, as they profess to do, but the heavenly bodies. 'Celsus, too, spread the sane r.isinformation. So did Petronius. The source for this false belief is difficult to ascertain. It is conjectured that the words, 'then Thou in heaven' (1 Kings, 8:52), nay have furnished then the basis for this belief. With the Bible for support, this belief found further confirmation in the Jewish practice of lifting the eyes heavenward in prayer. The expression, 'yirath shamayin, 'may also have served to nis- lead then. "Tacitus, the historian, has done nuch to disseminate false opinions about Jewish life and thought. He claimed that Jews worship the ass. He writes: 'iWhen Israel left Egypt to journey to Canaan, the wilderness presented severe hardships because of lack of water to drink. The distress was keenly felt by the generation in general. when the languishing pilgrims had given way to deep despair, Moses espied a number of wild asses headed for a place where a heavy rock surrounded by grass stood; Learn- ing that there was water in that place, Moses lead his people to it. Thus were a finished folk delivered through the miraculous guidance of wild asses. So great was the relief that joy found expression in prayers of thanksgiving to these asses. Since that time Jews had made a deity of the ass, displaying its image as an object of worship in their sanctuaries.' Jewish writers have been at a loss to explain the grounds for this impossible belief about their people. How did it cone to be circulated? It is probable that the idea got started through a misreading of the passage in Numbers 20:10 Someone mistook 'hanoria' for 'chanorin.' Seeing that Moses addressed himself to asses, and having heard of the story of the miraculous inter- vention of wild asses when the thirst of the generation in the wilderness was great, this someone, connecting the story with the passage in the Bible, thought he had perfectly reliable ground for belief in the Jewish worship of the ass. It is further probable that this sane would-be scholar read the story into the words of the passage in Genesis 56:24. Convinced now that the deification of the ass by Jews had basis in legend and literature, he made such emendation in the text as suited his belief: he changed 'ha-yainin' for 'hanayin', the letter ayinn' in 'biroso' for the letter 'aloph', and 'Moshe' for 'Anah'. The passage then was made to yield additional proof for the belief he was so willing to spread. No less a writer than Plutarch was pleased tQ repeat the same falsehood." Waco Wolfe Macht #55 THE PLACE OF NASHIM IS THE ORDER OF THE MISHNAH The books, tractates, treatises and divisions of the Mishnah have some logical or ideological arrangement---since the Mishnah pur- ports to be a codification and compilation of the Law. In making a scientific study of Seder Nashim, why does it succeed Seder Moed. One explanation is that the arrangement is in accord vith that of the Torah, which is the prior and prime authority. In Leviticus some of the precepts pertaining to the festivals (Moadim) precede those concerning women. To this explanation two valid objections might be raised. First, according to an oft-repeated remark in Rashis commentary on the Torah, there is no logical or historiological sequence in the Pentateu6h. Secondly, in Leviticus recitals on the festivals also succeed as well as precede the interdictions concerning women and the family. Tosefoth Yom Tov would find some ground for the place of Nashir in Isaiah xxxiii.6. "And the -stability of thy times shall be a strength of salvation---wisdom and knowledge." 1. Emunat -- Zoraim.............Social stability based on agriculture 2. Ittecho -- Moed..............Seasonal changes and seasonal festivals 3. Hosen -- Nashim.............Family security and purity 4. Yeshuoth -- Nezikin..........Help (salvation) through civil rights and adjustments 5. Hochmath -- Kcdoshim.........The intelligence to distinguish between sacred and profane 6. Va-daas -- Taharoth..........Purity based on a knowledge of the minutiae of the ritual law. (See Resh Lakish in B. Madlikin p 50a) The reasoning concerning this sequence is logical enough. But in spite of the ingenuity displayed in the interpretation of the Scriptural verse, its application to the arrangement of the Nishnah is far- fetched and at best only a drush or Asmakta RAMBAM states that Nashim precedes Nezikim because the verses, "If a man sell his daughter....." (Ex. xxi, 7), and "And if men strive together and hurt a woman......" (Ex. xxi, 22), precede, "And if an ox gore a man......" (Ex. xxi, 28); that is, the verses alluding to women (Nashim) come before those describing damages (Nezikin). Superficially one might find fault with such reasoning. All the Scriptural verses referred to deal chiefly with civil and criminal matters, not with family life, with which Seder Nashim is primarily concerned. Besides, the order in the Torah, if we are to believe Rashi, may be wholly accidental. VJhat Rambam may really mean, however, is that in the organization of community life economic and familial consideration (con- tained in the first three Sedarim of the Mishnah) take precedence over civil adjudications (Das Polizel-Recht). Psychologically the place of Nashim in the Mishnah may possibly be explained on the theory of an association of ideas or words. The last Mishnah in Seder M oed formulates a certain aspect of ritual purity. This may, in turn, suggest a treatise on family purity (Toharot-Hamispachoh) that is, Nashim. But this too is far-fetched. The subject matter of the Mishnah in Moed is wholly unrelated to family morals. #56 Instead, the order of the first three treatises of the Mishnah (and of the last three, too) follow a logical sequence, least for the period in which they were compiled; No Biblical corroboration is required, though we should naturally expect the Rabbis of the Talmud and their commentators to seek Scriptural support. Zeraim, dealing principally with the regulations concern- ing agriculture, comes first, since agriculture was the basic industry. It is followed by Mloed, a treatise on seasonal changes and festivals, both closely associated with agriculture. Nashim succeeds, because next to economic states family security and community morals were the most paramount issue, at least in ancient society. (The last three treatises, dealing with civil suits, Nezikin, laws of holiness, Kadashim, and laws of ritual purity, Taharoth, are logical enough in their arrangement). Fort Smith Samuel Teitelbaum ELIJAH 1AND CHANUKAH From the time when our ancestors settled in Canaan and applied the local agricultural festivals to Yahveh, their God of the desert, the Jews have shown a tendency to borrow from their neighbors and assimilate their ways into Jewish forms. One example of such a transformation has been they way Purim has made of the Catholic carnival a merry Jewish institution. Nowadays we must recognize that thousands of Jc;ish families are seduced yearly by Christmas with its gift-giving and its Santa Claus. Is it not possible that our Jewish genius for absorption may transfer the Christmas spirit to Chanukah just as the Purimspiel has taken over the carnival? This has been attuemted with some success. Elijah's role in Jewish folklore is one of prime importance and the Rabbis tell many tales about his wanderings through the world; yet his only role in current Jewish life is in the Seder service at Passover. By means of an original bit of haggadah, Elijah becomes also the presiding genius of Chanukah. The story to tell is this: NMattathias, as a result of his defiance to the Syrians of iModin, had to flee to the hills with his sons. Be- fore they departed, however, they laid out bags for the provisions and other necessities they would require. But they were very tired, and they decided to postpone their packing until after they had had a nap. Thile they were asleep, Elijah, the friend of all good Jews in distress, came and crammed the bags with choice foods and other good things. The Maccabees were now equipped for their flight as soon as they awoke. Therefore, Jewish boys and girls may leave Chanukah bags out- side their doors when they go to bed on the first night of Chanukah, and if they have been good, Elijah will fill the bags with gifts. At the religious school Chanukah celebration, Elijah also appears in a black robe and beard to distri- bute the presents. This is a custom which appeals to children, while at the same time it strengthens the Chanukah observance and requires no apology from us as Jews. Abram Vossen Goodman Austin, Texas #57 JUDAISM AND THE SACREDNESS OF LIFE Several little children, playing on one of New York's crowded sidewalks were injured, and one of them killed, by shots fired from a speeding automobile by irresponsible gangsters aiming at an enemy. The shots were not intended for the children. The shooting was merely a part of the continuous gang warfare with which we have been sorely harassed in recent years. The situation of course aroused the wrath of the entire community. Civilized people the world over agreed that such an appalling disregard for the sacredness of human life was beyond the pale of human decency. It lessened the horror of the outrage not one whit to understand that the criminals had no desire to injure helpless babes but if the helpless babes happened to be in their way well, it was just too bad! Revolting indeed and yet, when we pause to consider, just how does the attitude of brazen outlaws toward helpless children in their way differ from the attitude of civilization toward helpless children who happen to be in the way during a period of industrial or international conflict? There is surely no desire on the part of industry to harm or endanger the lives of little children; yet if children happen to be in the way of larger profits in the eternal conflict between capital and labor let them take the consequences. Do our ideals of civilization protect the weak, innocent and helpless though they be, from starvation, disease, and death brought about as a consequence of a strike or lockout? Indeed not! This very condition is often used as a means of bringing the strikers to terms; and civilization condones it as a deplorable but necessary evil of the economic struggle. Civilization refrains from inter- ference and the Red Cross is forbidden by its charter to feed the families of strikers. They may render aid to sufferers from an "act of God," but not to sufferers from acts of man. And the same reasoning applies to the attitude of civilization in international conflict. A gangster, an outlaw, who with an unwitting shot, kills or maims a child at play who happens to be in his way, arouses the righteous wrath of the nation. And this is right, just and understandable. An airman dropping gas or bullets from the skies upon a whole community of helpless women and children, is part of the accepted method of warfare between two avaricious nations. This is applauded and honored, and the airman is hailed as a hero. The nations of the world have, it is true, seems to realize the cruelty and the futility of war, and denounce war as an instrument of international policy and prepare with unabated intensity for the next. Judaism has much to say on the subject of sacredness of human life. The Talmud is replete with lessons exalting the value of human life, and the obligation to preserve it and sustain it, and the admonition and warning that man has no right to destroy that which he cannot create. A highly educated Gentile once said to a rabbi, "Your religion places Law above everything else. All else, even life itself seems to be secondary." This of course is not an overstatement of the fact. Judaism does elevate the Law to a place of prime importance, but there is one thing to which the Law itself gives precedence, and that is Life. Human Life is the supreme gift of God to man. The law concerning Sabbath observance, probably the most definite, most stringent and oft-repeated law in all the Holy teachings, takes secondary place when it appears to conflict #58 with certain exigencies for the promotion and preservation of human life. If the observance of the Sabbath in the smallest degree violates the safety of, or in any way endangers human life, the Talmud insists that the law of Sabbath observance be for the time suspended. This is Israel's attitude toward the sacredness of life. And we are shocked today at the killing of a child by a gangster, and we grieve at deeds of violence committed by irresponsible individuals. Our attitude toward the sacredness of human life as a whole is still apathetic. New Rochelle, N. Y. Alvin S. Luchs INVOCATION AT REPUBLICAN NATIONAL CONVENTION AT CHICAGO Conscious of the vast universe, O God, in which our earth is smaller than a grain of sand, and our life less than a fleeting moment, we are filled with awe and reverence, and with bowed heads tremblingly stand before Thee. The greatness to which we lay claim, the achievements of which we are proud, the ambitions which dazzle our eyes, fade away in utter insignificance before Thy presence. Humility fills our being and such humility is the beginning of wisdom. Under its influence may those who have gathered here to plan for the welfare of our Republic cast aside all selfish consideration, all pride and vainglory. May conviction and principle and not careerism and the desire for power animate them. In these days of storm and stress, when millions of human beings languish in despair and lead a tortured existence on the abyss of want and of misery, let all other considerations but their well-being be secondary. May the spirit of the ancient prophets permeate this assemblage, that their sympathy for the underprivileged, their passion for social justice, and their recognition of human brotherhood may be recorded in its decisions. 0 our God, purge us of national arrogance and vanity. Help us to recognize that we are members of the family of nations, and that no com- plete happiness can be ours unless that happiness is shared by all men. Destroy then in our souls the petty, the base and the selfish, which alienate us from our fellowmen and from Thee. Truly Thou hast been generous with us. May we be equally generous in administering Thy bounty in the interest of all. May we Americans, true to the ideals of the founders of our nation, renew our allegiance to the principles of religious, political and economic freedom. May we march forth to the four corners of our country to dissipate the clouds of despair and gloom and thus strengthen the faith of our fellow-citizens in the ultimate establishment of Thy Kingdom of righteous- ness and peace. May such hopes and motives guide us that all men may benefit and Thy name, 0 God, be magnified throughout all the earth. With hope and with courage, with faith in humanity and with idealism in our souls, let us carry on the heritage of the ages. Amen. Ferdinand M. Isserman St. Louis #39 THE SEAT OF THE POOR (Eugene Manuel, Wio lived from 1823 to 1901, was a French poet and educator whose maternal grandfather had been chief cantor of the synagogue of the Paris Consistoire. As a poet, Manuel earned a place for himself in nine- teenth-century French literature both for the exp.ortness of his craftsmanship and the humanitarianism of his subject-matter. His two volumes of verse, Pages intimes and Poemes populaires, published in 1866 and 1871 respectively, contain about a dozen poems on stricly Jewish themes; perhaps the best of these is the one here reproduced in fairly faithful translation, "la Place due pauvre", written in 1867. The original is composed of rhymed couplets of the twelve-syllable lines typical of French poetry and known as alexandriness"; the translator has deemed it wise to substitute for this the equally typical English blank-verse line). I love this ancient custom of the Jews, Which justifies the joy the happy know: At eve, when all are gathered for the meal, Have listened to the grace intoned aloud, The children, buzzing swarm, each in its turn, Have kissed the brow of the old patriarch And watched the servant busy at her tasks, Then ever is a seat reserved for him, The poor man, whatsoever he may be; Though wan and wretched, welcomed is he always As soon as he appears upon the threshold. Now 'tis a scholar, grave and meditative, Vhose sunken cheek betrays protracted hunger, Or else a beggar in a threadbare caftan, A traveler from far-off, unknown ghettos, And who, descended to such low estate He scarce is bitten by the tooth of shame, Inclines his servile and degraded back At this unwonted hospitality; Now 'tis an orphaned child is bidden in, Gazed at with awe by all the other children Stricken with pity for his ragged garments, his famished glances at the toothsome dishes And the hot haste with which he eats the food, Sometimes it is a sad-eyed invalid Weeping with pain, a ward of charity; Or else a passing student, ushered in, Clings to his book as he doth take his seat, Admires the dresser with its copper lamp, The glist'ning cloth, the handsome large-eyed Jewess, Smiles timidly to young and old alike, And, hungrily devouring each new morsel, Relates his sorrow far from home and loved ones. Each evening in the self-same way they welcome The needy stranger, set at once at ease; At synagogue or on the street they've found him And, friend to friend, hold gentle converse with him. #40 "Blessed is He in whose high name thou comest," They say, "thine is this table, eat and drink!" And when he passes back across the threshold, The mother speeds him off with food or coin Or with a cloak to fend against the cold, Which he receives with humble gratitude. Ah! might we but return to this old custom, The poor would feel less bitterness at heart, A sacred shrine would be the rich man's home; For then it might be said the poor man's seat At table is the seat of God Himself! Austin, Texas (Translated from the French by Aaron Schaffer) ON THE MEKILTA OF RABBI SIMEON BEN YOHAI Lauterbach (proceedings of the Amer. Academy for Jewish Research, IV, pp 116 ff.) has pointed out several passages found in the Midrash HaGadol and elsewhere which belong to the Mekilta of R. Simeon, but were overlooked by Hoff- mann when he reconstructed that work. I wish to call attention to several passages included by Hoffmann which are not part of the original Mekilta of R. Simeon. Further study will probably reveal other passages to be added. MRS p. 100, lines 12-14, this passage is hardly Tannaitic. The statement "heaven and earth are interested parties" seems dependent on Abodah Zarah 5 a (Amoraic) and the word asekin is suspicious. MRS p. 101-102s the legend of Moses' struggle with the angels, corresponds to the version found in the Babli rather than that given in Palestinian sources; already declared spurious in Ginzberg, Legends of the Jews, VI, p 47, n. 248. MRS p. 102, 10 lines from bot. From yaza kal to al raglehem taken word for word (with few variants) from Pirke Rabbi Eliezer, ch. 41. The next clause probably belongs to PRE also, tho not in our texts; it contains a fusion of two legends which are kept separate in Tannaitic sources. The next sentence, through citation of Ps. 62.12 may be part of MRS, but probably not. All parallels to this aggadah are Amoraic. Albany Bernard J. Bamberger, "THE REALITIES AND SHAMS OF SUCCESS" "The largest part of life is given over to process of education whose ultimate aim is the discovery of the realities as against the shams. We seek it. in art and in the sciences and in literature and in politics. It is the crux in religion. An unerring discrimination between the realities and the shams is the summation of life's wisdom. It is the philosopher's stone. The question with which we are told Pontius Pilate concerned himself, "WVhat is truth?" is, in essence, the question-"What is reality and what is sham?" Life comes to us in so many guises that it is hard to decide what is real and what sham, or rather, the world comes to us so elaborately dressed that we have difficulty in separating the garment from the body, the shack from the real. What is passing and what is per- manent, what is temporary and what eternal, what is the mode and what the substance, what is transient and what is elemental-this has been the problem of all religion, art and science". David Lefkowitz Dallas THE FASCINATION OF FOLKLORE A fascinating field for the student of ceremonies and sociology is that of Jewish folklore, in whose more primitive vestigial stages demonology plays its universally accustomed role. A Responsum to the question, "Should One Cover the Head When Participating in Divine Worship?" (Yearbook, Central Conference of American Rabbis, 1928) and a paper on "The Ceremony of Breaking a Glass at Weddings" (Hebrew Union College Annual, Volume II, 1925) prove Professor Jacob Z. Lauterbach to be an outstanding student of such phenomena from the Talmudic point of view. The latter is one of a group of wedding ceremonies having an extremely ancient origin and significance, based upon a common superstitious belief. The idea underlying this group of ceremonies is the primitive heathen belief that bvil spirits or demons are jealous of human happiness and seek to destroy it by harming the happy mortal. The first reaction to this belief was an attempt to hide from the demons. Of the multitude of practices thus moti- vated, I shall here cite two that are most familiar--the bridal veil and the marriage canopy. Despite later reinterpretations and rationalizations, the fact seems to remain that these were originally intended to serve as simple devices to hide the bride and groom in order to protect them from the evil spirits. Pointing out how unsatisfactory and uncertain such tactics were in coping with the powers unseen, Dr. Lauterbach traces the natural history of Jewish ceremonies in general and of "The Ceremony of Breaking a Glass at Weddings" in particular. From his very interesting analysis there emerges a. threefold strategy. "The first was to fight the demons and drive them away. The second was to bribe them by gifts and conciliate them. The third was to deceive them by making them believe that the per- son whom they envy and seek to harm is not to be envied at all, since he is not as happy as they imagine him to be but is rather worried and burdened with grief." The resort to fighting or frightening away the evil spirits may be exemplified at random by the still persistent and more or less universal practice of giving the bridal party a noisy send-off, including the rattle of tin cans. The attitude of propitiating the demons by offering them gifts is still prevalent in the contemporary custom of scattering rice after the newly married couple. It is true that this latter type of popular practices has also been interpreted as symbolizing thehcpo of human fruitfulness; but according to Dr. Lauterbach this is a subsequent reinterpretation or rationalization. The strategic device of fooling the stupid demons by making them believe that the people were mourning and not rejoicing--and therefore hardly to be envied, inasmuch as they appeared to have troubles enough already--is typified to this day by the (not exclusively) Oriental habit of weeping at a wedding. Leavenworth, Kansas SAMUEL HALEVI BARON #42 PHILOSOPHY OF HISTORY THE TIMES MAKE THE MAN Some sixty or more M'chash've ha-Ketz or "Calculators of the End"-- that is, specialists in Millennarian chronology--are known to Jewish history by name. Each had his way of computing the age of the world and interpreting the supposed Messianic prophecies found in the pseudepigraphic Book of Daniel. And so Messiahs came and Mesiahs went, only to develop into pseudo-Messiahs. Nothing daunted, the Rabbis and M'chash've ha-Ketz simply reinterpreted the unfulfilled prophecies, projected the Messianic date into the more distant future, and re- vised their notions of the Creation calendar and the advent of the Millennium. Thus it is that it was possible for Jewish history in the first eighteen centuries of the Christian era to record the rise and fall of some fifty Messiahs or Messianic movements. In view of the prime importance of the calculations themselves as a factor in the rise of pseudo-Messiahs and Messianic movements, it is little to be wondered at that Greenstone's book on the subject is called not "Messiahs in Jewish History" but The Messiah Idea in Jewish History, and that Silver's more recent book is called not "A History of Messiahs in Israel" but A History of Messianic Sieculation in Israel. Significantly enough, the latter work is devoted entirely (according to the arrangement of its contents) to "Messianic Calculation," its "Methodology," "The Calculators" themselves, and the "Opposition to Messianic Calculation;" whereas it refers to the "Pseudo-Messiahs" only briefly and incidentally. Nothing better illustrates the contention of some historians, psychologists, and sociologists that is isn't the man that makes the times, but rather the times that make the man. That is not to say, however, that "the times" partake of some mystic quality or magic potency, that they are something impersonal or trans- cendental in nature. Whon we aver that "The times make the man, not the man the times," "we must nevertheless allow for the fundamental fact that the times are made by men--not by an isolated man of greatness or genius or leadership, to be sure, but certainly by men collectively, by a human society composed of men. By "the times" we therefore mean the social environment, created by society, and in. turn creating the individual personality. For, as Cooley so strikingly points out, human nature is unthinkable apart from social nature. Leavenworth, Kansas SAMUEL HALEVI BARON POWER OF SILENT HOURS "What we need is the call of Jeremiah. In his day, seemingly, they were running about as continuously and in a similarly head-long manner as our generation is, and their efficiency-experts were proclaiming the revelation of speed and unflagging work under the spell of progress. And lo. He gave them a new revelation: "Thus saith the Lord, stand in the ways and see and ask for the old paths, where is the good way, and walk therein, and ye shall find rest for your souls." And Job felt the-need of a similar admonition to his generation, for he told his people: 'Stand still and consider the works of God". This is the thing we need in this hurried and harried age, that we might halt in the crush of things to consider, to rest and to meditate, or just to loaf. James Harvey Robinson in his "Mind in the Making" and otherss have recently shown us that truly creative thinking takes its source in day-dreaming, in that wool-gathering process which was looked down upon by our efficient age as mental loafing. The need of the age is to stand in the ways, to stand still and consider, to ruminate the great mouthful which the present generation finds itself possessed of, that it may assimilate it all without any subsequent in- digestion. Dallas David Lefkowitz #43 A HOME-MADE PARABLE About forty years ago a great army maneuver was held in Jasla. This was no ordinary annual maneuver, but an event that came only once in every six years--the Kaisermenever, attended by the Emperor Franz Josef himself. The whole city was decorated and illuminated and hung with Austrian flags during his several weeks' stay, and the place swarmed ,with dapper officers and soldiers in dazzling dress uniforms. Many there were who journeyed to Jaslo to observe the splendid, machine-like maneuvers of the finest regiments gathered from all the empire and, above all, to catch a glimpse of their beloved Emperor. Among the thousands who thus made pilgrimage was a certain Chasid from another Galician town. Like Israel Baal Shem Tov, the founder of Chasidism, who once astonished his disciples by going to a tight-rope performance, this latter-day saint, too, had but one object in mind--to extract from his experience its ethical signifi- cance, ausnehmen a Mussar Haskel, as the quaint Yiddish idiom expresses it. "I went to see how men give homage to a king of flesh and blood," he said, "and I pondered: If so much glory and honor be accorded to this Melech Basar va-Dam, then how much the more ought mortals worship and adore the Melech Malche ha- Melachim, the King of kings!" On the very day this Chasid was in Jaslo he witnessed an incident that left a deep impression on his mind, and of which he often spoke in later years. Franz Josef had reviewed a detachment of troops and was passing between massed, motley lines of the curious and of those who sought to do him honor, when of a sudden he bade his military escort halt. His eye had fallen upon a Jeqv of more than middle age, bearded, wearing peoth or ear-locks, and clad in a black, begirdled bekeshe or kaftan. What was it that had attracted towards this humble Austrian subject the attention of the Kaiser-koenig, sovereign of a maelstrom of nations? It was the military decorations that adorned the breast of this Jew, the gaily colored ribbons standing out in marked contrast with the severe black background furnished by the long coat he had on. At once Franz Josef recognized him as a veteran of an old campaign whom he himself had dec- orated years ago for bravery and distinguished service. Old soldier that he was, this pious Polish Ghetto Jew saluted his commander-in-chief; and the thousands of onlookers marveled as the Emperor shook hands with him and paused for a moment's chat before proceeding on his way. No sooner had the imperial party vanished from the scene than the aged veteran was surrounded by Jews who pressed in from all sides to congratulate him with cries of Mazzal Toy on the high honor he had received. With awe they looked upon him, and not a one but envied him his good furtune in having been addressed by the head of the house of Hapsburg. The extraordinary events of those few minutes set the Chasid of Gorlice again a-thinking, and he mused: " "How eagerly we seek to set eyes upon this Melech Basar va-Dam, this mortal king, if only once in a lifetime; and what envy is showered upon the lucky man with whom he condescends to exchange a word! Al achath kamah ve-khamah--should we not be all the more eager to hold communion with the Melech Malche ha-Melachim, the King of kings, a precious privilege which is ours every day of our earthly life?" Such was the typically meditative reasoning of a humble member of the Chasidic sect of Joeish mystics. lho was he? It happens in this case to have been none other than my own grandfather. Zecher Tzaddik li-Bherakhah -the memory of the righteous brings blessing. Leavenworth, Kansas SAMUEL HALEVI BARON #44 MOLOKANS The characteristic features of a civilization includes law, language, land, literature, folkways, sanctions, social customs and insti- tutions, traditions and religion. The Molokans are a religious sect in Los Angeles (numbering six thousand souls) who exemplify all these features. Their sect separated from the Greek Orthodox Church a century ago, and have braved many perils since then to preserve their conscience. In 1906, the sect was finally ex- iled from Russia. They came to the United States where in Los Angeles, they have built their churches, schools, and social structure. Religion is the very essence of their corporate life. Their church is considerably more than house of worship; it serves them as social center, classroom, meeting place, city of refuge and hope. In their worship, they use a sacred language--Russian, which they want to preserve. Their meagre literature includes the Russian version of the Bible--Old and New Test- aments (with greater emphasis upon the Old) and their few commentaries. Even though they were exiled from Russia, and have no sympathy with the Soviets, they cherish an affection for their holy land--Russia. Distinctive folkways and social traditions they retain, in their dress, their food, their greetings. The men wear Russian blouses at services without neckties; the women come in brightly-colored dresses which they made, and heads are covered with lovely shawls. They permit no images, altars, or ecclesiastical furniture in their church. Their very name, Molokans, is a reference to their quasi-Kosher preferences for milk and dairy products. They observe Biblical festivals, and their services on Saturday night and Sunday suggest that they regard both days as sacred. They observe rites and traditions which they are anxious to perpetuate, and which their children often discard as un-American. These rites deal primarily with the intimate offices of life: in bereavement, in memorial services, in marriage. They permit no instrumental music; the music being chiefly of group singing of traditional melodies (often without words). The form of worship is reading from Scriptures by several of the elders in turn, with a few words of commentary, and the congregational humming of melodies. Religion, in the ordinary sense, hardly covers the full nature of their association. The Molokans are a religious community knit by blood ties, united by common sacrifices in the past and by common aspirations for the future, with tender recollection of a sacred land from which they are ex- iled, and a sacred language they would not lose. They cherish traditions and customs and folkways that are distinctively theirs. Their corporate life is religious, strongly interwoven with social usages and considerations. Are they an object lesson of what is meant by Judaism as a civilization? David B. Alpert Tyler #45 CONGREGATIONAL SINGING IN THE BIBLE There once existed a regular and orderly ritual or rituals in which the congregation played an active part by singing certain assigned sections of the ritual, conducted by a priest or leader. However, the Bible fails to re- veal any definite ritual, or liturgy, in Gvhich the various parts are marked, noting where the leader or the congregation should respond though vast material convinces that such rituals did exist, at least for certain occasions. In many places, the Bible states explicitly that certain groups functioned as leaders in the ritual, or were appointed to sing in special choirs on occasion; and that the people or congregation responded at designated places. Singing was highly developed, especially antiphonal singing by trained groups. This type of singing is very noticeable in some of the Psalms, especially Psalms 46,52, and 80. Our first task shall be to show that music was an integral part of the service by the Hebrews of the Bible, by enumerating Bible passages of the Bible. Amos 5:23 in denouncing the current worship of the time, he says: "Take thou away from Me the noise of thy songs," etc. "The writer of Psalm 42, in recalling the practices of his people in Palestine says: "These things I remember, and pour out my soul with- in me, How I passed on with the multitude, and led them to the House of God, with the voice of joy and praise, a multitude keeping holyday." No doubt the Psalm- ist refers to the service customarily held on this festive occasion when the people sang songs of praise to God in the Temple. Jeremiah 33.11, in speaking of the restoration of his people alludes to the service in Jerusalem, to which the people responded says:------ "the voice of them that say, Give thanks to the Lord of Hosts, for the Lord is good, for his mercy endureth forever, even of them that bring offerings of thanks- giving into the house of the Lord." The Psalm of thanksgiving, Ps. 100:2, tells that the people came before God with singing: "Come before His presence with singing." At the dedi- cation of the wall of Jerusalem (Noh 12.27) we find that "they sought the Levites out of their places, to bring them to Jerusalem to keep the dedication with glad- ness both with thanksgiving, and with singing," etc. During the time of the exile in Babylon, there was no altar nor sacrifice, and their strong religious feeling utilized song and praise, and hearing the words of inspired teachers. The sons of Asaph, who had acted as the choir in Solomon's temple--some of them as poets and composers for the choir--kept up their identity while on the banks of the Euphrates, and sang before the new altar when they came back to their old home. Another hint of singing in Biblical times is in Psalms: 41, 72, 89, 106, where we have benedictions of these psalms probably dating from Temple times. They contain the formula which the people intoned after singing of the several books, with occasionally "Amen." In Neh. 12:45-47 we learn that in the days of Ezra and Nehemiah, the regular services instituted by David were carried out. This particular incident occurred at the time of the return from Babylon #46 and the consecration of the second Temple. "And they kept the word of their God, and the word of the purification, and so did the singers and the porters according to the commandment of David and of Solomon his son. For in the days of David and Asaph of old there were chiefs of the singers, and songs of praise and thanksgiving unto God. And all Israel in the days of Zerubbabel, and in the days of Nehemiah, gave the portions of the singers and the porters, as every day required; and they ahllowed for the Levites; and the Levites hallowed for the sons of Aaron." In 558, Cyrus became the king of Babylon, and published his famous decree allowing the Jews to return to Jerusalem. The first colony under Zerubbabel, of the House of David, built an altar on the sacred spot. In the book of Ezra, describing this great event, we find one line of our present Prayer Book of which the continuous use may be traced back to the days of the old commonwealth. It was sung by men who had seen the first Temple, as we know frm Jeremiah: "Give thanks to the Lord, for He is good, for His mercy en- dureth forever." (Ezra 3:11, Jer. 33:11 with slight variation.) Thus we see that music played an important role in the re- ligious life of the people and in the Temple service itself, that priests and lay people participated in song. It was highly organized, at least from the standpoint of the singers; various groups were appointed to sing at functions, sometimes Levites, or special choirs, and frequently the people also took a part. In the time of Solomon, hundreds of men and women singers, arranged in two choirs, had assigned places upon the steps of the Temple. When the builders laid the foundation of the Temple, Exra 3:10-11 writes: "They set the priests in their apparel -- the Levites the sons of Asaph with cymbals, to praise the Lord, according to the direction of King David of Israel. And they sang one to another praising and giving thanks unto the Lord: "for He is good and His mercy endureth forever toward Israel." And all the people shouted with a great shout, etc." Here we note that the Levites were entrusted with the singing in this ceremony and that the people participated by joining in with a great shout at the end of the song. The Hallel and the Hodu in the Psalms were part of the oral worship of the sanctuary. The Hosanha and "Boruch" formulas date from the time of the Temple. The latter form became more predominant in public and private prayer. In the earliest times the people prayed only occasionally and the benedictions were merely incidental utterances of thanks for mercies vouchsafed as for rescue from danger, etc. In I Chr. 25:7 we have the number given singers in the Temple; "And the number of them, with their brethren that were instructed in singing unto the Lord, even all that were skilful, was two hundred fourscore and eight." David, we learn, was the first to ordain Asaph and his brethren as singers to give thanks unto the Lord. This he did when the ark of the covenant of God was set in the midst of the tent-I Chr. 16:7: "Then on that day did David first ordain to give thanks unto the Lord by the hand of Asaph and his brethren." Then follows vv. 8-56, the song of thanksgiving for the occasion, and, the people responded with "amen" and "praised be the Lord." Sometimes the music was rendered by special choirs. Thus Psalms 15, 20 and 38 were probably rendered by two choirs. Or the choir and congregation #47 participated in singing, each rendering certain assigned portions: The choir first singing a line of the song and the congregation responding with a simple recurring phrase or refrain after each line. Psalms 156, and 118:1-4 were sung so. From II Chr. 29:50 we know that Hezekiah commanded the Levites to sing praises to the Lord, and also in I Chr. 15:16, when David calls for the Levites to appoint the singers- probably their regular function. The building of the Temple invited public prayer, ascribed to Solomon, at its dedication: I Kings 8:12:15, There must have been some singing in this service and also in the subsequent services held in the Temple. But communal prayer -- or liturgy is hardly found prior to the separation of Israel and Judah. We have services well established at the time of the pro- phets: Is. 1:15, "Yea, when ye make many prayers, I will not hear." There were many methods of rendering song. The Psalms were to be sung antiphonally. (See 56.52.80). In the Temple there was anti- phonal singing, choirs responding to one another. (Neh. 12:51). In the orient the precentor still sings a strophe repeated three of four tones lower by other singers. Some Psalms, such as Ps, 15, 40, and 58 were rendered by means of two choirs. Another example of antiphonal singing, is in Deut. 27: 15-26 where Levites addressed the people and the people responded after each verse with "Amen", there being twelve in all. In the time of David, often a small choir sang the main theme with the refrain sung by the congregation. The refrain was a simple re- curring phrase after each line as in Ps. 156 and 118; 1l4. The leaders had the tradition of the music and imparted it to the general body of the chorus. In II Chr. 20; 20-21 gives an example of the refrain type. Jehoshaphat calls to the people to believe in the Lord and the prophets and tells the people to pray, to sing unto the Lord and they sang: 'Give thanks unto the Lord, for His mercy endureth forever.' The rendition of the music was not always orderly, sometimes there was tumult, confusion and hysterical shouting. Thus in Lev. 9:24. When the burnt-offering was consumed on the altar, "The people shouted and fell on their faces." Also in II Chr. 5:15, we see that singing was not in unison: "And it came to pass, when the trumpeters and singers were as one, to make one sound to be heard in praising and thanking the Lord --- and praised the Lord 'for He is good, for His mercy endureth forever,' "The same thing we find to be true in Ezra 3:11 after the Levites finished their song:" And all the people shouted with a great shout, when they praised the Lord," etc. These few examples show that the music was not always in orderly fashion, nor always pleasant to the ear. Often there were songs rendered at important national epochs in the life of the Hebrew people. When the Israelites successfully evaded the Egyptian enemies, Ex. 15:1-18, the Song of the Red Sea, that Moses and the children of Israel sang this song and that Mirian responded with v.21, "Sing ye to the Lord," etc. In II Sam. 22:1-25:7 David gave a song of thanksgiving to God upon being delivered from his enemies. Deborah and Barak after the Israe- lites had been successful in destroying Jaban, king of Canaan, sang Moses, just before he relinguished leadership of the people over to Joshua, sang the Haazinu, in Deut 52. These were songs for the various occasions upon which Israel rejoiced in its victory. See also Psalms 46, 48, 76. #48 The liturgical Psalms and Ritual hymns give an idea of the importance of song in ancient Israel, and convey some of the ideas which were expressed by the ancient Israelites, and the manner in which their worship was conducted. First we have the various ritual hymns, the Hallelujahs; Ps. 112-118, 135, 146-150, (acrostic) 111-112, Accession Hymns: Ps. 47, 95, 95- 100; the festal hymns: 55, 67, 81, (acrostic) 145, the Votive hymns 66, 96 and antiphonal 98, 92, I Sam. 2:1-10, Benedictions: Ps. 20, 21, 45, Numbers 6:24-6, Psalm 154, Doxologies Ps. 41, 13, etc. Then again we have the vari- ous phases of the liturgy of Praise Ps. 34, 45, of Supplication: 86, of Penitence: 150, of Devotion 4,52 (acrostic) 25, of Judgment-- 7, 94, The songs of Ascents: Ps. 120.154; the exile songs: 120-123, 124, 126, 129, 150. The Pilgrim songs: 121, 122, 125, 127, 128, 151, 153: The Temple hymns 132, 134. Then a group of simple Psalms; 3, 6, 12, 22, 28, 54, 71, 159. Those with refrain: 56, 57. Antiphonal and Acrostic: 9, 10: Then a group of Psalms which deal with the various themes of the world and life. The Meditative and worldly life 1, the Devout life- 15, life as a passing Day-90, work and home-- 127, home life-128, the Lord thy Keeper: 121, the Heavens above and the Law within-19, Man the Viceroy of God 8, a song of God's House 84, a Song of Unity- 155. Besides there are a few "folk songs", the song of the Sword: Genesis 4-25-4; Of the well--Numbers 21; 17-18; Husbandry Song Prov. 27: |25- 27; war ballad- Joshua 10:12-15; and fragments of others in Numbers 21: How vast the themes of the Psalms! The songs that the Israelites Oung, show great depth of poetic soul. Every aspect of life, religion, and of that unique personality--Israel, Israel who loved life, and God, and people, with its land, it labors, was sung sometimes with exultation and praise. The music of the ancient Hebrews inspired adherents, lead them out of darkness, gave them strength and courage, and bound them together in common brotherhood. After the destruction of the Temple it was considered sinful to sing before the coming of the Messiah. Music was prohibited to the exiles as late as Hai Gaon, and many of the Temple melodies have disappeared. New spontaneous ones arose out of.the emotions of the people; and many new tunes were absorbed into the services by adaptation. The Anshe Maamad heard these tunes and carried them back to their communities teaching them. Many of the Levites participated in the services of the Synagogue and acted as precentors because of their fine ability and special training in song. The Pharisees furthered synagogue ritual and music. They ordained that Bible lessons in the Synagogue be read at stated times, that Psalms of praise be sung on the Festivals, and on the feast of Maccabees, that prayers be said three times a day, to bless God after, and before meals; And helped create the music for these occasions. Sidney A. Wolf Corpus Christi #49 THE BATTLE OF "JEREMIAH" Fierce verbal and written battles have been waged between Jew and Christian over every book of the Bible. Passages in Jeremiah have been selected which fundamentalist Christians regard as indisputable proof of the truth of fundamental Christianity. Three interpretations of each passage will be given: a. The traditional Christian interpretation, b. The traditional Jewish reply, and c. The opinion of the "higher critics." These interpre- tations are quite typical of the entire field of Biblical controversy and suggest the agreements and disagreements that have marked the development of Jewish and Christian Biblical exegesis. The clash of opinion is based only on what Jeremiah meant. The first is 3:16-17, "And in those days, when you have multiplied and increased in the land,' is the oracle of the Lord, 'men shall no more speak of 'The ark of the covenant of the Lord' -- it shall neither be remembered, nor mentioned, nor sought after, nor made anew-- but at that time they shall call Jerusalem 'The throne of the Lord,' and all the nations shall gather there, to celebrate the name of the Lord in Jerusalem, and shall no more follow the stubborn promptings of their evil minds.'" The Christians say that this means that, in the Messianic per- iod, the Jews will cease to obey the Torah. Isaac of Troki, in "Chizzuk Emuna" (Book I chap. 24), written at the end of the 16th century, maintains that the verse does not refer to the Torah at all but to the Ark in which the Torah was kept. The Ark will dis- appear in the Messianic period but the Torah will never disappear. The "critics" believe that these verses were among Jeremiah's earliest prophecies and are part of a longer section (2:2 to 4:4). This whole section contains no reference to the Messianic period, but is a call to immedi- ate national repentence. These particular verses mean that, if Judah repents its sins, there will be no further use of the Ark as the symbol of Israel's spiritual heritage, because Jerusalem itself will be God's throne and Palestine the spirit- ual center of the world. Next is 14:8-9, "0 thou who art the hope of Israel, Its savior in time of trouble, Why shouldst thou be like a stranger in the land, Like a traveler who turns aside to lodge for a night? Why shouldstthou be like a man overcome by sleep, Like a warrior who is powerless to help? Yet thou, 0 Lord, art in the midst of us, And thy name we bear--abandon us not!" Christians say that these verses clearly refer to the life and mission of Jesus. #50 Isaac of Troki ("Chizzuk Emuna" Book 1 chap. 25) replies, "You Christians are accustomed, in all your complaints and answers to bring evidence for your beliefs from part of the words of the prophets without considering the intent of their words and without looking at the adjoining verses and with- out considering similar passages in prophetic literature; because it is not your desire to know the truth, but to triumph and to conceal the words of truth with erring words." Isaac maintains that vv. 1-9 form a unity and constitute a prayer which Jeremiah offered up to avert a threatened famine in Judah. As proof he quotes v.1, "The word of the Lord that came to Jeremiah in regard to the drought." The "critics" are unanimous in their belief that these two ver- ses form one of the most sublime passages in the Bible. God is not "a far-off God who occasionally visits His people, but One who is in their midst, sharing their pain." (George Adam Smith "Jeremiah" p. 348). Modern Christian scholars, influenced by the traditional Christian interpretation, maintain that Jeremiah here hinted at vicarious atonement, as shared even by God Himself. Jewish "critics" contest this interpretation and say the verses merely voice the pro- phet's belief that God is immanent as well as transcendent. The next p.ssagc is.15:1, "Then the Lord said to me, 'Though Moses and Samuel stood before me, I would show no favor toward this people. Send them out of my sight, and let them go." This clearly indicates, say the Christians, that God has cast Israel aside forever. Isaac replies (Book I chap. 27) that this refers only to the Babylonoan exile and is not a permanent rejection. That God will ultimately forgive Israel and cause her to return to Palestine is indicated by 32:37ff, "I will gather them from all the lands to uhich I have driven them in my anger, my fury, and my great wrath, and will bring them back to this place, and will settle them in security; and they shall be my people, and I will be their God, --I, etc." The "critics" have little to say about this verse. Most of them believe that it was not written by Jeremiah and that it can not be dated. 17:4 proves, say the Christians, that God will never allow the Jews to return to Palestine. This verse reads. "I will make you loosen your grip on the heritage which I have given you, and will make you serve your enemies in a land which you know not; for you have kindled my wrath to a fire which shall burn forever." The traditional Jewish reply, as found in "Chizzuk Emuna" (Book I chap. 26) is that ad olom, which concludes the verse, does not mean "forever" but denotes a future time known to God but.not to inru It could not mean "forever" because the prophets, in many places, foretell the ultimate return of the Jews to Palestine. The "critics" say that ad olom, as used in this verse, does mean "forever." They list this among Jeremiah's earlier statements, in which he threatens the nation with utter doom unless it repents immediately. The correct interpretation of the next passage Chapter 18, "The Parable of the Potter," has been a bone of contention between Jew and Christian, between Jew and Jew, between Christian and Christian. We consider only vv.7-10, the center of the polemical controversy: "As the clay in the potter's hand, so are you in my hand, 0 household ofIsrael! Christians say even though God originally intended to save Israel, He finally decided to cast her off forever because of her sins. Isaac replies (Book I chap. 27 of "Chizzuk Emuna") that in ordinary situations, God rewards good with good and evil with evil. But God's promise that He will eventually restore Palestine to its former greatness and will cause Israel to return and to dwell there, is no ordinary promise. It was made un- conditionally, with no proviso regarding Israel's future failures or successes. The promise was not made in connection with the Babylonian exile, but refers to a time in the far-distant future. The certainty of its fulfillment is indicated by 31:35-37, "Is the oracle of the Lord, 'Then shall the race of Israel cease from being a nation Before me forever." Many prominent "critics," including Cornill, Skinner, Erbt, Gil- lies, and others believe that these verses, i.e. 18:7-10, are post-exilic. The writer agrees with George Adam Smith, that Jeremiah wrote them. The significance of the whole parable, which (undoubtedly is one of Jeremiah's earlier utterances), is: wr Israel willing to repent, God would forgive her; but she is not willing to repent and so her doom is sealed. Vv. 7-10 fit in very well with this interpretation. The battle of "Jeremiah" reaches its climax in chapter 31. Stormy controversies have raged around every verse in this chapter, particularly three passages: 31:15,22b and 31-34. Matthew 2:16-18 read as follows: "Then Herod saw that he had been tricked by the astrologers, and he was very angry, and he sent and made away with all thd boys in Bethlehem and in all that neighborhood who were two years old and under.....Then the saying was fulfilled which was uttered by Jeremiah (31:15), 'E cry was heard in Ramah! Weeping and great lamenting! Rachel weep- ing for her children, and inconsolable because they were gone.'" Joseph Albo, (15th century) pointed out the absurdity of this bit of New Testament exegesis in his "Ikkarim" (Book III chap. 25). It is obvious from the context, he says, that the verse refers to the conquest of Israel by Assyria. Isaac of Troki "Chizzuk Emuna" Book I chap. 28) carries the argu- ment a step further, and declares that, if the Christians are correct, the verse should mention (not Rachel) but Leah, from whom the tribe of Judah was descended. Furthermore, v.v. 16 and 17 speak of the returning of the "children," which clearly indicates that the prophet did not have in mind the babies killed by order of Herod. Isaac says that the "children" referred to are the lost Ten Tribes, who will some day return to Palestine. #52 The "critics" declare these verses are part of a lamentation uttered by Jeremiah after the fall of Jerusalem in which he voiced his grief over the destruction of Israel and Judah and hoped that Jews would eventually be restor- ed to Palestine. The weeping of Rachel is, of course, merely a figurative ex- pression. The "critical" interpretation is practically identical with that found in Jewish tradition. Thu last passage is the one which has created most dissention, in 31:31-34, "Behold! days are coming," is the oracle of the Lord, "when I will make a new covenant with the household of Israel. Christian interpretation of this passage is well known: When Jesus came, he gave to the world a brith hadoshoh, a new covenant, a New Testament, which abrogated that given to Israel on Mt. Sinai. The old Torah was a legal document, but the new Torah is claimed an ethical and spiritual discipline written on the hearts of men. The new Torah, will bring to the whole world, in- cluding Israel, eternal salvation. Isaac of Troki points out ("Chizzuk Emuna" Book I chap. 29 and Book III chap. 97) that the phrase brith hadoshoh means not "new Torah" but "new covenant." This new covenant-relationship between God and Israel does not refer to a new Torah. At Sinai, the Israelites entered into a covenant with God, in which they promised to be faithful to Him. Theybroke their promise and, as a punishment, were exiled from Palestine. But, at some future time, they will return to Palestine and will consummate with God a new covenant to stand forever. The Torah given to Moses on Sinai will be the law of the new order. The Torah is eternal and unchangeable. The interpretation of Christians is entirely with- out foundation. The "critics" are divided into two camps in their understanding. Smend, Duhm, and Erbt say that Jeremiah did not write them and that they are post post-exilic. Smith, Buttenwieser, Giesebrecht, Cornill, Peake, Skinner, and Gillies say that Jeremiah did write them. Smith denies the validity of Duhm's arguments. He says that Jeremiah used the word "covenant" in a figurative sense, and argues, as does Buttenwieser, that, to Jeremiah, "Torah" meant "revelation." Smith and Buttenwieser both be- lieve that Jeremiah prophesied that, in the future, a new revelation would be given to Israel replace the Sinaitic revelation. Smith clings to the theory that this new revelation is that given to the world by Jesus of Nazareth. Button- wieser, with characteristic breadth of vision, finds, in the new revelation of Jeremiah, a noble picture of that future age when all mankind will be one, wor- shipping at the shrine of the Holy One of Israel and consecrating their lives to the pursuit of justice and righteousness. This study shows anew that each interprets the facts in his own manner. Surely all can agree: "We have had enough of this sort of fighting. The time has come for creedal and denominational peace. What a glorious day it will be when Catholic, Protestant, and Jew will seek in words of Jeremiah to understand and know God." David Max Eichhorn Texarkana #53 RABBAH GAMALIEL II. Leader and Administrator. From a Kallah Lecture. The year 70 marked a turning point in Jewish history. The Jewish commonwealth was destroyed, Jewish nationality disrupted, and the Temple burnt down. Whether the tears which Titus is said to have shed at the sight of the devastation really flowed from the depth of his heart, or whether they were hypocritical history cares little about that; and it mattered little even to the Jewish people. Israel had been struck a severe blow, and they stood deeply shaken, wounded to their innermost souls. One need notdoscribe, at this point, the sufferings endured by the men living in that period; one need not depict how slain were heaped upon slain, how destruction progressed step by step, how men closed up, with their own bodies, breaches in the walls, how courage sustained the waning strength of weakened arms. We find all this recorded upon the pages of history. Suf- fice it to say, that from that time on, a tearful drama unfolds itself before our eyes. And yet, it is not a tragedy. Judaism knows not only how to suffer and resist, but knows also how to preserve and create spiritual forces. It knows how to live, even after it has long been considered dead. A few years ago I had the honor to lecture before the Kallah about a great personality of those troublesome days, about Rabban Gamaliel the Second, the reorganizer and savior of the sunagogual service; that lecture is now printed in a volume containing my lectures held before the members of the Kallah. Here, however, I am discussing Rabban Gamaliel as the leader who instituted laws for the purpose of preserving and keeping intact the unity and solidarity of his people in thosedays of distress. His leadership reached a form of dictatorship, and brought about a strong opposition against him, even within the ranks of his closest friends. This opposition finally led up to his resignation from the presidency, and it is described in full in the famous passage known as "Bo Bayom", in b. Berakot 28a. The text in Borakot tells the following story: 'It happened that a disciple came to Rabbi Joshua b. Hnaanyah, and asked him whether the recitation of the evening prayer was obligatory or optional. Rabbi Joshua replied that it was optional (R'shut). The same disciple, who the passage tells us later was Rabbi Simeon b. Yochai, then went to R. Gamaliel and asked him the same question. R. Gamaliel ruled that the evening prayer was compulsory (Hova). The disciple reported to R. Gamaliel that R. Joshua had ruled otherwise, and R. Gamaliel said: "Wait here until the members of the assembly enter." When the assembly convened, the Shoel, the clerk, presented the question of the evening prayer before the gathering. Rabban Gamaliel again ruled that the recitation of the evening prayer was compulsory, and then asked whether any member of the assembly opposed this ruling. Rabbi Joshua replied: "No". Then Rabban Gamaliol said: "How dare you say that! It was reported to me that you had decided differently; that you had said that the recitation of the evening prayer was optional." #54 Rabb~n Ga.maliel then angrily continued: "Joshua, stand on your feet, and let the witness face you and testify against you". R. Joshua stood and said: "If I were alive and the witness dead, I could deny his report, as a liv- ing person can deny the word of a dead one. But since I am alive and he is alive, how can I deny his testimony?" Rabban Gamaliel then rebuked him publicly, while R. Joshua remained standing before the assembly. And the people could not endure it any longer, and became rebellious. And they said to Hutzepit Hameturg'man, who was acting as the speaker of the assembly: "Stand up and do something. We cannot allow that Rabban Gamaliel continue to insult R. Joshua. Last year, on two occasions, Rabban Gamaliel acted similarly. Now he again insults R. Joshua, and we cannot tolerate it any longer. Let us impeach him." And they did. Then they appointed R. Eleazar b. Azaryah as president. And the text further tells, that on that day the watchman was removed from the door of the assembly house, and all disciples werd permitted to enter; R. Gamaliel, during his presidency, had denied admission to many, saying 'any disciple whose innermost thoughts do not correspond with his outside appear- ance (of piety), shall not enter the assembly-house.' On that memorable day, al- so, an entire tractate, Eduyot, Testimonies, was compiled. And the passage goes on to tell us, that whenever "Bo Bayom" is mentioned in the Talmud, as, for ex- ample, in Tractate Yadayim, it refers to that memorable day. On that day, all unfinished Halakot were also decided. It is remarkable, that Rabban Gamaliel did not leave the assembly-house on that busy day, but stayed and participated in the important discussions. The historian realizes, that it was not only Rabban Gamaliel's harsh attack upon R. Joshua that aroused the displeasure of the assembly and cost him his position. This incident formed but a small link in the chain of the many acts which Rabban Gamaliel performed, in his effort to restore unity within Juda- ism. In those unusual times, he was forced to use unusual methods. In order to strengthen the authority of the assembly in Jabneh, he had to strengthen his own authority as well; in order to abolish old dissensions, and prevent new quarrels that threatened the very existence of Judaism, he had to make use of his official title "Nasi", which was recognized by the Roman government, and which brought him recognition of his authority as president of the assembly. On another occasion, before the incident related in Berakot occurred, he was forced to humiliate his opponent R. Joshua b. Hananyah publicly; he ordered Joshua to appear before him in traveler's garb on the day which, according to Joshua's reckoning, should have been the Day of Atonement. Rabban Gamaliel could not afford to suffer any contradiction to his declaration concerning the New Mo6n (R.H.II, 9). However, he showed that it was, for him, only a matter of principle, and he had no in- tention of humiliating Joshua personally, for, rising and kissing Joshua on the head, Rabban Gamaliel greeted him with the words: 'Welcome, my master and my pupil; my master in learning, and my pupil in that you accepted my words'. Rabban Gamaliel even used the instrument of the ban relentlessly against his opponents. He placed his own brother-in-law, Eliezer ben Hyrcanos, under the ban, when the latter refused to submit to Gamaliel's decisions (B.M.59b). Jewish people were ever accustomed to Democratic principles and Democratic leadership, and they look- ed, therefore, with disfavor upon Rabban Gamaliel's dictator rulings; they even suspected him of seeking his own power and glory, rather than the power and glory of Judaism. However, the more we know about his life and personality of the man, the better can we appreciate his rulings. The words which Gamaliel uttered when he placed Eliezer ben Hyrcanos under the ban, amply prove that Gamaliel's aims were unity and harmony, and not dictatorship and personal power. At that occasion, he said: 'Lord of the universe, it is manifest and known to Thee that I have done it not for my own honor, nor for that of my house, but for Thy honor, that factions may not increase in Israel'. #55 These and a few more similar occasions caused the displeasure of the people. Thus, the story told in Berakot was only one episode in the active life of that energetic leader; it was an episode, however, which deprived him of his position. Further evidence that Gamaliel sought only to bring about reconciliation and peace between the various factions, can be drawn from the fact that, instead of retiring in anger after his impeachment on that memorable day, he remained in the assembly house, and took part in the deliberations conducted by the new president, Rabbi Eleazar ben Azaryah. He acted as a plain member of the assembly, until his opponent, Rabbi Joshua ben Hananyah brought about restoration of Gamaliel's position, by forming a joint presidency, in which Gamaliel and Eleazar b. Azaryah shared honors. And we must not content ourselves to stop at this point. Every powerful personality reflects certain traits of his own upon the characters of those he influences. In fact, it may be said that the farther a leader reaches into the inner life and soul of his followers, the greater is his effect upon posterity. The influence of & great personality upon those whose leader and master he becomes, is even greater than the sum total of his deeds and knowledge. One personality may leave behind generations of followers, and another may leave numbers of books. But the influence the former exerts upon the inner life of his followers is greater, by far, than the effect the latter may produce through his books and writings. And such was the personality of Rabban Gamaliel, that pos- terity regarded his actions as inspired by the 'Ruah Hakodesh' (Erubin, 64b). In order to obtain complete knowledge of a tree, we must examine not only its root and stem, but also its bark, branches, and its manner of growth; thus also must we examine the life and deeds of a historic person- ality, before we can form an estimate of his character. Although no historical work has been written about Rabban Gamaliel, we learn about the economic conditions of his time (in the year 90 and later), and about the spiritual reconstruction that took place during that period, we learn all this from the many Halakot ascribed to the great Nasi, from his many decisions and rulings that are scattered in Talmudic literature, and from the various passages relating incidents in the life of Rabban Gamaliel. It has already beeh mentioned in what position Palestine, and especially Judea, found itself in those days. Following the destruction of the Temple, the economic conditions, as well as the mode of living, underwent a com- plete change. Old laws and regulations ~vich had been closely connected with the social and economic life in Palestine, -equired modification, and new laws were sorely needed; the people sought a man who could meet the new times and act according to new ideas, and such a man was found in the person of Rabban Gamaliel. Let us examine one incident that occurred on that memorable day, on the 'Bo Bayom'. -t is related that on that day, as soon as Rabban Gamaliel lost his presidency, a proselyte of Ammon appeared before the assembly, and asked that he be received into the Jewish fold. Rabban Gamaliel then only a plain member of the assembly, but still an active participant in the dis- cussions was of the opinion that the Ammonite should not be accepted into #56 the Congregation of Israel; Rabbi Joshua said that the proselyte should be received into the Jewish fold, Rabbi Joshua's opinion carried greater weight at that time, and the proselyte was accepted. The questions now arise: Why did the Ammonite appear before the assembly asking to be received as a Jew just at the time when Rabban Gamaliel lost his presidency? Also, why was Rabban Gamaliel against the acceptance of the proselyte, thus acting contrary to the traditions of his great ancestor, Hillel? These questions can be answered easily, if we accept the theory that many Rabbinical laws are the outcome of economic and political con- ditions, or the results of persecutions. It is almost an accepted fact among historians, that economic conditions are a great factor in the shaping of history. In the Middle Ages, for example, mental decay went hand in hand with the economic and social breakdown. It is also a matter of fact that many Halakot were intended to be put into enforcement only during normal times. The Halakah always attempt- ed to secure just relations between individuals, groups and political factions, and due to the fact that religious sentiment ever prevailed among the Jews, the Halakah regulated also the social and economic life. But with the approach of a new period in history, when old forms of economic life upheld by so many rules and regulations were suddenly broken, when greater complexity and variety in economic relations appeared, a modification of old laws v;as needed. Let us take as an illustration the law of Meshikah, the sale of goods by taking possession of goods. In the Mishna Baba Meziah IV, 2, we read: 'If one has taken possession of the fruits,, but has not paid the money, he cannot withdraw from the sale; if he has given the money, but has not taken possession of the fruits, he can withdraw from the sale. But they (the Rabbis) said "He who took account of the men of the generation of the Flood and the men of the generation of the confusion (Babel), will also take account of him who does not stand by his word"'. Thus reads the Mishna. In the Talmud, Baba Moziah, 47b, rabbi Johanan says: 'Accord- ing to the Torah money acquires goods. Vhy, then, did the Mishna state that Meshikah, "Taking up" the goods, acquires the goods? This was decreed lest the seller say to the buyer: "Although you have paid for the wheat, I cannot deliver it to you, since your wheat was burned in the loft"'. The Talmud then asks: 'Does not the one who threw the flame finally have to pay for it?' And replies: 'This was a decree lest fire should occur unavoidably'. 'If the wheat is in his keeping, he will risk his life and take pains to rescue it, otherwise he will not risk his life, and will take no pains to rescue iti. The theory has been set forth in an issue of the Jewish Quarterly Review (1935) that these fires were caused by Roman incendiaries during the Hadrianic persecutions, about 155 C. E. To my mind, however, fires by Roman soldiers and incendiaries must have occurred even earlier than during the Hadrianic period, namely, during the years 70 155 and later, at the time of Rabban Gamaliel. During that period, outlaws and robbers increased in number, insecurity of life and movable property prevailed in Judaea, and enhanced the difficulties of maintenance and reconstruction. Judaea, especially those places around Jabneh, #57 suffered from Roman military forces and from bandits and robbers, even more than Galilee. In Judaea war followed war, and Rabban Gamaliel journeyed to Caeseraea, where the Roman governor then had his palace and also to Rome, for the purpose of intervening for his people. In Jabneh a military garrison was stationed, and imperial stores of produce were also there. But private stores were not secure, even from Roman soldiers. The Tosephta Dammail, 15 speaks of the Otzar Melakim, the Otzar Yabneh, and the Otzar shel Yahid. Of course, everyone could buy produce from the imperial stores and be safe, since the stores were guarded by soldiers; but it was insecure for a Jewish merchant to buy grain from a Jewish store and pay for it, thus following the old law (Biblical and Rabbinic), that the delivery of the purchasing money makes the sale binding, since, in all probability, before it could be delivered, it might be reduced to ashes. The fire would probably have been started either by the Roman soldiers who tried, in that way, to compel Jewish merchants to buy only from imperial stores, or by bandits. The Jewish farmers would not risk their lives and take pains to rescue the produce. And yet, business had to go on. Trade in grain and farm produce was essential to the life of Judaea, as this was practically the only trade left to the Jews in that part of Palestine. There was no prohibition against the use of gold or silver coins. The same passage in Baba Meziah also rules: 'gold acquires silver, but silver does not acquire gold, etc.'. Thus, it appears that gold and silver coins were not rare with the Jewish merchant; but of what value was the money, if the produce that he was buying was threatened with fire. Something had to be done to protect the Jewish merchant. The assem- bly then rose to the occasion and modified the old law, ruling that only Meshi- kah, the formal possession of goods, should make the sale final, and not the mere transference of money. But later, when conditions in Palestine became better, possibly through the intervention of Rabban Gamaliel, and the farmers were not afraid lest their produce be burned, they began the practice of with- drawing from the sales if the goods had not been delivered, only on account of price fluctuation. Then the curse mentioned above was formulated, in order that no farmer might take advantage of an emergency law for his private benefit; and those farmers or merchants who broke their word were considered as despicable as the generations of the Flood, the Dor Hamabul, and the generation of Division, the Dor Haflagah. (Compare above mentioned article and A. Buechler, The Economic conditions of Judaea, London, 1912). Although Gamaliel's name is not connected with this Mishna, still we may consider it as one of his institutions. It was Gamaliel's system during his presidency at the assembly of Jabneh, that after a new law had been passed by a majority vote, the members of the minority had to submit completely to the majority, and give up their previous opinions on that law. Their decisions were taken off the records, their opposition was broken up entirely, and their names were forgotten. Thus, it became difficult to ascertain later the names of the members opposing certain laws. Suh laws are known as 'S'tam', and we can trace many of them back to the time of Rabban Gamaliel, when he ruled supreme. The Mishna under discussion is one of these 'S'tam' Mishna, and is one of those Halakot, to my mind, that was passed at the assembly at Jabneh. It is only in a Tosephta, in Tractate Damnai, that we find Rabban Gamaliel's name connected with a ruling of this nature. The Tosephta deals with the question of the produce stores of the Samaritans, vwho delivered their pro- duce to the imperial stores. Tlis fact, it seems, aroused the indignation of Rabban Gamaliel against the Samaritans, although he had previously favored them. #58 He then issued a prohibition against their slaughtered animals, and considered their bread as 'Pat shol Akum'. (Dammai, IV, 24). The later generations, however, could not understand why Rabban Gamaliel had changed his attitude toward the Samaritans. They did not know why he had, in previous years, recognized as valid Samaritan signatures on a 'Get', but later considered the Samaritans as enemies. The Tosephta in Dammai was interpreted as referring to Samaritan worship of birds on Mount Gerizim, while the word 'Sheniskalk'lu' could be ex- plained literally, 'they have gotten spoiled', namely, they turned to the Romans. Up to the year 70, during the war, they were united with the Jews against Rome. The above instances show how economic and political conditions affected some laws that were passed at Jabneh. To return to the question of the Ammonite who sought admission to the Jewish fold. In this case, too, we must consider the conditions of the time in which Rabban Ganaliel lived. Teupora mutantur, and times indeed had changed since the period of Rabban Gamaliol's great-grandfather, Hillel the Elder. Then, in the times of Hillel, Palestine was still comparatively independent, although that independence was a gift from Rome, bestowed upon certain persons, rather than upon the people at large. Also, the Jews had then, like other nations, a king, Herod, even though the latter was only a king of the Jews, and not a Jewish king. Yet, the Temple, the pride and glory of the Jewish people, still existed, the Jewish population numbered millions, and there was no cause to fear that proselytism would increase, and thus endanger Jewish life. But the situation was quite different in the days of Rabban Gamaliel. During the long war, from 66 to 70, the Romans destroyed, besides Jerusalem, also many other towns, forts and villages, and depopulated them. It is reported that over a million Jewish people perished in a very short time. Only those who surrendered to the Romans were spared, but their number was hard- ly more than fifty thousand. Among those who were spared were many priests of high standing, nobles and wealthy landowners, to whom Titus and Vespasian restored their former properties, as a reward for their surrender. Butthe whole of Judaea was declared the private property of the Roman emperor. The Jewish land was divided among 8000 Roman veterans, and othet military officials filled the remaining cities and villages. The poorer class were deprived of their meager holdings, and were forced to do various tasks for the comfort of the Romans. This fact is recorded in the Mekilta 19, 1, where we read the following: 'Rabban Johanan ben Zaccai said to some Jews: "You would not pay the shekel to God, now you have to pay fifteen shekalim tax to the govern- ment; you would not repair the roads and markets for the pilgrims, now you are forced to repair them for the government"'. No wonder, therefore, that under such circumstances, Rabban Gamaliel considered the acceptance of proselytes as threatening to the very nerve of Jewish life. (Compare A Buechkler, The Economic Conditions of Judaea). A very interesting question was addressed to Rabbi Eleazar ben R. Zadok ( a younger contemporary of Rabban Gamaliel) by his disciples concerning the proselytes (Horayoth 15a): 'I'hy do people prefer to marry a proselyte, #59 rather than a freed maid-servant?' This question throws light upon the status of proselytes at that time. The proselyte girls weredoubtless daughters of Roman officials, who had met Jewish young men. For Jewish men, marriage to a Roman girl meant the return of their land and property, and, in some cases, even the management of an imperial store. Consequently, such a marriage was considered a stroke of luck. Rabbi Eleazar ben Zadok, therefore, answered the question by stating that Roman girls were not 'Arur', they did not belong to the unfortunate class in which were many others. (Compare A. Buechler, The Economic Conditions of Judaea). There were probably also many Jewish girls who wished to marry Roman veterans, in order to improve their conditions. Rabban Gamaliel, realizing the danger threatening numerically impoverished Israel, if their young men and women were to marry non-Jews, even though the latter had embraced Judaism. He, therefore, decided to prohibit the acceptance of any proselytes. He was not only opposed to the acceptance of an Ammonite into the fold. He knew that it was impossible to consider any race as entirely pure, and he also knew that there were no pure Ammonites, as Rabbi Joshua so convincingly proved. Hence, 'Bo Bayom', on that day, and not before, did the Ammonite proselyte appear before the assembly, knowing well that Rabban Gamaliel's ob- jection would at that time be voted down and over ruled. And indeed, on that memorable day it was decided to accept proselytes. Gamaliel's temporary removal from the presidency brought to light a tractate on ancient Halakot and tradit- ions. These Halakot, called'Eduyot', 'Testimonies evidences of the sages', had been suppressed by Rabban Gamaliel, since those decisions had been voiced by the minority. Rabban Gamaliel was afraid lest those Halakot and the names of their authors bring about further strife and dissensions within the ranks of Israel; such had been the case during the time of Hillel and Shammai, when the Torah was almost divided into two Torahs. Gamaliel's love of harmony and unity drove him to takesuch drastic and undemocratic measures, and pass a ruling to conceal the names of the members of the minority groups. This ruling, of course, hampered the development and spreading of learning. Thus, 'Bo Bayom', on that day, the Tractate Eduyot, Testimonies, was compiled. And it was no easy task. The members of the assembly issued a call to all who had any recollection of old laws or decisions that had been over- ruled by a majority in the assembly house. About 500 forgotten Halakot and suggestions were thus brought to light. The Tractate Eduyot, 1, 5, even speaks of two weavers who appeared before the assembly and testified that they re- membered a long forgotten ruling about a certain question concerning ritual baths; the assembly promptly accepted that ruling as a law. They felt that dur- ing future controversies these laws might help to solve many Halakic problems. By accepting these old Halakot and mentioning the names of their authors, also, by opening the doors of the assembly to anyone who wished to pursue Jewish st-udy- the assembly opened, on that day, on the 'Bo Bayom', new channels for learning and added stimulus to the spiritual reconstruction after the great war. The spread of Jewish learning constituted the platform of new administration under the leadership of Rabbi Eleazar ben Azaryah. His short message to the assembly is characteristic, as it showed the spirit of a new age, an age of spiritual reconstruction. And these were the words of the new presi- dent: 'The words of the Torah are like a plant. A plant must grow and develop; #60 the words of the Torah, too, must grow and develop'... Growth and development, that is the new platform. Rabban Gamaliel's platform was economic reconstruction, but on Bo Bayom emphasis was laid on spiritual reconstruction. Committies were appointed with that purpose in view; measures were immediately taken to define which books can be accepted as parts of the holy scriptures (Yadayim, III, 5). The opinions of individual scholars were recognized, their names were given due mention, which had not been done before, and a new title was instituted, the title of Rabbi, which the sages of the following generations bore. The schools of Rabbi IshmaAl. and Rabbi Akiba *ere also the consequences of that memorable day. Rabban Gamaliel finally grasped the pre- vailing spirit, he saw whither the wind was blowing, and sought out Rabbi Joshua, his opponent. Rabbi Joshua was a needle maker, and Rabban Gamaliel found him in his house, blackened with soot. 'I see that you are using charcoal', said Rabban Gamaliel. 'Woe to the generation, whose leader you are', answered Joshua. 'You do not even know the privations of scholars, nor how they maintain them- selves.' A reconciliation followed, and Gamaliel was reinstated as presi- dent. He, then, helped, and became the leading spirit in the great spiritual reconstruction which followed the Bo Bayomm until another war broke out, namely, the Hadrianic war. This is how I understand the happenings on that memorable day in Yabneh, though it differs, to a great extent, from the story given in the books on Jewish history. Abraham I. Schechter, Ph.D. Providence #61 HAGGAI From The Hebrew From The Septuagint Chapter I. Chapter I. 1. In the second year of Darius the king, in the sixth month, on the first day of the month, the word of the Lord came through the agency of Haggai the prophet to Zerubbabel, the son of Sheal- tiel, governor of Judah, and to Joshuah, the son of Jehozadak, the great priest, saying: 2. Thus saith the This people has said: yet come to build the Lord of Hosts: The time has not House of the Lord. 3. And the word of God came through the agency of Haggai the prophet. 4. Is it time for you to dwell in your ceiled houses while this house is desolate? 5. Now, thus saith the Lord of Hosts: Consider your ways. 6. Ye have sown much and brought in little; you eat but you are not satisfied; you drink but you are not sated; you wear garments but are not warmed; and he who earns wages collects enough for a bag with holes. 9. You looked for much and there was but a little--when you brought it home I cursed it, because my house is lying deso- late and you are running each to his own house. 10. Therefore the heavens withhold the dew and the earth its produce. 11. And I have summoned a sword over the land and the mountains and upon the corn, and upon the wine, and upon the oil, and upon that which the earth produces, up- on man and upon animal, and upon all the labour of the hands. In the second year, in the reign of Darius the king, in the sixth month, the first day of the month, came the word of the Lord by the hand of Haggai the prophet, saying, Speak to Zorobabel the son of Salathiel of the tribe of Jouda, and to Jesous the son of Josedek the great priest, say- ing: Thus saith the Lord Almighty, saying, This people say, The time has not come to build the House of the Lord. And the word of the Lord came by the hand of Haggai the prophet, say- ing, How is it time now for you to dwell in your own houses with cupolas (or vaulted roofs), while My house is desolate? And now, thus saith the Lord Al- mighty, Consider your ways. Ye have sown much and gathered little; ye ate and not unto sufficiency; ye drank, and not to drunkenness; ye clothed yourselves and were not warmed therewith; and he that collected wages, collected for a pierced bag. Thus saith the Lord Almighty, Put your hearts to your ways; Go up into the mountain and fell timbers; build the house, and I will take pleasure in it, and I will be glorified, saith the Lord. #62 7. So saith the Lord of Hosts, Consider your ways. 8. Go up to the mountain and bring wood, build the House so that I may take delight in it and be honored with it, saith the Lord. 12. Zerubbabel, the son of Shealtiel, and Joshua, the son of Jehozadak, the great priest, and all the rest of the people hearkened to the voice of the Lord their God, and to the words of Haggai the prophet which the Lord sent to them and the people did fear the Lord. 13. Then Haggai, a messenger of the Lord, spoke the message of the Lord to the people: I am with you, saith the Lord. 14. Then the Lord stirred up the spirit of Zerubbabel, the son of Shealtiel, gov- ernor of Judah, and the spirit of Joshua, the son of Jehozadak, the great priest, and the spirit of all the rest of the people. 15. On the twenty-fourth day of the sixth month, in the second year of DCrius the king. Chapter II. 1. In the seventh month, on the twenty-first of the month, the word of the Lord came through the agency of the prophet Haggai, saying: 2. Speak to Zerubbabel, the son of Shealtiel, the governor of Judah, and to Joshua, the son of Jehozadak, the great priest, and to all the rest of the people, saying: 3. VWho among you is left who saw this house in its pristine glory and how do you see it now? Is it not as nothing in your eyes? 4. Now be strong, Zerubabbel, saith the Lord, and be strong Joshua the son of Jehozadak, the great priest, and be strong all the people of the land, saith the Lord, and work, for I am with you, saith the Lord of Hosts. Ye have looked for much, and a little came. And it was brought home, and I caused it to sprout. Therefore, thus saith the Lord, Because my house is desolated, and ye chase every one to his own house. Therefore the heaven refrains from dew and the earth keeps back her fruitage. And I will bring & sword upon the earth, and upon the mountains, and upon the grain, and upon the wine, and upon the olive, and whatever the earth brings forth, and upon men, and upon the cattle, and upon all the labors of their hands. And Zorobabel the son of Sala- thiel of the tribe of Jouda heard, and Jesous the son of Josedek the great priest, and all the rest of the people, the voice of the Lord their God, and the words of Haggai the prophet, as the Lord their God sent him to them, and the people feared (were afradi) before the face of the Lord. And Haggai the messenger of the Lord among the messengers of the Lord spake to the people: I am with you, saith the Lord. And the Lord roused the spirit of Zorobabel the son of Salathiel of the tribe of Jouda, and the spirit of Jesous the son of Josedek the great priest, and the spirit of the rest of the people, and they came, and they did the work of the House of the Lord Almighty their God. Chapter II. On the four and twentieth day of the sixth month, in the second year, in the reign of Darius the king. In the seventh month, on the one and twentieth day of the month sake the Lord by the hand of Haggai the pro- phet, saying: #653 5a. (The covenant which I made with you when you went out of Egypt). b. And my spirit is standing in your midst; do not be afraid. 6. In a little while I will shake the heaven, and the earth, the sea, and the dry land for thus saith the Lord of Hosts. 7. I shall'shake all the nations: the desirable things of all the nations shall come and I shall fill this house with glory, saith the Lord of Hosts. 8. Mine is the silver, and mine the gold, saith the Lord of Hosts. 9. Greater shall be the glory of the latter House than the original, saith the Lord of Hosts, and in this place I will place peace, seith the Lord of Hosts. 10. On the twenty-fourth day of the the ninth month in the second year of' Darius, the word of the Lord came through the agency of Haggai the pro- phet, saying: 11. Thus saith the Lord of Hosts, ask the priests for direction. 12. If a man carries hallowed flesh in the skirt of his garment and touches with his skirt bread, pottage, wine, oil, or any food, is it (also) hallowed? And the priest -nswered: No. 13. Haggai Said, If one 1:ho has been defiled by a dead body touches any of these (aforementioned foodstuffs), does it become defiled? And the priests answered: It is defiled. 14. Then Haggai answered: So is this people before me, saith the Lord, and so are all the works of thuir hands, and that which they sacrifice there is unclean. Speak now to Zorobabel the son of Salathiel of the tribe of Jouda, and to Jesous the son of Josedek the great priest, and to all the rest of the people, saying: Who is there of you who saw this house in its former glory? And how do you see it now? As though nothing were before you? And now be strong, 0 Zorobabel, saith the Lord, and be strong, 0 Jesous the son of Josedek the great priest, and let all the people of the earth be strong, saith the Lord, and work, for I am with you, saith the Lord the Almighty. And my spirit standeth in your midst; be of good cheer. For thus saith the Lord Almighty, Yet once I will shake the heaven and the earth and the sea and the dry land. And I will shake together all nations, and the elect of all nations and the elect of all nations shall come and I will fill this house with glory, saith the Lord Almighty. For great shall be the glory of this house the last above the first, saith the Lord Almighty, and in this place I rill give peace, saith the Lofd Almighty, even peace of soul for its own possession to every creature, to rebuild this temple. On the four and twentieth day of the ninth month, in the second year, in the reign of Darius, came the word of the Lord to Haggai the prophet, saying: Thus saith the Lord Almighty, In- quire now of the priests the law, saying, If a man take holy flesh in the hem of his garment, and with the hem of his garment touch bread, or pottage, or wine, or oil, or any food, will it be holy? And the priests answered and said, No. #64 15. 'Now consider from this day forward; Before a stone was placed upon another in the Temple of the Lord. 16. What were you? When one came to a heap of twenty measures, there were but ten, when one came to the winevat to drain fifty measures, there were twenty. 17. I smote you with blasting, mildew and hail in all the works of your hands, but you did not return to me. 18. Consider from this day for- ward from the twenty-fourth day of the ninth month, from the day on which the Temple of the Lord was founded, consider it. 19. Lo, the seed is yet in the barn, and the vine, the pomegranate, and the olive-tree have not borne fruite; from this day I will bless you. 20. "And the word of the Lord came to Haggai the second time on the twenty-fourth of this month saying: 21. Speak to Zerubabbel, governor of Judah, saying: I will shake the heavens and the earth. 22. And I shall overthrow: the throne of the kingdoms, and I shall destroy the strength of the kingdoms of the nations; and I shall over- throw the chariot, and those that ride therein; and the horses and their riders shall be brought down, each by his brother's sword. 23. On this day, saith the Lord of Hosts, I will take thee, C Zerubbabel ben Shealthiel, My servant, saith the Lord; and I will place thee as a signet; I.have chosen thee saith the Lord of Hosts. New translation from the Hebrew by Selwyn Russlander, Port Arthur And Haggai said, If one who is de- filed, the uncleanness on a corpse, shall touch any of these, will it be de- filed? And the priests answered and said, It will be defiled. And Haggai answered and said, So is this people and so this nation be- fore me, saith the Lord, and so are all the works of their hands, and whosoever draws near there, he shall be defiled because of their early getting, and they shall be in anguish from the face of their labors, and ye have hated the least in the gates. And now lay it to your hearts from this day and onward, before stone was laid on stone in the temple of the Lord. How ye were, when ye cast into a box of barley twenty measures, and there was but ten measures of barley, and ye went to the winevat to draw out fifty measures, and there were but twenty. I have smitten you with barrenness, and with wind-blight, and with hail-storm storm, all the work of your hands, and ye have not returned to me, saith the Lord. Submit now your hearts from this day and onward, from the four and twentieth day of the ninth month, and from the day that the Temple of the Lord was founded. Lay it on your hearts, whether anything shall be seen on the threshing- floor, and whether any longer the vine- yard, and the figtrec, and the pome- granate, and the olive-tree do not bear fruit; from this day I will bless. And the word of the Lord came a second time to Haggai the prophet, on the four and twentieth of the month, saying: Speak to Zorobabel the son of Salathiel of the tribe of Jouda, saying, I will shake the heaven and the earth, both the sea and the dry land. #65 And I will overturn the thrones of kings, and I will destroy the power of kings of the nations, and I will overthrow chariots and their charioteers, and horses and their riders shall come down, each one by the sword of his brother. In that day, saith the Lord Almighty. I will take thee, Zorobabel the son of Salathiel, My servant, saith the Lord, and I will set thee as a seal, for that I have chosen thee, saith the Lord the Almighty. New translation from the Septuagint by Rev. Malcolm Purcell Westminster Presbyterian Church Port Arthur Knowledge of Haggai arid his historical background is slight. Jewish tradition is rich in details. Thus we learn that Haggai was born in Cladea during the captivity and returned with Zerubbabel. In the Septuagint, he is listed as the author of Psalms CXII, CXLV, and CXLIX. In B.B. 15a, he is listed among the men of the great synagogue. Haggai is credited with various Takkanoth, such as the intercalation of Adar (R H 19b); a decision in favor of enlarging the altar, a decision permitt- ing the bringing of the sacrifices independently of the existence of the Temple (Mid. 11.1; Zeb. 62; Ycr Naz ii, 7); the organization of the priestly service into twenty-four relays (Tosef. Taani iii; Taan 28) and other references to his activi- ties include R H 9; Yeb 16a; Kid 43 a; Hul 137b; Bek. 57; Nan 53a. Haggai takes his place as one of those who helped to work out the foundations of the later priestly cult. He may not have been a priest, but surely he aided in establishing priestly authority. Although Haggai never saw the actual accomplishment of the building of the Temple, his work was of value in inspirng the people to continue in the do- solate land in which they found themselves in exile. The Book of Haggai describes a will to conquer, a will to succeed, and the accomplishment to some degree of these very aspirations. Sclwyn D Russlondcr Port Arthur #66 JEREMIAH CHAPTERS 50-51 The authenticity of chapters 50-51 of Jeremiah, containing a lengthy oracle against Babylon, has rightly been denied by most modern com- mentators. Jeremiah's general attitude towards Babylon, as expressed through- out his prophecies, is irreconcilable with the tone and contents of these chapters. The appendix of chapters 50-51 ( Ch. 51 verses 59-64) dates this oracle from the fourth year of Zedakiah's reign. But in chapter 28, a prophecy likewise dated from the fourth year of Zedkiah, Jeremiah definitely dispels the sanguine hope of the people for the speedy downfall of Babylon. In the letter sent to the exiles, he urges them to settle in the country of their captivity with a relative permanency, for deliverance would not be wrought by the Lord before the elapse of seventy years. In the later years of Zedekiah's reign, the prophet suffers himself to be branded as a traitor rather than change his conviction about the disastrous outcome of the struggle of his people against Babylon. How could we then explain such a sudden and diametrically opposed change in the policy of the prophet as we meet with in chapters 50-51? How could Jeremiah predict the speedy downfall of Babylon, if we find him prophecying, even after the destruction of Jerusalem, that Nebuchadnezzar would conquer Egypt without any exertion. They who hold these chapters to be genuine, argue that the thoughts developed here at length are briefly touched upon by the prophet in chapter 25, vv. 12-16, as well as in chapter 27 v. 7. In both of these passages Jeremiah predicts the downfall of Babylon. But the arguments based on these utterances are not conclusive. Although believing in the long dura- tion of the captivity, Jeremiah had implicit faith in the future restoration of the exiles. He gave expression to this conviction in the letter he sent to the exiles, (chapter 29), also in chapter 28 v. 22 and in many other passages. For the prophet knew that Babylon would not voluntarily free the captives, and that their return was conditional on the downfall of the empire. Hence, in chapter 27 v. 7, after giving the terminus ad quem of the captivity, it was natural for J eremiah to refer to the downfall of Babylon as the con- ditio sinequa non of the return of the exile. As to chapter 25 w. 12-26, the genuineness of these passages is very doubtful. Verse 15, which is the sequel of verse twelve is obvioul :;l- an interpolation, no less than v. 14, which is entirely missing in the Sep-ua- agint. Verse 26 b. though also absent from the Septuagint, may be justified, as Jeremiah could very well have included Babylon among the nations upon whom God's judgement would be executed, for, as previously mentioned, the prophet must have presupposed the annihilation of the Chaldean power. But, on the other hand, the relentless and vindictive hatred which spouts from chapters 50-51, could not have had its source in the heart of Jeremiah. For Jeremiah regarded the Chaldeans not merely as the cruel oppressors and despoilers of Israel, but as the executors of God's judgement, and as such, they fulfilled a divine purpose. This circumstance mitigated Jeremiah's enmity against them and toned down the harshness of his utterances regarding their final punishment. The prophecy itself offers proof which renders its date, as given in the appendix (chapter 51 v. 59), an anachronism. Chapter 51, v. 33 states explicitly that the overthrow of the city is imminent. The beseiging #67 enemy is addressed as if it were actually engaged in the conquest. The Medes and other northern nations are not only alluded to, but are mentioned by name, (chapter 51 vv 11, 27). Giving every allowance to the vivid imagination of the writer for anticipating future events and picturing them as if they were taking place in the present, this realistic and detailed description of Babylon's down- fall could not have been conceived at a time when the Chaldean empire was at the zenith of her glory. All this points to a time when the doom of Babylon was actually sealed and Israel's deliverance was awaited with an expectancy amount- ing to certitude. Besides these evidences, literary considerations compel us to as- cribe the prophecy to a later period than given in the appendix. Chapters 50- 51 bear such a close resemblance to the exilic prophecy in Isaiah chapter 13, that we have to assume a relation of dependence between the two. Isaiah chapter 13 itself lacks originality and depends on literary predecessors. Yet, its literary quality excels by far the standards of Jeremiah chapters 50-51. Hence, we are forced to the conclusion that the latter was written under the influence of the former and not vice versa. But some commentators maintain that the appendix has no connection whatsoever with the preceding prophecy. They consider it a narrative in itself, that may be historically true. The journey of Zedokiah to Babylon, though not mentioned elsewhere, if considered in the light of chapter 27 might be a histori- cal fact. Having joined the neighboring nations who had formed an alliance against Babylon, Zedekiah could have felt the need of appearing in person at the Chaldean court to allay Nebuchadnezzar's suspicion about his loyalty, Jere- miah's request to Seraiah to pronounce Babylon's doom upon his arrival to the country, is not out of accord with Jeremiah's hostile attitude to Babylon. This view, however, is not borne out by the text. For even if we admit that verse 60 b. is the interpolation of the writer of the oracle, verse 61 b. surely re- fers rather to the oracle than to the brief tWo sentences which Seraiah was commanded to recite. Besides, at a time when Jeremiah's whole effort was bent upon arousing his people to the invincible strength of Babylon and making it realize the great danger to which Zedekiah's perfidy exposed it, surely, at the height of such a campaign, he would not have counteracted his efforts by an em- phatic prediction of Babylon's doom. Thus, the appendix is just as spurious as the oracle itself. Nevertheless, its author cannot be identified with the writer of the oracle, for the closing words of 64 b. clearly indicate that the oracle finishes with verse 58. We can hardly give an analysis of these chapters, for they have neither any division nor any methodical development. They are full of repeti- tions and abound in passages literally taken from other writings of Jeremiah. Thus chapter 50 vv 41-43 and 44-46 are adapted from chapters 6 vv. 22-24 and 49 vv. 19-21. Chapter 51 vv. 15-19 is identical with chapter 10, w. 12-16. But while the writer inserts the other borrowed passages quite skilfully in the texture of his discourse, the last passage has no meaning in its present position. If we prefix chapter 10 v. 10 to the quotation, the transition would be lees abrupt. As to the date and author of these chapters, we have very little indication in the prophecy. From a number of parallel passages we nay corclude that it is of later date than Isaiah chapters 13-14, v.1-23. Nevertheless it is not a mere literary product of a post exilic writer in the disguise of Jere- miah. We have seen that the appendix does not belong to our author, and thus #68 it is the superscription alone that ascribes the prophecy to Jeremiah. But we know that in most cases the superscriptions were added by the compilers. Why then should we make an exception regarding this prophecy? The author of this chapter wrote his composition under Jeremiah's influence: he imi tater? and copied his great model, but we cannot prove that he pretended to write in the name of Jeremiah. As to the attitude of the commentators, who after painful search- ing, find striking parallels scattered all over the biblical canon, for each word and particle occurring in these chapters, let us emphatically say that the author of this oracle wrote in Hebrew and had the same privilege to use a Hebrew vocabulary as any other prophet. To maintain like Duhm that for instance chapter 50, v.7 is an imitation of Zech. chapter 11 v. 5 is, to say the least, ridiculous. The verse is certainly based on Jeremiah Chapter 2, v.5. In all probability the writer of Jeremiah chapters 50-51 lived shortly before the downfall of Babylon, when the thought of vengeance, so pro- nounced in this oracle, was fed by the bitter hatred for past wrongs and the prospect of deliverance in the near future. Samuel Rosinger Beaumont #69 JERUSALEM AS SEEN BY THE JEWISH TRAVELERS DURING THE CRUSADES Thanks to the Crusades, the center of gravity of world history shifted to Palestine for two centuries. The cream of Europe's knight- hood and the dregs of the world's scum hastened to the Holy Land in order to perform the "will of God"; which, when interpreted, meant to redeem the Holy Sepulchre and to pillage and massacre the Infidel. They advanced towards Palestine. Other thousands sailed equally anxious to attain their goal, equally certain of the outcome, the raising of the Cross over the battle- ments of Jerusalem. There was a long and bitter fight before the city fell in 1099. With a combination of religious frenzy and ruthless cruelty, the vic- tors attended a solemn service of thanksgiving after they had massacred every last Jew and Moslem in the city, killing them with the same fervor that accompanied their prayers. But the story of the wretched Latin Kingdom or the triumphs of the chivalrous Saladin, hardly concern us here. Our concern is for the experiences of those Jews who ventured into the Holy City and lef t behind them accounts of what they saw when it occupied the center of the world's stage. These Jewish travelers came with strange, purblind eyes. They paid scant attention to the Palestine of their day which was covered by Christ- ian shrines and governed by foreign lords. What they sought was the remains of the past, that past which was theirs alone, of which nothing on earth could rob them. And just because they ignored what the Christian writers emphasized, be- cause they looked at the hills and valleys about Jerusalem with the hungry eyes of exiles returning home, their descriptions are invaluable to us. We may associate their sentiments and emotions with the poetry of that sweet singer, Jehuda Halevi, who sang and dreamt all his life long of the day when he would finally set eyes upon Zion. At last, he left his home in Spain, he braved a long sea voyage, and he gazed upon the city which had inspired his greatest efforts. Halevi could describe that yearning which burn- ed inarticulately in the hearts of other Jews, and he wrote of it: "0 city of the world, with sacred splendor blest, My spirit yearns to Thee from out far- off west"-----. The first of the Jewish travelers who entered Palestine dur- ing the Crusades, and whose description has been preserved was Rabbi Benjamin ben Jonah, (called Benjamin of Tudela, because he came from Tudela in Navarre). One of the outstanding travelers of his age, he set off from his native city and took Europe, Western Asia, and adjoining parts of Africa in his stride. Included in his descriptions are accounts or such out of the way places as Persia, India, and China, although it is hardly likely he visited them. Benjamin's contribution to our knowledge of the Middle Ages can scarcely be underestimated. As writers of his time go, he shows rare understanding and accuracy. Not only that, but he includes much precious in- formation which cannot be found elsewhere. To give but two examples of his transcendent importance, one need only point out that he was the first European #70 author to mention China and that his account of David Alroy is the main source of our knowledge concerning that notorious charlatan. When did Benjamin visit Jerusalem? Your critical scholars seize upon certain allusions to Pope Alexander III, and place the time of his visit to Palestine somewhere between 1168 and 1170. . 1. "Essay on the Geographical Literature of the Jews" in Asher's edition of Benjamin's_Itinerary Yol._II,_255. -- ------------------ Benjamin of Tudela has proved to be a mysterious character about whom we know almost nothing. He set out on a long journey which carried him through many lands, and no doubt, he was obliged to endure many hardships, but yet, no one is able to explain what reasons prompted him to leave his home in Navarre and wander into regions which were not known to his fellow townsmen, even by name. Of course, writers have been busy constructing theories. As in the case of all the travellers with whom we deal, Ben- jamin's journal suffers severely from confusion due to scribal errors and omissions. The details with which be describes one town and the haste with which he passes over another of equal importance are strong proofs of this fact. Apparently, editors pruned wherever the subject matter did not interest them, in some cases leaving but a bare mention of a community. Even as early as 1429, Rabbi Isaac Israel of Pisa commented upon this fact. "Apparently", he wrote, "this book of Rabbi Benjamin is incomplete, but I have not found any more of the manuscript." 1 The next Jewish traveler who attracts our attention came L. Esienstein "Ozar Massaoth" 17 to Palestine about fifteen years after Benjamin. His name was Rabbi Petachya of Regensburg, and, unlike Benjamin, he was an Ashkenasic Jew. His travels carried him through Europe and the East, but his journal has been tragically mangled. This was to a large extent due to the fact that he entrusted the task of compiling it to others. The editor seems to have been Rabbi Judah the Pious, for he is mentioned as having refused to include certain facts concerning an astrologer of Nineveh lest he be suspected of believing in his claims. 1 The utmost confusion shown in various parts of the account points to the carelessness or incompetence of those responsible for editing. Petachya left his notes on various scrolls, and the compiler failed to unite them properly, removing sentences from their contexts. The account of Jerusa- lem is thus divided, and extraneous material is introduced between the two parts. Petachya's visit to Palestine occurred between 1174 and 1187. Petachya is not so valuable to the student of the time as Benjamin, for he does not give as many important facts and details about the country. His account is characterized by fantastic legends which he seemed to gather wherever he went. In the foreword it is even stated that: "He wrote down all the rarities,.miracles and wonders of the Holy One Blessed Be He which he saw and heard."2 1. L. Grunhut, "Rundreise des R. Petachjah aus Regensburg" 2. Grunhut, 1. Of course, one may blame the shortcomings of Petachya on his compiler who admitted in certain instances, as we have seen, that he employed his editorial prerogative in leaving out details when he saw fit. We know as little about Petachya's life as we have learned of the career of Benjamin. Regensburg was his home; he probably came of a good family. Petachya has something to say about his own appearance, and states that inasmuch as he was well dressed, people imagined"him to be rich. 1 The third man who comes within our range is Rabbi Jacob ben Nathaniel the Cohen. Unfortunately, his account is broken up into fragments which seem to have been shuffled and then published in the most senseless, incoherent fashion possible. We know absolutely nothing about the man or whence he came. Even a brief and blundering foreword to his work is lacking.. Attempts, however, have been made to discover his country by an analysis of his Hebrew style, but this has not been successful. From the tone in which he concluded his records, one may judge that Jacob came to Palestine as a pilgrim. He expressed the hope at the end that in accordance with his merit in writing the - - - - -- - - - - - - - - -1--- 1. _Grunhut,1_6 _G -- work, he would deserve to return to the Land of Israel and die there. The date of his journey must be set before 1187, because we are told that the Christians occupied the land. There is no available proof, however, which will help us fix the date of his visit more closely. When we encounter our next traveler, Samuel ben Simson, political conditions in Palestine had been revolutionized through the victories of the irresistible Saladin. No longer was the Cross to be seen on the battlements of Jerusalem; it had been supplanted by the restored Crescent, and Christian Palestine was now only a slender strip along the seacoast. Samuel ben Simson made his visit at the beginning of the thirteenth century and according to his own testimony, he left Jerusalem in 1210.2 He traveled with a great scholar, Rabbi Jonathan ben David the Cohen, of Lunel in Southern France, and it is therefore surmised that Samuel was likewise a Provencal. Although we know little about our author's life, he himself made his record of travel a personal journal couched in the first person, and he supplied little details which the other chroniclers, in a more objective mood, disregarded. The fifth and last traveler who has given us information concern- ing the Holy Land was a certain Rabbi Jacob of Paris. From an extant letter we learn of the purpose of the journey and some scant facts about the man who '-made it. The mission which Jacob undertook was the collection of money from distant communities for the large academy attended by three hundred students over ich -- - - - - ---- ---- - - - 1. Grunbut, 6 2. Heinrich Gross, "Etude sure Simon ban Abraham Sens," Revue Des Etudes Juiver, Vdl VI, 177 5. EisensteinL 62 Rabbi Yechiel presided in Paris.t Yechiel bon Joseph wrs the famous Rabbi- who took part in the controversy with Nicholas Donin which preceded the de- struction of the Talmud. As Yechiel became head of the Academy in 1224 and continued in that capacity until the unsafe conditions of life drove him to #72 Palestine in 1244, we must place the journey of Jacob between those two dates. In Palestine, Jacob was particularly interested in the graves that he saw there. The first words of an introduction attached to his journal declare: "These are the journeys of Israelites who desired to go and prostrate themselves in prayer at the tombs of the saintly and holy ancestors in the Land of Israel." 2 The author makes good this claim by proceeding to furnish us with facts concerning some eighty tombs in Palestine about which he discourse with more or less detail. To judge from Jacob's account Palestine must have been one vast mausoleum. Not that he quite neglected other matters; but sepulchres were always of paramount importance to him. These Jewish travelers covered only a brief period of the Crusades. The age itself stretched over two full centuries, running from 1099 to 1291. Only eighty-five years of this is described by our authors who, roughly speaking, came to Jerusalem between 1168 and 1245. What is more, their records compared with the descriptions of Arab and Christian writers, are all too brief. So many de- tails found elsewhere are overlooked by the Jews who came to Palestine. And yet, - -- ---- - ---- -- -- - --- -- - - 1. Carmoly "Itineraires de la Terre Sainte" 183 2. Eisenstein, 66 thanks to heir superior educa ion7 they came Belter-equrppe fpe o appreciate the country than the Gentiles. And what is more, they covered much of a purely Jewish character in which the others naturally had no interest. Let me quote here the words of a Christian scholar, Colonel Claude Conder: "Crusading typography subsequent to 1100 A.D. is so hopelessly obscured by the ignorance of priests and pilgrims alike, and by the continual transference of sites from their true place known by the early Christians into new positions, quite irreconcilable with the requirements of the original narrative, that it must be considered entirely valueless in fixing the real sites." "The mediaeval Jewish pilgrims appear, as a rule, to have had a much more accurate knowledge, both of the country and of the Bible, their assertions are borne out by existing remains and are in accordance with scriptural narrative, and the indications contained in their writings frequently appear to be of the greatest value. " Here, then, is the justification for the study of mediaeval Jerusalem through Jewish eyes. Jerusalem under the rule of the Latin Kingdom was a city of strange contrasts. It belonged to the Orient, situated as it was in the Judaean mountains with almost five centuries of Moslem rule behind it; and yet now that the Christ- ians had returned, the Franks did everything in their power to make the city a replica of the feudal states in the West. The mosques were converted into churches; new buildings were erected in the Italian-Norman style; the old citizens 073 having been massacred or expelled, their place was taken by a motley throng which included Jacobites, Syrians, Greeks, Georgians, Franks, and every other race in Christendom.2 1. Claude Conder "Christian and Jewish Traditions", Palestine Exploration Fund Quarterly Statement, 1877, p. 36 2. Adler, 24 Jerusalem at that time had practically no Jews at all. Petachya found but one living there. When we tuin to Benjamin, however, we see the statement: "About two hundred Jews live in one corner of the city beneath the Tower of David."'l Here we have a glaring cdftradiction, for such a discrepancy can hardly be looked at in any other light, when we consider how few were the years which.intervened between the visits of the two travelers. Nevertheless, if one goes to the Roman manuscript of Benjamin's itinerary, he will find the declara- tion made that there were four Jews in Jerusalem.2 In this case the "four" was expressed by the letter dated,(4), and it is very plausible to assume that some copyist read the as a Keth (200), and interpreted the Jewish population as two hundred. I am in favor of discarding two hundred as the number and re- placing it by four. It should be noted that Benjamiti said that the Jews lived under the tower of David. At the same time, there was a quarter in the north- eastern part of the city which the Crusaders called the Juiverie. Without.the slightest evidence that any Jews were living there during this period, certain Christian scholars have jumped to the conclusion that there were other Jews in the city whom Benjamin failed to mention.5 The truth of the matter is that the quarter known as the Juiverie had been the ghetto before the Jewish population was annihilated. One can point to various cities in Europe where, when the last Jews were gone, their name still clung to the neighborhood in which they had -- ------------------------------------- 1. Adler, 25 2. Grunhut, 29 5. Claude Conder, "The City of Jerusalem", 286 dwelt. The Giudecca of Venice bears their name today. Furthermore, when the Jews were readmitted to England by Cromwell, they found a street in London still known as Old Jewry which had been a center of Jewish life four hundred years be- fore. In the case of Jerusalem after the restoration of the Turkish rule, the Jews crowded near the Gate of Zion at the opposite end of the city. 1 And there they have lived continuously to this day. Benjamin tells us details about the Jewish dyers of Jerusalem, who had their own dye-house, and maintained their monopoly in the city by a small rent to the king year by year. The one Jew whom Petachya found in Jerusa- lem was a certain Rabbi Abraham, a dyer, but Petachya says that he had to pay a heavy tax to the king for the right to follow his occupation.2 Benjamin met him also, and called him "el Constantini", an allusion to the place of his origin. Benjamin also stated that he was a pious hermit, but said nothing about the fact that he was a dyer. Dyeing seems to have been the favorite Jewish occupation cf the Middle Ages; a century before the Crusades, Mukaddasi, the Arab geographol had mentioned how Jews predominated in that calling.5 #74 The Jewish pilgrims who drew near to the city were well aware that the ancient glory of Zion had departed; cruel and fanatical strangers held sway in the Holy City; the site of God's Temple itself was desecrated by a 1. Guy Le Strange, "Palestine under the Moslems", 215 2. Grunhut, 52 5. Le Strange, 215 ----------------------------,---------------- Christian shrine. Small wonder, indeed, that the Jewish travelers approached the goal of their heart's desire with weeping and wailing. "The great cohen from Lunel and I came to Jerusalem from the west, and vhen we saw it, we tore our clothes as was proper for us; our emotions welled up within us, and we wept bitterly", said Rabbi Samuel ben Simson,l thus fulfilling the Talmud's command. Jacob of Paris made the ceremony accompanying the approach to Jerusalem somewhat more elaborate. He describes the arrival from the north as follows: "When one reaches Scopus, he sees Jerusalem from there, and he makes a tear (in his clothes). And when he comes to Jerusalem he goes up to one of the ruins from which he sees the Mountain of the House, the wall of the Outer Court, the Court of Women, the Court of Israel, the site of the Altar and the sites of the Temple, the Sanctuary, and th- Holy of Holies; then one makes a second tear for the Temple."2 These scenes of mourning for the Jerusalem that had been and for the Temple which was no more, indicate the complete dejection with which the Jewish pilgrims approached the city. Benjamin called Jerusalem a small city with three walls by way of protection.3 He said that the city had four gates, although Christian and Moslem sources speak of many more. And yet, this failure to mention the names of the other gates, was no oversight on his part. He spoke of the main entrance to the city, and did not consider the others worthy of discussion.4 The gates he referred to were: the Gate of Abraham, more frequently known as the Damascus 1. Eisenstein, 65 2. Eisenstein, 66 3. Adler, 25 4. "The City of Jerusalem" (PalestinePilgrims' Text Society)_ _ Gate, to the north, the Gate of David, now familiar to visitors of Jerusalem as the Jaffa Gate, on the west; the Gate of Jehoshaphat, St. Stephen's Gate today, on the east, near the Temple site; and the Gate of Zion on the south.1 Only the western gate goes back to Biblical days. Even at the time of the destruction of Jerusalem by Titus, the Gate of Jehoshaphat and the Gate of Zion were not in existence, the latter not having been established for the obvious reason that the city and its walls extended farther south in the days of Herod than at the period of the Crusades. Later, Benjamin has reason to refer to a fifth gate of a different type, which I shall discuss in another connection. #75 The Gate of David is the only one going back to Biblical times, and in ancient days was known as the Valley Gate. The many pilgrims, such as Samuel ben Simson, who made their first entry into Jerusalem through its portals, were attracted by a large tower nearby, known as the Tower of David. This build- ing which had an origin far later than the times of the poet king, is neverthe- less, responsible for the alteration in the name of the gate by its side. While the tower does not go back to the Biblical period, its antiquity is well estab- lished by the Herodian style of its masonry, and by the fact that its dimensions are the same as those of the Tower of Phasaclus which Josephus describes in his "Wars"2. This then was one of the defences of Jerusalem when Titus beseiged the city. Benjamin does not attempt to give the date of the tower's erection, but contents himself by saying that it was built by "our fathers."l He makes it 1. Adler, 24 2. V, iv, 3; Charles Warren and Claude Conder, "The Survey of Western Palestine. Jerusalem." 267 clear, however, that they were responsible only for the lower part of the wall, and that the Moslems built the remainder. Jacob of Paris likewise fails to dis- cuss the origin of the building. He merely remarks that the huge stones proven it to have been an ancient stiicturei2 Colonel Conder, the authority on Palestinian archeology, is of the opinion that the Crusaders, and hot the Moslems, built the additional portion.3 The first place which every Christian pilgrim sought, was the spot which to him was sacred above all others, the reputed grave of Jesus in the Church of the Holy Sepulcher. The Jewish visitors alluded to it, but with brevity which betrayed their feelings concerning this great shrine of Christendom. Petachya mentions the location of "the Grave" as he called it.4 Benjamin said: "The great church which is called the Sepulchre is there; that is where the man whom the erring ones visit, is buried."5 Jacob ben Nathan actually had the courage to visit the spot, for he speaks as follows: 1. Adler, P. 23 2. Adler, P. 25 5. "The City of Jerusalem" p. 134 4. "The City of Jerusalem" p. 55 ----------------------------------------------- "I stood at the grave of ....... (the man, which is) four cubits from the House of Stoning," 1 According to this, he found (at least to his own satisfaction) the location of the House of Stoning, something which modern scholars have failed to do. Not far from the Holy Sepulchre was the huge establishment of the Knights of St. John or Knights Hospitalers, who very generously aided the poor and the sick. Benjamin gave the number of Knights as four hundred, and mentioned how they cared for the sick, both in life and in death.2 Their #76 ministrations to the poor are mentioned by Petachya also.5 There was one church in Jerusalem towards which all the Jewish pilgrims turned with mournful eyes, recalling with sorrow the time when God's House in all its glory had occupied that same spot. Titus destroyed the Sanctuary; Hadrian desecrated the Holy site with a Temple of Jupiter; at a later time, the Moslems, not without great reverence, erected their mosque; and now the Christians had transformed it into a church, the Templum Domini. This name was given in the artless belief that the building was none other than the ancient Temple of the Jews.4 The Jewish pilgrims knew that the building dated back no father ---------------------------------------------- li Sippur Massaoth, 15; 2. p. 25 5. p. 55 4. John of Wurzburg "Description of the Holy Land" (Palestine Pilgrims' Text Soci -t)p, 15 ______ -_ -- -- -- --- than the Arab occupation, but Benjamin made the same error which many later writers have fallen heir to, declaring that the builder of the mosque was the Caliph Omar,l when it really wds 'Abd al Malik who ruled a half century later.2 Petachya tells a strange tale about the building df the mosque by a caliph who desired the Jews to have exclusive use of it. He reports as follows: "Some leaders came and addressed the Arab ruler, 'There is an old man among us who knows where the Temple and the Outer Court stood.' The king forced the man to appear before him. He was fond of the Jews, and he said, 'I will build a Temple there, and no one shall worship there but the Jews.'" 5 It is very possible that neither Benjamin nor Petachya gained entrance to the church, but it is clear that Judah of Paris was inside for he has left us a detailed description of what the interior of the Dome of the Rock was like. His visit was made when the building had- been restored by the Moslems to its original state, that of a mosque. He wrote: "The Arab rulers erected a very imposing building about the Sh'thiyah Stone, and they made it a mosque. Above it they built an exceedingly beautiful dome. The edifice is built upon the site of the Holy of Holies and of the Temple. In front of the building beside the altar they set up columns support- ing the dome which rises above them. It appears that this is the site of the middle altar which was in the Court of Israel."4 P 24 John of Wurzburg "Description of the Holy Land" Conder, "The City of Jerusalem" 259, 240 Grunnut, 32 Eisenstein, 67 #77 The Sh'thiyah Stone, concerning which Judah of Paris spoke, is a large and irregular rock invested with many Talmudical legends. It was the spot upon which Abraham prepared to sacrifice Isaac; it was the pillow that Jacob used when he dreamed of angels climbing heavenward (Westminster Abbey has a rival claimant for this honor),; it was the stone upon which the Ark stood; it is in fact, the navel or center of the whole world.1 Not con- tent with all that the Talmud had to say about the rock, the Moslems invented new tales concerning it, some of which were connected with Mohammed himself. Jacob of Paris went on to tell about the Mohammedan services which were held in the Dome of the Rock, but not without a sneer of superiority. He said: "The Moslems gather there on their festivals in very great numbers, and surround the place in a sort of chorus, as Israel was wont to do on the seventh day of Succo h to make an improper comparison."" In this manner did the Jews refer to the sacred ceremonies of the ancient Temple, now invested in their minds with so much of holiness and grandeur. The Jews who came to Jerusalem when it was under Christian rule, must have been struck by the fact that this church was bare of all images in contrast to other Christian houses of worship. Both Benjamin and Petachya mention the fact, and the latter explains the phenomenon by repeating some traditions which must have developed by way of explanation for so strange an omission. He reports: "The gentiles came and set up crosses there, but they fell. Theythen fastened the Cross to the joists of the wall; nevertheless, the Houste of ----- -- -- -- -- -------------- -------------------- -- -- -- -- ---- 1. J. Horovicz "Geschichte des Sch'thijasteines", passim 2i Eisenstein, 67 ---------- ----------------------------------- -- -- -- -- --- Holies would not permit it to stand,1 Not far from.the Templum Domini in the Haram area stood another building which, in Moslem days, had been known as the Aksa Mosque, but which was now a church known as the Temple of Solomon. The Knights Templars made it their headquarters, and incidentally, owed the name of their order to thy building. Benjamin, who had not been deceived into believing that the ancient Temple was still standing, was credulous enough to imagine that the Templars actually made use of Solomon's palace.2 Of the Knights Templars, themselves, Beijamih Says: "Thirx hundred of them go out every day to the tournament. Besides, these, there are the knights who have come from the land of France and other Christian countries who pledge them- selves to serve a certain number of days or years until the fulfillment of their vows."5 One is naturally curious to learn about the reliability of the traveler's statement that they numbered three hundred, but the Christian writers seemed less interested in furnishing statistics about the order than in giving us facts concerning the more sordid aspects of their activities, something which Benjamin ignores. John of Wurzburg, who visited Jerusalem at this time, was outspoken enough to reproach them for treachery to the Christian arms.4 Ben jamin remarks: "In Jerusalem connected vith Solomon's palace are the Stables which he erected with great stone, thus making a very strong building. No edifice comparable to this may be seen in all the world."5 Theoderich writing at just the same time, also waxes enthusiastic on the subject: 1. Grunhut, 55 2. p 23 3. p. 23 4. "Description of the Holy Land" 5i P, 24- horse with grooms."l After such hyperbole, it is well to know the dimensions of the Stable. They are ninety-one yards long and sixty-six yards wide, and contain thirteen galleries.2 When Jacob of Paris came to Jerusalem after the return of the Moslems, he apparently failed to hear of the tradition of Solomon's Stables, but he seems to have referred to the substruction in rather vague terms. He wrote: "There are caves opening into the wall of the Outer Court and extending under the Mountain of the House. Some say that they reach as far as the Sh'thivah Stone."5 Nevertheless, they became known as stables because they were so used by the Crusaders, and even to this day, one may see the marks of the holes to which their horses were tethered. Herr Schick believed that the walls were build by Herod as foundations for a great hall,4 but it appeared to Dr. Immanuel Benzinger that the substructions themselves were erected during the Arabic period.5 Colonel Conder on the other hand, was of the opinion, that the reconstructions go farther back to Justinian. #z79 ^lltD1 i; /9 Just without the north side of the Haram stands the remains --------~------------------------------------- 1. "Description of the Holy Places" (P. P. T. S.) 31 2. Baedeker "Palestine and Syria" 62 5. Eisenstein, 67 4. "Reports from Jerusalem", Palestine Exploration Fund. 5. Baedeker, 62 ----------------------------"--------"" "--------- of an ancient pool, known as the Birket Israel. Benjamin visited, and des- cribed it as the place where the priests washed before their sacrifices. He further pointed out that Jews who visited it wrote their names on the wall.1 An interesting feature of the Haram Area is a certain double gate on the eastern side which has been blocked up for centuries. This gate was sacred to each of the three sects Judaism, Islam and Christianity, and each one had a different reason, strangely enough, for regarding the place as holy. Petachya called the gate the Gates of Mercy, using the plural because of its dual nature. Ho says: "There is a gate in Jerusalem known as The Gates of Mercy, which is blocked with stone and plaster so that no Jew and likewise no Gentile, can pass through it.; ....... The Jews have a tradition that the Shekinah went into exile through this gate, and that some day it will re- turn through it."2 The Moslems gave each side of the gate a different name. According to Ibn 'Abd Rabbih, a tenth century writer, one side was known as the Bab at Taubah, the Gate of Repentance, "where Allah vouches saved repen- tance to David". The second gate followed the Jewish usage, for it was called the Bab at Rahmah, the Gate of Mercy. This was the gate "of which Allah has made mention in his book, saying 'A gate within which is mercy; while without the same is Torment'".2 The place of torment mentioned is the Valley of Jehoshaphat. \ --------------------- ---------------------------- ----- _- -.--- S1. Adler, p. 24 2. Grunhut, 34-35 3. Le Strange, 165; Koran LVII _,- ------------------ - ------- -------------------- The Jews might believe that the Shekinah had departed through AMe he gate' they might live in hope that one day it would make its return by the same route; but the Christians felt that Christ himself had ridden through it on Palm Sunday when he came to Jerusalem to die for the salvation of man- kind. They therefore called it the Golden Gate. During the age of the Cru- sades, it was blocked with stone and plaster which was only cleared away for the sacred process>tn held yearly on Palm Sunday.1 (Theoderich says that it was also open on September 14th, the day of the exaltation of the Cross.)2 During exactly the same period in which John of Wurzburg and Theoderich wrote, Petachya paid his visit, found the gate blocked, and not knowing that it was opened at regular intervals, solemnly proceeded to tell a legend about an attempt to open the gate which was frustrated by divine intervention. He writes: "One time the Gentiles desired to remove the obstruction and open the gates but the Land of Israel shook, and there was a commotion in the city until they ceased."3 This legend given by Petachya is repeated by other Jewish writers who came after him.4 Petachya noted the fact that the gate was opposite the Mount of Olives, and then made the statement that it was higher than the mountain itself. This is untrue, for the highest point on the Mount of Olives is 2680 feet above sea level,5 while the Haram Area attains an altitude on only 2440 feet. Suddenly, Petachya recalls some applicable Biblical verses, and he proceeds: ----------------------------------------- 1. John of Wurzburg, 19 2. Theoderich, 36 5. Grunhut, 34 4. "Samuelband", Mekize Mirdamin, 27, 47 5. Grunhut, 35 -----------------------------------;, , "From the Mount of Olives one may see it (The Gate of Mercy). 'And His feet shall stand in that day upon the mount of Olives (Zechariah XIV, 3).' 'They shall see eye to eye the Lord returning to Zion (Isaiah LII, 8).' His route will be through that gate. Men pray there." And now we come to an inexcusable blunder which Benjamin made in locating the Gate of Mercy. He does not place it at the east end of the Haram where it should be, but instead, he associates it with the Wailing Wall on the opposite side, He says: "In front of this place (the Templum Domini) is the western wall, one of the walls which belonged to the Holy of Holies. It is called the Gate of Mercy, and thither all the Jews go to pray at the wall of the Outer Court."l To this day, notably late on Friday afternoon, the Wailing Wall is the gathering place of Jews who come to mourn the passing of the former glory of Zion. This happens to be an authentic sito, probably the most ancient remain of the Sanctuary which we possess.2 #81 Jacob of Paris gave a description of the wall of the Outer Court which he stated surrounded it on four sides. He said that it was 360 cubits long. Actually, the Outer Court was 135 cubits square, but if we add the 187 cubits that comprise the length of the Inner Court, we obtain a total length of 522 cubits. 3 This is probably what the author meant by this 360 cubits. The height of the wall, he said, was sixty cubits. The ancient cubit was not a fixed measure of length, but by assuming it to be equal to sixteen inches, as Colonel Conder does,1 we find the height of the wall to be -- -- -- -- -- -- -- -------------- ------------- -------------- -- -- 4. Adler, 24 2. "Survey of Westerh Palestine"., 194 51 Jewish Encilotaedia "Temple, Plan of Second", Vol XII, 90 eighty feet. Ih that Gase, JaIob of7Pariss mad e ae vey ciirite estiiatfe, foF ~ modern measurements have proven the southeast angle of the wall to be 77.5 ft. high.2 Jacob o0 Paris thought that in olden days the wall was another sixty cubits higher.3 This particular traveler also found a mysterious synagogue in Jerusalem which is mentioned nowhere else. Let me quote him: "There is a synagogue of Elijah the Prophet- may his name be remembered for good: in the heart of Jerusalem. The place for the Scrolls of the Law is hewn out of the wall, and four letters are carved in the stone."4 The four letters are those used in writing God's name. One more comment about Jerusalem itself from Jacob of Paris. He remarked on its present location, and pointed out with a certain amount of accuracy that the city had shifted since ancient times. He said: "The city of Jerusalem is now to the west and norfi of the Mountain of the House, It is not as it was in former times to the south of the mountain, concerning which it was said, 'Whereon (the mountains) was as it were the frame of a city on the south (Exekiel, LX, 2)', and also' Mount Zion the uttermost parts of thenor:th (Psalm XLVIII, 3)'. For the mountain was to the north of Jerusalem."5 At the end, our friend became quite confused, and apparently took Mount Moriah (the Mountain of the House) for Mount Zion. In other connections, however, he identified Mount Zion correctly. 1. "City of Jerusalem", 125 2. "Survey of Western Palestine". 141 3. Eisenstein, 67 4. Eisenstein, 67 5. Eisenstein, 67 Austin Abram Vossen Goodman Austin Abram Vossen Goodman #82 MEMORIAL TRIBUTE Life has no ache which compares with that of death. To see a loved one who but a short while ago lived and moved among us, lie mute and motionless; those lips erstwhile voing words of love and cheer now closed, sealed---those eyes through which glowed the deep records of a human soul, all dull, unconscious; to feel no more the loving touch of a tender hand--- to share no longer our joys and sorrows; these are poignant moments in human life which fill us with dumb despair. How can a loving Father so afflict His children? Yet God has given us the bosom of hope, Since man first suffered the pang of death's separation, they have refused to believe that their dear ones are gone forever.... And you who in this solemn hour call to mind your dead--consider the fact of existence. Here is human life, its thoughts, its struggles, its sacrifices, its failures, its consecration and its loves. Here is the story of the age-long evolution from the first germ of life to the heart and mind of man, the story of the slow and painful rise from brute to divinity. Here is history's record of the struggle for freedom and stability, a struggle of race against race, people against people, a story thriling with the splendor of high words spoken, sanctifbd by the names of heroes and saints and martyrs. Here is the story of human achievement. Here above all, are the stories of the lives of men and women--lives shot through with the pain of unfulfillment --with the injustice of unmerited failure or of undeserved success--lives like yours and mine---simple, humble lives, so often incomplete. These facts cannot be understood unless they point onward to completion. I believe in the existence of God. I believe that there is divine justice in the world. Without immortality there can be ho justice. Shall youths cut off in their budding manhood, removed before the natural measure of their life is full, be no more? Shall all those who spend their days in agony of toil and pass in weariness have no opportunity to know joy and gladness? What a piece of work is man! Has God created us only to destroy us? Have all the efforts of the ages to make from a savage heart an aspiring soul been for naught? Remember your joy in the work of your hand? Shall He who moulded as a potter mouldshis clay suffer His handiwork to be destroyed forever? 0, be comforted, ye who mourn. Think not your dead are lost to you. That form you laid to rest was not the loved one of your heart--it was but his earthly habitation. There is such a thing as the human spirit. The soul exists--it does not die; it is immortal! Morris S. Lazaron Baltimore #83 THE NEED OP A SCIENTIFIC APPROACH TO THE STUDY OF RELIGION All knowledge of the external world is, elementally, made up of either sense impressions or mystical revelations (with the latter needing the test of the former to prove their reality). The sense impressions fundamentally give us, at best, little islands of data, infinitossimal reference points, with- out meaning or connection except as we learn to supply them by fitting them in- to the totality of our i7oltanschauung. By the use of classification and generalization (thinking) we link the isolated and discrete elements into percepts or concepts; and we label those as "true" when we find them to be mutually consistent and as "illusions" or "delusions" when mutually contradictory. This basic fact leads us to four dif- ferent ways of studying anything:- (1). Historical or Literary Research, (2) Philosophic Postulation, (5). Applied Science, (4). Pure Science. These four methods of organizing knowledge may be used in any field, architecture, law, botany, or anything else. It is not the purpose of this presentation to hold out a brief for any particular one of them to the exclusion of others in any realm of study. Only a combination of all four can obtain even a slight approximation to reality. Now the person who desires to study religion, also, must resort to one of these four ways of interpreting his basic sensory facts. The first method, that of historical or literary research, attempts to enumerate and classify the sensory data as perceived by others; and gives us, in religious study, such approaches as the following: Biblical Criticism, Talmudic Law and Codes, Midrashic, Mediaeval, and even Modern viewpoints, archaeology, history per so, literature per se, and a host of other subjects, which usually constitute almost all of a theological school's curriculum, which is regretful, for it forces a relatively insignificant part on the other methods in the edu- cation for the ministry. The second method, that of philosophic pastulation has for its emphasis the supplying, through our rational processes, of the logical links necessary for an internally consistent system or pattern of the external sen- sory data of our experience, or of some one else's experience. In religious study, though receiving a great deal of verbal emphasis, the stress is most often the result of a confusion between what is really the literary or histori- cal study of works of philosophic import, such as the "Moreh", the "Chovos", which indicate the use of the philosophic method by the original author, but of the first approach, alone, by the present student. The writer remembers only one actual course, in all of his seven years at Divinity School, making use of the philosophic approach. The third oethod, that of applied science, which.brings to attention ways and means of manipulating the sensory data for our own purposes, has received, of course, a slightly larger proportion of time, but has been made applicable, unfortunately, only in so far as it concerns the work of the ministry. itself. There are such specialized professional techniques of training provided such as homiletics, pedagogy, social service, and the like. There should be included also actual techniques for the worshiper. The fourth and last method, the sure scientific, suffers from oven worse neglect than either of the two preceding; and in an age, such as ours, when science has received due, or even undue, emphasis, it should be considered as important that this claim at least a proper proportion of attention. W84 The science of religion is very specialized type of investi- gation. It is an attempt to break up into their constituent elements, the usual human behavior aspects, Qhich we, call "religious", to analyze, and to resynthesize the phenomena of worship into categories, principles, and laws, for the purpose of understanding them and, possibly, even predicting them. Be- ing a study of a particular type of human behavior it should be classified, by definition, as a branch of Psychology. (We must be careful to differentiate this scientific type of psychology from the old philosophic psychology famil- iar to us in Aristotelian and mediaeval literature. This psychology, like all science, is at home in the laboratory, with instruments of measurement and techniques of accuracy tested by proceeduros devised by the mathematical sta- tistician). The sensory data of religious phenomena, unlike practically all other branches of knowledge, have not been, at all, adequately handled in this way. The apparent reason is that there has been a certain fear on the part of religious leaders, themselves, that too much religious insight might result in skepticism or agnosticism, a fear that, unfortunately, indicts the complete- ness of their own faith. Such matters as these, the "sense of presence", the efficacy of prayer, the phenomena of faith healing, the mystical state of "orison", the nature and cause of religious intolerance, the effects of symbol- ism and ceremony, worship, inspiration, faith, itself, can be studied in the laboratory and with the techniques of modern science; and have been thus studied by a few psychologists, such as Jamesj Ames, Coo, Starbuck, Leuba, Pratt, Trout, and even Freud. It is my suggestion to my colleagues and others interested in religion that they do not allow the continued neglect of three of the four methods of religious study, and particularly the last. The scientific study of religion, that is religious psychology, should be given an important place in the curriculum of all our divinity schools and should provide, at-least, a small percentage of the reading material of every minister. Walter Gilbert Peiser Baton Rouge, La. #85 THE FUNCTION OF THEOLOGY IN SPIRITUAL JUDAISM A Contribution to the Kallah Book Contemporary chaos in philosophy and civilization demands a study of fundamental concepts. The science of principles in Judaism has been the subject of flagrant neglect, In Wissenschaft des Judentums the current emphasis on history should be shifted to theology. Definition of Juda- ism should become primary; other branches of Jewish learning, ancillary. Chroni- cle, law, poem, story, prophecy, rabbinic utterance-halacha and haggada, must contribute to theological formulation. The translation of Jewish sciences in- to values of Jew.ish theology will give us a more adequate viei. of the religion of Israel. The essence of Jrudism must be abstracted from the literature of Judaism. We constantly forget that the purpose of all mitsvoth, the end of all ceremony, is the contemplation of Divine Principles and the acquisition of faith. Maimonides' word is quite to the point: "Reverence for God is pur- pose of all study." (Morch III. 52). This is the end of study. It is also the beginning of practice. For in Judaism, ethics is the consequent of the ology: and the first cause of the good life is Imitatio Dei. Moreover, our people are constantly asking for the pronouncouonts. of Judaism on questions of God, iunortality, free will, evil, the origin auu destiny of ian and the universe in which he lives. Jewish the.-- olegy, the philosophy of Torah, alone can supply the answers to these questions. Israel is entitled to that philosophy of life which is its inherent birthright. Rabbis must learn and teach a clarified and reformulated Jewish theology to young and old. hat Judaism is, not what Judaism does, supplies the answer to the deepest cry of the hour. Rabbis must be able to make reply to this she'elah. It is de profundis. Cosmologies and cosmogonies of our own day throw the gauntlet to man's covetousness of stability and order. In physical science, Quantum theory has given us the discontinuity of Nature, and relativity its mobility. Men look to the principles of religion for order and permanence. Jewish theology can give Israel the sense of value and meaning in a universe of energy and mathematical law. A dedication to this task will be the function of a Spiritual Judaism. By serving thus, Judaism may become pragmaticlly instrumental in bringing men out of the disconsolate darkness of chaos into the light of an ordered world. It need not be a final world. Ezra G. Gotthelf Erie, Penna. #86 SANCTIONS IN JUDAISM What makes a thing Jewish? The question is a most significant one because Judaism has been, and is, an evolving religion. Truth in Judaism, there- fore, has been relative, not absolute; it has been dynamic, not static; it is "in the making," not "made". It has, therefore, been an elusive, as well as an ever growing, evolving, and expanding quest; it has been an eternal quest because it has been a quest for the Eternal. An idea is Jewish if it ever found its way into authoritative, classic, Jewish literature, thought, and practice, and if it was re-emphasized, reaffirmed, and reaccepted by succeeding generations of the wisest, greatest, and best of Jewish scholars, or if introduced at any time by such men of learning. Every one of these words deserves special underscoring, and should have a comment- ary. Evolution in religion has frequently been unconscious, rather than conscious. The Talmud, by its interpretations, modifications, and qualifications, helped to make evolution in Judaism conscious. Hillel's "prosbul" represents the practical abrogation of a so-called "Divine" law because it ceased to function humanly. An illustration might be helpful. A sieve, in Talmudic times, permitted the 'chaff to go through and retained the grain. If we could use the Talmudic sieve to symbolize this body of authoritative, classic, Jewish literature, thought, and practice, and if we could conceive of Father Time ceaselessly turning the handle, only that is Jewish which once found its way into the sieve and did not fall through as chaff with thd ceaseless changes in time, place, circumstances, and the onslaughts of scientific thought and the illumination of new knowledge. This is but half of the story. The other half lies in the intro- duction of new ideas at any time which must receive the sanction.of the wisest, greatest, and best Jewish scholars and which in turn must stand the crucial test of being accepted, emphasized, and re-emphasized by succeeding generations of Jewish scholars. The ultimate sanction in Judaism is life. Because scholarship represents the deepest interpretation of life, scholarship is supreme in Jewish life. Louis L. Mann Chicago /#87 "WHAT NEXT FOR JEWS?" The Jew must be constructive, not of the things clamored for by handful of the possessing and the powerful, but constructive of the things for which the highest traditions of Israel have stood, and destructive of the things that Israel has for nearly four millenia opposed--the wrongs of injustice and enslavement. ".'"Destructive' is often a misleading term, for not seldom it means no more than disturbing or provoking. The mightiest figures in Israel's matchless history have been destructive--Abraham of idolatry, Moses of enslavement and injustice, the prophets of kingly misrule and nationalistic wrongs. And the glory of the Jew it has been to dare to be destructive of the things which conscience, the Voice of God in his soul, compelled him to oppose! "Because they have been so dedicated Jews must be equal to the great responsi- bility, collectively as a people, individually as persons. The Jew dare never forget that at one and the same time, the Father and Founder of the Jewish people emerged out of the darkness of idolatry into the light of loyalty to a purely spiritual concept of the Universe, he, the Jew was bidden not only to destroy the false, the wrongful, the idolatrous, the godless, the inhuman, but he com- manded in words which he may never forget, BE THOU A BLESSING. "What is to be next for Jews, must be answered by the nations which purport to be under the sovereignty of a dispensation of love and compassion. What next is to come from Jews. And only to be answered by Jews themselves, if they re- member that they are commissioned and committed to the quest of truth, to the furtherance of justice, to the magnifying of righteousness and then such com- mission places upon the Jew the supreme responsibility of noblesse oblige!" Stephen S. Wise New York PRAYER FOR THE SICK I will bless the Eternal who hath given me counsel: mine inmost thoughts also have taught me in the night watches. They call upon me: Son of man, what meanest thou? How long wilt thou sleep? Arise and call upon thy God! 0 take heed and guard thy soul diligently, ere she be taken away from thee. On the marrow thou mayest be called away; for thou art a stranger here. There is but one stop between thee and death. Without thy will, thou wast brought into life; without thy will, thou shalt go. Remember this! Lo! thou liftost thine eyes to God yet thy heart clings to earthly pursuits and thy prayers are empty spunds; thy tongue is soft but thy heart is obdurate. Thy lips utter praise but evil dwelleth within thee. How often hast thou suffered thyself to be guided by men rather than by the promptings of the best within thee, And now, to whom wilt thou turn in the day of thy trouble? When sickness layeth thee low upon thy bed, when thy life runneth to its close, when all the burden and frustration and sorrow of life come upon thee-- where wilt thou seek help and to whom wilt thou fly for refuge? Out of thy heart they cry will come: 0 my God help ne and save me! God is good and His tender mercies are for all. He is near to all who call upon Him, who call upon Him in truth. When thou lookest to the right and to the left, when thou findest every door closed before thee, to whom thon,wilt thou turn but to God? And He will strengthen thy heart! Therefore be strong and of good courage. Reflect on thy past, walk humbly, rebdke the tempter and repell him; Be diligent and delay not. Look upon God with all the earnestness of thy heart. Hold fast thino in- tegrity; curb thy passion. Be courageous and undismayed! Draw deep from the inexhaustible spring of life and everlasting salvation. Then shalt +hou lift up thy face and be heartened, for bright hope shall fill thee and thy heart shall be strengthened and fortified against all evil. For the Lord thy God will be with thee, whithersoever thou goest. Morris S. Lazaron Baltimore, MD. #89 ADVERTISEMENT PUBLISHED SEPT. 1859--FEB. 1860 IN OCCIDENT OF PHILADELPHIA "The Hebrew Congregation Beth Israel (House of Israel) is desirous of engaging a gentleman who is capable to act as Chazan, Shochet, Mohel and Bangal Koray; one who is able to deliver occasional discussions would be pre- ferred. Fixed salary $1000.00 per annum, besides perquisites which if he be a Mohel will reach considerable amount, as there is no 1Mohol in the country. Applications in person or in writing with necessary testimonials must be di- rected to the President, M. A. Levy, or C. Davidson, Secretary, No expenses paid. Israelite will please copy. Houston, Texas." The Occident, March 15, 1860, contained the following: "Houston, Texas. The Rev. Z. Emmich was engaged March 1 as Chazan, Shochet and Mohel of Congregation Beth Israel of Houston. Mr. Emmich rather more than a week ago made a flying visit to Lafayette, La., and the J ews there were favorably impressed with his ready defense of Orthodoxy. His repu- tation in other respects is very good and he is well spoken of by those who have had a more familiar intercourse with him than we can boast of, and we trust that in his new field of labor he may succeed to walk before the people with a pious example which they should hasten to follow. Mr. Emmich officiated for the first time on Parshath Shekahim, and the president expressed the satis- faction of the community to him at the conclusion of the service. The congre- gation we learn was established on the 8th of May last year and comprises now thirty contributing members. Most of our brothers there are in a prosperous pecuniary condition, several are well educated men and keep the Sabbath and festivals strictly, and do no business whatever on the sacred days. The congre- gation owns in the middle of the city several adjoining lots on which there has been erected a wooden structure, the front of which is used as a synagogue, the back portion as a meeting room. The synagogue is handsomely fitted up and as the people have now a proper minister we trust that it will be constantly filled by the faithful. "Let us congratulate the first congregation of Texas, as they have succeeded so well in making a choice for Chazan especially as in his capa- city as Mohel they have one ready in hand to initiate their children in the covenant of Abraham all to those who fear God and were anxious for His world. "Let us hear often from the new society all that is good and pleasant." Houston M. N. Dannenbaum (Grandson of Rev. Emmich) #90 THE RE-DISCOVERY OF FAITH "We moderns are finding ourselves driven to the development and acceptance of a faith whereby we can pilot our way out of the jungle of the times." "We have lived through the World War and its aftermath; we have passed through the Corrupt Decade of the Twenties, and we are now seeking to repair the havoc created by the creedlcssness and codelessness of our contemporaries. We are endeavoring to create a community of effort in our economic life, and, in days of crisis, to achieve a voluntary solidarity in our political affairs. Our efforts, however, can meet with success unless there is a re-affirmation of the moral and spiritual fundamentals upon which our social order has rested. "We must recapture the essence and items of the liberal ideal, and apply it to the affairs of our national and international effort. Lib- eralism ha.t been betrayed in the camp of its frio-nds, and has been victimized, not only in lands where despotism has been habitual, but also in commonwealths boasting a long tradition of freedom. "We must believe again that the selfish interest of the indi- vidual must be subordinated to the common good, and that only in communality of economic enterprise can there be social health. We must create a nowe sense of morality among our youth, in clinging then to accept public service, what- ever the sacrifice it involves, rather than personal aggrandizement through private effort. We must recover our recognition of the power, making for righteousness in history, and in human affairs, and realize again that if one generation eats the sour grapes of villainy, the next generation is destined to pay the bitter penalty. We must not consider ourselves above the working of the'moral law, and realize that in business, in personal life, and in national concerns, there is reward for integrity, and punishment for dishonor. Our age must find a pattern of ideals by which to measure its conduct, and it must recover standards which satisfy, not by the test of immediate enjoyment, but by the more severe canons of posterity's judgment. Only thus can we regain our moral moorings, and restore our moral health." Louis V Newman New York City WE ARE OUR BROTHER'S KEEPERS Outside of palm and evergreen shrubbery, I have no trees in my front yard. Yet, my lawn is covered with dry sycamore leaves which the wind blows over not only from adjoining neighbors' property, but also from across the street, and any place whence it listeth. While I am rking these leaves together, I look upon them as symbols of that close relationship in which we human beings are bound up :with one another. No individual, country or even continent, can live in isolation from the rest of the world. My neighbor's condition and conduct affects me most vitally. The ':ind may blow from his property to mine vorse things than seared sycamore lea-tes. It may blow the germs of an infectious disease over to my house, and bring me and mine to grief. It may blow over to my yard his children, who might be very undesirable companions to mine. It may blow over his cantankerous and con- tentious spirit, and thus make life miserable for mc. But, on the other hand, the wind may bring to me precious things from my neighbor. If he keeps his promises in a tidy and prim con- dition, a spirit of imitation and emulation will flow to no on the rings of the wind, and my yard will show a cleaner and neater appearance. If he is a man of education and refinement, I shall welcome his children as companions for mine. If he is a man of culture, and has that fine neighborly spirit which glows from a generous heart and tactful soul, blessings will be vafted to me from his personality. Thus, for better or worse, we are bound together by the ties of common interest. And not until we realize this inescapable solidarity and unshirkable responsibility for each other, can we hope to find a healing for the many ailments that beset us. Samuel Rosinger #92 JEWISH EDUCATION IN ASHKENAZIC LANDS From 1600-1800 Education has been a most important phase of Jewish life ever since (when, according to the rabbis) Jews offered their children as a guarantee that they would keep the Torah. Knowledge has been the mark of Jewish aristocracy. The am haarez has been the butt of quips and jokes. Preparation for Bar Mitzvah ceremonies made it necessary for the boy to have rome Hebrew knowledge. We find, therefore, that every generation has labored mightily to found and pre- serve its schools, to secure teachers, to train its youth for a life of devout study. This paper covers that period in Jewish history enclosed by ghetto walls. It differs widely in its import and in its organization from our own milieu. We can hardly hope to draw more than the vaguest of parallels with today. The cheder, for example, has no counterpart in today's Jewish life. The Yeshiva has been centralized in Cincinnati, Chicago and New York. The Talmud rh, the central Jewish school, has more in common with our present day religious schools, even tho they are today organized along congregational lines. We shall surey the Talmud Torah of the pre-eman6ipation period in Germany, Poland, and Lithuania. The questions to be answered are: 1. Who was responsible for Jewish Education? 2. What were Jewish children taught? 3. What pedagogic methods were used? 4. What were tho aims of Jewish education in those days? The answers come from many sources. Collected by Assaf in his Mekorot Letoldot Hachinuch Beyisroel, and by Guedemann in his Quellenschriften .zur Geshichte des Unterrichts and der Eziehungen bei den doutschn J.Tuden are fragmentary sources of the period. The other sources are varied, come of them biographical or Memoirs, (for example the Memoirs of Glueckel S_ HIL_~1 Jgoldot Jocob Joseph); testaments, (such as that of Moses Chasid); letters..(sych ao that of Herz Homburg to the heads of Galician communities); response and novellae; and the communal ordinances of many cities (among them Worms, Cracow, the Lithuanian Vaad, etc.). I. Who was responsible for Jewish Education? The Talmud Torah was not a Bureau of Education nor a central Hebrew school. The average boy of parents who could so afford attended a cheder. The Talmud Torah was a communal school for orphans and for the education of the poor and the dispossessed. In Moravia, a father who could not pay for his child's education might turn to the authorities for help, but he was not allowed to take his children out of school to learn a trade. In Hesse, they gave money to a father that he might in turn pay a teacher without enbarassment. Only in the larger communities where numbers permitted or rather forced the issue, were there special schools. In the small communities, the Talmpd Torah children were sent to private chre:.. with the other students of the town. Altho there are extensive records on the selection of communal officers for the supervision of Chedarim, the records of such selections are not available for the ajpmud To rah. In many cases there were particular societies that made the Talmud Torah their particular concern and the officers were probably chosen from the midst of such societies. In Zalkiev, for example, four Kuppah Gabbaim were chosen. They had to be married and also learned. They rotated from month to month, each in his month examining the Behelfern. They were expected to visit the school twice a week and to manage the funds. It was only during times of stress or depression that communal organizations came to the aid of these private societies. B. Where did the Talmud Torahs derive their funds? Cracow had a most ingenious system of collecting funds. The Talmud Torah Veroin received:one sixth of all funds collected on Mondays and Thursdays in all synagogues and schools by passing the plate; one and a half groschen a month from each member of the Verein; one tenth of private gifts made in synagogues; the rent of one building for religious purposes at 15 groschen a week; and all funds collected by plate passing at weddings and other ceremonies. C. Teachers. There are no lists of requirements for teachers. Experience was no criterion nor popularity nor personality. He was to be god-fearing and educated. Usually teachers were selected by the chief rabbi or the educational board of the community. The spring fairs were the market for wools and hide, and for Melammedim. The Yeshivot of a section would usually have a Kallah convention during that period at the site of a fair, and there other communities would pick out learned young bachurim to be malammedim in their communities. Jacob Emden warned against selection of unqualified teachers who might become swell- headed at being teachers and give ritual decisions. He insists that the teachers be paid good salaries that fees for parkingg sheilos" might not lure him, and also that he must have a certificate from a Beth Din. Once elected, a teacher had to pay dues or taxes, based on the number of private pupils he had. These funds helped indigent teachers and likewise went to teachers in Talmud Torahs. Teachers had to be married, and had to continue studies leading to the degree of Chaver, These must be accom- plished within two years. There were many itinerant melammodim in those days, their activities circumscribed by many takkanot. A non-native teacher could teach two years in one community, (remaining sometimes with the permission of his wife and his home town Beth Din). They were taxed heavily, and sometimes toothe number of their pupils was limited. The relation of the teacher to the parents of pupils was a knock-down drag- out fight in many cases. A teacher of Cheder could not handle pupils as did teachers of Talmud Torah. One teacher complained that the teachers had to #94 be bootlickers of the community and that to avoid this, education should be under communal regulation. Competition between teachers was regulated closely. Price cutting was not allowed. House to house solicitation of pupils, and transference of pupils was barred after the semester.began. D. Pupils. Private or public classes were limited in size. Forty pupils was the average to a teacher of Elementary Hebrew when he had two helpers. The increasing difficulty of the subject made for smaller classes, for example, in teaching Tossefot, eight to ten pupils was the maximum. E. Time. Since all pupils were to be prepared for Bar Mitzvah We may imply that regular schooling lasted until a boy was thirteen. His education began usually at tho age of five, altho some as early as three. After thirteen, the majority went into trades or shops and the minority continued their studies until preparingfor yeshiva and Careers as rabbis, teachers, chazzanim, The average school day was about seven hours from Sunday to Wednesday. In winter, children rose before dawn and had an hour class before worship. At ton was lunch time; and another snack at two o Jclock for school dismissed just before Mincha. On Thursday were the weekly examinations, usually by a Parnass or a Gabbai by way of checking up on the instruction of the teachers. There were probably two semesters from the last of Tishri to the first of Nissan; the other from the last of Nissan to the first of Tishri, a ten month year of Jewish schooling, F. Text books.. Basic texts were the Bible with Rashi, the Mishnah, Thalud and commentaries. Other books in regular and popular use included: Eeer Moshe, a Yiddish dictionary to the Pentateuch and Magillot, required in Cracow; Frankfort a Oder used Redaks book on Roots, Michlal Yofi, a book on grammar and other grammatical books; Bible dictionaries included the Aruch Hakatzer, Makre Dardeke; for ethics there were such books Die Gute Lehre, by Jagel and Ele Hamitzvot by R. Gedalian Taikus II. What were Jewish children taught? The curriculum of Jewish education in those times was roughly the same from community to community. A child began the alof bet when he was five, then prayers. At the age of six or seven he began Bible (Tanach) and a taste of Mishnah at ten or eleven. By thirteen or so, he right be ready for Talmud; if not, he was returned to the Tanach for the prophets and holy writings.. Not often was grammar taught.. and our elaborate courses in grammar for rabbinical students today were formerly unlaknom. A general practice was to teach according to the parfsha of the week. A chilv seldom reads consectively thru the Torah..buht a bit here and there, and would start over again next year. Eron thi Torh, the child went direct- ly to Mishnah. The study of prophets was not often encouraged. #95 In addition to Hebrew, Yiddish, writing and reading was a frequent subject. Arithmetic to the extent of the multiplication tables to be used in business was provided. The education of the Cheder and Talmud Torah was largely halakic rather than agadic. Parents taught the child to pray, and regulated his action. At school, he learned religious laws, especially ritual, to obey as an adult Jew. Children under ten were not welcome in the synagogue except on the gayer holi- days. The teacher was responsible that his children bd neat and clean and say grace before and after meals. The main job of the school was to teach the Jewish.tradition. Morals, it was felt, would be the by-products of such teaching, The most corrosive element of the curriculum of those days was the desire for precocity. Teachers boasted if a child of eight engaged in pilpulistic dis- putes, and many responsible rabbis complained about the show-off education given especially in Poland. Many students knew the Bible only thru quotation, in Talmudic passages. The peshat was a rare way of presenting the Tanach. Legalistic education lowered the spiritual calibre of the age and paved the way for its own downfall. II What pedogogic methods were used? No books were then written on the art of teaching. Volumes of experimental or practical psychology were not available. Human nature was deemed fixed and invariable, in which peoplareacted in unison. It is only the occasional by-statement that mentions how to teach. It was almost taken for granted that if a teacher knew his material he could teach. Probably the main pedagogic idea of the period is that there is no royal road to learning. The project, the motivation, the lesson in appreciation, the studying of individual differences, played no part in their educational scheme. The child learned by constant repetition, by rote, by hammering, by deep un- deviating study. That teacher was successful who pounded knowledge into the heads of his pupils..and sometimes that pounding was literal. For adults, the prescribed method of study took into account the will of man. Children were not expected to have a will. But adults were cautioned to re- view their work, to work slowly and regularly.."make thy study a fixed habit".. He was advised to develop mnemonic help, to study in a well-lighted room, with well bound and printed books....But for the children, no such advice was given. The child who started school was bribed with money..or gifts from "angels" dropped from the ceiling. Honey and sweets were spread on a slate...for the child to taste:.."The Torah shall be as honey in thy mouth." They sought to kindle the child's desire to be a great rabbi, or to get a wealthy wife, until he could be appealed to study for study's sake. We may be sure there were good and poor teachers then as now, that he with personality, patience and kindliness taught well...and he who was sharp and acid failed to teach proper attitudes, though he may have satisfied the communal heads. There wore some requirements against mixing groups in the school. Children studying the alphabet should not be taught in the same room with those study- ing Talmud. Teachers were expected to cprialize in either elementary or advanced teaching...but naturally the smaller communities must have been much as in our rural one room schools. #96 On discipline, the rule was spare the rod and spoil the child. Only younger children, however were to be physically punished. Older youth, probably after bar mitzvah were expected to respond to praise or blame..Solomon Maimon's autobiography as illustration, gives graphic picture of the poorer type of discipline in the poorer type of teacher. His bitterness undoubtedly led him to exaggerate; his teacher may have been over-diligent in that general practice. IV. Just what was the education of those times aiming at?..in terms of what purposes did they teach their children? Inductively, we might state that the aim of the educational system was Jewish education for all males. This education consisted of Jewish tradition which most clearly expressed the Ashkenazic spirit. The Ashkenazic emphasized (unlike the Sephardic Jew) the observance of Jewish law, rather than re- flection upon Jewish thought and ideals. In'Spain, poetry, higher mathematics, astronomy, Arabic, and so forth were included in the cifrriculum; in Germany and Poland, however the text books were solely Bible, Mishnah, the Talmud. Very little stress was laid on the ethical, the philosophical, or the poetic. The Ashkenazic Jew had to know the ritual law thoroly, to observe that law, and to submit to authority in case of dispute. His personality and beliefs were largely left to himself, his behavior was to be identical with that of others. The Bible was studied, therefore, not as a literary document, but as a law code, and more, as a stopping stone to the oral law in Mishnah and Talmud. Learning in the law was the highest ideal, and the Rabbi was its Symbol. Obedience to the learned law was the next highest ideal,.it found expression in the education of the average boy. In short..the adult life and ideals of the Ashkenazic community were perpetuated thru its schools. When we realize this truism...we realize how important education is..not only for the Jews of tomorrow, but again for their children. If our schools are to reflect only our life today...then progress ceases...if progress is to be made..our schools must aim at a higher Jewish life than the present. Robert I. Kahn Houston Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2010 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Last updated October 10, 2010 - - mvs
http://ufdc.ufl.edu/UF00072065/00001
CC-MAIN-2015-32
refinedweb
50,926
66.88
Typedef container enabling iteration over compile-time type list. More... #include <Tsqr_TestUtils.hpp> Typedef container enabling iteration over compile-time type list. One can use the typedefs in a Cons to "iterate" recursively over a list of types, that is defined at compile time. CarType may be any type; these are the "values" in the type list. CdrType must be either a Cons or a NullCons. The names Cons, Car, and Cdr come from Lisp. (Don't write "Lisp" in all caps, unless you are referring to early versions of the language.) A cons is a list. If x is a cons, then (car x) returns the head of the list, and (cdr x) returns the rest of the list. Definition at line 169 of file Tsqr_TestUtils.hpp.
http://trilinos.sandia.gov/packages/docs/dev/packages/kokkos/doc/html/structTSQR_1_1Test_1_1Cons.html
CC-MAIN-2014-15
refinedweb
128
75.91
On Wed, 13 Jun 2001, Neil Macneale wrote: > In article <9g5fc4$m8u$01$1 at news.t-online.com>, "Jochen Riekhof" > <jochen at riekhof.de> wrote: > > > I am missing something like the c/Java ?: operator. > > The ?: operator is overrated. For the time you save typing, you > are wasting someone else's because they need to figure out what you were > thinking. Trust me, this is true. Compare the following actual examples: public static final String aan(String s) { char x = s.charAt(0); return ((( x == 'a') || (x == 'e') || (x == 'i') || (x == 'o') || (x == 'u') || (x == 'A') || (x == 'E') || (x == 'I') || (x == 'O') || (x == 'U')) ? "an " : "a " ); } def aan(name): """Utility which returns 'a' or 'an' for a given noun. """ if string.lower(name[0]) in ('a','e','i','o','u'): return 'an ' else: return 'a ' Now, if you're getting paid per line of code, I could see how the first example works better for you... but this was the *least* convoluted use of the ? operator in all of the code that I could find; and I think it's pretty clear which approach looks nicer. > > if elif else is not a proper substitute for switches, as the variable in > > I have found that using a dictionary of function pointers sometimes gives > the switch statement feel. For example, point to constructors... > > cases = {"dog": Dog, "cat": Cat, "rabbit": Rabbit} > > def createPet(type="cat"): > if casses.has_key(type): return casses[type]() #Good input... > else: return None # bad input, or 'default' in C/java The idiom that I've come to particularly like in Python, given a case like that: class PetShop: def pet_cat(self, name): ... def pet_dog(self, name): ... def pet_dinosaur(self, name): ... def buyPet(name="pooky", petType="cat"): petFunc = getattr(self, "pet_%s" % petType, None) if petFunc: return petFunc(name) else: # 'default' case mentioned above; usually raise something > The above code is generally hard to read, so use sparingly and comment > well. The thing I like about it is that the keys can be of any type. One > problem is that all the functions called are going to need similar > parameters, but sometimes its a usefull trick. If you use the specially-named-methods approach, it's almost self-documenting! I use this all over the place and I really like the way it helps to organize code (it also makes testing easier, since each method can be tested separately). It's like you can invent your own "adjectives" to describe methods. try-doing-*that*-in-java-ly y'rs, ______ __ __ _____ _ _ | ____ | \_/ |_____] |_____| |_____| |_____ | | | | @ t w i s t e d m a t r i x . c o m
https://mail.python.org/pipermail/python-list/2001-June/077346.html
CC-MAIN-2020-24
refinedweb
447
73.47
in reply to Writing a Test Harness I am not sure if it is related but the has been a lot of CPAN activity in the Tapper namespace lately from AMD and it seems to me from the docs to be a large scale test-harness of some kind. You might want to do some code diving and see if it is useful. Indeed. It is not really clear from the documentation of Tapper, but I believe this is mainly the work of renormalist who uses it to test and benchmark OSes and search those results in his work for AMD. So, likely, Tapper is of interest to you if you want to run and aggregate various tests on multiple machines and environments. Lots Some Very few None Results (211 votes), past polls
http://www.perlmonks.org/?node_id=896527
CC-MAIN-2016-07
refinedweb
133
70.06
22 July 2011 05:00 [Source: ICIS news] SINGAPORE (ICIS)--Indian Oil and Haldia Petrochemical (HPL) have raised their domestic list prices for polypropylene (PP) for the third consecutive week because of short supply of spot material, sources close the companies said on Friday. The price increment was announced at Indian rupees (Rs) 1/kg, effective 20 July, the sources said. The new PP prices are now at Rs85.00-86.50/kg ($1.91-1.95/tonne) ?xml:namespace> Indian Oil is currently running only one of its two 300,000 tonne/year PP lines at Panipat because of feedstock shortage, while HPL’s 340,000 tonne/year facility is shut for a two-week turnaround. Reliance Industries, meanwhile, just rolled over its PP list prices from last week, a source close to the company said, without stating the reason. “Tight supply in the local market is the key reason for the bullish sentiment. And this is likely to lengthen to August,” a source close to Indian Oil said. Traders and converters are still scrambling to secure material from the Indian domestic market amid low-to-negligible inventories and as offers for August imports will only be out next week. “We have to buy some [PP] to start building our inventories before the prices shoot up significantly,” a local converter said. Spot domestic prices are heard at Rs86-87/kg DEL New Delhi, while spot import prices were discussed at $1,540-1,570/tonne (€1,078-1,099/tonne) CFR (cost and freight) ($1 = €0.70 / $1 = Rs44
http://www.icis.com/Articles/2011/07/22/9479266/indian-oil-haldia-petrochemical-hike-pp-offers-for-third-week.html
CC-MAIN-2015-11
refinedweb
260
58.82
On Thu, May 21, 2009 at 11:01 AM, Ben Finney ben+python@benfinney.id.au<ben%2Bpython@benfinney.id.au wrote: Jeremiah Dodds jeremiah.dodds@gmail.com writes: hmm, the 80-character convention does not stop me from unconsciously writing really complex list comprehensions, I just write them like so: def foo(f, a, b, c): return [[((f(x,y) i, i) if i % 2 else 0) for i, x in enumerate(a) if f(y, x) == a + x] for y in [c(z) for z in range(a, ab+c, c)]] not that that's really any better. On the contrary, I find that much easier to grasp than the same statement on a single line. You have been required, by choosing to follow the 80-column limit, to choose points at which to break the line; and have responded by breaking it up into conceptually discrete chunks and indented to suggest the structure. This example is, for me, a very convincing (anecdotal) demonstration of why an 80-column limit is a good constraint to follow. Oh, yes - I consider it much easier to read than the single-line equivalent. What I meant by "not that that's really any better" was more along the lines of "that statement should probably be refactored". It's very rare that I run into a case where a convoluted list comprehension like that isn't better written some other way. Sometimes I end up with stuff like that when I've made incorrect assumptions while designing a program, etc. > But yeah, this is all anectodal evidence and personal taste, as Raymond points out. Yet it's also more than that; to call it “personal taste” is to imply that it's nothing more than aesthetics. If that's all it were, I'd care far less for changes in convention. I consider it rather more importantly a matter of software ergonomics, which should therefore not be changed unless there's good supporting evidence that the proposed change results in improvement. I tend to agree. That's very well-said.
https://mail.python.org/archives/list/python-ideas@python.org/message/SHVF5R42XP7MHEUAXSAWK7LBWHDA2RPY/
CC-MAIN-2020-29
refinedweb
348
68.7
Introduction The Csound Python API provides classes and functions to use the Csound API fromPython. An interesting issue with Python is that we can use an enhanced versionof the Python shell, IPython [1], for interactive sessions.In this paper, a basic class encapsulating commands to run a Csound session ispresented, and examples are given of a real-time session with score events. Thereader is expected to be comfortable with the Python programming language[2] and to have a basic knowledge of Csound [3]. I. IPython For this article we will need the following installed: Csound, Python, the interactive Python shell IPython,and the Python modules numpy, scipy and matplotlib. On mostLinux distributions there are prebuilt packages of all these components. On Windows,the simplest way to setup these is to install binaries. For example with Python 2.6, you can getan msi file here,the Csound installer from theCsound Page at SourceForge,an IPython binary from the IPython site,numpy and scipy binaries from SciPy.org,and matplotlib from its SourceForgepage (the download link on the right side). Windows users also need to install thepyreadline module to havea console with colors. The IPython shell offers some goodies for an interactive use of Python:TAB-completion, exploring your objects, the %run command, input and output cache,%hist command, and a lot of other facilities. When launched with the pylabflag and the scipy profile (ipython -pylab -p scipy), IPython offers aready-to-go interactive environment similar to MATLAB® but with the scriptingpower of Python. Finally if we add to this environment access to Csoundvia its API, we get a very powerful system for interactive experimentation. Note: All of the examples presented in this article have been tested on Linux and on Windows XPwith Csound 5.12 and Python 2.6. While I could not test these examples on Mac OS X, they should be able to work. One can find instructions to install SciPy for Mac OS Xhere.Note that they strongly recommend installing theofficalPython distribution instead of using the one shipped by Apple. II. CsoundSession In this article, a Csound session consists of a running Csound engine with a Python interpreterlistening for user input. Our basic class for running a session is called CsoundSession. Itinherits from the Csound class which is an interface to the Csound API. We willalso use the CsoundPerformanceThread class to perform a CSD file [4]in a separate thread.Initially it might make sense to make our class inherit from both the Csound and theCsoundPerformanceThread classes as Python allows multiple inheritance. However, doing sowould put both classes on the same level. In fact, the Csound class is tied to awhole session while the CsoundPerformanceThread class corresponds to a singleperformance within a session. We want to be able to perform successive CSD files during a singlesession. Therefore our CsoundSession class is designed to have an attribute of type CsoundPerformanceThread. Launching a session To start a session, open up a terminal (Command Prompt on Windows), change directories to the directory inwhich there is a copy of the csoundSession.py file,and then launch an IPython shell: ~$ cd 'our working directory'~$ ipython -pylab -p scipyPython.IPython profile: scipy Welcome to pylab, a matplotlib-based Python environment. For more information, type 'help(pylab)'.In [1]:(In the IPython shell, the default prompt is In [n]: where n isthe number of the command line typed by the user. The answer to the user command isdisplayed with an Out[n]: prompt). To begin, first import everything from the csoundSession module and then create aCsoundSession object. Please note that the first letter of the module name is alowercase 'c' while the first letter of the class name is an uppercase 'C'. In [1]: from csoundSession import *In [2]: cs = CsoundSession()In [3]:Next, we can display the methods and attributes of our object with the dir() command. We can also print some information about Csound using those API functions which work even ifno CSD file is loaded. In [3]: dir(cs)Out[3]: ['AddSpinSample', 'AppendOpcode', 'ChanIASet', 'ChanIASetSample', 'ChanIKSet', 'ChanIKSetValue', 'ChanOAGet', 'ChanOAGetSample', 'ChanOKGet', 'ChanOKGetValue', 'Cleanup', 'Compile', 'CreateConfigurationVariable', 'CreateGlobalVariable', 'DeleteChannelList', 'DeleteConfigurationVariable', 'DeleteUtilityList', 'DestroyGlobalVariable', 'DestroyMessageBuffer', 'DisposeOpcodeList', 'EnableMessageBuffer', 'Get0dBFS', 'GetChannel', 'GetChannelPtr', 'GetControlChannelParams', 'GetCsound', 'GetDebug', 'GetEnv', 'GetFirstMessage', 'GetFirstMessageAttr', 'GetInputBuffer', 'GetInputBufferSize', 'GetKr', 'GetKsmps', 'GetMessageCnt', 'GetMessageLevel', 'GetNchnls', 'GetOutputBuffer', 'GetOutputBufferSize', 'GetOutputFileName', 'GetRtPlayUserData', 'GetRtRecordUserData', 'GetSampleFormat', 'GetSampleSize', 'GetScoreOffsetSeconds', 'GetScoreTime', 'GetSpin', 'GetSpout', 'GetSpoutSample', 'GetSr', 'GetStrVarMaxLen', 'GetTable', 'GetUtilityDescription', 'InitializeCscore', 'InputMessage', 'IsScorePending', 'KeyPressed', 'ListChannels', 'ListConfigurationVariables', 'ListUtilities', 'Message', 'MessageS', 'NewOpcodeList', 'ParseConfigurationVariable', 'Perform', 'PerformBuffer', 'PerformKsmps', 'PerformKsmpsAbsolute', 'PopFirstMessage', 'PreCompile', 'PvsinSet', 'PvsoutGet', 'QueryConfigurationVariable', 'QueryGlobalVariable', 'QueryGlobalVariableNoCheck', 'Reset', 'RewindScore', 'RunUtility', 'ScoreEvent', 'ScoreExtract', 'ScoreSort', 'SetChannel', 'SetChannelIOCallback', 'SetConfigurationVariable', 'SetControlChannelParams', 'SetDebug', 'SetExternalMidiInCloseCallback', 'SetExternalMidiInOpenCallback', 'SetExternalMidiReadCallback', 'SetHostData', 'SetHostImplementedAudioIO', 'SetInputValueCallback', 'SetMessageCallback', 'SetMessageLevel', 'SetOutputValueCallback', 'SetScoreOffsetSeconds', 'SetScorePending', 'Stop', 'TableGet', 'TableLength', 'TableSet', '__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_destroy__', '__swig_getmethods__', '__swig_setmethods__', '__weakref__', 'CSD', 'getCsdFileName', 'note', 'pt', 'pydata', 'resetSession', 'scoreEvent', 'startThread', 'stopPerformance', 'this']In [4]: cs.GetSr()Out[4]: 44100.0In [5]: cs.GetKr()Out[5]: 4410.0In [6]: cs.GetNchnls()Out[6]: 1In [7]: cs.GetScoreTime()Out[7]: 0.0In [8]: cs.getCsdFileName()In [9]:The dir(cs) command returns a list of strings that are the method names of theCsound class (the parent class of our CsoundSession class), followed by theattribute and method names of the object class that was inherited by the Csoundclass (from '__class__' to '__subclasshook__'), then some method names providedby the SWIG wrapper and finally our own attributes and method names. Note thatthe Csound class method names begin with an uppercase letter while our own methodnames begin with a lowercase letter. Therefore our scoreEvent method is differentfrom its parent class ScoreEvent method. Performing a CSD file To produce some music, Csound needs an orchestra and a score. We load both of themfrom a CSD file named simple.csd.It contains a single intrument (instr 1) and a score including a single f0 event with of duration of14400 seconds (four hours). The -d -m0 flags are used to minimize the amount ofmessages displayed by Csound. (Note: If your sound card does not support a sampling rate of 96000 Hz,try with a lower sr) <CsoundSynthesizer><CsOptions> -d -o dac -m0</CsOptions><CsInstruments>sr = 96000ksmps = 100nchnls = 20dbfs = 1 instr 1idur = p3iamp = p4icps = cpsoct(p5)ifn = p6irise = p7idec = p8ipan = p9kenv linen iamp, irise, idur, idecasig oscili kenv, icps, ifna1, a2 pan2 asig, ipan outs a1, a2 endin</CsInstruments><CsScore>f 0 14400</CsScore></CsoundSynthesizer>The file is loaded and started with the resetSessionmethod which takes the file name as argument: In [9]: cs.resetSession("simple.csd")PortAudio real-time audio module for CsoundPortMIDI real time MIDI plugin for Csoundvirtual_keyboard real time MIDI plugin for Csound0dBFS level = 32768.0Csound version 5.12 (double samples) Jul 29 2010libsndfile-1.0.21Reading options from $HOME/.csoundrcUnifiedCSD: simple.csdSTARTING FILECreating optionsCreating orchestraCreating scoreorchname: /tmp/csound-16QorA.orcscorename: /tmp/csound-Xdi5rI.scoRAWWAVE_PATH: /usr/local/share/csound/rawwaves/rtmidi: PortMIDI module enabledrtaudio: ALSA module enabledorch compiler: instr 1 sorting score ... ... doneCsound version 5.12 (double samples) Jul 29 2010displays suppressed0dBFS level = 1.0orch now loadedaudio buffered in 1024 sample-frame blockswriting 4096-byte blks of shorts to dacSECTION 1:In [10]:This method compiles the orchestra and the score and starts the performance in aseparate thread using a CsoundPerformanceThread object. Note that thelines displayed by Csound (from 'Portaudio... to 'SECTION 1:') are not precededby an Out[10]: prompt because those lines are not a valuereturned by the resetSession method, but a direct output from Csound. As the performance is running in a separate thread, we still can enter commands from the top level: In [10]: cs.GetSr(), cs.GetKr(), cs.GetNchnls()Out[10]: (96000.0, 960.0, 2)In [11]: cs.GetScoreTime()Out[11]: 9.6229166666666668In [12]: cs.getCsdFileName()Out[12]: 'simple.csd'In [13]:Note that the three values returned in the tuple are from after loading the CSD file, and that these aredifferent from the default values we received when the CSD file was not loaded. We could also have started the session and the performance in a single operation, givingthe CSD file name as argument to our object constructor. In the following display, we stopthe performance and leave the interactive shell. We then launch a shell and start a new Csound session: In [13]: cs.stopPerformance()inactive allocs returned to freespaceend of score. overall amps: 0.00000 overall samples out of range: 00 errors in performance181552 2048-byte soundblks of shorts written to dacIn [14]: quit()Do you really want to exit ([y]/n)? y~$ipython -pylab -p scipy...In [1]: from csoundSession import *In [2]: cs = CsoundSession("simple.csd")PortAudio real-time audio module for Csound...SECTION 1:In [3]:Now that a CSD file is being performed, we can send score events to Csound usingthe scoreEvent and note methods of our cs object . III. Sending Score Events The scoreEvent method takes two or three arguments: - eventType -- a character denoting the event type: 'a', 'e', 'i', 'f', or 'q'. - pvals -- an iterable (tuple, list or array) containing the pfields for that event. - absp2mode (optional, default=0) -- a flag indicating how to interpret the event start time. The second element of the pvals sequence is as usual the event start time. This time is measured in beats relatively to the time when the event was sent to csound. If the value of absp2mode is different from 0, the event start time is counted from the beginning of the performance instead. In this latter case, if the performance time counter is already beyond the absolute start time given, the event will be ignored. 'a' Statement The 'a' score statement is used to advance the score time by a specified amount: In [3]: cs.GetScoreTime()Out[3]: 6.5708333333333337In [4]: cs.scoreEvent('a', (0, 0, 6000))In [5]: time advanced 6000.000 beats by score request#return key hit to get the right promptIn [6]: cs.GetScoreTime()Out[6]: 6025.260416666667In [7]: In [3]: we display the current score time in beats, which means seconds herebecause the default tempo is 60 beats per second. In [4]: the score time is advanced 6000 beats. The 3 values in the tuple are respectivelyp1 (no meaning here), p2 (start time), p3 (number of beats to advance). A start time of 0means executing the 'a' statement as soon as it is received. In [5]: the message returned by Csound is displayed mixed with the prompt fromIPython for the next command. We hit the <return> key to get an empty prompt line. In [6]: we verify that the current score time has been advanced. In [7]: cs.scoreEvent('a', (0, 6100, 500), 1)In [8]: cs.GetScoreTime()Out[8]: 6057.0249999999996In [9]: time advanced 500.000 beats by score request#return key hit to get the right promptIn [10]: cs.GetScoreTime()Out[10]: 6629.1750000000002In [11]: In [7]: we ask Csound to advance the score time 500 beats when it will have reached theabsolute score time of 6100 beats (the absp2mode argument is different from 0). In [8]: we verify that the score is still running and that it has not yet reachedthe advance point. In [9]: after a few seconds, Csound tells us it has advanced the score time (at beat 6100). In [10]: the score time is now more than 6600 beats. In [11]: cs.RewindScore()end of section 1 sect peak amps: 0.00000SECTION 1:In [12]: cs.GetScoreTime()Out[12]: 8.0416666666666661In [13]: In [11]: we rewind the score time to zero. 'e' Statement The 'e' statement is used to mark the end of the score: In [13]: cs.GetScoreTime()Out[13]: 376.04166666666669In [14]: cs.scoreEvent('e', ())In [15]: Score finished in csoundPerformKsmps().inactive allocs returned to freespaceend of score. overall amps: 0.00000 overall samples out of range: 00 errors in performance24694 2048-byte soundblks of shorts written to dac#return key hit to get the right promptIn [16]: In [14]: we send an 'e' statement to Csound. As there is no pfield (empty tuple),the effect is immediate. In [15]: Csound displays messages denoting the end of the performance. In [16]: cs.resetSession()PortAudio real-time audio module for Csound...SECTION 1:In [17]: cs.GetScoreTime()Out[17]: 7.4249999999999998In [18]: cs.scoreEvent('e', (0, 15))In [19]: cs.GetScoreTime()Out[19]: 25.729166666666668In [20]: Score finished in csoundPerformKsmps().inactive allocs returned to freespaceend of score. overall amps: 0.00000 overall samples out of range: 00 errors in performance1340 2048-byte soundblks of shorts written to dac#return key hit to get the right promptIn [21]: In [16]: we start a performance of the last loaded CSD file ('simple.csd'). In [17]: the performance is running. In [18]: we ask Csound to end the performance in 15 beats from now. In [19]: the performance is still running. In [20]: Csound tells us that it has finished the performance. In [21]: cs.resetSession()PortAudio real-time audio module for Csound...SECTION 1:In [22]: cs.GetScoreTime()Out[22]: 2.6666666666666665In [23]: cs.scoreEvent('e', (0, 20), 1)In [24]: cs.GetScoreTime()Out[24]: 18.987500000000001In [25]: Score finished in csoundPerformKsmps().inactive allocs returned to freespaceend of score. overall amps: 0.00000 overall samples out of range: 00 errors in performance938 2048-byte soundblks of shorts written to dac#return key hit to get the right promptIn [26]: cs.resetSession()PortAudio real-time audio module for Csound...SECTION 1:In [27]: In [21]: new performance... In [23]: we ask Csound to end the performance when it will have reached theabsolute time 20 beats. In [24]: still running... In [25]: score finished. In [26]: ready for new adventures! 'f' Statement We can use the function table statement to generate function tables. In [27]: cs.scoreEvent('f', [1, 0, 4096, 10, 1])In [28]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [29]: cs.TableLength(1)Out[29]: 4096In [30]: cs.TableLength(2)Out[30]: -1In [31]: cs.TableGet(1, 1024)Out[31]: 1.0In [32]: cs.TableSet(1, 1024, -1.0)In [33]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [34]: cs.TableSet(1, 1024, 1.0)In [35]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [36]: In [27]: ftable 1 is generated with a single sine wave. The second argumentis a list containing the pfields for the 'f' statement: p1=1, ftable number.p2 = 0, generate the ftable right now. p3 = 4096, length of the ftable in samples.p4 = 10, use GEN10. p5 = 1, only the first partial. In [28]: we play a one second 440 Hz note using ftable 1. The note method ofthe CsoundSession class will be discussed in the next section. In [29]: we can get the table length from the API. In [30]: if the ftable does not exist, TableLength returns an error value (-1). In [31]: we can read a single value from within an ftable. Here we get the value ofthe 1025th sample of ftable 1. Indexes of an ftable are in the range [0, length[. In [32]: we write the value -1.0 to the 1025th location of ftable 1. This causes adiscontinuity in the sine wave. In [33]: we can ear clicks in the note due to the discontinuity. In [34]: we write back the original value to the 1025th location of ftable1. In [35]: no more discontinuity, pure sine wave... In the next examples, we will see how to use directly the data from an ftablethrough a numpy array. A numpy array is a data structure that can supportindexing and slicing operations. If the data in the array are contiguous as in a Carray, we should be able to create a numpy array with its buffer pointing to thedata of the ftable. Thus we can manipulate the ftable data from their Csoundbuffer without copying them,thanks to the addons of numpy arrays. First we must obtain a pointer to the ftable data. This is done with theCsoundMYFLTArray class of the API. This class wraps a Csound MYFLT array. Ithas a GetPtr method. When called without argument, this method returns apointer to a pointer to a MYFLT. Creating a CsoundMYFLTArray object andpassing its GetPtr method without argument to the GetTable API function,fills the internal pointer of the CsoundMYFLTArray object with a MYFLT pointerto the ftable data: In [36]: tbl = csnd.CsoundMYFLTArray()In [37]: tblSize = cs.GetTable(tbl.GetPtr(), 1)In [38]: tblSizeOut[38]: 4096In [39]: tbl.GetValue(1024)Out[39]: 1.0In [40]: tbl.SetValue(1024, -1.0)In [41]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [42]: tbl.SetValue(1024, 1.0)In [43]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [44]: In [36]: we create an empty CsoundMYFLTArray object. In [37]: we make our object point to ftable 1 data, and we get ftable 1 length asa return value. In [39] .. In [43]: click test to verify that we have a direct access to ftable 1 data. Once our CsoundMYFLTArray object is pointing to the ftable data, we canget a pointer to any value inside the ftable by using its GetPtr methodwith an index within the ftable range as argument. Thus calling GetPtr(0)returns a pointer to the ftable buffer. With this pointer, we can initialize a floator a double array using the appropriate Csound Python API function. Assuming thatwe're using a double version of Csound we would have: In [44]: tblDoubleArray = csnd.doubleArray_frompointer(tbl.GetPtr(0))# If the float version of Csound is used,# the following line should be typed instead:# tblArray = csnd.floatArray_frompointer(tbl.GetPtr(0))In [45]: tblDoubleArray[1024]Out[45]: 1.0In [46]: tblDoubleArray[1024] = -1.0In [47]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [48]: tblDoubleArray[1024] = 1.0In [49]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [50]: tblDoubleArray[1022:1027]---------------------------------------------------------------------------TypeError Traceback (most recent call last)/home/pinot/Articles/console-python/<ipython console> in <module>()/usr/local/lib/python2.6/dist-packages/csnd.py in __getitem__(self, *args) 211 __swig_destroy__ = _csnd.delete_doubleArray 212 __del__ = lambda self : None;--> 213 def __getitem__(self, *args): return _csnd.doubleArray___getitem__(self, *args) 214 def __setitem__(self, *args): return _csnd.doubleArray___setitem__(self, *args) 215 def cast(self): return _csnd.doubleArray_cast(self)TypeError: in method 'doubleArray___getitem__', argument 2 of type 'size_t'In [51]: len(tblDoubleArray)---------------------------------------------------------------------------TypeError Traceback (most recent call last)/home/pinot/Articles/console-python/<ipython console> in <module>()TypeError: object of type 'doubleArray' has no len()In [52]: In [44]: we create a double array pointing to ftable 1 data. (If the floatversion of Csound is used, the line in the comment should be typed instead) In [45] .. In [49]: our click test is successful. Moreover, we can now access theftable samples by indexing the array instead of using get or set functions. In [50]: slicing does not work. In [51]: neither do the len function. A bit more work is needed to get full Python functionalities. Fortunately, Python provides a "swiss knife" for accessing C sharedlibraries from pure Python code: the ctypes module. In [52]: import ctypesIn [53]: bufAdr = tbl.GetPtr(0).__long__()In [54]: tblBuffer = ctypes.ARRAY(ctypes.c_double, tblSize).from_address(bufAdr)# If the float version of Csound is used,# the following line should be typed instead:# tblBuffer = ctypes.ARRAY(ctypes.c_float, tblSize).from_address(bufAdr)In [55]: tblBuffer[1024]Out[55]: 1.0In [56]: tblBuffer[1024] = -1In [57]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [58]: tblBuffer[1024] = 1In [59]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [60]: tblBuffer[1022:1027]Out[60]: [0.99999529380957619, 0.99999882345170188, 1.0, 0.99999882345170188, 0.99999529380957619]In [61]: len(tblBuffer)Out[61]: 4096In [62]: In [53] : we get the pointer to the ftable data as a long integer, which is theusual format for pointers in C. In [54] : we create a ctypes array with elements of type c_double, length equalto tblSize, and buffer pointing to ftable 1 data. This array presents thebuffer interface which allows slicing operations. (If the floatversion of Csound is used, the line in the comment should be typed instead) In [55] .. In [59]: our click test is OK. In [60]: slicing now works... In [61]: and the len function as well. The preceding example (from In [27]: to In [61]: ) has been presented for pedagogicalpurposes. Our CsoundSession class has a method called getTableBufferthat does the same job: it takes an ftable number as argument and it returns a ctypesarray with the appropriate c_float or c_double type depending on theversion of Csound that is used (float or double). Thus we can replace our last exampleswith the two following commands: In [62]: cs.scoreEvent('f', [1, 0, 4096, 10, 1])In [63]: tblBuffer = cs.getTableBuffer(1)In [64]: All the material presented until now was core Python stuff. CsoundSessionitself is written to be used with core Python. But remember, we use an environmentwith numpy and matplotlib. It's time now to take advantage of thosetools. In [64]: tblArray = numpy.frombuffer(tblBuffer)# If the float version of Csound is used,# the following line should be typed instead:# tblArray = numpy.frombuffer(tblBuffer, float32)In [65]: plot(tblArray)Out[65]: [<matplotlib.lines.Line2D object at 0xa69bb6c>]In [66]: axis([0, tblArray.size, -1.1, 1.1])Out[66]: [0, 4096, -1.1000000000000001, 1.1000000000000001]In [67]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [68]: In [64]: we turn our buffer into an numpy array. Note, because IPython wasstarted with the scipy profile, we could have also simply written tblArray = frombuffer(tblBuffer), without mentioning the numpynamespace. (If the floatversion of Csound is used, the line in the comment should be typed instead) In [65]: a simple command lets us plot our data. In [66]: we define some extra vertical space for a nicer drawing (see below). In [67]: listen to our familiar sine note. We can now alter ftable 1 in a more interesting way than putting a singlediscontinuity: we'll insert a notch into the first half of the sine wave. In [68]: tblArray[512]Out[68]: 0.70710678118654746In [69]: m = (-0.5 - tblArray[512]) / (1024.0 - 512.0)In [70]: b = tblArray[512] - 512.0 * mIn [71]: x = arange(512,1025)In [72]: tblArray[512:1025] = m*x + bIn [73]: tblArray[1024]Out[73]: -0.5In [74]: tblArray[1025]Out[74]: 0.98825700000000005In [75]: tblArray[1025:1537] = tblArray[1023:511:-1]In [76]: plot(tblArray)Out[76]: [<matplotlib.lines.Line2D object at 0x95e0ccc>]In [77]: axis([0, tblArray.size, -1.1, 1.1])Out[77]: [0, 4096, -1.1000000000000001, 1.1000000000000001]In [78]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [79]: In [69], In [70]: we define the slope m and the y-intercept b ofthe equation of a straight-line going down from point (512, tblArray[512]) topoint (1024, -0.5). In [71]: we define an array of abscissa values. In [72]: we fill the ordinate values in the ftable 1 data by applying our straightline formula to the abcissa values array. In [75]: positions 1025 to 1536 of the array are filled with the same valuesthan positions 1023 downto 512 (symetric pattern around a vertical axis at position1024) In [76], In [77]: we plot the altered sine wave (green lines) over the originalone (blue lines) (see below). In [78]: listen to the new sound. In [79]: cs.scoreEvent('f', [1, 0, 4096, 10, 1])In [80]: tblArray = frombuffer(cs.getTableBuffer(1))# If the float version of Csound is used,# the following line should be typed instead:# tblArray = frombuffer(cs.getTableBuffer(1), float32)In [81]: cs.note([1, 0, 1, 0.5, 8.75, 1, 0.05, 0.3, 0.5])In [82]: In [79]: back to our sine wave. In [80]: make sure that tblArray points to the right data. For the next section, we generate three ftables containing classical waveforms.ftable 101 is a band limited triangle wave, ftable 111 is aband limited square wave, and ftable 121 is a band limited impulse. The latterone is built with sine waves so that it starts with a zero value. We wrotesome functions in a python script called sessionUtils.py,so that we can play with them by changing their arguments. The script is loadedwith the IPython magic command %run. Each time we modify the script, we canreload the modified script with the %run command. The script includescomments about some traps to avoid. If you fixed the orchestra sampling rate toa lower value than 96000 Hz you'll have to change the last argument of the blTriangle,blSquare, and blImpulse functions to a lower number of harmonics to avoidfoldover: In [82]: %run sessionUtils.pyIn [83]: blTriangle(cs, 101, 4096, 25)In [84]: blSquare(cs, 111, 4096, 25)In [85]: blImpulse(cs, 121, 4096, 25)In [86]: clf(); drawTable(cs, 101); drawTable(cs, 111); drawTable(cs, 121)# If the float version of Csound is used,# the following line should be typed instead:# clf(); drawTable(cs, 101, float32); drawTable(cs, 111, float32); drawTable(cs, 121, float32)In [87]: cs.note([1, 0, 1, 0.5, 6.75, 101, 0.05, 0.3, 0.5])In [88]: cs.note([1, 0, 1, 0.5, 6.75, 111, 0.05, 0.3, 0.5])In [89]: cs.note([1, 0, 1, 0.5, 6.75, 121, 0.05, 0.3, 0.5])In [90]: Then we generate interpolated ftables between ftable 101 and ftable 111, andbetween ftable 111 and ftable 121. We have now 21 ftables to play with: In [90]: interpolateTables(cs, 101, 111)# If the float version of Csound is used,# the following line should be typed instead:# interpolateTables(cs, 101, 111, float32)In [91]: interpolateTables(cs, 111, 121)# If the float version of Csound is used,# the following line should be typed instead:# interpolateTables(cs, 111, 121, float32)In [92]: We can listen to two series of 110 Hz notes using successively our ftables: In [92]: for i in range(101, 112): cs.note([1, i-101, 0.7, 0.4, 6.75, i, 0.05, 0.3, 0.5]) ....: ....: In [93]: for i in range(111, 122): cs.note([1, i-111, 0.7, 0.4, 6.75, i, 0.05, 0.3, 0.5]) ....: ....:In [94]: 'i' Statement The 'i' score statement sends a note to the orchestra to be played by aninstrument. Because this statement is used very often during a session, theCsoundSession class provides a note method which is a syntacticsugar for a scoreEvent('i', ...) call. We already used it in the examplesof the last section. It has an argument of type tuple, list or array, representingthe pfields for the note to be played. To illustrate the use of the note method, we will build a musical structurebased on a ruled surface: a hyperbolic paraboloid. This idea was introduced byIannis Xenakis in 1954 in his first orchestra piece Metastasis. He used stringglissandi as interlaced straight lines to obtain sonic spaces of continuousevolution [5]. To draw a hyperbolic paraboloid in a 3D space, we use two non-coplanar lines (the bluelines in figure 7), and we join them by straight lines intersecting the two baselines at equally spaced points on them (the red lines in figure 7).Those lines run along a ruled surface called a hyperbolic paraboloid: In [94]: from mpl_toolkits.mplot3d import Axes3DIn [95]: fig = figure()In [96]: ax = Axes3D(fig)In [97]: nlines = 41In [98]: l1 = array([linspace(1, -1, nlines), ones(nlines)*(-1), linspace(-1, 1, nlines)])In [99]: l2 = array([linspace(1, -1, nlines), ones(nlines), linspace(1, -1, nlines)])In [100]: sl = skewlines(l1, l2, 100, ax)In [101]: In [94] to In [97]: we initialize a 3D figure in matplotlib. In [97]: We will generate 41 skew lines. In [98], In [99]: our two base lines are the non parallel diagonals of two opposite faces ofa cube with length 2 sides. In [100]: the ruled surface is drawn by the skewlines function of oursessionUtils.py script. The figure can be rotated by dragging the mouse on it(in the figure window, not on the fixed picture of this article). Due to a bug inthe show routine, Windows user will have to close the figure window beforeentering further commands. So, each call to skewline from Windows has tobe preceded by the fig = figure() and ax = Axes3D(fig) commands.Linux users do not need to do this. For our example, we use 17 skew lines on a hyperbolic paraboloid (figure 8), butinstead of playing glissandi, we play 400 overlapping notes (grains) along each line.The values along the 'x' axis are interpreted as pan values, the 'y' axis representstime, and the values along the 'z' axis are pitches. Each grain uses one of the ftables(101 to 121) defined in the last section. All the work is done by the playHPfunction of our sessionUtils.py script. The whole example has a duration oftwo minutes, playing 400 * 17 = 8600 notes: In [101]: nlines = 17In [102]: l1 = array([linspace(1, -1, nlines), ones(nlines)*(-1), linspace(-1, 1, nlines)])In [103]: l2 = array([linspace(-1, 1, nlines), linspace(1, -0.25, nlines), zeros(nlines)])In [104]: sl = skewlines(l1, l2, 400, ax)In [105]: playHP(cs, sl, 4.00, 8.75, 120, 101, 121)In [106]: The above call to playHP should produce sounds like this. 'q' Statement The 'q' score statement is used to quiet an instrument: In [106]: cs.note([1, 0, 30, 0.5, 6.875, 101, 0.05, 0.3, 0.5])In [107]: cs.scoreEvent('q', (1, 0, 0))In [108]: Setting instrument 1 off#return key hit to get the right promptIn [109]: cs.note([1, 0, 10, 0.5, 7.875, 101, 0.05, 0.3, 0.5])In [110]: cs.scoreEvent('q', (1, 0, 1))In [111]: Setting instrument 1 on#return key hit to get the right promptIn [112]: cs.note([1, 0, 10, 0.5, 7.875, 101, 0.05, 0.3, 0.5])In [113]: In [106]: we start a long 110 Hz note. In [107]: we ask Csound to quiet instrument 1: p1 = 1 (instrument number),p2 = 0 (immediatly), p3 = 0 (mute). In [108]: Csound tells us that instrument 1 is off. Note that this does notaffect the note actually played. In [109]: we try to play a 220 Hz note. It is not heard. In [110]: we ask Csound to unmute instrument 1. In [112]: we try again to play a 220 Hz note and this time we hear it. Coda Csound, Python, and the SciPy suite form together an incrediblypowerful set of tools to experiment with. This paper has only surveyed a small part of what is possible. Thesetools may seem complex (and they surely are!) but one can find a lot ofdocumentation available. High level mathematics languages like Matlab, Octave or Scilab can giveexamples and ideas. Some ideas: modify the orchestra in a text editor while it isperformed by a CsoundSession object, and then load it into another CsoundSessionobject so that there is no sound interrruption. Modify the CsoundSession classso that the scoreEvent method can store into a text file a line in score formatfor each event it sends to Csound. Thus when the session ends, we can usethis text file to copy and paste events into a <CsScore> section of a CSDfile. IV. Conclusion This article presents some mechanisms of the Csound API: launching a Csound session,performing a CSD file, getting information from Csound, using multithreading, accessingCsound internal buffers, and playing with score events. The Csound API offers many morepossibilities such channel I/O, callback functions, and MIDI control. Using Python and the Csound API allows themusician-programmer to explore these new territories in realtime. References [1] Fernando Perez, Brian E. Granger, "IPython: A System for Interactive Scientific Computing," Computing in Science and Engineering, vol. 9, no. 3, pp. 21-29, May/June 2007. [2] Python Software Foundation, The Python Tutorial, Release 2.7, December 28, 2010. [3] Richard Boulanger, An Instrument Design TOOTorial, Boston, Massachusetts, March, 1991. [4] Barry Vercoe et Al. 2005. The Canonical Csound Reference Manual.. [Accessed Dec. 27, 2010]. [5] Iannis Xenakis, FORMALIZED MUSIC: Thought and Mathematics inMusic, Pendragon Revised Edition, Pendragon Press, 1992. Links An Instrument Design TOOTorial Writing your own .csd files
http://www.csounds.com/journal/issue14/realtimeCsoundPython.html
CC-MAIN-2015-40
refinedweb
5,430
67.45
Same great maps plus a SLA, support, and control over ads The Google Maps API is now integrated with the Google AJAX API loader, which creates a common namespace for loading and using multiple Google AJAX APIs. This framework allows you to use the optional google.maps.* namespace for all classes, methods and properties you currently use in the Google Maps API, replacing the normal G prefix with this namespace. Don't worry: the existing G namespace will continue to be supported. For example, the GMap2 object within the Google Maps API can also be defined as google.maps.Map2. Note that this reference documentation refers only to the existing G namespace. If you only want to use the map to display your content, then you need to know these classes, types, and functions: If you want to extend the functionality of the maps API by implementing your own controls, overlays, or map types, then you also need to know these classes and types: Instantiate class GMap2 in order to create a map. This is the central class in the API. Everything else is auxiliary. This class represents optional arguments to the GMap2 constructor. It has no constructor, but is instantiated as an object literal. This class represents options passed within the googleBarOptions parameter to the GMapOptions object. It has no constructor, but is instantiated as an object literal. Note that the GGoogleBar object, like the GInfoWindow is not constructed, but is automatically attached to the map object, and enabled through properties described here. These constants are passed in GGoogleBarOptions.linkTarget, and define the default target for links in result info windows. These constants are passed in GGoogleBarOptions.resultList, and define how the result list is displayed. These constants define the layering system that is used by overlay to display themselves on the map. There are different layers for icons, shadows, the info window, the shadow on the info window, and transparent mouse event catching objects. You need to use this type if you subclass from GOverlay. Instantiate this class to add keyboard bindings to a map. The key bindings are the same as for the maps application. This interface is implemented by the GMarker, GPolyline, GTileLayerOverlay and GInfoWindow classes in the maps API library. You can implement it if you want to display custom types of overlay objects on the map. An instance of GOverlay can be put on the map with the method GMap2.addOverlay(). The map will then call the method GOverlay.initialize() on the overlay instance to display itself on the map initially. Whenever the map display changes, the map will call GOverlay.redraw() so that the overlay can reposition itself if necessary. The overlay instance can use the method GMap2.getPane() to get hold of one or more DOM container elements to attach itself to. GInfoWindow has no constructor. It is created by the map and accessed by its method GMap2.getInfoWindow(). An array of instances of this class can be passed as the tabs argument to the methods GMap2.openInfoWindowTabs(), GMap2.openInfoWindowTabsHtml(), GMarker.openInfoWindowTabs(), GMarker.openInfoWindowTabsHtml(), and the GMarker.bindInfoWindow*() variants. If the array contains more than one element, the info window will be shown with tabs. Every InfoWindowTab object contains two items: content defines the content of the info window when the tab is selected, and label defines the label of the tab. The properties are passed as arguments to the constructor. For the openInfoWindowTabs() methods, content is a DOM Node. For the methods openInfoWindowTabsHtml(), content is a string that contains HTML text. Instances of this class are used in the opts? argument to the methods openInfoWindow(), openInfoWindowHtml(), openInfoWindowTabs(), openInfoWindowTabsHtml(), the bindInfoWindow*() variants, and showMapBlowup() of classes GMap2 and GMarker. There is no constructor for this class. Instead, this class is instantiated as javascript object literal. As the name of this class indicates, all properties are optional. A. Before these methods can be invoked, the marker must be added to a map. All these events fire only if the marker is not inert (see constructor). Instances of this class are used in the opts? argument to the constructor of the GMarker class. There is no constructor for this class. Instead, this class is instantiated as a javascript object literal. As the name of this class indicates, all properties are optional. This is a map overlay that draws a polyline on the map, using the vector drawing facilities of the browser if they are available, or an image overlay from Google servers otherwise. Instances of this class are used in GPolyline's constructor. There is no constructor for this class. Instead, this class is instantiated as a javascript object literal. As the name of this class indicates, all properties are optional. This is very similar to a GPolyline, except that you can additionally specify a fill color and opacity. Instances of this class are used in GPolygon's constructor. There is no constructor for this class. Instead, this class is instantiated as a javascript object literal. As the name of this class indicates, all properties are optional. This object displays a rectangular image overlay on the map whose position remains fixed as the viewport changes. Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. A GScreenPoint identifies a point on the viewport of the map by an X and Y coordinate, each of which can represent fractional or absolute positioning depending on the value of the optional constructor parameters. A GScreenSize indicates the size of a rectangular area of the map, determined by the width and height parameters. Each of those parameters can represent fractional or pixel size depending on the value of the optional constructor parameters. This object creates a rectangular image overlay on the map, whose boundaries are defined by GLatLngBounds. An icon specifies the images used to display a GMarker on the map. For browser compatibility reasons, specifying an icon is actually quite complex. Note that you can use the default Maps icon G_DEFAULT_ICON if you don't want to specify your own. A GPoint represents a point on the map by its pixel coordinates. Notice that in v2, it doesn't represent a point on the earth by its geographical coordinates anymore. Geographical coordinates are now represented by GLatLng. In the Google Maps coordinate system, the x coordinate increases to the right, and the y coordinate increases downwards, though you may use GPoint coordinates however you wish. Notice that while the two parameters of a GPoint are accessible as properties x and y, it is better to never modify them, but to create a new object with different paramaters instead. A GSize is the size in pixels of a rectangular area of the map. The size object has two parameters, width and height. Width is a difference in the x-coordinate; height is a difference in the y-coordinate, of points. Notice that while the two parameters of a GSize are accessible as properties width and height, it is better to never modify them, but to create a new object with different paramaters instead.
http://code.google.com/apis/maps/documentation/reference.html
crawl-001
refinedweb
1,176
57.06
cloner don't refresh On 02/02/2017 at 10:13, xxxxxxxx wrote: Hi , when I try to change the cloner type with python in the script manager , the mode changes , but the interface don't update until I set the type manually . I tried the .message , with some flags but couldn't find the right one , any advice on how to solve this problem ? thanks :) On 02/02/2017 at 10:34, xxxxxxxx wrote: Did you tried c4d.EventAdd() On 02/02/2017 at 19:48, xxxxxxxx wrote: sure , it is always in the end of my code On 03/02/2017 at 01:04, xxxxxxxx wrote: Maybe you should post a code because maybe I missunderstand waht you mean by type but here doing the following working correctly import c4d import random def main() : op[c4d.ID_MG_MOTIONGENERATOR_MODE] = random.randint(0,3) c4d.EventAdd() if __name__=='__main__': main() You could also try to setDirty On 03/02/2017 at 01:31, xxxxxxxx wrote: Originally posted by xxxxxxxx Maybe you should post a code because maybe I missunderstand waht you mean by type but here doing the following working correctly even in your code it is the same problem , check the pic : the cloner mode is set to grid array but the interface is for the object mode (the previous mode which I set manually ) On 03/02/2017 at 01:57, xxxxxxxx wrote: For me is working correctly when I press the button execute. Everything is updated correctly. Maybe you tried it in a thread context? And I guess dev will as kyou your c4d version (My last code working on the last R17/R18) On 03/02/2017 at 02:08, xxxxxxxx wrote: Originally posted by xxxxxxxx For me is working correctly when I press the button execute. Everything is updated correctly. Maybe you tried it in a thread context? And I guess dev will as kyou your c4d version (My last code working on the last R17/R18) thanks for help , the problem was weird , if my cloner don't have child then it doesn't update , but if I put an object under it it works fine . On 03/02/2017 at 08:55, xxxxxxxx wrote: Hi guys, I'm sorry for chiming in so late. Are you really sure, it's solved on your end? I still can reproduce the initial problem even with children here. I'll investigate further on Monday. On 03/02/2017 at 09:39, xxxxxxxx wrote: at the moment every thing is ok check this code if it working in your end or not (it is running fine with me ) import c4d from c4d import gui , utils def main() : spline = doc.GetActiveObject() #you have to select and editable spline if spline == None or spline.GetType() !=5101: gui.MessageDialog("Select a spline to start !") return clo = c4d.BaseObject(1018544) # define cloner cir = c4d.BaseObject(5179) # define n-side spline cir.InsertUnder(clo) doc.InsertObject(clo) # create cloner clo[c4d.ID_MG_MOTIONGENERATOR_MODE]=0 clo[c4d.MG_OBJECT_LINK] = spline clo[c4d.MG_SPLINE_MODE]=3 c4d.EventAdd() if __name__=='__main__': main() On 06/02/2017 at 06:53, xxxxxxxx wrote: Hi, you are lucky as you create the cloner and set the mode just once. If you were trying to implement a script, which for example toggles the mode between linear and radial, then you'd run into the same issue again (the AM interface not properly reflecting the mode change). The problem is, that after a change of this parameter a MSG_DESCRIPTION_CHECKUPDATE is needed. Unfortunately this message is currently not supported in our Python SDK, so it's currently not possible to reliably switch the mode parameter of a MoGraph cloner from Python. I have set this message type on the list of our Python todos. On 06/02/2017 at 20:30, xxxxxxxx wrote: Thanks for your help :)
https://plugincafe.maxon.net/topic/9936/13379_cloner-dont-refresh
CC-MAIN-2019-22
refinedweb
643
69.21
This page explains the quotas and limits for Google Kubernetes Engine clusters, nodes, and GKE API requests. GKE's per-project limits are: - Maximum of 50 clusters per zone, plus 50 regional clusters per region. - Maximum of 5000 nodes per cluster. - Maximum of 1000 nodes per cluster if you use the GKE ingress controller. - 100 Pods per node. - 300,000 containers. The rate limit for the GKE API is 10 requests per second. You might also encounter Compute Engine resource quotas. Additionally, for projects with default regional Compute Engine CPUs quota, container clusters are limited to three per region. Resource Quotas Starting with GKE 1.11.4, for clusters with five nodes or fewer, gke-resource-quotas objects are listed in the output of kubectl get resourcequotas --all-namespaces. Currently the quotas are set to a very large number, so they are virtually unlimited.
https://cloud.google.com/kubernetes-engine/quotas
CC-MAIN-2019-09
refinedweb
144
58.89
Original content created by Cam Davidson-Pilon Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian). %matplotlib inline import numpy as np import scipy.stats as stats from IPython.core.pylabtools import figsize import matplotlib.pyplot as plt figsize(12.5,3) colors = ["#348ABD", "#A60628", "#7A68A6", "#467821"] x = np.linspace(0,1) y1, y2 = stats.beta.pdf(x, 1,1), stats.beta.pdf(x, 10,10) p = plt.plot(x, y1, label='An objective prior \n(uninformative, \n"Principle of Indifference")') plt.fill_between(x, 0, y1, color = p[0].get_color(), alpha = 0.3) p = plt.plot(x,y2 , label = "A subjective prior \n(informative)") plt.fill_between(x, 0, y2, color = p[0].get_color(), alpha = 0.3) p = plt.plot(x[25:], 2*np.ones(25), (TODO).: $$ \mu_p = \frac{1}{N} \sum_{i=0}^N X_i $$: figsize(12.5, 5) gamma = stats.gamma parameters = [(1, 0.5), (9, 2), (3, 0.5), (7, 0.5)] x = np.linspace(0.001 ,20, 150) for alpha, beta in parameters: y = gamma.pdf(x, alpha, scale=1./beta): n = 4 for i in range(10): ax = plt.subplot(2, 5, i+1) if i >= 5: n = 15 plt.imshow(stats.wishart.rvs(n+1, np.eye(n)), interpolation="none", cmap = "hot") ax.axis("off") plt.suptitle("Random matrices from a Wishart Distribution");: $$f_X(x | \; \alpha, \beta ) = \frac{ x^{(\alpha - 1)}(1-x)^{ (\beta - 1) } }{B(\alpha, \beta) }$$: figsize(12.5, 5) params = [(2, 5), (1, 1), (0.5, 0.5), (5, 5), (20, 4), (5, 1)] x = np.linspace(0.01, .99, 100) beta = stats.beta for a, b in params: y = beta.pdf(x, a, b) lines = plt.plot(x, y, label = "(%.1f,%.1f)"%(a,b), lw = 3) plt.fill_between(x, 0, y, alpha = 0.2, color = lines[0].get_color()) plt.autoscale(tight=True) plt.ylim(0) plt.legend(loc = 'upper left', title="(a,b)−X)$.. rand = np.random.rand class Bandits(object): """ This class represents N bandits machines. parameters: p_array: a (n,) Numpy array of probabilities >0, <1. methods: pull( i ): return the results, 0 or 1, of pulling the ith bandit. """ def __init__(self, p_array): self.p = p_array self.optimal = np.argmax(p_array) def pull(self, i): #i is which arm to pull return np.random.rand() < self.p[i] def __len__(self): return len(self.p) class BayesianStrategy(object): """ Implements a online, learning strategy to solve the Multi-Armed Bandit problem. parameters: bandits: a Bandit class with .pull method methods: sample_bandits(n): sample and train on n pulls. attributes: N: the cumulative number of samples choices: the historical choices as a (N,) array bb_score: the historical score as a (N,) array """ def __init__(self, bandits): self.bandits = bandits n_bandits = len(self.bandits) self.wins = np.zeros(n_bandits) self.trials = np.zeros(n_bandits) self.N = 0 self.choices = [] self.bb_score = [] def sample_bandits(self, n=1): bb_score = np.zeros(n) choices = np.zeros(n) for k in range(n): #sample from the bandits's priors, and select the largest sample choice = np.argmax(np.random.beta(1 + self.wins, 1 + self.trials - self.wins)) #sample the chosen bandit result = self.bandits.pull(choice) #update priors and score self.wins[choice] += result self.trials[choice] += 1 bb_score[k] = result self.N += 1 choices[k] = choice self.bb_score = np.r_[self.bb_score, bb_score] self.choices = np.r_[self.choices, choices] return Below we visualize the learning of the Bayesian Bandit solution. figsize(11.0, 10) beta = stats.beta x = np.linspace(0.001,.999,200) def plot_priors(bayesian_strategy, prob, lw = 3, alpha = 0.2, plt_vlines = True): ## plotting function wins = bayesian_strategy.wins trials = bayesian_strategy.trials for i in range(prob.shape[0]): y = beta(1+wins[i], 1 + trials[i] - wins[i]) p = plt.plot(x, y.pdf(x), lw = lw) c = p[0].get_markeredgecolor() plt.fill_between(x,y.pdf(x),0, color = c, alpha = alpha, label="underlying probability: %.2f" % prob[i]) if plt_vlines: plt.vlines(prob[i], 0, y.pdf(prob[i]) , colors = c, linestyles = "--", lw = 2) plt.autoscale(tight = "True") plt.title("Posteriors After %d pull" % bayesian_strategy.N +\ "s"*(bayesian_strategy.N > 1)) plt.autoscale(tight=True) return hidden_prob = np.array([0.85, 0.60, 0.75]) bandits = Bandits(hidden_prob) bayesian_strat = BayesianStrategy(bandits) draw_samples = [1, 1, 3, 10, 10, 25, 50, 100, 200, 600] for j,i in enumerate(draw_samples): plt.subplot(5, 2, j+1) bayesian_strat.sample_bandits(i) plot_priors(bayesian_strat, hidden_prob) , optimally we can attain the reward/pull ratio of the maximum bandit probability.("Total Regret of Bayesian Bandits Strategy vs. Random guessing") plt.xlabel("Number of pulls") plt.ylabel(. trials = 500 expected_total_regret = np.zeros((10000, 3))"); plt.figure() [pl1, pl2, pl3] = plt.plot(expected_total_regret[:, [0,1,2]], lw = 3) plt.xscale("log") plt.legend([pl1, pl2, pl3], ["Upper Credible Bound", "Bayesian Bandit", "UCB-Bayes"], loc="upper left") plt.ylabel("Exepected Total Regret \n after $\log{n}$ pulls"); plt.title( "log-scale of above" ); plt.ylabel("Exepected Total Regret \n after $\log{n}$ pulls"); Because of the Bayesian Bandits algorithm's simplicity, it is easy to extend. Some possibilities: If interested in the minimum probability (eg: where prizes are a bad thing), simply choose $B = \text{argmin} \; X_b$ and proceed. Adding learning rates: Suppose the underlying environment may change over time. Technically the standard Bayesian Bandit algorithm would self-update itself (awesome) by noting that what it thought was the best is starting to fail more often. We can motivate the algorithm to learn changing environments quicker by simply adding a rate term upon updating: self.wins[choice] = rate*self.wins[choice] + result self.trials[choice] = rate*self.trials[choice] + 1 If rate < 1, the algorithm will forget its previous wins quicker and there will be a downward pressure towards ignorance. Conversely, setting rate > 1 implies your algorithm will act more risky, and bet on earlier winners more often and be more resistant to changing environments. Hierarchical algorithms: We can setup a Bayesian Bandit algorithm on top of smaller bandit algorithms. Suppose we have $N$ Bayesian Bandit models, each varying in some behavior (for example different rate parameters, representing varying sensitivity to changing environments). On top of these $N$ models is another Bayesian Bandit learner that will select a sub-Bayesian Bandit. This chosen Bayesian Bandit will then make an internal choice as to which machine to pull. The super-Bayesian Bandit updates itself depending on whether the sub-Bayesian Bandit was correct or not. Extending the rewards, denoted $y_a$ for bandit $a$, to random variables from a distribution $f_{y_a}(y)$ is straightforward. More generally, this problem can be rephrased as "Find the bandit with the largest expected value", as playing the bandit with the largest expected value is optimal. In the case above, $f_{y_a}$ was Bernoulli with probability $p_a$, hence the expected value for a bandit is equal to $p_a$, which is why it looks like we are aiming to maximize the probability of winning. If $f$ is not Bernoulli, and it is non-negative, which can be accomplished apriori by shifting the distribution (we assume we know $f$), then the algorithm behaves as before: For each round, Return to 1 The issue is in the sampling of $X_b$ drawing phase. With Beta priors and Bernoulli observations, we have a Beta posterior — this is easy to sample from. But now, with arbitrary distributions $f$, we have a non-trivial posterior. Sampling from these can be difficult. There has been some interest in extending the Bayesian Bandit algorithm to commenting systems. Recall in Chapter 4, we developed a ranking algorithm based on the Bayesian lower-bound of the proportion of upvotes to total votes. One problem with this approach is that it will bias the top rankings towards older comments, since older comments naturally have more votes (and hence the lower-bound is tighter to the true proportion). This creates a positive feedback cycle where older comments gain more votes, hence are displayed more often, hence gain more votes, etc. This pushes any new, potentially better comments, towards the bottom. J. Neufeld proposes a system to remedy this that uses a Bayesian Bandit solution. His proposal is to consider each comment as a Bandit, with the number of pulls equal to the number of votes cast, and number of rewards as the number of upvotes, hence creating a $\text{Beta}(1+U,1+D)$ posterior. As visitors visit the page, samples are drawn from each bandit/comment, but instead of displaying the comment with the $\max$ sample, the comments are ranked according to the ranking of their respective samples. From J. Neufeld's blog [7]: [The] resulting ranking algorithm is quite straightforward, each new time the comments page is loaded, the score for each comment is sampled from a $\text{Beta}(1+U,1+D)$, comments are then ranked by this score in descending order... This randomization has a unique benefit in that even untouched comments $(U=1,D=0)$ have some chance of being seen even in threads with 5000+ comments (something that is not happening now), but, at the same time, the user is not likely to be inundated with rating these new comments. Just for fun, though the colors explode, we watch the Bayesian Bandit algorithm learn 15 different options. figsize(12.0, 8) beta = stats.beta hidden_prob = beta.rvs(1,13, size = 35) print(hidden_prob) bandits = Bandits(hidden_prob) bayesian_strat = BayesianStrategy(bandits) for j,i in enumerate([100, 200, 500, 1300]): plt.subplot(2, 2, j+1) bayesian_strat.sample_bandits(i) plot_priors(bayesian_strat, hidden_prob, lw = 2, alpha = 0.0, plt_vlines=False) #plt.legend() plt.xlim(0, 0.5) [ 6.78509844e-03 9.68721665e-02 3.16101371e-02 8.88059449e-02 3.32812651e-02 6.59572621e-02 7.91635546e-02 5.97822577e-02 1.17088549e-01 1.29945195e-05 3.66798062e-02 5.77077187e-02 4.32774140e-02 6.94914246e-02 1.22741733e-01 5.13528129e-02 3.29414904e-01 5.13320236e-02 5.35031763e-02 1.57610420e-02 1.94570205e-02 1.11759388e-01 3.23349076e-02 2.04068995e-02 1.47822753e-01 8.24022697e-03 3.20395660e-04 4.45643230e-03 6.42090321e-03 7.29322919e-02 8.18486095e-02 5.05066236e-03 1.73946201e-01 6.48018322e-02 7.70657954e-03] Specifying a subjective prior is how practitioners incorporate domain knowledge about the problem into our mathematical framework. Allowing domain knowledge is useful for many reasons: plus many other reasons. Of course, practitioners of Bayesian methods are not experts in every field, so we must turn to domain experts to craft our priors. We must be careful with how we elicit these priors though. Some things to consider: From experience, I would avoid introducing Betas, Gammas, etc. to non-Bayesian practitioners. Furthermore, non-statisticians can get tripped up by how a continuous probability function can have a value exceeding one. Individuals often neglect the rare tail-events and put too much weight around the mean of distribution. Related to above is that almost always individuals will under-emphasize the uncertainty in their guesses. Eliciting priors from non-technical experts is especially difficult. Rather than introduce the notion of probability distributions, priors, etc. that may scare an expert, there is a much simpler solution. The trial roulette method [8] focuses on building a prior distribution by placing counters (think casino chips) on what the expert thinks are possible outcomes. The expert is given $N$ counters (say $N=20$) and is asked to place them on a pre-printed grid, with bins representing intervals. Each column would represent their belief of the probability of getting the corresponding bin result. Each chip would represent an $\frac{1}{N} = 0.05$ increase in the probability of the outcome being in that interval. For example [9]: A student is asked to predict the mark in a future exam. The figure below shows a completed grid for the elicitation of a subjective probability distribution. The horizontal axis of the grid shows the possible bins (or mark intervals) that the student was asked to consider. The numbers in top row record the number of chips per bin. The completed grid (using a total of 20 chips) shows that the student believes there is a 30% chance that the mark will be between 60 and 64.9. From this, we can fit a distribution that captures the expert's choice. Some reasons in favor of using this technique are: Many questions about the shape of the expert's subjective probability distribution can be answered without the need to pose a long series of questions to the expert - the statistician can simply read off density above or below any given point, or that between any two points. During the elicitation process, the experts can move around the chips if unsatisfied with the way they placed them initially - thus they can be sure of the final result to be submitted. It forces the expert to be coherent in the set of probabilities that are provided. If all the chips are used, the probabilities must sum to one. Graphical methods seem to provide more accurate results, especially for participants with modest levels of statistical sophistication. Take note stock brokers: you're doing it wrong. When choosing which stocks to pick, an analyst will often look at the daily return of the stock. Suppose $S_t$ is the price of the stock on day $t$, then the daily return on day $t$ is : $$r_t = \frac{ S_t - S_{t-1} }{ S_{t-1} } $$ The expected daily return of a stock is denoted $\mu = E[ r_t ]$. Obviously, stocks with high expected returns are desirable. Unfortunately, stock returns are so filled with noise that it is very hard to estimate this parameter. Furthermore, the parameter might change over time (consider the rises and falls of AAPL stock), hence it is unwise to use a large historical dataset. Historically, the expected return has been estimated by using the sample mean. This is a bad idea. As mentioned, the sample mean of a small sized dataset has enormous potential to be very wrong (again, see Chapter 4 for full details). Thus Bayesian inference is the correct procedure here, since we are able to see our uncertainty along with probable values. For this exercise, we will be examining the daily returns of the AAPL, GOOG, MSFT and AMZN. Before we pull in the data, suppose we ask our a stock fund manager (an expert in finance, but see [10] ), What do you think the return profile looks like for each of these companies? Our stock broker, without needing to know the language of Normal distributions, or priors, or variances, etc. creates four distributions using the trial roulette method above. Suppose they look enough like Normals, so we fit Normals to them. They may look like: figsize(11., 5) colors = ["#348ABD", "#A60628", "#7A68A6", "#467821"] normal = stats.norm x = np.linspace(-0.15, 0.15, 100) expert_prior_params = {"AAPL":(0.05, 0.03), "GOOG":(-0.03, 0.04), "TSLA": (-0.02, 0.01), "AMZN": (0.03, 0.02), } for i, (name, params) in enumerate(expert_prior_params.items()): plt.subplot(2, 2, i+1) y = normal.pdf(x, params[0], scale = params[1]) #plt.plot( x, y, c = colors[i] ) plt.fill_between(x, 0, y, color = colors[i], linewidth=2, edgecolor = colors[i], alpha = 0.6) plt.title(name + " prior") plt.vlines(0, 0, y.max(), "k","--", linewidth = 0.5) plt.xlim(-0.15, 0.15) plt.tight_layout() Note that these are subjective priors: the expert has a personal opinion on the stock returns of each of these companies, and is expressing them in a distribution. He's not wishful thinking -- he's introducing domain knowledge. In order to better model these returns, we should investigate the covariance matrix of the returns. For example, it would be unwise to invest in two stocks that are highly correlated, since they are likely to tank together (hence why fund managers suggest a diversification strategy). We will use the Wishart distribution for this, introduced earlier. Let's get some historical data for these stocks. We will use the covariance of the returns as a starting point for our Wishart random variable. This is not empirical bayes (as we will go over later) because we are only deciding the starting point, not influencing the parameters. # I wish I could have used Pandas as a prereq for this book, but oh well. import datetime import collections import ystockquote as ysq import pandas as pd n_observations = 100 # we will truncate the the most recent 100 days. stocks = ["AAPL", "GOOG", "TSLA", "AMZN"] enddate = "2015-04-27" startdate = "2012-09-01" CLOSE = 6 stock_closes = pd.DataFrame() for stock in stocks: x = np.array(ysq.get_historical_prices(stock, startdate, enddate)) stock_series = pd.Series(x[1:,CLOSE].astype(float), name=stock) stock_closes[stock] = stock_series stock_closes = stock_closes[::-1] stock_returns = stock_closes.pct_change()[1:][-n_observations:] dates = list(map(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d"), x[1:n_observations+1,0])) And here let's form our basic model: import pymc3 as pm import theano.tensor as tt from theano.tensor.nlinalg import matrix_inverse, diag, matrix_dot prior_mu = np.array([x[0] for x in expert_prior_params.values()]) prior_std = np.array([x[1] for x in expert_prior_params.values()]) init = stock_returns.cov() with pm.Model() as model: cov_matrix = pm.WishartBartlett("covariance", np.diag(prior_std**2), 10, testval = init) mu = pm.Normal("returns", mu=prior_mu, sd=1, shape=4) Applied log-transform to c and added transformed c_log_ to model. Added new variable c to model diagonal of Wishart. Added new variable z to model off-diagonals of Wishart. Here are the returns for our chosen stocks: figsize(12.5, 4) cum_returns = np.cumprod(1 + stock_returns) - 1 cum_returns.index = dates[::-1] cum_returns.plot() plt.legend(loc = "upper left") plt.title("Return space") plt.ylabel("Return of $1 on first date, x100%"); figsize(11., 5 ) for i, _stock in enumerate(stocks): plt.subplot(2,2,i+1) plt.hist(stock_returns[_stock], bins=20, normed = True, histtype="stepfilled", color=colors[i], alpha=0.7) plt.title(_stock + " returns") plt.xlim(-0.15, 0.15) plt.tight_layout() plt.suptitle("Histogram of daily returns", size =14); Below we perform the inference on the posterior mean return and posterior covariance matrix. with model: obs = pm.MvNormal("observed returns", mu=mu, cov=cov_matrix, observed=stock_returns) step = pm.NUTS() trace = pm.sample(5000, step=step) [-------100%-------] 5000 of 5000 in 40.4 sec. | SPS: 123.8 | ETA: 0.0 figsize(12.5,4) #examine the mean return first. mu_samples = trace["returns"] for i in range(4): plt.hist(mu_samples[:,i], alpha = 0.8 - 0.05*i, bins = 30, histtype="stepfilled", normed=True, label = "%s" % stock_returns.columns[i]) plt.vlines(mu_samples.mean(axis=0), 0, 500, linestyle="--", linewidth = .5) plt.title("Posterior distribution of $\mu$, daily stock returns") plt.legend(); (Plots like these are what inspired the book's cover.) What can we say about the results above? Clearly TSLA has been a strong performer, and our analysis suggests that it has an almost 1% daily return! Similarly, most of the distribution of AAPL is negative, suggesting that its true daily return is negative. You may not have immediately noticed, but these variables are a whole order of magnitude less than our priors on them. For example, to put these one the same scale as the above prior distributions: figsize(11.0,3) for i in range(4): plt.subplot(2,2,i+1) plt.hist(mu_samples[:,i], alpha = 0.8 - 0.05*i, bins = 30, histtype="stepfilled", normed=True, color = colors[i], label = "%s" % stock_returns.columns[i]) plt.title("%s" % stock_returns.columns[i]) plt.xlim(-0.15, 0.15) plt.suptitle("Posterior distribution of daily stock returns") plt.tight_layout() Why did this occur? Recall how I mentioned that finance has a very very low signal to noise ratio. This implies an environment where inference is much more difficult. One should be careful about over-interpreting these results: notice (in the first figure) that each distribution is positive at 0, implying that the stock may return nothing. Furthermore, the subjective priors influenced the results. From the fund managers point of view, this is good as it reflects his updated beliefs about the stocks, whereas from a neutral viewpoint this can be too subjective of a result. Below we show the posterior correlation matrix, and posterior standard deviations. An important caveat to know is that the Wishart distribution models the inverse covariance matrix, so we must invert it to get the covariance matrix. We also normalize the matrix to acquire the correlation matrix. Since we cannot plot hundreds of matrices effectively, we settle by summarizing the posterior distribution of correlation matrices by showing the mean posterior correlation matrix (defined on line 2). cov_samples = trace["covariance"] mean_covariance_matrix = cov_samples.mean(axis=0) def cov2corr(A): """ covariance matrix to correlation matrix. """ d = np.sqrt(A.diagonal()) A = ((A.T/d).T)/d #A[ np.diag_indices(A.shape[0]) ] = np.ones( A.shape[0] ) return A plt.subplot(1,2,1) plt.imshow(cov2corr(mean_covariance_matrix) , interpolation="none", cmap = "hot") plt.xticks(np.arange(4), stock_returns.columns) plt.yticks(np.arange(4), stock_returns.columns) plt.colorbar(orientation="vertical") plt.title("(mean posterior) Correlation Matrix") plt.subplot(1,2,2) plt.bar(np.arange(4), np.sqrt(np.diag(mean_covariance_matrix)), color = "#348ABD", alpha = 0.7) plt.xticks(np.arange(4) + 0.5, stock_returns.columns); plt.title("(mean posterior) standard deviations of daily stock returns") plt.tight_layout(); Looking at the above figures, we can say that likely TSLA has an above-average volatility (looking at the return graph this is quite clear). The correlation matrix shows that there are not strong correlations present, but perhaps GOOG and AMZN express a higher correlation (about 0.30). With this Bayesian analysis of the stock market, we can throw it into a Mean-Variance optimizer (which I cannot stress enough, do not use with frequentist point estimates) and find the minimum. This optimizer balances the tradeoff between a high return and high variance. $$ w_{opt} = \max_{w} \frac{1}{N}\left( \sum_{i=0}^N \mu_i^T w - \frac{\lambda}{2}w^T\Sigma_i w \right)$$ where $\mu_i$ and $\Sigma_i$ are the $i$th posterior estimate of the mean returns and the covariance matrix. This is another example of loss function optimization. If you plan to be using the Wishart distribution, read on. Else, feel free to skip this. In the problem above, the Wishart distribution behaves pretty nicely. Unfortunately, this is rarely the case. The problem is that estimating an $NxN$ covariance matrix involves estimating $\frac{1}{2}N(N-1)$ unknowns. This is a large number even for modest $N$. Personally, I've tried performing a similar simulation as above with $N = 23$ stocks, and ended up giving considering that I was requesting my MCMC simulation to estimate at least $\frac{1}{2}23*22 = 253$ additional unknowns (plus the other interesting unknowns in the problem). This is not easy for MCMC. Essentially, you are asking you MCMC to traverse 250+ dimensional space. And the problem seemed so innocent initially! Below are some tips, in order of supremacy: Use conjugancy if it applies. See section below. Use a good starting value. What might be a good starting value? Why, the data's sample covariance matrix is! Note that this is not empirical Bayes: we are not touching the prior's parameters, we are modifying the starting value of the MCMC. Due to numerical instability, it is best to truncate the floats in the sample covariance matrix down a few degrees of precision (e.g. instability can cause unsymmetrical matrices, which can cause PyMC3 to cry.). Provide as much domain knowledge in the form of priors, if possible. I stress if possible. It is likely impossible to have an estimate about each $\frac{1}{2}N(N-1)$ unknown. In this case, see number 4. Use empirical Bayes, i.e. use the sample covariance matrix as the prior's parameter. For problems where $N$ is very large, nothing is going to help. Instead, ask, do I really care about every correlation? Probably not. Further ask yourself, do I really really care about correlations? Possibly not. In finance, we can set an informal hierarchy of what we might be interested in the most: first a good estimate of $\mu$, the variances along the diagonal of the covariance matrix are secondly important, and finally the correlations are least important. So, it might be better to ignore the $\frac{1}{2}(N-1)(N-2)$ correlations and instead focus on the more important unknowns. Another thing to note is that the implementation of the Wishart distribution has changed in from PyMC to PyMC3. Wishart distribution matrices are required to have certain mathematical characteristics that are very restrictive. This makes it so that it is impossible for MCMC methods to propose matrices that will be accepted in our sampling procedure. With our model here we sample the Bartlett decomposition of a Wishart distribution matrix and use that to calculate our samples for the covariance matrix (). Recall that a $\text{Beta}$ prior with $\text{Binomial}$ data implies a $\text{Beta}$ posterior. Graphically: $$ \underbrace{\text{Beta}}_{\text{prior}} \cdot \overbrace{\text{Binomial}}^{\text{data}} = \overbrace{\text{Beta}}^{\text{posterior} } $$ Notice the $\text{Beta}$ on both sides of this equation (no, you cannot cancel them, this is not a real equation). This is a really useful property. It allows us to avoid using MCMC, since the posterior is known in closed form. Hence inference and analytics are easy to derive. This shortcut was the heart of the Bayesian Bandit algorithm above. Fortunately, there is an entire family of distributions that have similar behaviour. Suppose $X$ comes from, or is believed to come from, a well-known distribution, call it $f_{\alpha}$, where $\alpha$ are possibly unknown parameters of $f$. $f$ could be a Normal distribution, or Binomial distribution, etc. For particular distributions $f_{\alpha}$, there may exist a prior distribution $p_{\beta}$, such that: $$ \overbrace{p_{\beta}}^{\text{prior}} \cdot \overbrace{f_{\alpha}(X)}^{\text{data}} = \overbrace{p_{\beta'}}^{\text{posterior} } $$ where $\beta'$ is a different set of parameters but $p$ is the same distribution as the prior. A prior $p$ that satisfies this relationship is called a conjugate prior. As I mentioned, they are useful computationally, as we can avoided approximate inference using MCMC and go directly to the posterior. This sounds great, right? Unfortunately, not quite. There are a few issues with conjugate priors. The conjugate prior is not objective. Hence only useful when a subjective prior is required. It is not guaranteed that the conjugate prior can accommodate the practitioner's subjective opinion. There typically exist conjugate priors for simple, one dimensional problems. For larger problems, involving more complicated structures, hope is lost to find a conjugate prior. For smaller models, Wikipedia has a nice table of conjugate priors. Really, conjugate priors are only useful for their mathematical convenience: it is simple to go from prior to posterior. I personally see conjugate priors as only a neat mathematical trick, and offer little insight into the problem at hand. Earlier, we talked about objective priors rarely being objective. Partly what we mean by this is that we want a prior that doesn't bias our posterior estimates. The flat prior seems like a reasonable choice as it assigns equal probability to all values. But the flat prior is not transformation invariant. What does this mean? Suppose we have a random variable $\textbf X$ from Bernoulli($\theta$). We define the prior on $p(\theta) = 1$. figsize(12.5, 5) x = np.linspace(0.000 ,1, 150) y = np.linspace(1.0, 1.0, 150) lines = plt.plot(x, y, color="#A60628", lw = 3) plt.fill_between(x, 0, y, alpha = 0.2, color = lines[0].get_color()) plt.autoscale(tight=True) plt.ylim(0, 2); Now, let's transform $\theta$ with the function $\psi = log \frac{\theta}{1-\theta}$. This is just a function to stretch $\theta$ across the real line. Now how likely are different values of $\psi$ under our transformation. figsize(12.5, 5) psi = np.linspace(-10 ,10, 150) y = np.exp(psi) / (1 + np.exp(psi))**2 lines = plt.plot(psi, y, color="#A60628", lw = 3) plt.fill_between(psi, 0, y, alpha = 0.2, color = lines[0].get_color()) plt.autoscale(tight=True) plt.ylim(0, 1);
http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter6_Priorities/Ch6_Priors_PyMC3.ipynb
CC-MAIN-2018-39
refinedweb
4,715
51.75
Address fields autofill app for forms using brazilian CEP field. django-cep This application enables Django powered websites to have autofilled address fields in forms based on brazilian CEP field. Installation To install django-cep simply run: pip install django-cep Configuration We need to hook django-cep into our project. Put cep into your INSTALLED_APPS at settings module: INSTALLED_APPS = ( ... 'cep', ) Bind the cep urls.py into your main urls.py with something like: url(r'^cep/', include('cep.urls')), Usage Currently the only syntax supported is setting the IDs of the address fields in the widget of the CEP field. For other ways to set this up, see the NEXT-STEPS file. Import the django-cep widget CEPInput in your forms.py: from cep.widgets import CEPInput Set your CEP field for using the CEPInput, with the correct address fields ID, for example: my_cep_field = ChangeToMyCEPFieldModelName(label=u"CEP", help_text="Format: XXXXX-XXX", widget=CEPInput(address={ 'street': 'id_street_field', 'district': 'id_district_field', 'city': 'id_city_field', 'state': 'id_state_field' })) That stands for a street field ID equals id_street_field, district field ID equals id_district_field, city field ID equals id_city_field and a state field ID equals id_state_field. Also note that the JavaScript used in this app requires JQuery to run properly. It is highly recommended that you use Django Localflavor’s BRStateChoiceField for the State field, to make it render the correct brazilian state from the list. 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/django-cep/
CC-MAIN-2017-51
refinedweb
251
56.96
HELP [URGENT]968683 Oct 16, 2012 9:46 AM Hi, I really need someone to help me with this code it needs to be done by tonight and it wont work if some one would be willing to fix it for me it would be greatly appreciated Edited by: 965680 on Oct 16, 2012 7:46 AMEdited by: 965680 on Oct 16, 2012 7:46 AM import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator extends JFrame { JButton add ,subtract, multiply, divide; JTextField num1 , num2 ; JLabel result , enter1 , enter2 ; public Calculator () { setLayout (new GridBagLayout()); GridBagConstraints c = new GridBagConstraints (); enter1 = new JLabel ("lst: "); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; add(enter1,c); num1 = new JTextField(10); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; c.gridwidth = 3; add(num1 , c ) ; enter2 = new JLabel ("2nd: ") ; c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 0; c.gridy = 1; c.gridwidth = 1; add (enter2 , c ) ; num2 = new JTextField(10); c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 1; c.gridy = 1; c.gridwidth = 3; add (num2 , c ) ; add = new JButton ("+"); c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 0; c.gridy = 2; c.gridwidth = 1; add (add , c ) ; subtract = new JButton ("-") ; c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 1; c.gridx = 2; add (subtract , c ) ; multiply = new JButton ("*") ; c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 2; c.gridy = 2; add (multiply , c ); divide = new JButton ("/"); c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 3; c.gridy = 2; add (divide , c); result = new JLabel(""); c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 0; c.gridy = 4; c.gridwidth = 4; event a = new event () ; add.addActionListener(a) ; subtract.addActionListener(a) ; multiply.addActionListener(a) ; divide.addActionListener(a) ; } public class event implements ActionListener { public void actionPreformed(ActionEvent a) { double number1 , number2 ; try { number1 = Double.parseDouble(num1.getText()) ; } catch (NumberFormatException e) { result.setText("Illegal Data"); result.setForeground(Color.RED) ; return; } try { number2 = Double.parseDouble(num2.getText()) ; }catch (NumberFormatException e) { result.setText("illegal data"); result.setForeground(Color.RED); return; } String op = a.getActionCommand(); if (op.equals("+")) { double sum = number1 + number2 ; result.setText(number1 + "+" + number2 + "=" + sum ) ; result.setForeground(Color.RED) ; } else if (op.equals("-")) { double diff = number1 - number2 ; result.setText (number1 + "-" + number2 + "=" + diff) ; result.setForeground(Color.RED); } else if (op.equals("*")) { double factor = number1 * number2 ; result.setText (number1 + "*" + number2 + "=" + factor) ; result.setForeground(Color.RED); }else if (op.equals("/")) { if (number2 == 0) { result.setText("Cannot Divide by 0") ; result.setForeground(Color.RED); } else { double quotient = number1 / number2 ; result.setText(number1 + "/" + number2 + "=" + quotient); result.setForeground(Color.RED); } } } } public static void main (String args []) { Calculator gui = new Calculator (); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setVisible(true); gui.setSize(250,175); gui.setTitle("Event Night Product!"); } } This content has been marked as final. Show 3 replies 1. Re: HELP [URGENT]TPD-Opitz Oct 16, 2012 10:40 AM (in response to 968683)Welcome to the forum. This is not urgent for anybody else than you. So if you want someone to help you we need a little mor information about in which way your code fails. What's the expected behavior and what does it instead? bye TPD 2. Re: HELP [URGENT]doremifasollatido Oct 16, 2012 10:00 AM (in response to 968683)You seem to have taken the code verbatim from the following thread: Re: Java Calculator HELP! What was wrong with the advice given in that thread? At least you posted the code with code tags this time. 3. Re: HELP [URGENT]rukbat Oct 16, 2012 11:20 AM (in response to 968683)Moderator Action and Comment: Since this is a duplicate of that earlier thread, this one is locked. If you indeed are a different person (else you just couldn't be bothered re-posting under that other forum account - so you created a new one for this post), get together with the other one and study together. It seems you both have the same classwork assignment to do. . ... and to reinforce what was said in the first reply here, there is no "urgent" in these forums. That is your issue and not anyone else's. Edit: A Google search, plugging the first couple of lines of the code into the search engine, finds numerous posts on this class assignment in various forums that go back 8+ years. Edited by: rukbat on Oct 16, 2012 12:18 PM
https://community.oracle.com/thread/2454742
CC-MAIN-2015-22
refinedweb
713
53.98
Hi, Is there any way to read the Internet header from the email? and changing it?Reply I have a question. Is is possible to record the position of the customized commandbar when user closes outllook? Therefore, i could create the customeized commandbar next time at the same spot. In my addins,everytime i close the word ,the toolbar will disappear the next time,I have to click the "COM Add-ins"tool to show my addins, how to solve this problem? In the .reg file ,the loadbehavier field is filled with "0x0000003"(auto load),but every time word closed, the field would become back to 0x0000002, why?Reply Originally posted by: Bjoern Schultze I'm looking for an event handler method, which will be executed on a click to an Item of the Outlook folder view and gets the name of that folder. Anybody can help me ? Outook Object Model Events -> F -> FolderSwitch EventReply ????????? ReplyReply Originally posted by: riaz33bd I have implemented toolbar button in new mail message window,But it don't respond me,Why?? How can I respond the toolbar button in new windows ? Can you helpe me? and give me many resource code?? Thank you,,,, my mail address is riaz33bd@yahoo.comReply Originally posted by: dharan Hello auther and all Its a great article !! thanks to auther !! but i need to have a authentication dialog to be fired when we click either of buttons on the toolbar as of now the auther has fired a message box. But the new dialog box must have UI and must contack a DB with which the data will be checked against . so help me plz. when i added a new dialog class it showed lot of errors and i included the afxwin.h in the dialog class's headr then it says "windows.h already included " and i have another doubt i could nt link the db (pl sql table ) with Crecordset class . i dont now how icld include dialog and Db facility withthe project ... help is appreciated thanks in advance dharani Originally posted by: Carolus" :-)) As in comment VC++ could not find the file <atlcontrols.h> . and #include as "ATLControls.h" BenOConner (2002/06/05) !" :-)) Originally posted by: Park I have succeeded in making button and command handler. I made another same project with different Project Name, Short Name, and Registry Value. When I click on the first project's button, there comes the reactions of first and second project handler in order. Such result occurs also when I click on the second project. Why is the second project's handler is called when I clicked on the first project's button, and why is the first project's handler is called when I clicked on the second project's button ? it is useless though I make uniquely the ID and dispid of SINK_ENTRY_INFO along with IDispEventSimpleImpl parameter. Can you help me? Thanks in advance, Park ReplyReply Originally posted by: Ducas thank you sooooo much ducas I tried to read this article i did, but i didn't get very far coz i didn't have enough time nor concentration at the time. could someone please answer me 1 question... will creating a COM add-in enable me to bypass the outlook security warning when i try send an email from my program and if so how? thank you sooooo much ducas Originally posted by: David V. Corbin I do not see where in the code the derivation from IDTExtensibility2 is. I also can not find it in any of the available namespaces. As a result the OnConnection(...) method never gets called and the add-in is not activated! Please help. (respond via e-mail if possible).Reply
http://www.codeguru.com/comment/get/48256910/
CC-MAIN-2016-22
refinedweb
620
74.49
You can read a static version of the notebook on nbviewer. OR You can run the code in a browser by clicking this link and then selecting distribution.ipynb from the list. The following is a summary of the material in the notebook, which you might want to read before you dive into the code. Random processes and variablesOne of the recurring themes of my books is the use of object-oriented programming to explore mathematical ideas. Many mathematical entities are hard to define because they are so abstract. Representing them in Python puts the focus on what operations each entity supports — that is, what the objects can do — rather than on what they are. In this article, I explore the idea of a probability distribution, which is one of the most important ideas in statistics, but also one of the hardest to explain. To keep things concrete, I'll start with one of the usual examples: rolling dice. - When you roll a standard six-sided die, there are six possible outcomes — numbers 1 through 6 — and all outcomes are equally likely. - If you roll two dice and add up the total, there are 11 possible outcomes — numbers 2 through 12 — but they are not equally likely. The least likely outcomes, 2 and 12, only happen once in 36 tries; the most likely outcome happens 1 times in 6. - And if you roll three dice and add them up, you get a different set of possible outcomes with a different set of probabilities. Representing distributionsThere are many ways to represent a probability distribution. The most obvious is a probability mass function, or PMF, which is a function that maps from each possible outcome to its probability. And in Python, the most obvious way to represent a PMF is a dictionary that maps from outcomes to probabilities. So is a Pmf a distribution? No. At least in my framework, a Pmf is one of several representations of a distribution. Other representations include the cumulative distribution function (CDF) and the characteristic function (CF). These representations are equivalent in the sense that they all contain the same information; if I give you any one of them, you can figure out the others. So why would we want different representations of the same information? The fundamental reason is that there are many operations we would like to perform with distributions; that is, questions we would like to answer. Some representations are better for some operations, but none of them is the best for all operations. Here are some of the questions we would like a distribution to answer: - What is the probability of a given outcome? - What is the mean of the outcomes, taking into account their probabilities? - What is the variance of the outcome? Other moments? - What is the probability that the outcome exceeds (or falls below) a threshold? - What is the median of the outcomes, that is, the 50th percentile? - What are the other percentiles? - How can get generate a random sample from this distribution, with the appropriate probabilities? - If we run two random processes and choose the maximum of the outcomes (or minimum), what is the distribution of the result? - If we run two random processes and add up the results, what is the distribution of the sum? Each of these questions corresponds to a method we would like a distribution to provide. But there is no one representation that answers all of them easily and efficiently. As I demonstrate in the notebook, the PMF representation makes it easy to look up an outcome and get its probability, and it can compute mean, variance, and other moments efficiently. The CDF representation can look up an outcome and find its cumulative probability efficiently. And it can do a reverse lookup equally efficiently; that is, given a probability, it can find the corresponding value, which is useful for computing medians and other percentiles. The CDF also provides an easy way to generate random samples, and a remarkably simple way to compute the distribution of the maximum, or minimum, of a sample. To answer the last question, the distribution of a sum, we can use the PMF representation, which is simple, but not efficient. An alternative is to use the characteristic function (CF), which is the Fourier transform of the PMF. That might sound crazy, but using the CF and the Convolution Theorem, we can compute the distribution of a sum in linearithmic time, or O(n log n). If you are not familiar with the Convolution Theorem, you might want to read Chapter 8 of Think DSP. So what's a distribution?The Pmf, Cdf, and CharFunc are different ways to represent the same information. For the questions we want to answer, some representations are better than others. So how should we represent the distribution itself? In my implementation, each representation is a mixin; that is, a class that provides a set of capabilities. A distribution inherits all of the capabilities from all of the representations. Here's a class definition that shows what I mean: class Dist(Pmf, Cdf, CharFunc): def __init__(self, d): """Initializes the Dist. Calls all three __init__ methods. """ Pmf.__init__(self, d) Cdf.__init__(self, *compute_cumprobs(d)) CharFunc.__init__(self, compute_fft(d)) When you create a Dist, you provide a dictionary of values and probabilities. Dist.__init__ calls the other three __init__ methods to create the Pmf, Cdf, and CharFunc representations. The result is an object that has all the attributes and methods of the three representations. From a software engineering point of view, that might not be the best design, but it is meant to illustrate what it means to be a distribution. In short, if you give me any representation of a distribution, you have told me everything I need to answer questions about the possible outcomes and their probabilities. Converting from one representation to another is mostly a matter of convenience and computational efficiency. Conversely, if you are trying to find the distribution of a random variable, you can do it by computing whichever representation is easiest to figure out. So that's the idea. If you want more details, take a look at the notebook by following one of the links at the top of the page.. I don't know how one would best define probability distributions in a FP language. I'll call on those with more expertise to give us some ideas at this point.
https://allendowney.blogspot.com/2016/06/what-is-distribution.html
CC-MAIN-2021-39
refinedweb
1,074
54.52
While creating ML models, our end goal is the deployment that takes it to the production which can take input and give an output of business models. The easiest form of deployment would be a GUI (Graphical User Interface). Gradio helps in building a web-based GUI in a few lines of code which is very handy for showing demonstrations of the model performance. It is fast, easy to set up, and ready to use and shareable as the public link which anyone can access remotely and parallelly run the model in your machine. Gradio works with all kinds of media- text, images, video, and audio. Apart from ML models, it can be used as normal python code embeddings. Deep Learning DevCon 2021 | 23-24th Sep | Register>> Gradio is a customizable UI that is integrated with Tensorflow or Pytorch models. It is free and an open-source framework makes it readily available to anyone. In this article, we will discuss gradio with its implementation. First, we will use it in finding the largest word in a sentence, and then we will implement it to predict the name of apparel. Let’s start with installing gradio In python installing any library is very easy with the command pip pip install gradio This will only take a few seconds to execute. Building a simple GUI of the largest word in a sentence Here we design a simple code that predicts the longest word in a sentence and gives the result in the GUI. import gradio as gr gr.reset_all() def longest(text): words = text.split(" ") lengths = [len(word) for word in words] return max(lengths) ex = "The quick brown fox jumped over the lazy dog." io = gr.Interface(longest, "textbox", "label", interpretation="default", examples=[[ex]]) io.test_launch() io.launch() The word ‘jumped’ is the longest with 6 characters thus it prints 6 as the result. Apart from example text, users can write their own sentences and see the predictions. In the code, the Interface function gr.Interface() allows the integration of the function call to be made to longest() containing the text as input here into a textbox, and output maximum length word in the sentence. The launch function finally allows the GUI to be visible as a UI. Gradio can handle multiple inputs and outputs. Gradio for ML models I have taken the fashion MNIST dataset which contains 70,000 grayscale images in low resolution into 10 categories, out of which 60000 images are for training and 10000 images for testing. These images are NumPy arrays of size 28X28, with pixel values ranging from 0 to 255. The class labels are as follows: 0 – T-shirt/top, 1 – Trouser, 2 – Pullover, 3 – Dress, 4 – Coat, 5 – Sandal, 6 – Shirt, 7- Sneaker, 8 – Bag, 9 – Ankle boot. import tensorflow as tf import gradio as gr (x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train = x_train / 255.0, x_test = x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128,activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile (optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=5) def classify_image(image): prediction = model.predict(image.reshape(-1, 28, 28, 1)).tolist()[0] return {class_names[i]: prediction[i] for i in range(10)} class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] sketchpad = gr.inputs.Sketchpad() label = gr.outputs.Label(num_top_classes=4) gr.Interface(fn=classify_image, inputs=sketchpad, outputs=label, interpretation="default", ).launch() Conclusion As we can see Gradio app predicts the sketch image as a T-shirt. In place of the sketch, normal images could also be used provided preprocessing is done as per the model requirements. Gradio could be used by anyone to provide demos to clients. You can find the complete notebook of the above implementation in AIM’s GitHub repositories. Please visit this link to find this notebook.
https://analyticsindiamag.com/guide-to-gradio-create-web-based-gui-applications-for-machine-learning/
CC-MAIN-2021-39
refinedweb
660
57.37
Im trying to use Dapper in an ASP.Net Core application to map multiple tables to one object with other objects as its properties. My tables are as follows (just basic summary): address_type table (lookup table) phone_number table (no user ids stored in this table, this table is just phone records) Basically whats happening is results get returned fine if all the users have no address or phone records or if only the first user in the list has address/phone records. What I want is if a user has an address/phone number then that dictionary is populated, otherwise I still want all the user info but that address/phone number dictionary will be empty. My objects look like the following: public class User { public uint id { get; set; } public DateTime modified_date { get; set; } public uint modified_by { get; set; } public string user_name { get; set; } public uint company_code { get; set; } public string email { get; set; } public bool active { get; set; } public string first_name { get; set; } public string last_name { get; set; } public Dictionary<uint, Address.Address> addresses { get; set; } public Dictionary<uint, Address.PhoneNumber> phone_numbers { get; set; } } public class Address { public uint address_id { get; set; } public AddressType address_type { get; set; } public string address_line1 { get; set; } public string address_line2 { get; set; } public string address_line3 { get; set; } public string city { get; set; } public string state { get; set; } public string country_code { get; set; } public string postal_code { get; set; } public sbyte is_po_box { get; set; } } public class AddressType { public uint id { get; set; } public string name { get; set; } } public class PhoneNumber { public uint id { get; set; } public PhoneNumberType phone_number_type { get; set; } public string phone_number { get; set; } public string phone_ext { get; set; } } public class PhoneNumberType { public uint id { get; set; } public string name { get; set; } } Here is my function where I try to use Dapper to map to the User class: public List<User> GetUsersByStatus(uint companyCode, string status) { if (companyCode == 0) throw new ArgumentOutOfRangeException("companyID", "The Company ID cannot be 0."); List<User> Users = new List<User>(); try { string sql = @"SELECT u.*, ad.*, adt.*, p.*, pt.* FROM master.user u LEFT JOIN master.user_has_address AS uha ON uha.user_id = u.id LEFT JOIN master.address AS ad ON ad.id = uha.address_id LEFT JOIN master.lookup_address_type adt ON adt.id = uha.address_type_id LEFT JOIN master.user_has_phone_number AS uhp ON uhp.user_id = u.id LEFT JOIN master.phone_number AS p ON p.id = uhp.phone_number_id LEFT JOIN master.lookup_phone_number_type pt ON pt.id = uhp.phone_number_type_id WHERE u.company_code = " + companyCode; switch (status) { case "1": // Active Status. sql = sql + " AND (u.active = TRUE)"; break; case "2": // Retired Status. sql = sql + " AND (u.active = FALSE)"; break; } sql = sql + " ORDER BY u.user_name"; using (var conn = new MySqlConnection(connectionString)) { conn.Open(); var userDictionary = new Dictionary<uint, User>(); conn.Query<User, Address, AddressType, PhoneNumber, PhoneNumberType, User>(sql, (u, ad, adt, p, pt) => { User user; if (!userDictionary.TryGetValue(u.id, out user)) userDictionary.Add(u.id, user = u); if (ad != null && adt != null) { Address address = ad; address.address_type = new AddressType() { id = adt.id, name = adt.name }; if (user.addresses == null) user.addresses = new Dictionary<uint, Address>(); if (!user.addresses.ContainsKey(adt.id)) user.addresses.Add(adt.id, address); } if (p != null && pt != null) { PhoneNumber phone = p; phone.phone_number_type = new PhoneNumberType() { id = pt.id, name = pt.name }; if (user.phone_numbers == null) user.phone_numbers = new Dictionary<uint, PhoneNumber>(); if (!user.phone_numbers.ContainsKey(pt.id)) user.phone_numbers.Add(pt.id, phone); } return user; }, splitOn: "id,id,id,id").AsQueryable(); Users = userDictionary.Values.ToList(); } } catch(Exception ex) { //TO DO: log exception } return Users; } I've tried tracing through it and in cases where the 3rd user (for example) has address/phone records, it seems to grab the first 2 users fine but then jump right out of the query portion when it gets to the record with address/phone numbers and then it returns an empty Users list. Does anyone have any idea what Im doing wrong? Turns out the main issue was the fact that I left the address_id parameter in the Address class named the way it was, it should ahve been just 'id'. I updated that and it works now, I did also update my code according to Palle Due's suggestion so that may have contributed as well. I'm not sure this is the solution, but I have a problem with this code: User user; if (!userDictionary.TryGetValue(u.id, out user)) userDictionary.Add(u.id, user = u); Remember that u is parameter of the lambda, and will be changed during execution. I would do this: User user; if (!userDictionary.TryGetValue(u.id, out user)) { user = new User(u); // Make a new instance of user userDictionary.Add(u.id, user); } Also you should definitely use parameters for your query: WHERE u.company_code = @CompanyCode"; And finally I don't think it should be the responsibility of this code to construct dictionaries for holding addresses and phone numbers. The User constructor should take care of that.
https://dapper-tutorial.net/knowledge-base/49987559/dapper-mapping-multiple-joins-to-single-object-returning-no-records
CC-MAIN-2021-10
refinedweb
822
58.89
==== ==== First aid, freeze dried food, preparedness seeds, long-term food storage kits, veggie packs, meat packs, and more! Be prepared for the polar shift and the 12/21/12 doomsday prediction! ==== ==== ID: 3138402 Author: Wayne Arthur Alexander Date Published: Oct 22, 2009 Title: The Rapture? Summary: I have observed that secular church leaders have a compulsive habit of drawing disciples unto themselves. They prom... Body: I have observed that secular church leaders have a compulsive habit of drawing disciples unto themselves. They promote a philosophy of church that empowers the preacher, not the congregation, teaching that ultimately keeps the pastor/priest leadership in control. The underlying result is that non-respondents are rejected while devotees come under a spell, subjecting themselves to men rather than to God.The apostle Paul proposed that devotees imitate him (1 Corinthians 4:16). However, Paul was not looking for personal followers. Paul encouraging imitation suggests that Christians must first know how to follow Christ. Firsthand knowledge ultimately means that I can follow Christ for myself. This is the direction the apostle is aiming disciples: At the infant level, they need Paul, but at the mature level, they need only depend on Christ. At some point, all mature believers ought to be able to say to immature believers, "Imitate me."Accordingly, Jesus calls himself the Son of God, but never refers to himself as God anywhere in the New Testament. Yes, Jesus is God. I'm only saying that as the Son he learned subordination (obedience) to the Father. As the Son of God, Jesus did only what he saw his Father doing (John 5:19), and taught only that which came from his Father (John 7:16). Jesus wants all disciples to hear from God as he did...to walk with God as he walked with God.So, whom are you imitating?In 1988, many awaited the coming Rapture. I was in Bible college at the time and remember it well. Publications went out detailing the events to occur. Well, the Rapture never happened. Yet, many Christians, imitating their prophets, believed it would. Evangelicals everywhere were speaking of the Rapture, even though scripture plainly tells us that no one knows the time of Christ's return (1 Thessalonians 5:1f). Disciples would know this fact if they cared to believe scripture. The truth is, disciples are afraid to confront God and the actualities of the biblical text. They are afraid to discover truth for themselves, but will believe the charlatans.Prophecies, such as the aforementioned Rapture, are predicted and taught out of fear - fear that is aggressive but hidden, hidden to the preachers as well as to their adherents. Their personal fears pervade their teachings. In this case, it is the fear of persecution. The very idea that God would allow his people to suffer is an atrocity in the minds of most Christians, especially Americans that have enjoyed so much of the world's riches for so long. Unwittingly, this fear has propagated a rapture mentality."The Rapture", as it is called, will rescue an elect few from persecution while the rest of the world, including disciples who weren't spiritually prepared for the Rapture, suffers intolerably. Raptured disciples go unscathed. But I ask you, where are the specifics of the Rapture written in scripture? When have the faithful of God not suffered: the Old Testament prophets, Jesus, the New Testament apostles, as well as others throughout church history? All suffered! Rapture is in the minds of unfaithful disciples are who are looking for a way out.I once heard an evangelist say on national TV that he was glad he would not be here after the Rapture because he knew he could not endure the persecution that would follow. Can you imagine Jesus or Paul making such a statement? Furthermore, what does this statement say about the lack of faith in the preacher that spoke it?Christian leaders know they cannot withstand the suffering that will come to Christians so they invented a means of escape. Disciples gullibly receive their biblical musings as truth because they too are fearful. We readily accept the lie because we are not prepared to die for Christ. But had we read scripture and trusted God, we would understand that no disciple is prepared for suffering or death until God prepares us for affliction. Disciples suffer persecution but their faith remains in tact because of the strength of God that resides in them (1 John 4:4).Rapture doctrine is not ancient, but fairly recent (circa 1830, see Barbara R. Rossing, The Rapture Exposed [New York: Basic Books, 2004], 22-23). Referencing Revelation 21:1, Rapture teaching speaks of the destruction of the earth "for the first earth and heaven had passed away." Their doctrine negates emphasis, however, on the passing of heaven as well...interesting. Revelation 21 speaks of a new heaven and earth, not because the old heaven and earth are destroyed, but because evil has been destroyed. The removal of evil makes everything new. Armageddon (found only in Revelation 16:16), is a fight against Satan and his evil cohorts.Of course, huge emphasis is placed 1 Thessalonians 4:14-17, with specific reference to being "caught up together with them in the clouds to meet the Lord in the air." The word "rapture" is not a Bible word. It comes from the Latin raptus, which is used as an equivalent for the Greek word arpadzo "to be taken away". Why use rapture? Perhaps it sounds more intimidating as a catchword than "arpadzo"."Air" comes from the Greek word "aer". In ancient animism, the air is the place of the spirits "who had to be taken into account". (Werner Foerster, Theological Dictionary of the New Testament, vol. 1, ed. by Gerhard Kittel [Grand Rapids; Eerdmans, 1964; reprint 2006], 165). In Ephesians 2:2, Satan currently rules the air. However, when Christ comes, he will take over the power of the air, where evil is removed and the righteous congregate. This apocalyptic, end-times description is used by Paul to comfort those that were misinformed about the end times and the loved ones that had died (4:13-16).Paul used "caught up" language to bring peace to the hearts of Christians anxiously awaiting the return of Christ. Modern preachers use the same language as part of a tribulation strategy that strikes terror in the hearts of Christians.Whom do you believe? I trust Paul. Circa 1830, see Barbara R. Rossing, The Rapture Exposed [New York: Basic Books, 2004], 22-23 Werner Foerster, Theological Dictionary of the New Testament, vol. 1, ed. by Gerhard Kittel [Grand Rapids; Eerdmans, 1964; reprint 2006], 165 Article Source: URL: ==== ==== First aid, freeze dried food, preparedness seeds, long-term food storage kits, veggie packs, meat packs, and more! Be prepared for the polar shift and the 12/21/12 doomsday prediction! ==== ====
https://issuu.com/wildersolutions/docs/the_rapture_907
CC-MAIN-2017-13
refinedweb
1,151
64.71
Main.cpp + mainwindow.ui = ?? i just need to know, is it possible to ".show()" my work in .ui and .cpp files in 1 window?? for example: @ #include "mainwindow.h" #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel lbl("123"); MainWindow w; w.show(); lbl.show(); return a.exec(); } @ (i added 2nd label in .UI file) - can i display both of labels in 1 window? - can i work (for exmpl, resize) 2nd lable by codding manually? - sierdzio Moderators Yes, you just need to add your label to the layout in your MainWindow class. Just a couple of custom methods to expose the relevant layout (or clever reparenting :)) and it should work. im newbie, so, ccan u write this lines? is it somthing like this?: ??->addWidget(lbl); - sierdzio Moderators There are many ways. One would be: @ lbl.setParent(mainWindow.centralWidget()); @ But I don't exactly know what the result would be. What I would do instead is to add method to your MainWIndow class that would expose one of the QLayout instances you have in the .ui and then add your label there. Sorry I won't write the code right now, it's 2 am in here now, I'm a tad too tired :D ty it's works ok. but - @ lbl.setParent(w.centralWidget());@ - after closing program error "Error - RtlWerpReportException failed with status code :-1073741823. Will try to launch the process directly" - is it possible to siglnal /slot this 2 widgets?
https://forum.qt.io/topic/27377/main-cpp-mainwindow-ui
CC-MAIN-2017-34
refinedweb
248
68.97
hai Thanks dude!, Very useful! Post your Comment J2ME Timer MIDlet Example J2ME Timer MIDlet Example This Example shows how to use of timer class. In this example we are using the Timer class to create the time of execution of application J2ME Timer Animation J2ME Timer Animation This application illustrates how to use the Timer class and implement it in the canvas class. In this Tutorial we have given you a good example Timer - Swing AWT Timer How can I make a simple countdown timer in my GUI?  ... { ProgressMonitor progress; static int counter = 0; Timer timer...("Progress bar timer Demo"); setSize(250, 100); setDefaultCloseOperation javascript timer countdown a certain period of time. The above given example "javascript timer countdown" allows...javascript timer countdown How to disable/enable the javascript timer countdown? <!-- CSS Code --> #txt { border:none; font JavaScript Clock Timer JavaScript Clock Timer...; In this section, we are going to show you a clock timer using JavaScript. In the given example, we have created the instance of Date to show the time. Here we have Scheduling a Timer Task Scheduling a Timer Task In this section, you can learn how to schedule a timer task to run at a certain time and repeatedly. There is an example given for the illustration Media MIDlet Example Media MIDlet Example Creating more then one player in a MIDlet, Here we have... with object 'key' and object 'value' which maps the keys to value. In this example we j2me timer and timer task j2me timer and timer task have anyone idea to change a direction of bubble, according to changing time. Please go through the following links: http Date Field Midlet Example Date Field MIDlet Example This example illustrates how to insert date field in your form. We...;extends MIDlet{ private Form form; private (" Timer and TimerTask Timer and TimerTask i have problem of java.lang.IllegalStateException: Task already scheduled or cancelled Text Field Midlet Example Text Field MIDlet Example This example illustrates how to insert text field in your form. We are using here two TextField (name and company). We are taking both TextField Java timer Java timer Hi. I want to use a timer in one of my java projects... java.util.Timer; import java.util.TimerTask; public class ToDo { Timer timer; public ToDo ( int seconds ) { timer = new Timer();   timer program using j2megiridharan July 23, 2013 at 7:43 PM hai Very useful!Serg3ant July 31, 2014 at 8:14 AM Thanks dude!, Very useful! Post your Comment
http://www.roseindia.net/discussion/22797-J2ME-Timer-MIDlet-Example.html
CC-MAIN-2014-52
refinedweb
417
63.59
Preface This is part 11 gives an introduction to building Scala applications using SBT (the Simple Build Tool). This will be done in the context of the Scalabha package, which I have created for primarily for my Introduction to Computational Linguistics class. Some supporting code is available in Scalabha for some basic natural language processing tasks; most relevant at the moment is the code that is in Scalabha that supports the part-of-speech tagging homework for the class. The previous tutorial showed how Scala code can be compiled with scalac and then run with scala. One problem we ended up with is that there were generated class files littering the working directory. Another thing we did not discuss is how a large system can be created in a modular way that organizes code and classes. For example, you might want to have code in different directories generate classes that can be used by one another. You also may want want to incorporate classes from other libraries into your own code. The solutions we’ll discuss to address these needs and more are build systems and packages. Note: The tutorial assumes you are using some version of Unix. If you are on Windows, you should consider using Cygwin, or you could dual boot your computer. Note: In this tutorial, I’ll assume you are using as simple text editor to modify files. However, note that the general setup you are working with here can be used from more powerful Integrated Developer Environements (IDEs) like Eclipse, IntelliJ, and NetBeans. Setting up Scalabha We’ll work with SBT, which is perhaps the most popular build tool for Scala. The Scalabha toolkit mentioned earlier uses SBT (version 0.11.0), so we’ll discuss SBT in the Scalabha context. The first thing you need to do is download Scalabha v0.1.1 Next unzip the file, change to the directory it unpacked to, and list the directory contents. $ unzip scalabha-0.1.1-src.zip Archive: scalabha-0.1.1-src.zip <lots of output> $ cd scalabha-0.1.1 $ ls CHANGES.txt README build.sbt project LICENSE bin data src Briefly, these contents are: - README: A text file describing how to install Scalabha on your machine. - LICENSE: A text file giving the license, which is the Apache Software License 2.0. - CHANGES.txt: A text file describing the modifications made for each version (not much so far). - build.sbt: A text file that contains instructions for SBT regarding how to build Scalabha - bin: A directory that contains the scalabha script, which will be used to run applications developed within the Scalabha build system and also to run SBT itself. It also contains sbt-launch-0.11.0.jar, which is a bottled up package of SBT’s classes that will allow us to use SBT very easily. There are some other files that are Perl scripts that are relevant for a research project and aren’t important here. - data: A directory containing part-of-speech tagged data for English and Czech that forms the basis for the fourth homework of my Introduction to Computational Linguistics course this semester. - project: A directory containing a single file “plugins.sbt” which tells SBT to use the Assembly plugin. More on this later. - src: The most important directory of all — it contains the source code of the Scalabha system, and is where you’ll be adding some code as you work with SBT. At this point you should read the README and get Scalabha set up on your computer, including building the system from source. In this tutorial, I will give some extra details on using SBT and code development with it, complementing and extending the brief information given in the README. Note that I will refer the environment variable SCALABHA_DIR below. As specified in the README, you should set this variable’s value to be where you unpacked Scalabha. For example, for me this directory is ~/devel/scalabha. Tip: to make it so that you don’t have to set your environment variables every time you open a new shell, you can set environment variables in your ~/.profile (Mac, Cygwin) or ~/.bash_aliases (Ubuntu) files. For example, this is in my profile files on my machines. export SCALABHA_DIR=$HOME/devel/scalabha export PATH=$PATH:$SCALABHA_DIR/bin SBT: The Simple Build Tool This is not a tutorial about setting up a project to use SBT — it is simply about how to use a project that is already set up for SBT. So, if you are looking for resources about learning SBT, what you’ll mainly find are resources to help programmers configure SBT for their project. These will likely confuse you (the Simple Build Tool is not so simple any more, when it comes to configuration). Using it is straightforward, but the kind of know-how that experienced coders have with using something like SBT is what you probably won’t find much help on. Here, I intend to give the basics so that you have a better starting point for doing more with SBT. First off, there is a bit of slight of hand with Scalabha that could be confusing. Rather than having users install SBT themselves, I have put the jar file for SBT in the bin directory of Scalabha; then, the scalabha executable (in that same directory) can pick that up and use it to run SBT. (My students and I have set up a number of Scala/Java projects in this way, including Fogbow, Junto, Textgrounder, and Updown.) The scalabha executable has a number of execution targets (more on this later), and one of these is “build“. When you call scalabha’s build target, it invokes SBT and drops you into the SBT interface. Do the following, in your SCALABHA_DIR. $ scalabha build [info] Loading project definition from /Users/jbaldrid/devel/scalabha/project [info] Set current project to Scalabha (in build file:/Users/jbaldrid/devel/scalabha/) > You could have achieved the same by downloading SBT and running it according to the instructions for SBT, but this setup saves you that trouble and ensures that you get the right version of SBT. It is just worth pointing out so that you don’t think that Scalabha is SBT – SBT is entirely independent of Scalabha. If you have had any trouble with the Scalabha setup, you can create an issue on the Scalabha Bitbucket site. That just means that I’ll get a notice that you had some problems and can hopefully help you out. And, it is possible that someone else will have had the same problem, in which case you might find your answer there. Most of the problems with this sort of setup are due to confusions about environment variables and unfamiliarity with command line tools. Compiling with SBT Let’s actually do something with SBT now. If you successfully got through the README, you will have already done what is next, but I’ll give some more details about what is going on. Because you may have run some SBT actions already as part of doing the README, start out by running the “clean” action so that we’re on the same page. > clean [success] Total time: 0 s, completed Oct 26, 2011 10:18:08 AM Then, run the “compile” action. > compile [info] Updating {file:/Users/jbaldrid/devel/scalabha/}default-86efd0... [info] Done updating. [info] Compiling 13 Scala sources to /Users/jbaldrid/devel/scalabha/target/classes... [success] Total time: 9 s, completed Oct 26, 2011 10:18:19 AM In another shell (which means another command line window), go to SCALABHA_DIR and list the contents of the directory. You’ll see that two new directories have been created, lib_managed and target. The first is where other libraries have been download from the internet and placed into the Scalabha project space so that they can be easily used — don’t worry about this for the time being. The second is where the compiled class files have gone. To see some example class files, do the following. $ ls target/classes/opennlp/scalabha/postag/ BaselineTagger$$anonfun$tag$1.class BaselineTagger.class EnglishTagInfo$$anonfun$zipWithTag$1$1.class <... many more class files ...> RuleBasedTagger$$anonfun$tag$2.class RuleBasedTagger$$anonfun$tagWord$1.class RuleBasedTagger.class These were generated from the following source files. $ ls src/main/scala/opennlp/scalabha/postag/ HmmTagger.scala PosTagger.scala Open up PosTagger.scala in a text editor and look at it — you’ll see the class and object definitions that were the sources for the generated class files in the target/classes directory. Basically, SBT has conveniently handled the separation of source and compile class files so that we don’t have the class files littering our work space. How does SBT know where the class files are? Simple: it is configured to look at src/main/scala and compile every .scala file it finds under that directory. In just a bit, you’ll start adding your own scala files and be able to compile and run them as part of the Scalabha build system. Next, at the SBT prompt, invoke the “package” action. > package [info] Updating {file:/Users/jbaldrid/devel/scalabha/}default-86efd0... [info] Done updating. [info] Packaging /Users/jbaldrid/devel/scalabha/target/scalabha-0.1.1.jar ... [info] Done packaging. [success] Total time: 0 s, completed Oct 26, 2011 10:19:02 AM In the shell prompt that we used to list files previously, list the contents of the target directory. $ ls target/ cache classes scalabha-0.1.1.jar streams You have just created scalabha-0.1.1.jar, a bottled up version of the Scalabha code that others could use in their own libraries. The extension “jar” stands for Java Archive, and it is basically just a zipped up collection of a bunch of class files. Scalabha itself uses another of supporting libraries produced by others. To see the jars that are used as supporting libraries by Scalabha, do the following. $ ls lib_managed/jars/*/*/*.jar lib_managed/jars/jline/jline/jline-0.9.94.jar lib_managed/jars/junit/junit/junit-3.8.1.jar lib_managed/jars/org.apache.commons/commons-lang3/commons-lang3-3.0.1.jar lib_managed/jars/org.clapper/argot_2.9.1/argot_2.9.1-0.3.5.jar lib_managed/jars/org.clapper/grizzled-scala_2.9.1/grizzled-scala_2.9.1-1.0.8.jar lib_managed/jars/org.scalatest/scalatest_2.9.0/scalatest_2.9.0-1.6.1.jar Of course, you may still be wondering what it means to “use a library” in your code. More on this after we talk about packages and actually start doing some code ourselves. Packages Projects with a lot of code are generally organized into a package that has a set of sub-packages for parts of the code base that work closely together. At the very high level, a package is simply a way to ensure that we have unique fully qualified names for classes. For example, there is a class called Range in the Apache Commons Lang library and in the core Scala library. If you want to use both of these classes in the same piece of code, there is an obvious problem of a name conflict. Fortunately, they are contained within packages that allow us to refer to them uniquely. - Range in the Apache Commons Lang library is org.apache.commons.lang3.Range - Range in Scala is scala.collection.immutable.Range So, when we do need to use them together, we are still able to do so without conflict. You’ve actually already seen some package names before, for example with java.lang.String and the distinction between scala.collection.mutable.Map and scala.collection.immutable.Map. To see the packages and classes in Scalabha, run the “doc” action in SBT. > doc [info] Generating API documentation for main sources... model contains 35 documentable templates [info] API documentation generation successful. [success] Total time: 7 s, completed Oct 26, 2011 10:22:23 AM. $ cd $SCALABHA_DIR $ cd src/main/scala/opennlp/ $ mkdir bcomposes Next, using a text editor, create the file Hello.scala in the src/main/scala/opennlp/bcomposes directory with the following contents. package opennlp.bcomposes object Hello { def main (args: Array[String]) = println("Hello, world!") } This is just like the hello world object from the previous tutorial, but now it has the additional package specification that indicates that its fully qualified name is opennlp.bcomposes.Hello. Because the source code for Hello.scala is in a sub-directory of the src/main/scala directory, we can now compile this file using SBT. Make sure to save Hello.scala, and then go back to your SBT prompt and type “compile“. > compile [info] Compiling 1 Scala source to /Users/jbaldrid/devel/scalabha/target/classes... [success] Total time: 1 s, completed Oct 26, 2011 10:35:15 AM Notice that it compiled just one Scala source: SBT has already compiled the other source files in Scalabha, so it only had to compile the new one that you just saved. Having successfully created and compiled the opennlp.bcomposes.Hello object, we can now run it. The scalabha executable provides a “run” target that allows you to run any of the code you’ve produced in the Scalabha build setup. In your shell, type the following. $ scalabha run opennlp.bcomposes.Hello Hello, world! There is actually a bunch of stuff going on under the hood that ensures that your new class is included in the CLASSPATH and can be used in this manner (see bin/scalabha for details). This will simplify things for you considerable. To make a long story short, getting the CLASSPATH appropriately set is one of the main points of confusion for new developers; this way you can keep on moving without having to worry about what is essentially a plumbing problem. Now, let’s say you want to change the definition of the Hello object to also print out an additional message that is supplied on the command line. Modify the main method to look like this. def main (args: Array[String]) { println("Hello, world!") println(args(0)) } Now save it, and try running it. $ scalabha run opennlp.bcomposes.Hello Goodbye Hello, world! Oops — it didn’t work?! I’ve just forced you directly into a common point of confusion for students who are switching from scripting to compiling: you must compile before it can be used. So, invoke compile in SBT, and then try that command again. $ scalabha run opennlp.bcomposes.Hello Goodbye Hello, world! Goodbye To see what happens when you produce a syntax error in your Scala code, go back to Hello.scala and change first print statement in the main method so that it is missing the last quote: println("Hello, world!) Now go back to SBT and compile again to see the love letter you get from the Scala compiler. [info] Compiling 1 Scala source to /Users/jbaldrid/devel/scalabha/target/classes... [error] /Users/jbaldrid/devel/scalabha/src/main/scala/opennlp/bcomposes/Hello.scala:5: unclosed string literal [error] println("Hello, world!) [error] ^ [error] /Users/jbaldrid/devel/scalabha/src/main/scala/opennlp/bcomposes/Hello.scala:7: ')' expected but '}' found. [error] } [error] ^ [error] two errors found [error] {file:/Users/jbaldrid/devel/scalabha/}default-86efd0/compile:compile: Compilation failed [error] Total time: 0 s, completed Oct 26, 2011 11:02:07 AM The compile attempt failed, and you must go back and fix it. But don’t do that yet. There’s a handy aspect of SBT in this write-save-compile loop that saves you time and effort: SBT allows triggered executation of actions, which means that SBT can automatically perform an action if there is a change to the stuff it cares about. The compile action cares about the source code, so it can monitor changes in the file system and automatically recompile any time a file is saved. To do this, you simply add ~ in front of the action. Before fixing the error, type ~compile into SBT. You’ll see the same error message as before, but don’t worry about that. The last line of output from SBT will say: 1. Waiting for source changes... (press enter to interrupt) Now go to Hello.scala again, add the quote back in, and save the file. This triggers the compile action in SBT, so you’ll see it automatically compile, with a success message. [info] Compiling 1 Scala source to /Users/jbaldrid/devel/scalabha/target/classes... [success] Total time: 0 s, completed Oct 26, 2011 11:02:49 AM 2. Waiting for source changes... (press enter to interrupt) This is a nice way to see if your code is compiling as you work on it, with very little effort. Every time you save the file, it will let you know if there are problems. And, you’ll also be able to use the scalabha run target and know that you are using the latest compiled version when you do so. As you develop your code in this way, you can invoke the “doc” action in SBT, then reload the index.html page in your browser, and it will show you the updated documentation for the things you’ve created. Try it now and look at the opennlp.bcomposes package that you’ve now created. Creating code that uses existing packages Now we can come back to using code from existing packages. In the past (if you’ve gone through all of these tutorials), you’ve seen statements like import scala.io.Source. That came from the standard Scala library, so it is always available to any Scala program. However, you can also use classes developed by others in a similar manner, provided your CLASSPATH is set up such that they are available. That is exactly what SBT does for you: all of the classes that are defined in the src/main/scala sub-directories are ready for your use. As an example, save the following code as src/main/scala/opennlp/bcomposes/TreeTest.scala. It constructs a standard phrase structure tree for the sentence “I like coffee.” package opennlp.bcomposes import opennlp.scalabha.model.{Node,Value} object TreeTest { def main (args: Array[String]) { val leaf1 = Value("I") val leaf2 = Value("like") val leaf3 = Value("coffee") val subjNpNode = Node("NP", List(leaf1)) val verbNode = Node("V", List(leaf2)) val objNpNode = Node("NP", List(leaf3)) val vpNode = Node("VP", List(verbNode, objNpNode)) val sentenceNode = Node("S", List(subjNpNode, vpNode)) println("Printing the full tree:\n" + sentenceNode) println("\nPrinting the children of the VP node:\n" + vpNode.children) println("\nPrinting the yield of the full tree:\n" + sentenceNode.getTokens.mkString(" ")) println("\nPrinting the yield of the VP node:\n" + vpNode.getTokens.mkString(" ")) } } There are a few things to note here. The import statement at the top is what tells Scala the fully qualified package names for the classes Node and Value. You could have equivalently written it less concisely as follows. import opennlp.scalabha.model.Node import opennlp.scalabha.model.Value Or, you could have left out the import statement and written the fully qualified names everywhere, e.g.: val leaf1 = opennlp.scalabha.model.Value("I") Second, Node and Value are case classes. We’ll discus this more later, but for now, all you need to know is that to create an object of the Node or Value classes, it isn’t necessary to use the “new” keyword. Third, the print statements are using the Scalabha API (Application Programming Interface) to do useful things with the objects, such as printing out the tree they describe, printing the yield of the nodes (the words that they cover), and so on. The scaladoc you looked at before for Scalabha shows you these functions, so go have a look if you haven’t already. Note that if you had left the triggered compilation on, SBT will have automatically compiled the TreeTest.scala. Otherwise, make sure to compile it yourself. Then, run it. $ scalabha run opennlp.bcomposes.TreeTest Printing the full tree: Node(S,List(Node(NP,List(Value(I))), Node(VP,List(Node(V,List(Value(like))), Node(NP,List(Value(coffee))))))) Printing the children of the VP node: List(Node(V,List(Value(like))), Node(NP,List(Value(coffee)))) Printing the yield of the full tree: I like coffee Printing the yield of the VP node: like coffee Make and use your own package By importing the classes you need in this manner, you can get more done by using them as you need. Any class in Scalabha or in the libraries that are included with it will be available for you, including any classes you define. As an example, do the following. $ cd $SCALABHA_DIR/src/main/scala/opennlp/bcomposes $ mkdir person $ mkdir music Now save the Person class from the previous tutorial as Person.scala in the person directory. Here’s the code again (note the addition of the package statement). package opennlp.bcomposes.person class Person ( val firstName: String, val lastName: String, val age: Int, val occupation: String ) { def fullName: String = firstName + " " + lastName def greet (formal: Boolean): String = { if (formal) "Hello, my name is " + fullName + ". I'm a " + occupation + "." else "Hi, I'm " + firstName + "!" } } Now save the following as RadioheadGreeting.scala in the music directory. package opennlp.bcomposes.music import opennlp.bcomposes.person.Person object RadioheadGreeting { def main (args: Array[String]) { val thomYorke = new Person("Thom", "Yorke", 43, "musician") val johnnyGreenwood = new Person("Johnny", "Greenwood", 39, "musician") val colinGreenwood = new Person("Colin", "Greenwood", 41, "musician") val edObrien = new Person("Ed", "O'Brien", 42, "musician") val philSelway = new Person("Phil", "Selway", 44, "musician") val radiohead = List(thomYorke, johnnyGreenwood, colinGreenwood, edObrien, philSelway) radiohead.foreach(bandmember => println(bandmember.greet(false))) } } When we did the compilation tutorial previously, Person.scala and RadioheadGreeting.scala were in the same directory, which allowed the latter to know about the Person class. Now that they are in separate packages, the Person class must be explicitly imported; once you’ve done so, you can code with Person objects just as you did before. Finally, to run it, we now must specify the fully qualified package name for RadioheadGreeting. $ scalabha run opennlp.bcomposes.music.RadioheadGreeting Hi, I'm Thom! Hi, I'm Johnny! Hi, I'm Colin! Hi, I'm Ed! Hi, I'm Phil! A note on package names and their relation to directories Package names are made unique by certain conventions that generally ensure you won’t get clashes. For example, we are using opennlp.scalabha and opennlp.bcomposes, which I happen to know are unique. Quite often these names will include full internet domains, in reverse, like org.apache.commons and com.cloudera.crunch. By convention, we put the source files that are in packages (and subpackages) in directory structures that reflect the names. So, for example, opennlp.bcomposes.music.RadioheadGreeting is in the directory src/main/scala/opennlp/bcomposes/music. However, it is worth noting that this is not a hard constraint with Scala (as it is with Java). There is a great deal more to using a build system, but this is where I must end this discussion, hoping it is enough to get the core concepts across and make it possible for my students to do the homework on part-of-speech tagging and making use of the opennlp.scalabha.postag package! Reference: First steps in Scala for beginning programmers, Part 11 – code blocks, coding style, closures, scala documentation project - Fun with function composition in Scala - How Scala changed the way I think about my Java Code - Testing with Scala - Things Every Programmer Should Know
http://www.javacodegeeks.com/2011/11/scala-tutorial-sbt-scalabha-packages.html
CC-MAIN-2015-22
refinedweb
3,928
56.45
C++ Check whether the number is Armstrong or not Hello Everyone! In this tutorial, we will learn how to Check whether given number is Armstrong or not, in the C++ programming language. What is an Armstrong number? In number theory, an Armstrong number in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits. (In programming, we usually define it for a 3 digit number) Example: 153 is an Armstrong number as 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. (same as the original number 153) But, 213 is not an Armstrong number as 2^3 + 1^3 + 3^3 = 8 + 1 + 27 = 36 (which is not equal to the original number 213) Code: #include <iostream> using namespace std; int main() { cout << "\n\nWelcome to Studytonight :-)\n\n\n"; cout << " ===== Program to check if the number is Armstrong or not ===== \n\n"; //variable declaration int n, n1, remainder, num = 0; //taking input from the command line (user) all at once cout << " Enter a positive integer : "; cin >> n; //storing the original value before modifying it n1=n; //Logic to check if it is Armstrong or not for a 3 digit number while( n1!=0 ) { remainder = n1 % 10; //storing the digits at the units place num += remainder*remainder*remainder; n1/=10; } cout << "\n\n\n"; if(num == n) { cout << n << " is an Armstrong number."; } else { cout << n << " is not an Armstrong number."; } cout << "\n\n\n"; return 0; } Output: Now let's see what we have done in the above program. Program Explained: Let's break down the parts of the code for better understanding. //Logic to check if it is Armstrong or not for a 3 digit number while( n1!=0 ) { remainder = n1 % 10; //storing the digits at the units place num += remainder*remainder*remainder; n1/=10; } The above code snippet is used to check whther a given 3 digit number is Armstrong or not. remainder = n1 % 10; This is used to store the digit at the units place into the remainder variable. num += remainder*remainder*remainder; This statement is used to perfrom the cubing overation and adding onto the previous sum to find the final sum of the cubes of all the digits of the given 3 digit number. n1/=10; This statement, divides the actual number with 10 so that the new value contains only the digits that has not been explored yet. We will recommend you to program this on your own and perform it's step-by-step analysis using pen-paper for the number 153, to develop better understanding. Keep Learning : )
https://studytonight.com/cpp-programs/cpp-check-whether-the-number-is-armstrong-or-not
CC-MAIN-2021-04
refinedweb
442
62.41
>>." Also try Perl 6 (Score:5, Insightful) Re:Seriously? (Score:0, Insightful) to those of you for whom basic reasoning and reading comprehension are too much to ask, i did NOT just claim that perl is dead. I only claimed that the frequency of releases alone is not a criteria for determining its dead-ness or alive-ness. now seriously, go get some remedial education if you thought I was claiming it was dead, because no one needs your wanton ignorance polluting the Internet, driving, voting, and buying into all the bullshit the media spews every day. Re:Perl has died in industry. . *cough* *cough* (Score:2, Insightful) ... unit tests. Re:netcraft didn't confirm but Perl is dying (Score:0, Insightful) What the fuck are you talking about? Perl is still the King of Scripting Languages and always will be, at least until it has some real competition. Ruby is the biggest fucking joke to hit software development in years. It takes the worst of Smalltalk, and combines it with the worst of Perl. Then it adds in a bunch of smug college students, sorry, "rockstar programmers", who can only toss together ass-licking Web frameworks that pale in comparison to NeXT's early releases of WebObjects. Python 3.0 has been a huge disaster. When we tried it at work, we found a huge number of problems with core modules. Many of them hadn't even been updated to support the Unicode string changes in Python 3.0! And a lot of the third-party Python software just plain won't work with Python 3.0. We couldn't fucking believe how horrible of an experience Python 3.0 was for us. Perl is the only scripting language that is solid, is reliable, is flexible, runs just about everywhere, has an intelligent developer community, and just works out of the box. There is no alternative to Perl. Re:I love Perl (Score:1, Insightful) This is exactly how it should work. I'm not a fan of perl, but this is how most scripting languages, and your shell, do it. ' means literal quotation, while " is more relaxed. Re:*cough* *cough* (Score:2, Insightful) Unit tests are only as good as the programmer that programs them. Many times, your solution is not cut and dry.:Also try Perl 6 (Score:3, Insightful) uh, I'd rather do an implementation in a language that's not in pre-release status. My clients like their money handled by language that 1. exists 2. has stable specification 3. has stable releases Re:netcraft didn't confirm but Perl is dying (Score:3, Insightful) Limitations in studio, please. Larry is old enough we should start placing bets, does he die before Perl 6 comes out? I'm accepting bets whether a card runs you over before you read the comment. Re:netcraft didn't confirm but Perl is dying :netcraft didn't confirm but Perl is dying (Score:3, Insightful) Yeah, I'm gonna use this statistic, but only the part of it that I like. Re:Perl has died in industry. (Score:3, Insightful) I thought there was a reverse string function. In that case, why is it an infinite recursion and not a method not found?:Great! Another language to learn! pick a totally random set of characters and use it to tell the code syntax parser to change modes! How brilliant! We can just use "qw" to mean "list of strings operator". Sure, why not, nobody would ever write a function called qw on their own, so there will never be a conflict. And now our code has random text in it which is hard to scan for and isn't surrounded by quotes and doesn't obey the same logic that any other text does. Seriously, consistency helps reduce the burden on a programmer. There is no excuse for a language that attempts to remove readability and consistency for the sake of reducing the number of keystrokes required to type a task. You can only save yourself typing time once, whereas readable code saves you time every day for years.:Great! Another language to learn! (Score:1, Insightful) Random unused symbols such as the at-sign, square brackets, and periods? E-mail must be difficult in that case. Also, "qw" stands for "quote words." Simple enough. Re:Also try Perl 6 :Perl has died in industry (mod away, kids) :Seriously? (Score:3, Insightful) I personally know of exactly one company that uses Perl at the moment, and that's only for text cleanup. Perhaps you don't know many companies :-) Re:What about 3rd party modules? (Score:1, Insightful) You Perl faggots always like to bring out CPAN, don't you? The last five or six times I've tried to install a module from CPAN on a modern Linux distribution, it has fallen flat on its face. First, you have to wade through 15 or 20 similar, yet equally shitty, modules before you find the one that actually sort of works. Then you have to pray that it installs correctly, which it usually doesn't. Finally, you have to try to figure out how to properly use the goddamn module, which is often as cryptic as anal warts and of course lacks documentation and helpful comments. But by that time, you've wasted a better part of a day, and you realize that Perl is a waste of time, CPAN is a waste of time, and that Python just works. 7000 modules each doing one thing very well are better than 70000 modules where 10 perform the same task, and all of them suck rotting goat penis. Re:What do people use Perl. Re:Seriously? develop with, simpler to maintain. Secret is very easy: Java pretty much never requires one to use brain during no phase of development process. Perl actually makes you want to use your brain. Because it's fun. Re:Perl has died in industry. (Score:1, Insightful) Better question is, what idiot decided to rename the string.reverse function to something that makes no sense to anyone but him and will cause head-desk-inducing errors for everyone who tries to reverse a string the way they do it in every other programming language since the Stone Age? Why should the name for the function to turn a series of characters from back to front be different from the name for the function to turn a series of arbitrary items back to front? Does perl6 not have namespaces or something?
https://developers.slashdot.org/story/09/10/03/1357211/Perl-5110-Released/insightful-comments
CC-MAIN-2016-44
refinedweb
1,096
72.56
Convert word doc to pdf - Wednesday, January 10, 2007 11:51 AM Hi, I need to convert word document to pdf file using C#.2 Iam having - MS visual studio 2005 professional (and also MS VS.2003 enterprise ed) - MS Office 2007 - I have downloaded SaveAsPDFandXPS (used to convert doc to pdf) - Microsoft Visual Studio 2005 Tools for Office Second Edition Runtime (VSTO 2005 SE) My question is Do i need "MS visual studio 2005 for office tools" version to work with ms word, so that i can convert word to pdf. All Replies - Wednesday, January 10, 2007 5:20 PMModerator Hi Chennai No, VSTO is not required to work automate the Word application. I've never tried it, but I'm told the ExportAsFixedFormat method should convert a Word 2007 document to pdf. If by "list out the namespaces required to work with the document" you mean the Help for the object model: The best way to access this is to start Word, press Alt+F11 to go into its IDE, then use the Help menu. This will take you to an online source. You can also press F2 in the IDE to bring up its object browser. - Friday, January 12, 2007 11:26 AM hello everybody I myself find out answer for this Add reference to MS.Wordprivate Microsoft.Office.Interop.Word.ApplicationClass MSdoc; //Use for the parameter whose type are not known or say Missing object Unknown = Type.Missing; private void word2PDF(object Source, object Target) { //Creating the instance of Word Application if (MSdoc == null)MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass(); try { MSdoc.Visible = false; MSdoc.Documents.Open(ref Source, ref Unknown, ref Unknown, format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; MSdoc.ActiveDocument.SaveAs(ref Target, ref format, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (MSdoc != null) { MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown); //WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown); } // for closing the application WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown); } } Prerequisite: MS word2007 with (Primary Interoperability assembly will be installed by default). plugin SaveAsPDFandXPS (free from MS Site) Karthik - Sunday, January 14, 2007 11:51 AM hello i like what you written it much much close to my style. but where can i find Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; it's not there how can i add it. kindly can you describe it very clearly Yours A/\/\RJX - Wednesday, January 17, 2007 7:47 AM Make sure you have reference to Word.12. It will automatically add Microsoft.Office.interop.word to your reference. Follow these for other office application. (Note: you should have installed VS 2005 Tools for Office 2nd Ed. Runtime (VSTO 2005 SE) (x86) For PDF conversion Plugin- SaveAsPDFandXPS) PDF conversion only works with Lastest MS Office 2007 only - Saturday, January 20, 2007 7:36 AMHello Friends, Have you some stable solution to convert Word to Pdf. You r talking about VS2005 has one dll for that or class for that. But what for VS2003. Have you some solution for that, Have you got dll file for that. Also please can you find out that the dll used in VS2005 (which you use) is also usable for VS2003. and working Ok!!. If you got some other dll or any solution please reply. - Sunday, January 21, 2007 6:43 AMModerator. - Monday, January 22, 2007 8:31 AMHello Friends, First of all Thanks for Reply. Now the issue is, I want to this for my web project... here We uses VS2003. So Is there any alternative Solution for that?.... Please If You have some idea then Reply.... - Monday, January 22, 2007 7:13 PMModerator If you're targeting Office 2003, then make sure the documents are saved in Word 2003 XML file format. You can then transform the result to the PDF XML format. There are already third-party solutions available; searching the Internet should turn them up. This approach is really the only viable one for a server- or web-interface as it doesn't involve running the Word application. - Saturday, October 13, 2007 12:44 PM Hi Friends, I am also coverting word document into pdf and I am having Office 2007 and MS visual studio 2005 I did the same as Karthik have mensioned above. But it gives me a exception below. System.Runtime.InteropServices.COMException (0x800A1066): Command failed at Microsoft.Office.Interop.Word.DocumentClass.SaveAs(Object& FileName, Objec t& FileFormat, Object& LockComments, Object& Password, Object& AddToRecentFiles, Object& WritePassword, Object& ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object& SaveNativePictureFormat, Object& SaveFormsData, Object& SaveAsAOCELette r, Object& Encoding, Object& InsertLineBreaks, Object& AllowSubstitutions, Objec t& LineEnding, Object& AddBiDiMarks) at ConsoleApplication2.Program.Main(String[] args) in C:\Documents and Settin gs\neeleshk\Desktop\test11\ConsoleApplication2\ConsoleApplication2\Program.cs:li ne 3 - Saturday, October 13, 2007 5:59 PMModeratorThe PDF file converter is not installed as part of Office, due to licensing issues raised by Adobe. It must be downloaded and installed separately. Are you sure the file converter is correctly installed on the machine where this error is being raised? - Monday, October 15, 2007 8:45 AM Hi Cindy, I am not using any kind of PDF file convertor rather i am trying to do this with C# code. and that code convert .doc to .rtf & .html without any error. and when i am trying it for PDF then it gives me exception like "The remote procedure call failed and did not execute. (Exception from HRESULT: 0x800706BF)" My steps are - First I have converted .doc to .rtf (converted successfully). - Then I have tried .rtf to .pdf (gives exception as messioned above) and I have also tried to convert .doc to .pdf then it give me exceptions. Thanks, Neelesh - Monday, October 15, 2007 2:48 PMModerator Hi Neelesh When Word saves a document to any file format other than its native *.doc format, it uses a file converter. This is true for RTF, for HTML, or for saving as plain text (just as examples). The difference between these file formats and PDF is that their file converters are installed by default when Office is installed. The PDF file converter is not part of the Office package. Originally, it was supposed to be, but Adobe threatened a lawsuit. Therefore, the PDF file converter must be downloaded and installed separately before you can use it. It doesn't matter whether you're automating Office or working as an end-user. - Proposed As Answer by Robert Taylor Friday, March 06, 2009 5:34 PM - - Thursday, December 27, 2007 3:50 AM I installed office 2003 on server and client, and use Microsoft.Office.Interop.Word to handle word by C#.But I can't start word on client.I'm not sure what's wrong with my codes? They just like: m_appWord =new Microsoft.Office.Interop.Word.Application(); m_appWord.Visible =true; m_appWord.DisplayAlerts =WdAlertLevel.wdAlertsNone; m_bStartupApp =true; bResult =true; and so on... Please give me your suggestions. Thanks a lot - Thursday, February 14, 2008 9:59 PMCould you give some insight on how to call this? i.e. Should this work? word2PDF("filename.doc", "filename.pdf"); Thank you. - Friday, March 07, 2008 9:52 PMThanks for the help so far but I am getting an error when I call the line of code to save the file as pdf. The error says that the application is busy. Any thoughts? {"The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))"} - Wednesday, March 19, 2008 12:12 PMHi Guys! I advice you to try the PDF Metamorphosis .Net, it able to convert RTF to PDF: So, at first you may convert DOC to RTF by MS Office and next RTF to PDF by Metamorphosis. This is a sample code on VB.Net: Dim p As New SautinSoft.PdfMetamorphosis p.RtfToPdfConvertFile("D:\Example.rtf", "D:\File.pdf") C# sample: SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis(); p.RtfToPdfConvertFile("D:\Example.rtf", "D:\File.pdf"); Best wishes, Max - Proposed As Answer by LaxmiRanBanned Wednesday, October 26, 2011 10:38 AM - - Tuesday, August 12, 2008 7:27 PM Not sure if this helps anyone but I recently had to convert Word 2003 docs to pdf. You basically print the document out as a postscript file, then take that file and run it through Adobe Acrobat Distiller. added a reference to COM lib "ACRODISTXLib" which is the Adobe Acrobat Distiller. privateWord.Document _myWordDoc; private Word.Application _myWordApp; privatestring filename_template = "C:\\doc1.doc"; private objectfilename_obj = (object)filename_template; privateobject missing = System.Reflection.Missing.Value; // our 'void' value private objectprintrange_obj = Word.WdPrintOutPages.wdPrintAllPages; private object true_obj = true; ... _myWordDoc= _myWordApp.Documents.Open(// load the template into a document workspace ref filename_obj, // and reference it through our myWordDoc ref missing, ref true_obj, // ReadOnly ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); stringdestination_ps = "C:\\doc1.ps"; objectdestination_ps_obj = destination_ps; string destination_doc = "C:\\doc1.pdf"; //save as pdf _myWordDoc.PrintOut(ref false_obj, ref printrange_obj, ref missing, ref destination_ps_obj, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref true_obj, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); PdfDistillerClassdistiller = new PdfDistillerClass(); distiller.FileToPDF(destination_ps, destination_pdf,""); - Wednesday, September 17, 2008 2:21 PM Hi all, great post. I write my console application and it work fine on Xp and Vista. I also try to include this code in a windows services application but it work fine in Xp and NOT in Vista. I try to go in debug mode and to analize object after "open" method, first to define assign document format: Code Snippetobject Unknown = Type.Missing; Word.Document ObjDoc = newApp.Documents.Open(ref _Sources, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown); // Specifying the format in which you want the output fileobject format = Word.WdSaveFormat.wdFormatPDF;Code Snippet"Il comando non è disponibile perché non c'è alcun documentoaperto" System.Runtime.InteropServices.ExternalException {System.Runtime.InteropServices.COMException} "Command not avaible because there isn't open document" System.Runtime.InteropServices.ExternalException {System.Runtime.InteropServices.COMException} ErrorCode -2146824040 There is someone that say me because on Vista it work as console application and not as windows services? thank's - Friday, March 06, 2009 5:36 PMYou need to install the word converter. If you load Word, click 'SaveAs' and see an option to save as XPS then you're ok. For Word 2007 go to this link... Robert - Saturday, April 04, 2009 6:19 PMThanks Robert, your solution helped me. - Tuesday, July 14, 2009 2:37 PM i appeared to me message say value out of range? what i do in this message? - Proposed As Answer by Kareem Koki Tuesday, July 14, 2009 2:41 PM - - Tuesday, July 14, 2009 2:46 PM Hi "My Ruf Account" ? I get message for this code and say value Out of range ? What do i do in this message ? replay to me fast ? - Wednesday, October 07, 2009 6:21 PMSegue link para gerar PDF utilizando C# e VSTO, Rodrigo Alves Romano New Cocnept - Soluções Inovadoras Blog Técnico: - Wednesday, January 20, 2010 7:14 PMIt just work fine for me. Thanks a lot for this article. - Wednesday, January 27, 2010 11:31 AMError occurred while exporting to PDF as "The export failed because this feature is not installed. " - Thursday, February 18, 2010 3:00 PM Is it mandatory Microsoft word to be installed on the system to convert Word Doc to PDF? - Monday, March 01, 2010 3:51 PMmrleokarthik , thank you very much for your code. It works perfectly! Much appreciated. Best regards, Sanasy - Tuesday, August 31, 2010 5:53 AM mrleokarthik , thank you very much for your code. It works perfectly! Much appreciated. Best regards, Sanasy i want open source solution to convert word(2003 r 2007) to pdf in any environment.. please help me..... - Tuesday, August 31, 2010 5:54 AMi want open source solution to convert word(2003 r 2007) to pdf in any environment.. please help me..... in .net 2008 - Thursday, January 20, 2011 12:03 PM Thanks! Worked fist try. Old post, but I am happy to report that this approach worked first try using: · VS2010 · Microsoft.Office.Interop.Word 12 · Office 2010 Professional No additional plugin required with current versions. Eric - Wednesday, February 16, 2011 3:06 AM. Never too old to learn - Tuesday, May 10, 2011 12:59 AM this what i was looking for. I have following questions if someone can answer. I'm using VS 2010, Office 2010 PIA 1>Does 2010 Office PIA has "Microsoft.Office.Interop.Word 12" or is it part of 2007 PIA? 2>Do i also need to install SaveAsPDFandXPS or is it already included in 2010 Office PIA? 3>Is VS 2010, 2010 Office PIA Sufficient or do i need to install Visual Studio 2010 Tools for Office Runtime? 4>Do i need to install actual copy of office on server or PIA is fine? 5>Can i run this code on web server? the conversion should happen on Web Server. - Tuesday, May 10, 2011 4:29 PMModerator Hi lax4u (all) I think this question is being handled in other, parallel discussions... Cindy Meister, VSTO/Word MVP - Tuesday, September 20, 2011 2:23 PMHave a try to use Spire.Doc, using System; using Spire.Doc; using Spire.Doc.Documents; namespace WordToPDF { class Program { static void Main(string[] args) { //Create a new document Document document = new Document(); //Load word 2007 file from disk. document.LoadFromFile("WordFile.docx"); //Save doc file to pdf. document.SaveToFile("Sample.pdf", FileFormat.PDF); } } } - Proposed As Answer by LaxmiRanBanned Wednesday, October 26, 2011 10:37 AM - - Thursday, February 02, 2012 6:12 PM Hi, I am using .net2005 and I am converting Word documents PDF using c#.net by using MS Word dll. My problem is after convertion when i check the PDF file all he fonts are embedded, but i don't want to embedded thr fonts. so how can i set the parameter for this while converting. Please do me needful. Regards, Sarath.V - Thursday, May 31, 2012 7:30 AM Hi, The UseOffice .Net library enables to any .Net application to convert word documents to pdf in C#: SautinSoft.UseOffice u = new SautinSoft.UseOffice(); string wordPath = "c:\Banana.docx"; string pdfPath = "c:\Banana.pdf"; int ret = u.InitWord(); if (ret==1) return; u.ConvertFile(inputFilePath, outputFilePath, SautinSoft.UseOffice.eDirection.DOC_to_PDF); u.CloseWord();Cheers, Max - Edited by Max Sautin Thursday, May 31, 2012 7:30 AM -
http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/f8989c05-d04a-4b4a-be0f-fc0055691de7
CC-MAIN-2013-20
refinedweb
2,461
58.18
The Sierpinski triangle has come up several times on this blog. Here’s yet another way to produce a Sierpinski triangle, this time by taking the bitwise-and of two integers. The ith bit of x&y is 1 if and only if the ith bit of x and the ith bit of y are both 1. The following C program prints an asterisk when the bitwise-and of i and j is zero. #include <stdio.h> int main() { int N = 32; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%c", (i&j) ? ' ' : '*'); printf("\n"); } } Here’s a screenshot of the output. 2 thoughts on “Fractal via bit twiddling” Thanks John. That’s an interesting pattern. Below is a c# implementation: I ended up code golfing with some colleagues and came up with this: perl -le ‘for$a(0..63){print map$a&$_&&$”,0..63}’
https://www.johndcook.com/blog/2019/11/26/fractal-via-bit-twiddling/
CC-MAIN-2019-51
refinedweb
153
73.17
46 On Tue, 30 Sep 2003 grubert@... wrote: > zope stx uses intending as a markup > for titles, reST uses intending for quotes and underline for markup. > > what would be needed is a stx-reader or RTFM. Well, what I need is a online tool which processes Zope-Book source to well and reasonable formatted HTML (and other formats). If this is not the intenion of docutils we should close this bug report. Kind regards Andreas. Hello, Debian optimistically plans a release of its next stable version (3.1,=20 "sarge") in December, which means that packages should be ready sometime ne= xt=20 month. At the moment, the python-docutils package there is from CVS because some=20 features people needed weren't available in 0.3. That's OK, but I wouldn't= =20 want to have moving-target versions in a release because Debian policy is=20 pretty strict WRT updating. Therefore I'd like to get docutils 0.3.1 into=20 Debian soon (i.e., within one month or so). Well, CVS says the version number's been 0.3.1 for a month now. ;-) What ne= eds=20 to be done until there's an "official" 0.3.1 release? Is there anything I c= an=20 do to help? =2D-=20 Matthias Urlichs | {M:U} IT Design @ m-u-it.de | smurf@...= org Disclaimer: The quote was selected randomly. Really. | net - - =46un things to do in an elevator: Wear a puppet on your hand and talk to other passengers "through" it. David Goodger <goodger@...> writes: > David Abrahams wrote: >> Is there a way to stick a single bold '*' character in a >> parsed-literal? > > This works for me: > > . parsed-literal:: > > foo ***** bar Wow, I'd never have guessed! I guess I really don't understand the parsing process. > To do a single emphasized asterisk, you need to escape: > > . parsed-literal:: > > foo *\** bar > > The reason is that "**" is found before "*", so without the > escape there's no closing "**" and a parsing error results. Thanks, -- Dave Abrahams Boost Consulting David Abrahams wrote: > Is there a way to stick a single bold '*' character in a > parsed-literal? This works for me: .. parsed-literal:: foo ***** bar To do a single emphasized asterisk, you need to escape: .. parsed-literal:: foo *\** bar The reason is that "**" is found before "*", so without the escape there's no closing "**" and a parsing error results. -- David Goodger For hire: Docutils: (includes reStructuredText:) David Abrahams <dave@...> writes: >). Aha. I found the answer, though I'm truly not sure why it works: foo **\ *** bar Seems to me that could just as well cause an empty bold region and an un-emboldened '*'. -- Dave Abrahams Boost Consulting). Many TIA, -- Dave Abrahams Boost Consulting Beni Cherniavsky wrote: >). Sounds good. From the to-do: "Units of measure? (See docutils-users, 2003-03-02.)" Patches welcome. > Sorry, I got confused and thought `TextElement` is too wide; it fits > the bill precisely. I added a bit documentation about it, please > verify I didn't say anything wrong. Looks fine, thanks. > Generally `doctree.txt` seems a bit confused about structural > elements I don't follow; can you provide examples? > Also, each element is assigned one cathegory in the detailed listing > but some belong to several (e.g. `field` is both a body subelement > and a bibliographic element). Patches welcome. -- David Goodger For hire: Docutils: (includes reStructuredText:) On Sun, 21 Sep 2003, David Abrahams wrote: > > The enclosed demonstrates what I believe to be a bug try cvs -- BINGO: This left unindentionally unblank --- Engelbert Gruber -------+ SSG Fintl,Gruber,Lassnig / A6170 Zirl Innweg 5b / Tel. ++43-5238-93535 ---+ This bug should be fixed now, in current CVS/snapshot: <>. -- David Goodger@... ************************************************************************ Receiving this email because you registered to receive special offers from one of our partners. If you would prefer not to receive future email, click: ************************************************************************ David Goodger wrote on 2003-09-18: > Beni Cherniavsky wrote: > >. ;-) > Oh, I see your attitude better now ;-). I misfixed it in my copy because I actually needed it to run. Since I released my script, I didn't like the thought somebody would download it and it would completely fail because of the bug. But thinking of it again, I'm the only user of my script at the moment, so you are completely right. I will be more patient in the future... -- Beni Cherniavsky <cben@...> Beni Cherniavsky wrote: > I'm trying to use inline raw latex math by making a raw > substitution. It doesn't work, the backslashes are replaced by null > characters and latex complains. Curiously, it only happens with > substitutions:: That's because it's a bug/oversight. Bugs and oversights tend to be exceptional. > I think the null characters shouldn't even appear in the document > tree after parsing. Correct. Null characters are part of an internal parser process. > I must confess I'm don't even begin to understand what goes on in > the parser The parser converts initial backslashes to null bytes with the "escape2null" function when it looks for inline markup. The null bytes are removed later in the process, after they've finished doing their "escaping". The substitution definition parsing code is calling "escape2null" too much. I'm close to a solution, but too tired to finish up tonight. >. ;-) -- David Goodger For hire: Docutils: (includes reStructuredText:) Since nobody came up with a fix and my `mathhack.py` script depends on it being fixed, I commited my wrong fix (mind you, it works, it's just at the wrong place which can still be felt by using the docutils-xml.py writer or quicktest.py). For the benefit of others, here is a test for it being fixed in the parser. Since it still *fails* (properly, I didn't fix the parser), I wasn't sure whether I should commit it... Index: test/test_parsers/test_rst/test_substitutions.py =================================================================== RCS file: /cvsroot/docutils/docutils/test/test_parsers/test_rst/test_substitutions.py,v retrieving revision 1.15 diff -u -r1.15 test_substitutions.py --- test/test_parsers/test_rst/test_substitutions.py 27 Mar 2003 03:56:37 -0000 1.15 +++ test/test_parsers/test_rst/test_substitutions.py 18 Sep 2003 18:27:33 -0000 @@ -33,6 +33,21 @@ <image alt="symbol" uri="symbol.png"> """], ["""\ +Raw substitution, backslashes should be preserved: + +.. |alpha| raw:: latex + + $\\alpha$ +""", +"""\ +<document source="test data"> + <paragraph> + Raw substitution, backslashes should be preserved: + <substitution_definition name="alpha"> + <raw format="latex" xml: + $\\alpha$ +"""], +["""\ Embedded directive starts on the next line: .. |symbol| -- Beni Cherniavsky <cben@...> I'm trying to use inline raw latex math by making a raw substitution. It doesn't work, the backslashes are replaced by null characters and latex complains. Curiously, it only happens with substitutions:: text\ |beta|\ text .. |beta| raw:: latex $\beta$ gives (passed through cat -A):: <substitution_definition name="beta"> <raw format="latex" xml: $^@beta$ The null characters appear in the document tree itself; the html writer also suffers it (but the null characters are less problematic for browsers than latex). I found `states.unescape` which I can easily apply in the writers (patch below) but I think the null characters shouldn't even appear in the document tree after parsing. I must confess I'm don't even begin to understand what goes on in the parser so I can't find the proper fix. Index: docutils/writers/html4css1.py =================================================================== RCS file: /cvsroot/docutils/docutils/docutils/writers/html4css1.py,v retrieving revision 1.91 diff -u -r1.91 html4css1.py --- docutils/writers/html4css1.py 1 Sep 2003 15:09:14 -0000 1.91 +++ docutils/writers/html4css1.py 17 Sep 2003 19:43:46 -0000 @@ -932,7 +932,9 @@ def visit_raw(self, node): if node.get('format') == 'html': - self.body.append(node.astext()) + # @@@ Wrong fix! + from docutils.parsers.rst.states import unescape + self.body.append(unescape(node.astext(), restore_backslashes=1)) # Keep non-HTML raw text out of output: raise nodes.SkipNode Index: docutils/writers/latex2e.py =================================================================== RCS file: /cvsroot/docutils/docutils/docutils/writers/latex2e.py,v retrieving revision 1.50 diff -u -r1.50 latex2e.py --- docutils/writers/latex2e.py 17 Sep 2003 17:41:36 -0000 1.50 +++ docutils/writers/latex2e.py 17 Sep 2003 19:43:46 -0000 @@ -1194,7 +1194,9 @@ def visit_raw(self, node): if node.has_key('format') and node['format'].lower() == 'latex': - self.body.append(node.astext()) + # @@@ Wrong fix! + from docutils.parsers.rst.states import unescape + self.body.append(unescape(node.astext(), restore_backslashes=1)) raise nodes.SkipNode def visit_reference(self, node): Beni Cherniavsky wrote on 2003-09-17: >? > Sorry, I got confused and thought `TextElement` is too wide; it fits the bill precisely. I added a bit documentation about it, please verify I didn't say anything wrong. Generally `doctree.txt` seems a bit confused about structural elements - either the subsections structure doesn't match cathegories or the cathegory lists should be expanded to include the sub-cathegories (like with body elements). Also, each element is assigned one cathegory in the detailed listing but some belong to several (e.g. `field` is both a body subelement and a bibliographic element). I fixed inline images and implemented ``align`` and ``scale`` attributes on images in LaTeX. Attributes still not handled: ``alt`` (not applicable in LaTeX), ``height`` and ``width`` (pixels meaningless in LaTeX, spec should probably be extended to allow sizes in percents), ``class`` (not directly applicable in LaTeX, perhaps some mapping to stylesheet hooks could be defined for all nodes alike). -- Beni Cherniavsky <cben@...> Beni Cherniavsky wrote on 2003-09-14: > I'm now working on implementing image attributes (scale, align, etc.) > for the latex writer. I bumped into a couple of issues. > I bumped into a harder issue: distinguishing inline images from stand-alone images. Normally the ``image`` directive creates an `image` node as a body element, but with help of substitutions, `image` also serves as an inline element. I need to tell these two uses apart. Currently the LaTeX writer always outputs newlines around images. This turns each image into a separate paragraph and should be inhibited for inline images. I could check the context of the image node by managing context info in other visit/depart methods or (probably simpler) inspecting the ``.parent`` chain. But I can't figure out a simple criterion for telling apart body vs. inline context.? -- Beni Cherniavsky <cben@...> Pierre-Yves Delens wrote: > When creating mailto hrefs with docFactory (*), What version of Docutils, DocFactory, ZRest? Did you check with the latest versions of all? If not, please try. > > .. _`dethier@...`: mailto:dethier@... Why are you doing so much unnecessary work? Just do:: >> "@" is converted to "@" in an attempt to fool email harvesters. You shouldn't see "&#64;". If you do, it's a bug. Please send a reproducible test procedure & data. >. Is "@" sent or "@"? If there's no ";", that would explain a lot. Either way, it sounds like a Zope issue. > What should I do, hopefully simple (I mean, without having to manually > escape the '@' wehen authoring Restructured Text) ? We could add an option to the HTML writer *not* to convert "@" to "@". Patches welcome! -- David Goodger For hire: Docutils: (includes reStructuredText:) Pierre-Yves Delens wrote: > Bonjour, Hi. Please send to docutils-develop, not docutils-develop-admin. > My config, at my ISP is: > unreleased version, Of what? > python 2.1.3, linux2 > (not yet Zope 2.7, nor 2.6.3) > > Viewing (in the EDIT view) a ZRest document in the ZMI is problematic > because of accentuated charachters (loved in French !). I don't know much about Zope (or anything starting with Z). Perhaps someone on the list can help? > Is there a solution for this ? at ZRest or at Zope level ? Is there a > version issue (Pyrhon, Zope) ? > Is there a solution while keeping with Python 2.1.3 compatible Zopes ? > > Thanks on forward > > ___________________________________________________ > P-Y Delens, Manager -- David Goodger For hire: Docutils: (includes reStructuredText:) Bonjour, When creating mailto hrefs with docFactory (*), .. _`dethier@...`: mailto:dethier@.... What should I do, hopefully simple (I mean, without having to manually escape the '@' wehen authoring Restructured Text) ? Thanks on forward (*) The HTML is produced without ZRest outside of Zope, for the while (due to versioning problem of Zope server at our ISP's) ___________________________________________________ P-Y Delens, Manager LIENTERFACES - PY Delens, sprl Avenue Dolez, 243 - 1180 Bruxelles phone : 32 2 375 55 62 mail : py.delens@... web : ___________________________________________________ engelbert.gruber@... wrote on 2003-09-14: > to sum up beni's requirements. > > 1. the title page should be standard latex: > Not a requirement. I just think that the default look-and-feel should match LaTeX's when possible. At least for title and author. > * easy if we only use title,author,date. > * harder if some other fields are required. > > could be done by building our own (fake standard) > titlepage supporting additional fields. > > additional fields displayed > > * like latexs date. > * as docinfo table. > Another choice: what material should go on the title page and what on the next page (for report/book document classes). > 2. the titlepage should contain the university logo > > see fancyhdr documentation, and write a short docu > for docutils. see tools/stylesheets/style.tex for a start. > How is `fancyhdr` connected? It would allow a logo on every page. Currently I just redefined ``\maketitle`` in my stylesheet, with the logo and hardcoded title/authors, as I wanted to position them... > 3. a real issue for the latex writer is: > > the latex writers document structure is: > > * head prefix > stylesheet is included here > * title > * head > * pdf_info > * body prefix > with \begin{document} > \maketitle > * body > * body suffix > > if the titlepage should be user modifyable we need a hook for the > titlepage construction. or maybe redefine maketitle in the stylesheet. > I think redefining maketitle is best approach, it will scale to cases where the user changes the titlepage completely. It also seems useful to put the matter after \maketitle into another command that can be redefined (``\aftertitle``). > and need to set latex variables for docinfo entries. > > * title,author,date > * docinfofulltable: with author and date > * docinfotable: without author and date > * maybe docinforevision, docinfo... > The main tradeoff is between a "pull" style (the user gives the structure, order and layout, using variables we have set to fill in the fields) and a "push" style (we give the structure, the user has hooks to style parts of it). I think the "pull" style's flexibility can't be matched, so I'd prefer it. The problem is that generic fields can't be done using the pull style (TeX has no normal list/dictionary data types to describe this ;-). Only the finite set of known fields can be done so. Generic fields would have to be done in the push style - the latex writer writes sort of a table but the real formatting is delegated to commands defined by the stylesheet. Moreover, as the set of known fields grows, fields that used to be generic become special and don't appear in the pull style unless the user explicitly handles them. That's the typical issue with pulling data - you lose anything not explicitly included. Solution: the user uses special commands to enumerate the fields he has explicitly handled. Perhaps the very use of a field in ``\maketitle`` should disable the output of it as a generic field. Also, we need to allow the stylesheet to detect which fields are present (only from the known set). Example of simple imaginary stylesheet:: \renewcommand{\maketitle}{ \begin{titlepage} \begin{center} \hfill {\Huge \bibfieldtitle} \hfill \ifbibfieldauthor{\LARGE \bibfieldauthor}\fi \hfill \end{center} \end{titlepage} } % \showedbibfieldtitletrue % Could be omitted for title \showedbibfieldauthortrue \renewcommand{\genericbibfield}[2]{ % name, value {\large #1: #2} } \renewcommand{\aftertitle}[1]{ % generic fields. \vskip \begin{center} #1 \end{center} } And this doesn't completely handle single/multiple authors yet... Probably this should be presented to the stylesheet as two fields "author" vs. "authors" of which at most one is defined. For "authors" we also probably need to repeat the "push" trick: the value of this field would have hooks for styling the separation between authors. It's easier to program python than TeX... Perhaps I'm loading too much into the tex stylesheet and some of this should be off-loaded to python. empy comes to mind... -- Beni Cherniavsky <cben@...> David Goodger wrote on 2003-09-15: > Beni Cherniavsky wrote: > > > The output of ``rst2latex.py --help`` is almost > > valid reStructuredText. Would be much simpler to run it and include > > the results in latex.txt automatically (the same could also be done > > with other tools). > > If documentation can be had by running ``rst2latex.py --help``, > there's no need to include that documentation in static docs. > Instead, write "run ``rst2latex.py --help`` to see the command-line > options" in the static docs. That's what's written in > <>. > Agreed. In general I think it's a useful goal that all command-line help of docutils tools is correct RST. > >. > > Are you using the latest code? I recently fixed some bugs in > Optik/optparse.py (latest optparse.py included in the Docutils > snapshot). Note that the optparse.py included with Python 2.3 has > these bugs; manual installation may be necessary to override the > stdlib module. > Manually installed => blank lines are fine now. Will this go into Python 2.3.1 or should installation of `optparse.py` be re-enabled for 2. > > I'm in the process of fixing the parser & spec, so placeholders in > angle brackets can contain anything but angle brackets. > Yes, this covers it all:: buildhtml.py --help | sed -e 's/<[^>]*>/PLACEHOLDER/g' | docutils-xml.py - /dev/null runs cleanly. Also checked for other tools. Only pep2html.py had problems - fixed and commited. -- Beni Cherniavsky <cben@...> On Mon, 15 Sep 2003, David Goodger wrote: > Beni Cherniavsky wrote: > > BTW, what's the point of manually maintaining the options table in > > ``docs/latex.txt``? > > If you're referring to the "Options on the Commandline" section, I'd > say there's no point. It shouldn't be there at all. removed > The section at > <> should be > completed in the style of the surrounding text. did (or tried to, now the commandline option documentation is in config.txt). _`attribution` collides with the same option from html4css1 -- BINGO: Einpflegen --- Engelbert Gruber -------+ SSG Fintl,Gruber,Lassnig / A6170 Zirl Innweg 5b / Tel. ++43-5238-93535 ---+ I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/docutils/mailman/docutils-develop/?viewmonth=200309
CC-MAIN-2017-30
refinedweb
3,058
59.5
In terms of sandboxing, your distribution might slap a clunky SELinux or AppArmor policy on Flash, but it may or may not be on by default. Given the above, and the fact I'm a 64-bit Linux user, I was really happy to see Chrome's latest dev channel include a native 64-bit Pepper Flash plug-in. What does this mean? - Security: sandboxing. Pepper plug-ins run inside Chrome's renderer sandbox. On Linux, this is chroot() and PID namespace based, so Flash in this context has no filesystem access, nor the ability to interfere with other processes. - Stability: native 64-bit build. Generally, stability and performance should be better than NSPluginWrapper on account of not having to bounce through an extra layer and process. - Security: 64-bit address space. It's harder to heap spray or JIT spray a 64-bit address space. Physical memory will typically run out long before the spray achieves a statistical likelihood of being at any particular memory location. There are some warts of course. Although it works ok on my Ubuntu box, there are lots of comments on the releases blog which indicate Flash is broken, particularly from Fedora users. There's also an ASLR failure (missing position independent executable) which will be fixed in the next revision. Overall, though, seems like a promising boost to Linux Flash security is heading towards the Chrome stable channel.
http://scarybeastsecurity.blogspot.com/2012_02_01_archive.html
CC-MAIN-2015-22
refinedweb
235
55.34
Refactoring; } $basePrice = $this->quantity * $this->itemPrice; if ($basePrice > 1000) return $basePrice * 0.95; else return $basePrice * 0.98; if ($this->basePrice() > 1000) return $this->basePrice() * 0.95; else return $this->basePrice() * 0.98; ... function basePrice() { return $this->quantity * $this->itemPrice; } def calculateTotal(): basePrice = quantity * itemPrice if basePrice > 1000: return basePrice * 0.95 else: return basePrice * 0.98 def calculateTotal(): if basePrice() > 1000: return basePrice() * 0.95 else: return basePrice() * 0.98 def basePrice(): return quantity * itemPrice calculateTotal(): number { let basePrice = quantity * itemPrice; if (basePrice > 1000) { return basePrice * 0.95; } else { return basePrice * 0.98; } } does not change the state of the object. If the method affects the visible state of the object, use Separate Query from Modifier. Replace the variable with a query to your new method.
https://refactoring.guru/replace-temp-with-query
CC-MAIN-2018-47
refinedweb
127
71.31
+9 Can i declare a struct in a header file test.h, define it in test.c file and after that use the struct in otherFile.c where i included the header file test.h. Or do i have to define the struct in the header file completly to use it in .c files where i included the header? 11/12/2019 9:32:23 PM 12 Answers +6 You can do it both ways but second way is more modular and gives more flexibility. With first way you would need to include test.c too everywhere you want to use your struct. +5 You just need to include "test.h" header file in otherFile.c then compile otherFile.c and test.c together from command line gcc test.c otherFile.c or if you are using an IDE you need to add test.c to the same project where you have otherFile.c and compile The other way is to have the complete definition of your struct and functions in the header fiile. Structure definition in the header is fine but function definitions in header is generally not recommended (but it totally depends on your project design) To use a function completely defined in .c file into another .c file you need to do something like this //test.c int fun() { return 10; } // otherFile.c #include <stdio.h> extern int fun(); // <<== this line is important int main() { printf("%d", fun()); } Then compile both files together Not sure if it can be done with structure. +4 When writing a header file always use the include guard, it will ensure that the header file is included only once classic way and the most portable way to do it // mystruct.h #ifndef _MYSTRUCT_H_ (can be all lowercase or mix) #define _MYSTRUCT_H_ typedef struct mystruct { int x; char y; } mystruct; #endif other ways to do it // mystruct.h #pragma once (may not be supported by all compilers) your struct definition +2 I have done that: In header file test.h( surrounded by #ifndef #define .... #endif): typedef struct mystruct mystruct; void mystruct func(); And in test.c file: struct { int x; int y}; void mystruct func(){ ..... definition } How would i use this function and struct in otherFile.c? (And btw thank you very much for your help :D) +1 I also have funktion declarations in the header file which i define in test.c. When i also include test.c the Compiler tells me that i have multiple definitons of the functions Is it even possible to declare the functions and the struct in the same test.c file and use the functions and the struct in otherFile.c ? And of course i included test.h in test.c Thank you thats actually my problem.. The complier tells me "error: dereferencing pointer to incomplete type 'mystruct'" (I thought thats not the problem so i used easier examples) My files actually look like this: test.h : typedef struct struct1 struct1; typedef struct struct2 struct2; struct2* func(struct1* s); test.c: struct struct1 { struct2* x; }; struct struct2 { struct2* y; }; struct2* func(struct1* s){ return s->x; } Otherfile.c #include "test.h" int main(){ ... struct1* 'm' points to allocated memory..... m->x } This only works when i define the struct already in the header file. When i do it like this the compiler tells me that im dereferencing pointer to incomplete type struct1 with "m->x" Thank you that was really helpful 😊 0 It always works when i define the struct in the header and only the function in test.c But when i define everything in c the otherFile.c it does not So i thought its maybe not possible that way (But could also be another problem then) GET THE FREE APP Learn Playing. Play Learning SoloLearn Inc.
https://www.sololearn.com/Discuss/2067422/struct-in-header-file/
CC-MAIN-2019-51
refinedweb
633
75.91
Here are a few things you'll have to change in your Silverlight 1.1 apps to get them working with the 1.1 Alpha Refresh: Get the SDK here: Microsoft Silverlight 1.1 Software Development Kit Alpha Refresh *** Note, as Jack Bond (thanks Jack) pointed out in the comments to this post, there seems to be a problem with the Silverlight.js file shipping with the 1.1 Alpha Refresh SDK pointing people to the 1.0 Silverlight plug-in. See the comments in this post for more details. PingBack from When are we going to get native textboxes, comboboxes and the like so that Silverlight becomes useful to actually do something instead of just show pretty pictures that move? The opportunity for Silverlight is to fulfill the web 2.0 promise and provide a rich user experience for interactive data driven applications via the internet with zero client footprint, but so far it's like the people at MS haven't even realized what they have on their hands and where it's true power is. (i.e. no System.Data namespace!) John We're committed to shipping a set of controls with Silverlight 1.1 they're just not in the Alpha. See for more details. You can still do a lot of great stuff, and there is a control model there. But I'll grant you it's hard work at the moment as the onus is on you to provide most of the plumbing and layout. Unless the 1.1 sdk has been updated, the silverlight.js file it contains is for v1.0. We needed to pull the 1.1 silverlight.js from the airline demo. details the full problem. Thanks Jack! That explains a behaviour we saw earlier today when sharing an app we're building with some folks who got into a "Get Silverlight" loop. Mike No problem, we're kind of surprised Microsoft hasn't updated the SDK by now. You might want to update bullet #1, in case someone doesn't look at the comments.
http://blogs.msdn.com/b/mikeormond/archive/2007/08/06/moving-to-silverlight-1-1-alpha-refresh-a-quick-checklist.aspx
CC-MAIN-2015-48
refinedweb
345
75.5
Months ago Freshbooks and 1Password decided to stop working together. I use Freshbooks to track my time for my business and I use 1Password for easy login to sites in general. For some reason, 1Password's auto-fill function stopped functioning on the Freshbooks login page. I reached out to 1Password was pleased with their response: they acknowledged the issue and they even went into technical detail as to what was causing the problem (a stray iframe on the page to was to blame). I figured I'd let the developers over at 1Password solve this issue. However, after a few more weeks of manually copying and pasting my password I decided it was time to take matters into my own hands. I had a vague notion that Firefox's Grease Monkey addon was designed to hack pages on your behalf. However, I'd never used it. And these days, I'm using Chrome as my primary browser. A bit of Googling confirmed that my thinking was in the right direction: Chrome offers a plugin named Tamper Monkey and it does the on the fly page hacking I believed I needed. I installed Tamper Monkey, and worked up the following script: // ==UserScript== // @name Freshbooks + 1password fixer // @namespace // @version 0.1 // @description Freshbooks and 1password aren't working together, so I'm writing some code to make them work together. // @author Ben Simon // @match // @grant none // ==/UserScript== (function() { 'use strict'; var trouble = document.getElementById("zendesk-widget-iframe"); if(trouble) { trouble.parentNode.removeChild(trouble); } })(); The script worked like a charm! With the errant iframe removed, 1Password was back to working. And best of all, I've added Tamper Monkey as a new tool to my toolbox.
http://www.blogbyben.com/2019/04/1password-and-freshbooks-not-on.html
CC-MAIN-2019-30
refinedweb
284
64.1
Answered by: How to reference new C# class in XAML Hi, I am using Visual Studio Express to create a Phone 7 application. I created a new c# class inside the project and now I want to just reference to it to add it as a Resource in the Main.xaml page. So I am not sure how to reference it. It seems to me that I would have to add that class to the namespace declarations but I can't find any documentation that talks about how to reference a new class created inside the project. The documentation only talks about how to add external classes packed in a *.dll. Can someone please point me to documentation that tells you how to reference a new created local class or how to do it? thanks - Moved by CoolDadTxMVP Wednesday, June 01, 2011 2:08 PM WPF related (From:Visual C# IDE) Question Answers Hello, take a look at the following location: Hope this helps, Miguel. - Marked as answer by Yves.ZModerator Wednesday, June 22, 2011 6:17 AM All replies Hello, take a look at the following location: Hope this helps, Miguel. - Marked as answer by Yves.ZModerator Wednesday, June 22, 2011 6:17 AM Hi mesarina, Hope the document Miguel referred helps you. If you still have any problem, please let me know. Yves Zhang [MSFT] MSDN Community Support | Feedback to us Get or Request Code Sample from Microsoft Please remember to mark the replies as answers if they help and unmark them if they provide no help.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/36b0f0b6-a7cb-49de-b277-1fdaf69c7360/how-to-reference-new-c-class-in-xaml?forum=wpf
CC-MAIN-2016-40
refinedweb
259
68.81
Groovy Goodness: Getting All But the Last Element in a Collection with Init Method In Groovy we can use the head and tail methods for a long time on Collection objects. With head we get the first element and with tail the remaining elements of a collection. Since Groovy 2.4 we have a new method init which returns all elements but the last in a collection. In the following example we have a simple list and apply the different methods: def gr8Tech = ['Groovy', 'Grails', 'Spock', 'Gradle', 'Griffon'] // Since Groovy 2.4 we can use the init method. assert gr8Tech.init() == ['Groovy', 'Grails', 'Spock', 'Gradle'] assert gr8Tech.last() == 'Griffon' assert gr8Tech.head() == 'Groovy' assert gr8Tech.tail() == ['Grails', 'Spock', 'Gradle', 'Griffon'] Code written with Groovy 2.4.
https://blog.jdriven.com/2015/01/groovy-goodness-getting-last-element-collection-init-method/
CC-MAIN-2022-40
refinedweb
126
76.32
> On 25 October 2011 19:42, Brian LeRoux <brian.leroux@nitobi.com> wrote: > > > Aim to tag Friday and Steve will package a release Monday. We'll do > > this on the* repos. > > > > Objections? > > > > Note this is not an Apache Callback release per se --- this is > > transitory for sure. Lots remains to be done for that to officially > > happen: > > > > - re-namespace to org.apache.callback.* > > - change all licenses and headers to the Apache License > > > > There's a little more involved in doing a release in the incubator. I think Brian is referring to a phonegap release from Nitobi, not a Callback release from the Incubator. Sort of "flush the queue" kind of stuff before starting to work 100% within the ASF. Is that the case? -- Gianugo Rabellino Senior Director, Open Source Communities, Microsoft Corp. Mobile: +1 (425) 786-8646 Twitter: @gianugo You might > want to have a glance at > and look into > > > For example, you'll need to call a vote on the release on the incubator list > - see > > %200.1- > incubating%20RC4#query:%5BVOTE%5D%20Release%20Droids%200.1- > incubating%20RC4+page:1+mid:d7odafgjg3uhz52t+state:results > for > a similar vote in process. > > > > Thanks, > > Andrew. > -- > asavory@apache.org / contact@andrewsavory.com >
http://mail-archives.apache.org/mod_mbox/incubator-callback-dev/201110.mbox/%3C669FD20FA9C6D4408948A6DB6DBE9B790CBC4F8B@TK5EX14MBXC122.redmond.corp.microsoft.com%3E
CC-MAIN-2017-13
refinedweb
200
57.16
Solution Sharing This is how I did it. I think it’s a lot more intuitive than the provided solution: def frequency_dictionary(words): frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency[word] = 1 return frequency I did it in one line def frequency_dictionary(words): return{key:(words.count(key)) for key in words} That’s quadratic though, should be linear. for example, a string of length 1000000 should take about 1000000 steps. Yours takes 1000000000000 steps You can test this yourself: # should complete in at the very most a second frequency_dictionary('a' * 1000000) Hi, ionatan, My code is inefficient too right? How should it be solved, better to run a normal for loop and update a empty dict with key and count? # Write your frequency_dictionary function here: def frequency_dictionary(words): return {word:words.count(word) for word in words} It’s exactly the same. Consider what count does. Expand its equivalent code: def frequency_dictionary(words): counts = {} for word in words: count = 0 for word_ in words: if word == word_: count += 1 counts[word] = count return counts What frequency_dictionary should be doing while iterating is to keep multiple running sums so the dict has to exist before you start iterating. For each value, add 1 to the corresponding sum. If you really wanted to one-line this then what you’re looking for is functools.reduce where you’d have a dict as the accumulator and as the function you’d have “increase the sum for this key”… but it isn’t pretty. …also collections.Counter already does this, but the point is to implement it def frequency_dictionary(words): return {word: words.count(word) for word in words} The point of the function being linear and not quadratic is so that it takes less time to execute? Less clock ticks, as it were. That’s a description of how the amount of work scales with the size of the input. For example, looking through a yellow pages to find a phone number by name can be done either by reading it from start to finish, or by doing binary search (start in the middle), which is more work? Reading from the start takes O(N) (linear) amount of work where N is the amount of names, and binary search takes O(log2 N) (logarithmic) amount of work Thank you all for sharing your beautiful code and many approaches. It really helps. Now to the very entry-level question…the first code on this post (a), is it a linear code? (b) is a quadratic code…hope I understood correctly. How do you see at once if the code is a linear or quadratic? a) def frequency_dictionary(words): frequency = {} for word in words: frequency[word] = words.count(word) return frequency b) def frequency_dictionary(words): return {word:words.count(word) for word in words} One easy thing to look for are nested loops. That would make it quadratic since the values in the inner loop are revisited with each iteration of the outer loop. Your code examples above only visit upon each piece of data one time. That would make it linear. However, … .count() is an iterator so can be viewed as an inner loop that revisits the data in words multiple times. So, … One could say that it is quadratic. This will still need more bearing out so keep drilling down this Big O rabbit hole. That makes sense…LMAO. I think I probably had the wierdest solution…that worked. def frequency_dictionary(words): new_dict = {} for word in range(len(words)): if word == 0: new_dict[words[word]] = 1 else: if words[word] == words[word - 1]: new_dict[words[word]] += 1 else: new_dict[words[word]] = 1 return new_dict Not nearly as efficient…but kinda shows how my mind works…lol…I don’t recall ever going over .count()…was that something that was ever reviewed and I forgot it? def frequency_dictionary(words): #Establish a blank list to reference words that have been added already reference = [] #Establish a dictionary to hold the words and associated count frequency = {} #starts the loop to iterate through the list entered as a parameter for word in words: #checks to see if the word has already been counted by using reference list if word in reference: #if the word has been counted already it moves to the next word in the parameter list continue #if the word has not been counted yet, it gets added to the reference list and then the .count() has to only run once through the parameter list else: reference.append(word) frequency[word] = words.count(word) # returns the created dictionary after the loop has terminated return frequency With this construction the code doesn’t have to iterate fully through the list and overwrite the entries in the created dictionary multiple times, nor does it need to keep track of the count with a incremented counter, and it only has to call the .count function multiple times. It also gives flexibility in terms of pre-selecting for certain words if need be, since you can hardcode values in the reference list to skip them. You have to iterate through the whole list, you’re counting them all, so you have to look at them all. Using list.count will iterate through that again. So since you’re using it several times you are iterating through the whole list several times. You’re also iterating through reference many times, its information is already available in your frequency dict and is available without iteration. Ideally what you would do is iterate through the list once, adding 1 for each item encountered. This might be easier to realize if you implement in and .count yourself, so that you are aware of what they are doing. Thank you for the reply, yet I need your answer broken down which many people don’t do. I’m working under the assumption that this quoted code from the beginning of the page is the ideal answer. When you say that I’m using .count several times, I thought what I was doing is using it less times than this code since the line for word in words: frequency [word] = words.count(word) appears to be calling .count() to assign a count for every single word in the parameter dictionary. If the solution uses .count() anyway, then why does my solution not help the problem by using it only several times as opposed to every single time? To your second point, how am I able to utilize the information in my frequency dict without iteration? Using .count() gets the count of all like elements in the list but that is iteration, and using manual incrementation by += 1 still requires iterating through the created dictionary in order to find a value to increment if it exists. If possible could you explain how the “adding 1 for each item encountered” doesn’t require a second level of iteration? And I don’t understand what you mean by “implement in and .count() yourself” because that is what I thought I was doing and the online code viewer doesn’t show things like a debug console or display the time it takes to actually run my code in ms. What can I do get a clearer understanding of the inner workings of these keywords/methods? list.count searches through the whole list, so if you do that once for each word then what you have is one loop nested inside another. if you for example have 100 unique words then you would be making a total of 10000 iterations, there should be 100. dict is lookup by key, it does not involve iteration. otherwise there would be no point you’d use list instead. Thank you but this answer is still not clear. When I said in the previous post I’m working under the assumption that the quoted code from the beginning of the page is the ideal answer. … since the line appears to be calling .count() to assign a count for every word in the parameter dictionary. The first part of your reply: list.count() searches through the whole list, so if you fo that once for each word then what you have is one loop nested inside another. reinforces what I was initially asking: If the ideal code appears to start a nested loop because .count() does appear to be called for each word, then how can this be avoided. Secondly, is the quoted code from the beginning of the page by prosowski the ideal solution? The second part of your reply: dict is lookup by key, it does not involve iteration. otherwise there would be no point you’d use list instead. is this referring to the use of the keyword “in”? If so, then is the code posted by mwail583 on Mar’19 the type of solution you meant by Ideally what you would do is iterate through the list once, adding 1 for each item encountered. My reply disqualifies that code as ideal. There should be a total of one iteration through the list. Each time count is used, it iterates through the list, so if you need to use count multiple times, then you’ve exceeded that limit of one, that’s no longer ideal. How you would avoid a nested loop is something you can answer by considering what a dict at all does. What does a dict provide, what is a dict? the operator in does not itself do anything, it is a request for membership testing, dict and list will do different things in response to those requests because they’re different structures and therefore obtain that information through different strategies Additionally, you can do better then O(n^2) with lists alone. You can get that down to O(n log n) which is much closer to linear than square. But you’ve got dict, so therefore you can do it in O(n), linear amount of time, for each unit of input you add you add one unit of time cost. Can somebody explain to me how it works : Why Apple returns 2 not 1 ? I did thru count method. # Write your frequency_dictionary function here: def frequency_dictionary(words): freqs = {} for word in words: if word not in freqs: **<________So first loop, apple is not in freqs | 2nd loop, apple is in freqs** freqs[word] = 0 <________apple = 0 ? | freqs[word] += 1 | 1 = 0 + 1 ? return freqs ***_______ returns freqs apple = 0 ? | returns 1 ?* # Uncomment these function calls to test your function: print(frequency_dictionary(["apple", "apple", "cat", 1])) # should print {"apple":2, "cat":1, 1:1} print(frequency_dictionary([0,0,0,0,0])) # should print {0:5}
https://discuss.codecademy.com/t/solution-sharing/462893
CC-MAIN-2020-16
refinedweb
1,785
70.33
Bug #7799 File descriptor limit issues with large number of entries 0% Description From: Jeff Dost <jdost@ucsd.edu> Subject: Factory glideFactoryEntryGroup.py not respecting FD limits Date: February 5, 2015 at 7:12:16 PM CST To: "glideinwms-support@fnal.gov" <glideinwms-support@fnal.gov> Hello glideinWMS support, I am in the process of trying out a test factory where I have about 600 entries in it. After reconfig, it is no longer able to stay up. Below [1] is the error I see in the factory log. It looks like the EntryGroup process is maintaining a hard coded maximum of 1024 FDs. Initially I tried manually increasing the hard and soft ulimit levels for the gfactory, but that only worked for the parent glideFactory process: glideFactory: grep 'open files' /proc/25342/limits Max open files 4096 4096 files EntryGroup: grep 'open files' /proc/25349/limits Max open files 1024 1024 files Poking around the code I found this (line 329 glideFactory.py, version v3_2_7_2): childs[group] = subprocess.Popen(command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, preexec_fn=_set_rlimit) and sure enough, the _set_rlimit callback is hard coding to 1024: def _set_rlimit(): resource.setrlimit(resource.RLIMIT_NOFILE, [1024, 1024]) In my opinion there is no good reason for this, it should just inherit whatever limits the glideFactory parent is set to. This way we can tweak the limits as needed on the gfactory user to avoid hitting them. Can you please take a look? Thanks, Jeff [1] [2015-02-05 16:06:16,777] WARNING: glideFactory:447: EntryGroup 0 STDERR: Traceback (most recent call last): File "/usr/sbin/glideFactoryEntryGroup.py", line 729, in ? File "/usr/sbin/glideFactoryEntryGroup.py", line 672, in main File "/usr/lib/python2.4/site-packages/glideinwms/factory/glideFactoryEntry.py", line 91, in init File "/usr/lib/python2.4/site-packages/glideinwms/lib/logSupport.py", line 232, in add_processlog_handler File "/usr/lib/python2.4/site-packages/glideinwms/lib/logSupport.py", line 76, in init File "/usr/lib64/python2.4/logging/handlers.py", line 59, in init File "/usr/lib64/python2.4/logging/__init__.py", line 757, in init IOError: [Errno 24] Too many open files: u'/var/log/gwms-factory/server/entry_UKI-SOUTHGRID-OX-HEP_t2ce06_longfive/UKI-SOUTHGRID-OX-HEP_t2ce06_longfive.err.log' [2015-02-05 16:06:16,777] WARNING: glideFactory:454: EntryGroup 0 exited. Checking if it should be restarted. [2015-02-05 16:06:16,777] WARNING: glideFactory:464: Restarting EntryGroup 0. [2015-02-05 16:06:17,017] ERROR: glideFactory:701: Exception occurred spawning the factory: Traceback (most recent call last): File "/usr/sbin/glideFactory.py", line 697, in main frontendDescript, entries, restart_attempts, restart_interval) File "/usr/sbin/glideFactory.py", line 484, in spawn childs[group].tochild.close() AttributeError: 'Popen' object has no attribute 'tochild' History #1 Updated by Parag Mhashilkar almost 6 years ago - Assignee set to Burt Holzman #2 Updated by Burt Holzman almost 6 years ago - Occurs In v3_0, v2_7, v2_7_1, v3_1, v2_7_2, v3_2, v3_2_1, v3_2_2, v3_2_3, v3_2_4, v3_2_5, v3_2_5_1, v3_2_6, v3_2_7, v3_2_8, v3_2_9, v3_3, v3_2_x, v3_x added Based on further investigation.. The gFEG instantiates glideFactoryEntry for every entry point. Each gFE sets up logging for itself, opening two (I think) FDs per entry. This isn't really necessary, since the entry log is only used in the children that are forked from the gFEG. One solution might be to change gFE.log to a function and init logging on first use. I think this has been around since v2_7_0 (the EntryGroup refactor) ! #3 Updated by Burt Holzman almost 6 years ago To be clear: the setting of the RLIMIT_NOFILE to 1024 was not actually the problem. We should really only need a handful of FDs per process. #4 Updated by Parag Mhashilkar over 5 years ago - Target version changed from v3_2_9 to v3_2_10 #5 Updated by Parag Mhashilkar over 5 years ago - Target version changed from v3_2_10 to v3_2_11 #6 Updated by Parag Mhashilkar over 5 years ago - Target version changed from v3_2_11 to v3_2_12 #7 Updated by Parag Mhashilkar almost 5 years ago - Target version changed from v3_2_12 to v3_2_13 #8 Updated by Parag Mhashilkar over 4 years ago - Target version changed from v3_2_13 to v3_2_14 #9 Updated by Parag Mhashilkar over 4 years ago - Priority changed from Normal to High - Target version changed from v3_2_14 to v3_2_15 #10 Updated by Parag Mhashilkar over 4 years ago - Assignee changed from Burt Holzman to Parag Mhashilkar #11 Updated by Parag Mhashilkar over 4 years ago - Target version changed from v3_2_15 to v3_2_16 #12 Updated by Parag Mhashilkar about 4 years ago - Target version changed from v3_2_16 to v3_2_17 #13 Updated by Parag Mhashilkar almost 4 years ago - Target version changed from v3_2_17 to v3_2_18 #14 Updated by Marco Mambelli almost 4 years ago - Target version changed from v3_2_18 to v3_2_19 #15 Updated by Parag Mhashilkar over 3 years ago - Assignee changed from Parag Mhashilkar to Dennis Box #16 Updated by Dennis Box over 3 years ago - Status changed from New to Feedback - Assignee changed from Dennis Box to Marco Mambelli Updated old v3/7799 branch by merge with branch_v3_2. Made modifications factory/glideFactory.py to inherit file limits from parent process by default. #17 Updated by Marco Mambelli over 3 years ago - Assignee changed from Marco Mambelli to Dennis Box #18 Updated by Dennis Box over 3 years ago - Status changed from Feedback to Resolved Feedback suggestions implemented, merged into branch_v3_2 #19 Updated by Parag Mhashilkar over 3 years ago - Status changed from Resolved to Closed Also available in: Atom PDF
https://cdcvs.fnal.gov/redmine/issues/7799
CC-MAIN-2020-50
refinedweb
922
51.78
Michael Niedermayer wrote: > Hi > > Attached patch adds generic metadata support to > ffmpeg.c, and the avi muxer and demuxer > The implementation should be pretty much as simple as possible. > > Differences to aurels variant > * flat metadata, no trees This is OK for me. I don't really care about trees. Anyway it's rarely used, so I simply won't support it in mkv at first. It can always be improved later in the mkv (de)muxer, flattening tags such as AUTHOR/ADDRESS. > * fully abstracted, implementation can be changed with no effect on ABI/API > * only a small set of muxers & demuxers are updated yet. > > Comments welcome, especally from aurel. First, several general questions/comments: * When a tag is muxed as key=value with its lang set to english and a default_lang flag, how should it be stored in AVMetaData ? I guess the value should be duplicated, like this: key = value key-eng = value * why is metadata.{c,h} in libavcodec while it's only used in libavformat ? I think the patch shouldn't touch libavcodec at all... Some details about the patch: Index: libavcodec/metadata.h =================================================================== --- libavcodec/metadata.h (revision 0) +++ libavcodec/metadata.h (revision 0) @@ -0,0 +1,38 @@ > + [...] > +#ifndef AVCODEC_METADATA_H > +#define AVCODEC_METADATA_H > + > + [...] > + > +#endif The missing comment on the #endif will upset Diego... > Index: libavcodec/avcodec.h > =================================================================== > --- libavcodec/avcodec.h (revision 16302) > +++ libavcodec/avcodec.h (working copy) > @@ -400,7 +400,50 @@ > */ > #define FF_MIN_BUFFER_SIZE 16384 > > + > +/* > + * public Metadata API. > + * Important concepts, to keep in mind > + * 1. keys are unique, there are never 2 tags with equal keys, this is also > + * meant semantically that is key=Author, key=Author2 is illegal as well. > + * All authors have to be placed in the same tag for the case of Authors. I think it's impossible to enforce in demuxer supporting generic metadata. How could a demuxer differentiate those 2 cases: - key=Author1, key=Author2 - key=IPV4, key=IPV6 The demuxer has no idea of the semantic. > + * 3. A tag whichs value is translated has the ISO 639 3-letter language code > + * with a '-' between appended. So for example Author-ger=Michael, Author-eng=Mike No support for country code (ISO 3166-1) ? Just a question, I personally don't care. > + * @return found tag or NULL, the value of the tag may be av_realloced or > + * changed by the caller, the key MUST NOT be changed. IMO there's no reason to encourage people messing directly with the tag value when there is a clean API to do it. > Index: libavformat/utils.c > =================================================================== > --- libavformat/utils.c (revision 16397) > +++ libavformat/utils.c (working copy) > @@ -2305,6 +2306,9 @@ > av_free(s->chapters[s->nb_chapters]); > } > av_freep(&s->chapters); > + if(s->meta_data) > + av_freep(&s->meta_data->elems); > + av_freep(&s->meta_data); You are leaking all the elems->key and elems->value. It may be worth adding a av_metadata_empty() function to do this... Overall, this patch looks like a sane basic implementation. It misses a few important things (see below) but the core API could probably already be commited (with no version bump, no (de)muxer change and no ffmpeg/ffplay change) so that we can improve it. Here are a few improvements that are IMO needed (and that I may provide a patch for, when basic API is commited): * Add a compatibility layer until lavf v53.0.0 so that people who read or write in AVFormatContext.title (or author or anything) with lavf 52.x.x still gets the correct behavior. This can probably be extracted and ported from my patch. * Add a bunch of #if LIBAVFORMAT_VERSION_MAJOR < 53 to remove all the old metadata API in next version * Add AVMetaData in AVStream, AVProgram and AVChapter (same as AVFormatContext). * Maybe add a way to normalize metadata keys for formats supporting only a limited set of keys. For example when muxing in mp3, if we have an 'artist' key but no 'author' key, the 'artist' should be stored instead of 'author'. This is only an internal API that can be added latter. * Several formats support storing ISO 639-2 lang in a separate field. If we store lang in the key field, we will probably need some internal helper functions to store/extract lang to avoid duplicating it in various muxers. This is only an internal API that can be added latter. When we are finally happy with the API, we can bump lavf minor, change all (de)muxers to the new API, and then update ffmpeg/ffplay. Does this plan sound OK ? Aurel
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-January/066694.html
CC-MAIN-2014-10
refinedweb
741
65.93
Opened 6 years ago Closed 22 months ago #15779 closed Bug (fixed) admin cannot edit records with value 'add' as primary key Description Problem If you have a model with a primary key field that has the value 'add' you won't be able to edit it in the admin screens. the admin will take you to the add page instead of the change page for that record. this is a problem with the design of the urls in the admin module. Example code follows: admin.py from polls.models import poll from django.contrib import admin admin.site.register(poll) model.py from django.db import models class poll(models.Model): id = models.CharField(max_length=200, primary_key=True) question = models.CharField(max_length=200) Reproducing - Create project and app, enable admin, add the above files and syncdb. - Go to the admin interface and select Add poll - specify 'add' as the id and 'test' as question - Save - Go back to the list - Open the same object - you will be taken to the add poll screen instead of the change poll screen for the selected object Change History (27) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by I agree with julien that the only sensible way to do this is to fix the URL structure. Technically I don't believe our backwards compatibility guarantee ever included the URL structure of admin apps. Since Django 1.1 we've had a fully capable URL reverser for the admin, and this has been the documented way to reverse admin views. So I'm going to accept on that basis - since we've documented the correct way to do it, if people have hard coded URLs then that is like using private methods instead of the exposed public interface. We should nonetheless include a note in the backwards compatibilities section of the release note. The patch would be quite simple, but there are some redirects which also assume the current structure and would also need to be fixed. (/me goes off to fix those hard-coded admin URLs in a really old Django app...) comment:3 Changed 6 years ago by comment:4 Changed 5 years ago by I'm going to call this ticket fixed in [16857]. After that revision, it is possible to implement a custom URL scheme in the admin app because it uses named URLs in the model CRUD workflow. There is an example of an instance of a model with a CharField PK with an 'add' value in the test case added in such commit: The customization process isn't completely straightforward because the named URL entry one is replacing needs to be removed from the ModelAdmin URL map to force the admin app to take in account the one we are installing (see the get_urls()/ remove_url() methods in the example linked above). Patches to make this easier are welcome. comment:5 Changed 5 years ago by After discussion with Ramiro and Julien in IRC, reopening this because it really ought to "just work" and the right way to make it "just work" is to reconsider the admin URL structure to remove ambiguity, as discussed above. Since this likely won't happen immediately, the workaround enabled by r16857 can be a useful stopgap for those who need it. comment:6 Changed 4 years ago by comment:7 Changed 2 years ago by I've done the first step of the work, by using reverse as much as possible in the various admin tests. comment:8 Changed 2 years ago by comment:10 Changed 2 years ago by comment:11 Changed 2 years ago by I am afraid that some users will have bookmarked existing edit URLs and are going to be annoyed when those now 404. I wonder if we should issue redirects for the old patterns and then have an option to turn them off for users affected by this issue. comment:12 Changed 2 years ago by I think we could safely add a temporary redirect raising a deprecation warning from the r'^(.+)/$' pattern as long as it appears after the r'^(.+)/edit/$' one. comment:13 follow-up: 14 Changed 2 years ago by Site users won't learn of that warning though. Is there a downside to keeping that redirect indefinitely? comment:14 Changed 2 years ago by comment:15 Changed 2 years ago by I've just added a complementary commit for the redirect. However, I think we should get rid of it after "some" releases... comment:16 Changed 2 years ago by comment:17 Changed 2 years ago by comment:18 Changed 22 months ago by This broke the password change link at /admin/auth/user/1/change/. We could change the URL in UserAdmin.get_urls() or update the link in the form: diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index 928c4c7..84fc757 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -98,7 +98,7 @@ class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField(label=_("Password"), help_text=_("Raw passwords are not stored, so there is no way to see " "this user's password, but you can change the password " - "using <a href=\"password/\">this form</a>.")) + "using <a href=\"../password/\">this form</a>.")) class Meta: model = User comment:19 Changed 22 months ago by comment:20 Changed 22 months ago by Having this relative link into help_text is doomed to fail. However, I don't see any simple workaround for now, so Tim's patch just needs a test. comment:21 Changed 22 months ago by The first paragraph of the Django URL dispatcher documentation says: "Cool URIs don’t change"... Do we really want to change the URL structure of every Django site out there for an extreme edge case like this? If I use a CharField as primary key nothing stops me from using "1/change" as key and we'll have exactly the same problem. If you insist on using a CharField as primary key adding some validation to exclude some "reserved" words is not to much of an ask. comment:22 Changed 22 months ago by If I use a CharField as primary key nothing stops me from using "1/change" as key and we'll have exactly the same problem. No, "1/change" would be converted to "change_2F1" in the URL. comment:23 Changed 22 months ago by Err... "1_2Fchange", of course. Yes this is an issue. Now we need to find the proper way to fix it. One (naive) idea is to make the "add/" url configurable, perhaps using a setting. But still, this wouldn't be ideal as a conflict would still potentially exist if whatever value you give to that setting is then used as a primary key. Really, the url schema for the admin is slightly flawed here. Down the track we might want to redesign it to avoid any sort of conflict -- but that would likely be heavily backwards incompatible.
https://code.djangoproject.com/ticket/15779
CC-MAIN-2017-04
refinedweb
1,172
70.02
Migrating to Meteor 1.4 Breaking changes These are all the breaking changes — that is, changes you absolutely have to worry about if you are updating your app from 1.3.x to 1.4. However, we recommend that you also consider the recommended changes listed below. The babel-runtime npm is usually required The babel-runtime npm package is generally required as a dependency since the Meteor babel-runtime package no longer attempts to provide custom implementations of Babel helper functions. To install the babel-runtime npm, simply run the following command in any Meteor application: meteor npm install --save babel-runtime New projects created with meteor create <app-name> will automatically have this package added to their package.json‘s dependencies. Binary Packages require a Build Toolchain The headline feature of Meteor 1.4 is the upgrade to Node version 4. Node 4 includes a changed ABI (application binary interface), which means that binary npm packages that your application uses will need to be recompiled. Some very common binary packages (such as npm-bcrypt) will already have been republished for the Node 4 platform, so if you are using a limited set of packages, this may not affect you; however if you are using less common dependencies, this may be an issue. If you have binary npm packages in your application node_modules directory, you should run meteor npm rebuild (after meteor update) in your application directory to recompile those packages. Meteor will automatically recompile any binary npm dependencies of Meteor packages, if they were not already compiled with the correct ABI. This will typically happen the first time you start your application after updating to 1.4, but it may also happen when you meteor add some:package that was published using a different version of Meteor and/or Node. In order for this rebuilding to work, you will need to install a basic compiler toolchain on your development machine. Specifically, OS X users should install the commandline tools (in short, run xcode-select --install). Windows users should install the MS Build Tools. Linux users should ensure they have Python 2.7, makeand a C compiler (g++) installed. To test that your compiler toolchain is installed and working properly, try installing any binary npm package in your application using meteor npm. For example, run meteor npm install bcrypt then meteor node, then try calling require("bcrypt") from the Node shell. Update from MongoDB 2.4 Meteor has been updated to use version 2.2.4 of the node MongoDB driver. This means Meteor now ships with full support for MongoDB 3.2 (the latest stable version) and the WiredTiger storage engine. We recommend you update your application to MongoDB 3.2. If you are currently using MongoDB 2.4, please note that the version has reached end-of-life and you should at the least update to version 2.6. Version 2.6 is the minimum version supported by Meteor 1.4. Updating your database to 2.6 is generally pretty painless. Please consult the MongoDB documentation for details about how to do so. As of 1.4, you must ensure your MONGO_OPLOG_URLcontains a replicaSetargument (see the changelog and the oplog documentation). NOTE: Some MongoDB hosting providers may have a deployment setup that doesn’t require you to use a replicaSetargument. For example, Compose.io has two types of deployments, MongoDB Classic and MongoDB+. The new MongoDB+ offering is a sharded setup and not a true replica set (despite the shard being implemented as a replica set) so it does not require the replicaSetparameter and Meteor will throw an error if you add it to your connection strings. If you see a failed authentication you may need to upgrade to SCRAM-SHA-1, essentially: use admin, db.adminCommand({authSchemaUpgrade: 1});. You may need to delete and re-add your oplog reader user. Remove debugger statementsDue to changes in Node 4, if you have debuggerstatements in your code they will now hit the breakpoint even without a debugger attached. This also means you can now debug without using the --debug-brkoption. Password reset and enrollment tokens now expirePassword Reset tokens now expire (after 3 days by default – can be modified via Accounts.config({ passwordResetTokenExpirationInDays: …}). PR #7534 See PR #7794 for infomation about splitting reset vs enrollment tokens and allowing different expiration times. Recommendations Update to Meteor 1.3.5.1 first Though not mandatory, it may be helpful to update your apps to Meteor 1.3.5.1 before updating to 1.4, since 1.3.5.1 is the most recent release before 1.4, and contains much of the same code as 1.4. To update an app to 1.3.5.1, run meteor update --release 1.3.5.1 in the app directory. When you are confident the app is working correctly, meteor update will take you all the way to Meteor 1.4. Update to MongoDB 3.2 Although Meteor 1.4 supports MongoDB 2.6 and up, as well as the older MMAPv1 storage engine, we recommend you update your database to use the new WiredTiger storage engine and use MongoDB 3.2. To update your production database to version 3.2 you should follow the steps listed in the MongoDB documentation. To update your storage engine, you should ensure you follow the “Change Storage Engine to WiredTiger” instructions in the 3.0 upgrade documentation. If you are using OS X or 64bit Linux, you can update your development database in a similar way (if you are running meteor as usual, you can connect to the development database at localhost:3001/meteor). However, if you are not concerned about the data in your development database, the easiest thing to do is to remove all local data (including your development database) with meteor reset. When you next start meteor, the database will be recreated with a 3.2 WiredTiger engine. If you are using Windows or 32bit Linux, you can update your development database to 3.2, however it will continue to use the MMAPv1 storage engine, as the 32bit MongoDB binary does not support WiredTiger. Use Nested Imports Thanks to the use of the reify library, Meteor now fully supports nested import declarations in both application and package modules, whereas previously they were only allowed in application code: One place this is particularly useful is in test files that are only intended to run on the client or the server — you can now use import wherever you like, without having to organize your tests in client or server directories.
https://guide.meteor.com/1.4-migration.html
CC-MAIN-2018-09
refinedweb
1,096
56.66
CodePlexProject Hosting for Open Source Software Hi *, i'm currently upgrading my projects from 2.2 to 4.0 with no big problems so far. But the test-projects are missing Microsoft.Practices.Composite.TestSupport for MockUnityContainer. Do i still have to use the old .dll or is this namespace also moved somewhere to Microsoft.Practices.Prism? kind regards Joachim Looking at the directory structure it appears thats it located under the folder called "Prism.TestSupport" and within that folder the project contains the namespace you are looking for in the 4.0 version of the framework. thx mvermef, that's solved. hhmmm, that's a little bit confusing. I'm sure i used the search function on the prism4 folders this morning with no luck.... np at all. P&P did some renaming of the namespaces with I think it was drop 5 or 6, then everything has been the same since. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://compositewpf.codeplex.com/discussions/235823
CC-MAIN-2017-39
refinedweb
189
79.06
Two ways of writing a recursive one-liner: (1) write the function with return statement in a single line such as in def f(x): return f(x+1), or (2) assign a lambda function to a variable name and use the variable name in the return expression of the lambda function such as in f = lambda x: f(x). To define a recursion base case, you can use the ternary operator x if c else y to return x if condition c is met, else y. Let’s dive into the problem and several detailed examples! Problem: How to write a recursive function in a single line of code? You may find this challenging because you need to define the function name, the base case, and the recursive function call—all in a single line of Python code! Related Article: To refresh your general recursion skills, check out my detailed blog article (including video). Here’s an overview of the different algorithms, we one-linerized recursively! 😉 Exercise: Run the code and test the results. Are they correct? Now change the inputs to the recursion base cases and run the code again! Are they correct? Let’s dive into each of those methods! Method 1: Recursive Fibonacci What are Fibonacci numbers? The Fibonacci numbers are the numbers of the Fibonacci series. The series starts with the numbers 0 and 1. Each following series element is the sum of the two previous series elements. That’s already the algorithm to calculate the Fibonacci series! We consider the following problem: Given a number n>2. Calculate a list of the first n Fibonacci numbers in a single line of code (starting from the first Fibonacci number 0)! # Method 1: Recursive Fibonacci def fib(n): return 1 if n in {0, 1} else fib(n-1) + fib(n-2) print(fib(10)) # 89 This one-liner is based on this Github repository but made more concise and more readable. It uses the ternary operator to compress the return value of the function. Explanation Ternary:. Method 2: Recursive Factorial Consider the following problem:. The figure shows three different rankings of the teams. In computer science terminology, you would denote each ranking as a “permutation”. A permutation is defined as a specific order of set elements (here: football teams). Using this terminology, our goal is to find the number of permutations of a given set (the set of all football teams). The number of those permutations has important implications in practice such as betting applications, match prediction, and game analysis. For example, when assuming 100 different rankings with equal probability, the probability of a specific ranking is 1/100 = 1%. This can be used as a base probability (a priori probability) for game prediction algorithms. Under these assumptions, a randomly guessed ranking has a 1% probability of being the correct outcome after one season. How to calculate the number of permutations of a given set? As it turns out, the factorial function n! calculates the number of permutations of a given set of n elements. The factorial is defined as follows: For example: Why does the factorial count the number of permutations of a given set of elements? The answer is very straightforward: Say, you have a set of ten elements S = {s0, s1, ..., s9} and ten buckets B = {b0, b1, ..., b9}. In the football example, there are twenty teams (the elements) and twenty table ranks (the buckets). To get a permutation of S - First, you take a random element from the set S. In how many buckets can you place this element? There are ten empty buckets so you have ten options. - Second, you take the next element from the set. In how many buckets can you place this element? There are nine empty buckets so you have nine options. - … - Finally, you take the last element from the set. In how many buckets can you place this element? There is only one empty bucket so you have one option. In total, you have 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 10! different options. Each option of placing elements into the buckets represents one permutation of the set elements. The number of permutations of a set with n elements is n!. You now know everything you need to know to solve the following problem: Write a Python one-liner solution that computes the number of permutations n! of a set with n elements. # Method 2: Recursive Factorial def fac(x): return 1 if x<=1 else x * fac(x-1) print(fac(10)) # 3628800 This one-liner is based on this forum post but, again, I improved readability and conciseness. For instance, it’s generally a good idea to handle the recursion base case first. The factorial function can be defined recursively as with the recursion base cases defined as The intuition behind these base cases is the following: A set with one element has one permutation. And a set with zero elements has one permutation (there is one way of assigning zero elements to zero buckets). Method 3: Factorial One-Liner with Lambda An alternative to calculate the recursive factorial in a single line is the following: # Method 3: Recursive Factorial with Lambda fac = lambda n: 1 if n<=1 else n * fac(n-1) print(fac(10)) # 3628800 The code uses the previously-discussed recursive definition. It creates a lambda function with one argument n. It assigns the lambda function to the name fac. Finally, it calls the named function fac(n-1) to calculate the result of the function call fac(n). By using the solution to the easier problem fac(n-1), we can construct the solution of the harder problem fac(n) by multiplying it with the input argument n. As soon as we reach the recursion base case n <= 1, we simply return the hard-coded solution fac(1) = fac(0) = 1. Let’s dive into a more advanced recursive one-liner: the Quicksort algorithm! Method 4: Recursive Quicksort One-Liner Next, you’ll learn about the popular sorting algorithm Quicksort. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm! This code is based on this detailed blog tutorial. If you want more explanations, check it out! problem:. []in the recursion base case (that is – the list to be sorted is empty and, therefore, trivially sorted). In any other case, it selects the pivot element as the first element of list Therefore, the result is: ## The Result print(q(unsorted)) # [2, 3, 6, 33, 33, 45, 54].
https://blog.finxter.com/python-one-line-recursion/
CC-MAIN-2022-21
refinedweb
1,098
55.84
Created on 2013-09-08 16:41 by jason.coombs, last changed 2014-02-25 15:23 by python-dev. This issue is now closed. In Python 2.x and 3.2, I used to use a Request subclass I created for overriding the method used: class MethodRequest(request.Request): def __init__(self, *args, **kwargs): """ Construct a MethodRequest. Usage is the same as for `urllib.request.Request` except it also takes an optional `method` keyword argument. If supplied, `method` will be used instead of the default. """ if 'method' in kwargs: self.method = kwargs.pop('method') return request.Request.__init__(self, *args, **kwargs) def get_method(self): return getattr(self, 'method', request.Request.get_method(self)) In Python 3.3, which now supports a method parameter, it broke this paradigm (because the method is stored in the instance and is always set to None in __init__ if not specified). I believe a paradigm where the method is stored as a class attribute and possibly overridden in an instance would be much better, allowing for subclasses to simply and directly override the method. For example: class HeadRequest(MethodRequest): method = 'HEAD' That straightforward example works very well if method is allowed to be a class attribute, but won't work at all if 'method' is always set as an instance attribute in __init__. And while it's possible for HeadRequest to override __init__, that requires HeadRequest to override that entire signature, which is less elegant than simply setting a class attribute. For Python 3.4, I'd like to adapt the Request class to allow the Method to be defined at the class level (while still honoring customization at the instance level). Hi Jason, Agree with you. This design change could be valuable in extending urllib.request.Request Thanks! I've created a clone in which to draft this work. I've added tests to capture the new behavior. New changeset 6d6d68c068ad by Jason R. Coombs in branch 'default': Issue #18978: Allow Request.method to be defined at the class level. New changeset 2b2744cfb08f by Jason R. Coombs in branch 'default': Issue #18978: A more elegant technique for resolving the method New changeset 061eb75339e2 by Jason R. Coombs in branch 'default': Issue #18978: Add tests to capture expected behavior for class-level method overrides. New changeset 8620aea9bbca by Jason R. Coombs in branch 'default': Close #18978: Merge changes. New changeset 7f13d5ecf71f by Jason R. Coombs in branch 'default': Issue #18978: Update docs to reflect explicitly the ability to set the attribute at the class level. Thanks for the this change, Jason. Docs could be updated to reflect this change (using ..versionchanged: directive). Thank you! New changeset 1afbd851d1c1 by R David Murray in branch 'default': whatsnew: Request.method can be overridden in subclasses (#18978).
http://bugs.python.org/issue18978
CC-MAIN-2015-06
refinedweb
458
68.77
40292/prevent-jobs-to-be-killed-from-web-ui You need to be careful with this. I am not sure about completely disabling the permission to delete jobs but you can disable deletion of jobs and stages from the Web UI. Use the following property with spark submit and you won't be able to delete the jobs from the Web UI. val sc = new SparkContext(new SparkConf()) ./bin/spark-submit <all your existing options> --spark.ui.killEnabled=false I think there is a timeout set ...READ MORE You can implement this as follows: First, add ...READ MORE For a user to have modification access .. code: import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.FileSystem import ...READ MORE Hey, you can use "contains" filter to extract ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/40292/prevent-jobs-to-be-killed-from-web-ui
CC-MAIN-2020-16
refinedweb
138
70.19
Released. FluidSynth works on all major platforms, so pyFluidSynth should also. FluidSynth 1.0.7 (or later version) (earlier versions probably work, untested) NumPy 1.0 or later pyFluidSynth is available as a source distribution from PyPI. pyFluidSynth is packaged as Python source using distutils. To install, run the following command as root: python setup.py install For more information and options about using distutils, read: Here is a program that plays a chord for a second. import time import fluidsynth fs = fluidsynth.Synth() fs.start() sfid = fs.sfload("example.sf2") fs.program_select(0, sfid, 0, 0) fs.noteon(0, 60, 30) fs.noteon(0, 67, 30) fs.noteon(0, 76, 30) time.sleep(1.0) fs.noteoff(0, 60) fs.noteoff(0, 67) fs.noteoff(0, 76) time.sleep(1.0) fs.delete() First a Synth object is created to control playback. The start() method starts audio output in a separate thread. To get sound, you need to choose an instrument. First load a SoundFont with sfload(), then select a bank and preset with program_select(). program_select(track, soundfontid, banknum, presetnum) To start a note, use the noteon() method. noteon(track, midinum, velocity) To stop a note, use noteoff(). noteoff(track, midinum) You can also manage audio IO yourself and just use FluidSynth to calculate the samples for the music. You might do this, for example, in a game with WAV sound effects and algorithmically generated music. To do this, create the Synth object but don't call start(). To generate the next chunk of audio, call get_samples(). get_samples(len) The length you pass will be the number of audio samples. Unless specified otherwise, FluidSynth assumes an output rate of 44100 Hz. The return value will be a Numpy array of samples. By default FluidSynth generates stereo sound, so the return array will be length 2 len. To join arrays together, use numpy.append(). To convert an array of samples into a string of bytes suitable for sending to the soundcard, use fluidsynth.raw_audio_string(samples). Here is an example that generates a chord then plays the data using PyAudio. import time import numpy import pyaudio import fluidsynth pa = pyaudio.PyAudio() strm = pa.open( format = pyaudio.paInt16, channels = 2, rate = 44100, output = True) s = [] fl = fluidsynth.Synth() # Initial silence is 1 second s = numpy.append(s, fl.get_samples(44100 * 1)) sfid = fl.sfload("example.sf2") fl.program_select(0, sfid, 0, 0) fl.noteon(0, 60, 30) fl.noteon(0, 67, 30) fl.noteon(0, 76, 30) # Chord is held for 2 seconds s = numpy.append(s, fl.get_samples(44100 * 2)) fl.noteoff(0, 60) fl.noteoff(0, 67) fl.noteoff(0, 76) # Decay of chord is held for 1 second s = numpy.append(s, fl.get_samples(44100 * 1)) fl.delete() samps = fluidsynth.raw_audio_string(s) print len(samps) print 'Starting playback' strm.write(samps) Not all functions in FluidSynth are bound. Not much error checking, FluidSynth will segfault/crash if you call the functions incorrectly sometimes.
http://code.google.com/p/pyfluidsynth/
crawl-003
refinedweb
494
63.15
Although it is possible to chain many if-else statements together, this is difficult to read. Consider the following program: Because doing if-else chains on a single variable testing for equality is so common, C++ provides an alternative conditional branching operator called a switch. Here is the same program as above in switch form: The overall idea behind switch statements is simple: the switch expression is evaluated to produce a value, and each case label is tested against this value for equality. If a case label matches, the statements after the case label are executed. If no case label matches the switch expression, the statements after the default label are executed (if it exists). Because of the way they are implemented, switch statements are typically more efficient than if-else chains. Let’s examine each of these concepts in more detail. Starting a switch We start a switch statement by using the switch keyword, followed by the expression that we would like to evaluate. Typically this expression is just a single variable, but it can be something more complex like nX + 2 or nX - nY. The one restriction on this expression is that it must evaluate to an integral type (that is, char, short, int, long, long long, or enum). Floating point variables and other non-integral types may not be used here. nX + 2 nX - nY Following the switch expression, we declare a block. Inside the block, we use labels to define all of the values we want to test for equality. There are two kinds of labels. Case labels The first kind of label is the case label, which is declared using the case keyword and followed by a constant expression. A constant expression is one that evaluates to a constant value -- in other words, either a literal (such as 5), an enum (such as COLOR_RED), or a constant variable (such as x, when x has been defined as a const int). The constant expression following the case label is tested for equality against the expression following the switch keyword. If they match, the code under the case label is executed. It is worth noting that all case label expressions must evaluate to a unique value. That is, you can not do this: It is possible to have multiple case labels refer to the same statements. The following function uses multiple cases to test if the ‘c’ parameter is an ASCII digit. In the case where c is an ASCII digit, the first statement after the matching case statement is executed, which is “return true”. The default label The second kind of label is the default label (often called the “default case”), which is declared using the default keyword. The code under this label gets executed if none of the cases match the switch expression. The default label is optional, and there can only be one default label per switch statement. It is also typically declared as the last label in the switch block, though this is not strictly necessary. In the isDigit() example above, if c is not an ASCII digit, the default case executes and returns false. Switch execution and fall-through One of the trickiest things about case statements is the way in which execution proceeds when a case is matched. When a case is matched (or the default is executed), execution begins at the first statement following that label and continues until one of the following termination conditions is true: 1) The end of the switch block is reached 2) A return statement occurs 3) A goto statement occurs 4) A break statement occurs 5) Something else interrupts the normal flow of the program (e.g. a call to exit(), an exception occurs, the universe implodes, etc…) Note that if none of these termination conditions are met, cases will overflow into subsequent cases! Consider the following snippet: This snippet prints the result: 2 3 4 5 This is probably not what we wanted! When execution flows from one case into another case, this is called fall-through. Fall-through is almost never desired by the programmer, so in the rare case where it is, it is common practice to leave a comment stating that the fall-through is intentional. Break statements A break statement (declared using the break keyword) tells the compiler that we are done with this switch (or while, do while, or for loop). After a break statement is encountered, execution continues with the statement after the end of the switch block. Let’s look at our last example with break statements properly inserted: Now, when case 2 matches, the integer 2 will be output, and the break statement will cause the switch to terminate. The other cases are skipped. Warning: Forgetting the break statement at the end of the case statements is one of the most common C++ mistakes made! Multiple statements inside a switch block With if statements, you can only have a single statement after the if-condition, and that statement is considered to be implicitly inside a block: However, with switch statements, you are allowed to have multiple statements after a case label, and they are not considered to be inside an implicit block. In the above example, the 4 statements between the case label and default label are part of case 1, but not considered to be inside an implicit block. If this seems a bit inconsistent, it is. Variable declaration and initialization inside case statements You can declare (but not initialize) variables inside the switch, both before and after the case labels: Note that although variable y was defined in case 1, it was used in case 2 as well. Because the statements under each case are not inside an implicit block, that means all statements inside the switch are part of the same scope. Thus, a variable defined in one case can be used in another case, even if the case in which the variable is defined is never executed! This may seem a bit counter-intuitive, so let’s examine why. When you define a local variable like “int y;”, the variable isn’t created at that point -- it’s actually created at the start of the block it’s declared in. However, it is not visible (in scope) until the point of declaration. The declaration statement doesn’t need to execute -- it just tells the compiler that the variable can be used past that point. So with that in mind, it’s a little less weird that a variable declared in one case statement can be used in another cases statement, even if the case statement that declares the variable is never executed. However, initialization of variables directly underneath a case label is disallowed and will cause a compile error. This is because initializing a variable does require execution, and the case statement containing the initialization may not be executed! If a case needs to define and/or initialize a new variable, best practice is to do so inside a block underneath the case statement: Rule: If defining variables used in a case statement, do so in a block inside the case (or before the switch if appropriate) Quiz 1) Write a function called calculate() that takes two integers and a char representing one of the following mathematical operations: +, -, *, /, or % (modulus). Use a switch statement to perform the appropriate mathematical operation on the integers, and return the result. If an invalid operator is passed into the function, the function should print an error. For the division operator, do an integer division. 2) Define an enum (or enum class, if using a C++11 capable compiler) named Animal that contains the following animals: pig, chicken, goat, cat, dog, ostrich. Write a function named getAnimalName() that takes an Animal parameter and uses a switch statement to return the name for that animal as a std::string. Write another function named printNumberOfLegs() that uses a switch statement to print the number of legs each animal walks on. Make sure both functions have a default case that prints an error message. Call printNumberOfLegs() from main() with a cat and a chicken. Your output should look like this: A cat has 4 legs. A chicken has 2 legs. Quiz answers 1) Show Solution 2) Show Solution In section "Variable declaration and initialization inside case statements", stated However, initialization of variables directly underneath a case label is disallowed, and will cause a compile error. This is because initializing a variable does require execution, and the case statement containing the initialization may not be executed! is default value disallowed too? I've tried initialize variable underneath a default label and compiler error pops up. Initialization is the way we normally give "default values" to variables. Not sure whether you're referring to something else. Sorry, i meant default label. And I've cleared up my question, as i was confused with the sentence "initialization of variables directly underneath a case label is disallowed", if i stated anything wrong, please correct me. When i tried to run this code without default label, Seems like the code work if there's no default or case label underneath initialization of variable z even if variable z is initialized underneath case 3. I guess it's better to have default label in every switch statement than it being left out. Yes, you have it correct. It does look like compilers will let you initialize a variable directly if there's no subsequent case, since there's no way to skip over that case. However, I would not recommend doing this, as it's bad practice, and will lead to trouble if you add additional cases later. Generally speaking, if you need to define a new variable inside a case, use a block. It'll save you headaches. Question : In the below program why there is no syntax error for case 1: which is written inside case 0's {}, something like NO matching switch found Information : Also when input1 is given as 1 it prints one. seems like C++ won't care about braces in case statements! (the assembly code generates a table) Switch/case statements are essentially a form of goto, and you can definitely goto the middle of a block, so although I was initially surprised that this worked, upon reflection I guess it makes sense. That said, you should avoid actually doing this on purpose, as it's pretty unclear what the behavior will actually be. Under STARTING SWITCH header u typed, the expression must evaluate to integral type, didn't u mean "integer", thank you for this tutorial u provide really awesome content! "Integral" means "of or denoted by an integer". So, same thing. 🙂 Hi, thx for the great tutorial so far! 🙂 I need some help with the following error (MS VS Community 2015): "(38): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)" I even tried to switch my printNumberOfLegs() function with yours from the solution, but had the very same error. This error message doesn´t make any sense to me! :/ It worked fine for me. Did you remember to include the iostream and string headers? Aahaha, the string header! Ofc it was such a simple mistake again. Thank you! 🙂 here is what i wrote Although i am using a C++11 capable compiler(GNU CC Compiler),but if i use enum class instead of enum, my compiler says that all the animals (PIG,CHICKEN,...) are not defined in this scope in getAnimalName() and printNumberOFLegs() functions. so why did you advice to use the enum class? or am i doing something wrong? You're doing something wrong. 🙂 If you use an enum class, then your enumerators need to be prefixed with the enumeration name. e.g. instead of CAT, you need to use Animals::CAT. OK,Thanks for clearing my confusion. I'll keep that in mind from now on. ? Im doing a java course which by the way is a breeze thanks to what I learned on here so Thanks for the awesome tut. My ? is in java switch statement conditional expression can also evaluate to a string is this not true in C++ also ? In C++, a switch must be an integer or enumeration type (or a class that is convertable to such). So basically, no, you can't switch on a string in C++. Thanks for the reply maybe they will add that ability later it would be nice I think that's unlikely to ever happen in C++ (it would be quite inefficient). For now, you can use a sequence of if/else statements. If you want something maybe more efficient, you can set up a std::map to map strings to enums, and then switch on the enums. In the quiz exercise (2), i want to get the animal name input from the user but i cant find a way to do so. Error: no suitable conversion function from "std::string" to "Animal" exists. Need some help in this case plz. Thanks! Yes, the problem here is that x is a std::string, and you are passing x as an argument to function getAnimalName(), but getAnimalName() has a parameter of type Animal. The compiler doesn't know how to convert a string to an animal. So you'll need to do this conversion yourself. The easiest way to do this is to write a function to do the conversion: how to take a input off data type 'Animal' directly ? example: here, since it is giving an error.is there a possble way to take input of animal directly from user ? Read the user's input as a std::string, then write a function to convert the std::string to an Animal. e.g. [code] #include<iostream> #include<stdlib.h> using namespace std; enum Animal { pig, chicken, goat, cat, dog, ostrich }; void getAnimalName(Animal animal) { switch (animal) { case pig: cout<<"pig"; break; case chicken: cout<<"chicken"; break; case goat: cout<<"goat"; break; case cat: cout<<"cat"; break; case dog: cout<<"dog"; break; case ostrich: cout<<"ostrich"; break; default: cout<<"invalid choice"; break; } } int printNumberOfLegs(Animal animal) { switch(animal) { case pig: return 4; case chicken: return 2; case goat: return 4; case cat: return 4; case dog: return 4; case ostrich: return 2; default: cout<<"\tinvalid choice\t"; return 0; } } int main() { system("cls"); int x; x=printNumberOfLegs(pig); cout<<"A\t"<<(getAnimalName(pig))<<"\thas\t"<<x<<"\tlegs."; } [\code] here, cout<<"A\t"<<(getAnimalName(pig))<<"\thas\t"<<x<<"\tlegs."; why isn't cout possible this way ?? Your getAnimalName() returns a void, and you can't send a void value to std::cout. If you make getAnimalName() return a std::string instead of void, then this should work. Mr Alex, good afternoon (I live in France), Please accept my many thanks for fixing. Now it functions perfect. With regards and friendship Georges Theodosiou The Straw Man Mr Alex, good morning, Please let me report you my problem. I use compiler coliru () and output is in quotes: quote main.cpp: In function 'int main()': main.cpp:30:28: error: 'printColors' was not declared in this scope printColors(COLOR_GREEN); ^ quote The function name had a typo (printColors instead of printColor). I've fixed the example. I think I remember you teaching us that variables declared inside of if/else blocks are not visible outside of the block. Does the same thing go for variables declared within a switch? If not, then what about declaring a variable within a block, within a case statement.... will that variable be visible outside of that block and outside of the switch statement? Variable declared in a block are only visible in the block in which they are declared, or in any sub-blocks. So for variables declared in a switch block or case block, those will only be visible in those blocks. Quiz 1 solution, compiles and seems to work just fine, except that the console prints "Invalid operator selected!" before "Results:". Just curious why this happens. Fantastic tutorial by the way! Loving it! When I compiled this with Visual Studio 2015 and tried a couple of inputs (5 3 + and 5 3 -) it worked fine. I don't see anything wrong (though the break statements in DoMath() are extraneous and can be removed). I should have clarified that better, I was referring to if I put in something other than one of the four basic operators (5 3 g for example). Function calls have higher precedence than operator<<, so DoMath() is evaluated before the other statements are printed. One way to fix this would be to have DoMath() return the result as a std::string instead of printing the value itself. For some reason this won't compile. Its telling me there's an unexpected end of file when searching for precompiled header? Love the tutorials by the way 🙂 Compiles fine for me. Sounds like maybe your stdafx.h is corrupt somehow. Try recreating your project. Ya thanks, I figured it out. It was just that I was using an old file the I'd previously used and in microsoft visual there was a two tabs (one being source tab). When I recreated the code in a new file there was no source tab and it all worked fine. Unfortunately I don't yet understand the UI of microsoft visual because I'm a newby. In time... Thanks for you reply 🙂 Hello Alex am learning a lot with your site but please could you show an example with the example you have illustrated in your tutorials. How do i start such an example from the the start then i continue from where you started in your example thats dealing with colors. I've updated the first example to be a full program that you can run. I wanted to modify question-2 so that it will only print the animal entered by the user. I tried to modify the main(), but I am not able to write proper switch() or if else statement. Can you help? int main() { std::string x; cout<<"enter the name of an animal\n"; cin>> x; if ( x == 'cat') { printNumberofLegs(Animal::cat); } else if (x == 'chicken') { printNumberofLegs(Animal::chicken); } return 0; } Your if statement is fine, but "cat" and "chicken" need to be in double quotes. Double quotes are for strings, single quotes for single chars. Whats a jump table also, I don't get how this works: [quote]Note that although variable y was defined in case 1, it was used in case 2 as well. All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases.[/quote] But doesn't the declaration statement have to executed for the variable to be accessable? I just answered this in the above comment. Seems to be a popular question this week. 🙂. I'll add a little more about this to the lesson itself. Abstractly, a jump table is a table (array) of instructions that "jump" the point of execution to a different place in the code (using some other value to select which branch to take). In C++, a switch statement acts as a form of jump table itself. Your switch provides the value to jump to, and the point of execution jumps directly to the case statement that matches. This is often more efficient than using a series of if/else statement. An array of function pointers also acts like a jump table. "All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases" sometimes i find that C++ does not make any sense. given that case will execute the next statement(s) if case evaluated to true until it encounters break, goto etc. that said "int y;" should not have executed and y should not have been declared. QUESTION : if the variable is declared inside a block will it still be visible in the rest of the cases ? >QUESTION : if the variable is declared inside a block will it still be visible in the rest of the cases ? no unless you use keyword "static" - the variable will be destroyed at the end of the block >sometimes i find that C++ does not make any sense. given that case will execute the next statement(s) if case evaluated to true until it encounters break, goto etc. that said "int y;" should not have executed and y should not have been declared. I'm confused about that too :c I've been chatting a bit on forums, and got this: So duration is what really matters. When the compiler compiles this: int y is created on line 2 and destroyed when the blocks ends. It can be used anywhere in that block. Execution path doesn't matter oh i see... so it gathers all the variable declarations within the entire switch statement and sort of creates the variable at the start of the block ? @J3ANP3T3R actually I made a mistake it can only be used anywhere under the declaration, however this is just a limitation set by the compiler. If it weren't for scope, then you could just put it anywhere, and it would still compile and run perfectly. At least thats what I have gathered Forum post is here: Yup! Although in the above example, case 3 is not allowed, because initialization DOES require execution, and if case 3 never executes, what value would variable z have if the default path were selected? It would be undefined. Where a variable is visible (scope) and where it is created/destroyed (duration) are two different things. The static keyword affects duration, not scope. I made an update to this lesson to try to make how this works a little clearer. Have a re-read and let me know if you're still confused. Yeah, switch statements are a bit weird. That's why I try not to use them for anything other than trivial lookups (where the body for each case is simply a return statement). That said,. As for the block question, anything declared inside a block is not visible to anything outside the block. Please help,i am unable to figure what's wrong with this code consoleapplication1.cpp(90): error C4700: uninitialized local variable 'cat' used It looks like you've declared two animals (cat and chicken) but never initialized them. Should be: This code gives me errors when i compile; Error message: ||=== Build: Debug in Learncpp5.3 (compiler: GNU GCC Compiler) ===| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp||In function 'double Calculate(char, double, double)':| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|15|error: case label ''-'' not within a switch statement| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|18|error: case label ''*'' not within a switch statement| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|21|error: case label ''/'' not within a switch statement| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|24|error: case label ''%'' not within a switch statement| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|25|error: invalid operands of types 'double' and 'double' to binary 'operator%'| C:\Users\Gloria.owner\Documents\Eddiemania\Learncpp5.3\main.cpp|27|error: case label not within a switch statement| ||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 5 second(s)) ===| In function Calculate(): Should be I wrote much more code than Alex provided in his answer. Definitely an opportunity for me to write code more efficiently. This is why I like quizzes so much. I changed the return type value for a division to double as part of the first quiz answer. If first integer is smaller than the second integer then without type casting I get 0 returned because precision is dropped. From: to: Very Small thing I noticed. In the very first example in this lesson you wrote an enum with a comma at the end of the last enumerator. I know this is not a big deal at all, and it would still compile, I just wanted to bear notice that I remembered that this is not proper conention when writing an enum. This is just proof of how great your tutorials are to remember such as minut detail thanks Alex! Typo fixed, thanks! At quiz 2 How should you even call the printNumberOfLegs() function to get the default case? Also if the default case would be picked wouldn’t you get the result : printNumberOfLegs(): Unhandled enumerator legs. ?:)) Cuz you put cout << "legs" after default case. As written, there's no way to get the default case. The default case here is meant to ensure that if we ever add another enumerator and forget to update the function to account for the new enumerator, the output gives us some clue that we now have a case that isn't handled properly. Yes, the output is funny in that case, but at least we _know_ it's wrong, can look into it, and then fix the function. For some reason, gives me integer division, whereas, gives me floating point division. Can't figure why that is The return type of the function is set to an int, so it's implicitly converting the double result back to an integer before returning the value to the caller. Alex, it seems like Mr. Dyablo copied your code, because the function you wrote too is set to return an int, not a double. (Todd-mode ON. B) ) Variables declared inside a switch statement follow the normal scope and duration rules, don't they? So a variable declared inside a case statement is destroyed at the end of the switch. Also it can be used inside other cases. Similarly, a variable declared inside a block within a case statement is destroyed at the end of the block, and is not accessible inside other case statements. Correct? Oh, whoops. 🙂 I've fixed the example. Your understanding of the scoping of variables in relationship to switches is correct. Thanks! 🙂 in quiz1 in your code : i think its better to use static_cast : what u think ? Sure. That's probably the more likely case. I've updated the example accordingly. I'm glad that i learned c++ from you bro. that's my honnor @Alex In the solution to Quiz Q.1, you have used in the default case instead of a break. Since, this could be a valid answer, isn't it error prone? Also, if I use break statement in the default case instead of a return statement, I get the following warning: In function 'int calculate(int, int, char)': test_45_switch_case.cpp:20:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ Why is it so? Isn't the control returning to the main() after the switch block is exited using break statement? > in the default case instead of a break. Since, this could be a valid answer, isn’t it error prone? Yes, absolutely. But we haven't really talked about error handling yet, so I'm keeping things simple for now. > Isn’t the control returning to the main() after the switch block is exited using break statement? If you replace the returns with a break, the break exits the switch block (not the function), and then the function continues to run to the end. Once the function ends, control returns to main. So in that case you've reached the end of the function without providing a return statement, so what value would the function return in that case? I'm surprised it only gave you a warning and not an error. @Alex You do not need to use explicitly in the first example code inside printColor(), since you have used using directive Using directives removed. 🙂 Thanks for noticing. Why does Visual Studio keep putting a red line under operator<< after '"A "' here? I know it means there's an error, but I don't get why it's showing an error there. Operator<< should be able to handle outputting strings. Edit: I overloaded operator<< to accept strings, but it ended up causing the program to crash when I run it. Please help. I can't tell from the limited information you've provided. hey alex in this code i have declared a variable in one of the case statemnts and it is running fine. Yep, I made a mistake here. You are allowed to declare variables inside the cases and assign values to them, but not initialize them. I've updated the lesson to reflect this. but Alex what is the use of restricting the initialization of a variable when i can use the variable by first declaring it and then assiging a value to it. Or what specifically is the purpose of restrictiong the initialization of variables in switch case statements. Thanks btw for your quick response. It has to do with the way switch statements are implemented (they are essentially goto statement in disguise, and goto statements are not allowed to jump past initialized values in C++). In many cases you can simply declare and assign a value to the variable rather than provide an initializer, but there are other cases where this is not possible, such as const values or references, which require initialization. But really, it's irrelevant, because declaring variables in a case outside of a block is something that should be avoided. Just put them in a block and be done with it. Hi Alex, My question is about C++11 syntax usage in the second quiz. How can 'Animal parameter' gets into the function getAnimalName(???), in case if i'm using enum class, istead of plain enum? The same question related to switch(???) statement. Thanks a lot! It was not obvious, for me. Alex, I'm still having problems understanding your different uses of the word color. In the first code above you have a function printColor it has (Colors color) after it as the argument. Can you please tell me if I have this right? There is one argument. Colors is the (Enum)type here and color is the variable used in the function printColor. Since there is never an assignment made to color (only comparisons) with the if/else statements below it the function just prints out: "unknown" (No Quotes). Now in the second code you have: switch (color) and none of the case statements are ever true so the default unknown is again printed out. Is this also right? Thanks > There is one argument. Colors is the (Enum)type here and color is the variable used in the function printColor. True. > Since there is never an assignment made to color (only comparisons) with the if/else statements below it the function just prints out: "unknown" (No Quotes). False. Because this is a function parameter, the value of this variable will be set by the caller. For example, the caller may do something like this: When printColor is called, the color variable (of type Color) will be initialized with the enum value COLOR_BLACK. This isn't any different to how function parameters work with fundamental data types, like integers or doubles. Name (required) Website
http://www.learncpp.com/cpp-tutorial/53-switch-statements/comment-page-2/
CC-MAIN-2018-13
refinedweb
5,224
62.68
While working on the updated script in Automating vCloud Director 1.5 & Oracle DB Installation, I did some digging in my lab deployment and noticed a few interesting things about the new vCloud Director 1.5 installation. The first thing I noticed after configuring a new Provider vDC and the vCloud Agent (stored in /opt/vmware/vcloud-director/agent) is pushed out to the ESXi 5 hosts, a new esxcli module is added for vCloud Director under /usr/lib/vmware/esxcli-vcloud There are 6 namespaces that ranges from simple configuration query, network fence management, account manage and also something called "esxvm" which I'll go into a little bit later. I am not sure why this is not in the vCloud Director documentation, I was not able to find any reference to the new esxcli operations. You may also notice the use of legacy "vslauser" (Virtual Software Lifecycle Automation) throughout vCloud Director, even though it was re-written from the ground up, it looks like VMware decided to either keep the name or some of the code related to the service account. Here is an example of running "esxcli vcloud about get" command: Here is an example of running "esxcli vcloud fence getfenceinfo" command: Lastly, here is an example of what "esxvm" namespace provides: As you can see above, there are two operations: disable/enable support for 64-bit nested virtual machines. This is exactly the same configuration as I blogged about in How to Enable Support for Nested 64bit & Hyper-V VMs in vSphere 5 but using esxcli interface with vCloud Director 1.5. Let's take a look at what happens when we run the "enable64bitnested" operation. No surprise, we see that it automatically appends the required vhv.allow = "TRUE" flag which enables the support of running nested 64-bit virtual machines within a physical ESXi 5 host. You might be asking, why is this in vCloud Director? Well if you attended VMworld 2011 or previous VMworlds and took part in the hands on labs, you will know that VMware utilizes vPods or nested ESXi to deploy their labs. I suspect, this functionality was added into vCloud Director so that VMware can easily leverage nested ESXi for hands on labs or vSel deployments just like they did with Lab Manager previously. While look into this, I recall a very interesting article by Jason Boche - Deploy ESX & ESXi With Hidden Lab Manager 4 Switch in which Jason identifies a hidden flag in the Lab Manager database that enables a special feature in deploying nested ESX(i) VMs including customization through the use of a special version of VMware Tools for ESX(i). I was curious to see if something similar existed in the new vCloud Director that provided similar functionality. Looking at the SQL install scripts located in /opt/vmware/vcloud-director/db/{oracle/mssql}, I noticed an interesting config called "extension.esxvm.enabled" in NewInstall_Data.sql file As you can see from the insert statement, by default this value is set to "false" and we can also confirm this after vCloud Director has been installed and configured by querying the database. Let's go ahead and update this value to "true" and let's see what happens. Once you have verified the value has been successfully updated, I decide to use the same trick that Jason had identified with the special "Uber Admin Screen" to load the changes. To my surprise, the trick still worked but the page was not super Uber .... To enable the screen, you will need to click on the "About" page and then click CTRL+U (ctr + shift + u), which will toggle the "Uber Admin Screen". The available options are quite limited as you can see but there are some new hidden options such as a new debug and console toggle. When you enable these options, you will see them at the bottom right of your screen including a counter of the amount of memory being used for your vCloud Director deployment. After toggling the hidden database feature, I was not able to see any additional pages relating to nested ESXi hosts, even after restarting vCloud Director. Through some testing, I found that the "extension.esxvm.enabled" actually controlled whether or not nested 64bit VM was enabled when the vCloud Agent was pushed out to ESXi 5 hosts. Instead of manually adding vhv.allow = "TRUE" or using esxcli vcloud esxvm enable64bitnested, vCloud Director will automatically configure the ESXi hosts for you. I still suspect there is probably a hidden interface in managing vESXi hosts and leveraging a specialized version of VMware Tools to automate the deployment of nested ESXi, but I have not found out yet. UPDATE: Take a look at this blog post for the full details on building your own vSEL - The Missing Piece In Creating Your Own Ghetto vSEL Cloud 6 thoughts on “Cool Undocumented Features in vCloud Director 1.5” Great article! Are you possibly aware of a way for getting the same result as in Lab Manager when setting the parameter EsxVmSupportEnabled to allow assigning a “No Ip” setting when deploying nested ESX hosts? Thanks @nkange, I’ve not really played much with Lab Manager so I don’t know, you may want to check out Jason’s article mentioned in the post if he indicates any such feature Have you figured out how to add the VMware ESX/ESXi guests types in as an option like Jason did in Lab Manager ? When you figure that one out I would love to know. Very nice find indeed and I think you are right there should be a way to check on those using VCD. I bet there may be something down in the API you can use of VCD that could help you home in on it… call it a guess… 😉 @Justin/chinggod Take a look at my new post for the deatails
http://www.virtuallyghetto.com/2011/09/cool-undocumented-features-in-vcloud.html?showComment=1315907331197
CC-MAIN-2017-17
refinedweb
985
54.05
MBSRTOWCS(3) BSD Programmer's Manual MBSRTOWCS(3) mbsrtowcs, mbsnrtowcs, mbsnrtowcsvis - convert a multibyte character string to a wide character #include <wchar.h> size_t mbsrtowcs(wchar_t * restrict pwcs, const char ** restrict s, size_t n, mbstate_t * restrict ps); size_t mbsnrtowcs(wchar_t * restrict pwcs, const char ** restrict s, size_t max, size_t n, mbstate_t * restrict ps); size_t mbsnrtowcsvis(wchar_t * restrict pwcs, const char ** restrict s, size_t max, size_t n, mbstate_t * restrict ps); mbsrtowcs() converts the multibyte character string indirectly pointed to by s to the corresponding wide character string, and stores it in the ar- ray pointed to by pwcs. mbsnrtowcs() behaves the same, but reads at most max octets from the string indirectly pointed to by s. mbsnrtowcsvis() behaves the same, but automatically converts input octets from 8bit to unicode. The conversion stops due to the following reasons: • The conversion reaches a null byte. In this case, the null byte is also converted. • mbsrtowcs() or mbsnrtowcs() has already stored n wide characters. • The conversion encounters an invalid character. • The mbsnrtowcs() function has already devoured max octets. Each character is converted as if optu8to16(3) is continuously called. In the case of mbsnrtowcsvis(), each character is converted as if optu8to16vis(3) is continuously called; if the max argument is initially set to 0, the remaining state is drained. After conversion, if pwcs is not a NULL pointer, the pointer object pointed to by s is a NULL pointer (if the conversion is stopped due to reaching a null byte) or the first byte of the character just after the last character converted. If pwcs is not a null pointer and the conversion is stopped due to reach- ing a null byte, the mbsrtowcs() and mbsnrtowcs() functions place the state object pointed to by ps to an initial state after the conversion has taken place. The behaviour of the mbsrtowcs() and mbsnrtowcs() functions is affected by the LC_CTYPE category of the current locale. These are the special cases: s == NULL || *s == NULL Undefined (may cause the program to crash). pwcs == NULL The conversion has taken place, but the resultant wide character string was discarded. In this case, the pointer object pointed to by s is not modified and n is ignored. ps == NULL mbsrtowcs() uses its own internal state object to keep the conversion state, instead of ps mentioned in this manual page. mbsnrtowcs() has an own internal state which is dif- ferent from the one of mbsrtowcs(). Calling any other functions in libc never change the inter- nal state of mbsnrtowcs() or mbsrtowcs(), which is initial- ised at startup time of the program. mbsrtowcs() and mbsnrtowcs() return: 0 or positive The value returned is the number of elements stored in the array pointed to by pwcs, except for a terminating null wide character (if any). If pwcs is not null and the value returned is equal to n, the wide character string pointed to by pwcs is not null terminated. If pwcs is a null pointer, the value returned is the number of elements to contain the whole string converted, except for a terminat- ing null wide character. (size_t)-1 The array indirectly pointed to by s contains a byte se- quence forming invalid character. In this case, mbsrtowcs() and mbsnrtowcs() set errno to indicate the error. mbsrtowcs() and mbsnrtowcs() may cause an error in the following cases: [EILSEQ] The pointer pointed to by s points to an invalid or incom- plete multibyte character. [EINVAL] ps points to an invalid or uninitialized mbstate_t object. mbrtowc(3), mbstowcs(3), optu8to16(3), optu8to16vis(3), setlocale(3) The mbsrtowcs() function conforms to ISO/IEC 9899/AMD1:1995 ("ISO C90, Amendment 1"). The restrict qualifier is added at ISO/IEC 9899/1999 "(ISO C99)". The mbsnrtowcs() function is a GNU extension. The mbsnrtowcsvis() function assumes codepage 1252 and maps holes into distinguishable codepoints. This extended function declares a macro with the same name that can be used to check for its presence. mbsnrtowcs() first appeared in MirOS #10. mbsnrtowcsvis() first appeared in MirOS #11. MirOS BSD #10-current October.
http://mirbsd.mirsolutions.de/htman/sparc/man3/mbsrtowcs.htm
crawl-003
refinedweb
672
52.6
The short answer is "Yes." Of course, the running time depends on exactly how big the dataset is. NCL's character matrix parsing speed is about as fast as PAUP*'s parsing (and we NCL writers are very proud of that), and its tree reading is slower that PAUP's but not terribly slow. v2.1 and later are much more efficient than previous versions. On a 2.6GHz i386 MacBook (with 4GB of RAM), Mark Holder obtained the following benchmark results for parsing a file (with comparisons to previous versions of NCL and PAUP* for reference): Because NCL rocks! Seriously, we do try hard to make the error messages helpful and have them accurately describe where the error occurs. This is definitely a strength of the library, and we strive to maintain it. Please let us know if you find a file that generates cryptic/unhelpful error messages (Also see Why do the error messages that NCL generates because of invalid files have the wrong column number?) So despite our generally rockin' error messages, there are some warts. It is tough to get accurate column numbers for errors. We try to support reporting of column numbers of errors because extremely long lines are common in TREES and CHARACTERS blocks. Let us know if you find misleading column numbers (check tab characters, first; NCL counts characters since the last newline. A tabstops are assumed to be set to 4, but this is admittedly arbitrary. Short answer: convenient appending to strings (including overloads of the "put to" operator). It is usually considered unsafe to derive from a class (such as std::string) that lacks a virtual destructor. NxsString does not have any additional data members that std::string does not, so we have gotten away with it. It is too late to reverse the decision to bundle a new string class. It is probably best to avoid using it when you don't have to. At one point we were going to abandon the use of NxsString, so newer functions take and return std::string objects. But we really don't want to break old code, so we are not going to complete the migration away from NxsString just for the sake of consistency of the API. Sorry about that, we realize that it makes the library harder to use for newer users. No good reason - history and backwards compatibility It is only the convenience header ncl.h that does this. Either do not include this file (and simply include the headers of the parts of ncl that you do use), or define a preprocessor macro NCL_AVOID_USING_STD to keep the contents of the std namespace from being "dumped" into your code's namespace. No good reason - history and backwards compatibility We were trying to declare functions that should be const, but that would break old code. So if you compile NCL without any special preprocessor directives, then NCL_COULD_BE_CONST will be converted to an empty string. But if you compile with the NCL_CONST_FUNCS preprocessor flag defined(-DNCL_CONST_FUNCS for most compilers), then NCL_COULD_BE_CONST will be replaced with the word const. In short if you want const-correctness checking, make sure that NCL_CONST_FUNCS is defined when you build NCL (the --with-constfuncs argument to configure will do this ), and that NCL_CONST_FUNCS is defined when you build your application. If you are not obsessive compulsive, don't worry about out it. Yes, we know that some more functions should be decorated with NCL_COULD_BE_CONST to improve const checking (and yes, it bugs us). Yes. See Dealing with Datatype=Mixed discussion.
http://phylo.bio.ku.edu/ncldocs/v2.1/funcdocs/FAQ.html
CC-MAIN-2017-17
refinedweb
594
61.67
> setarch i686 mock -r fedora-devel-i386 foo.src.rpm > > The 'setarch i686' is the important part. It really seems to me that mock ought to be taught to do this. There's no good reason that "you need setarch foo if `uname -m` !~ bar" shouldn't be part of that very config file that -r selects. > (some packages may actually need 'setarch i386', I last ran into this > with emacs a long time ago on RHL7.something. Don't ask. I won't even tell. I believe any package so affected by now has a kludge to do %ifarch blah\nsetarch i386 make dump\n%elsemake dump\n%endif or whatever. Thanks, Roland
http://www.redhat.com/archives/fedora-devel-list/2007-October/msg00474.html
CC-MAIN-2015-22
refinedweb
114
84.17
Ember.js and Data GET Now for number 4 in the Ember Data and REST server saga. Don't miss the others: - Serving a Static Directory With Flask - Installing Ember.js and Setting Up an App - Setting Up The Database For Ember.js REST Installing Ember Data Because Ember Data is still under very active development, I recommend downloading the latest passing Canary build here. After downloading the ember-data.js file movit it into the static/js/libs directory so it can be with it's friends Handlebars, jQuery, and of course Ember.js itself. Next, edit index.html and add the following after the script tag for Ember.js, but before the app.js tag: <script src="js/libs/ember-data.js"></script> Refresh your browser, or start the server and go to, and make sure there are not problems with loading the new Ember Data file. If you don't see any errors in the browser's JavaScript Console, congradulations you have successfully installed Ember Data. Party! Setting Up Ember Data It's time to adjust the static/js/app.js file to use Ember Data instead of a static jQuery $.ajax(). First, setup a Model object for our DVDs. Add the following to app.js after the App.Router.map section: var attr = DS.attr; App.Dvd = DS.Model.extend({ title: attr('string'), created_by: attr('string'), created_at: attr('date'), rating: attr('number'), file_url: attr('string'), }); Change the IndexRoute to use the new App.Dvd model instead of straight jQuery ajax: App.IndexRoute = Ember.Route.extend({ model: function() { return this.store.find('dvd'); } }); If you refresh your browser now, will will get a 404 error because we have only setup our /dvds route to respond to the POST HTTP method and we just sent it a GET method. So let's modify our super cool server.py file. Update The Server First, add a GET method to the /dvds route: @app.route('/dvds', methods=['POST', 'GET']) Next, add an elif to check for the GET and call a new function find_all(): elif (request.method == 'GET'): return json.dumps({"dvds": find_all(Dvd)}) Below the dvds() function add the the find_all() and jsonable() functions: def jsonable(sql_obj, query_res): """ Return a list of dictionaries from query results since SQLAlchemy query results can't be serialized into JSON evidently. """ cols = sql_obj.__table__.columns col_keys = [col.key for col in cols] obj_list = [] for obj in query_res: obj_dict = {} for key, value in obj.__dict__.iteritems(): if (key in col_keys): if (type(value) == datetime.datetime): value = value.strftime("%Y-%m-%d %H:%M:%S") obj_dict[key] = value obj_list.append(obj_dict) return obj_list def find_all(sql_obj): """ Return a list of all records in the table. """ q = session.query(sql_obj) return jsonable(sql_obj, q) The find_all() function performs an SQL query through the SQLAlchemy ORM we setup earlier, and jsonable() creates a nice Python list of dictionaries from the results. One sort of drawback with SQLAlchemy is that there isn't a built in method to create a JSON object from query results. Maybe that will be added in the future, but in the meantime the jsonable() helper should work just fine. Back in the browser at do a refresh and you should see an unordered list of strange output similar to: <App.Dvd:ember411:1> The reason for this strange output is because the the Handlebars template needs to be updated for our new Ember Data objects. Edit the index.html file changing {{each}} loop to: {{#each}} <li> {{id}} <br/> {{title}} <br/> {{created_at}} <br/> <br/> </li> {{/each}} Alrighty, we now have a cool REST GET method returning data from a SQL table. Woooo! Leave a Comment Markdown supported. Click @usernames to add to comment.
https://codepen.io/asommer70/post/ember-js-and-data-get
CC-MAIN-2018-43
refinedweb
619
66.94
Python Cansi Combo This is a pretty long blog-entry about combining python and good old fashioned C. The reason I keep it here is... well I was curious and wanted to learn this - what better way is there than to make a tutorial of it. Combining the programming language C and the programming language Python is fun, and almost as easy as making a Csharp Cansi Combo (with a lot more workarounds). This tutorial is pretty much based on the info found in the "official" page for the module ctypes (see "Read more"). Contents: - Python and C Part I: Import your silly dll - Python and C Part II: accept a C-string in python - Python and C Part III: Passing pointers, references and/or arrays to C - Python and C Part IV: Call-backs in Python - Python and C Part V: Call-backs in C - Python and C Part VI: Python and C Call-back combination - Read more 1 Python and C Part I: Import your silly dll Silly C-dll First make a miniature dll by with the following C-code __declspec(dllexport) void __stdcall hello() { printf("C >> hell o world!\n"); } And compile into a dll with for example this: cl c_test.c /LD /Zi Import to Python Now we use the namespace ctypes (included in Python 2.5+ only I think) to use windll and LoadLibrary. from ctypes import * mydll = windll.LoadLibrary("C:/temp/c_test.dll") returnvalue = mydll.hello() print "PY >> C returned", returnvalue Since there is no need to compile it we just execute this and enjoy the output. Output C >> hell o world! PY >> C returned 20 Think returncode is random right now - it is an integer per default. Do not do anything meaningful with it yet (see restype below for setting the return type of a function). 2 Python and C Part II: accept a C-string in python C returns a "string" This time our C-dll returns a string (for those of you who are familiar with C - that means a pointer to an array of chars that ends with a '\0'). #include <time.h> __declspec(dllexport) char * __stdcall get_time() { time_t ltime; time(<ime); return ctime(<ime); } We compile just like the last time: cl muddy_snake.c /LD /Zi (A small question I hope you readers might be able to answer: do we get a memory leak here? It seems someone provides us with a char* - don't we need to free it?) Python must accept a c_char_p Luckily for us there are all sorts of types already prepared for us in the ctypes library. If we do the conversion in a one-liner it is as the example below: from ctypes import * mydll = windll.LoadLibrary("muddy_snake.dll") present_time = (c_char_p(mydll.get_time())).value print "present time is", present_time # prints something like: present time is Thu Apr 04 21:20:58 2007 A little slower: >>> s = c_char_p(mydll.get_time()) >>> s c_char_p('Thu Apr 04 21:29:27 2007\n') >>> s.value 'Thu Apr 04 21:29:27 2007\n' Here s is of the type c_char_p and to get its value (the pythonic string that is) we use s.value, that returns a nice python string. There are I guess lots of other fun stuff to do with the c_str_p: >>> dir(s) ['__class__', '__ctypes_from_outparam__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_b_base_', '_b_needsfree_', '_objects', '_type_', 'from_param', 'value'] Also see restype below - I am not sure the above example should work as well as it does. 3 Python and C III: Passing pointers, references and/or arrays to C The C-code This time the C-code is a little more complex, but just a little: #include <stdio.h> /* * MY_SUM * * Summary * Computes the sum of all elements in a double array. * * Parameters * d_arr : pointer to array of doubles * arr_len : length of d_arr * sum : reference to the sum * * Returns * 0 if all is well * */ __declspec(dllexport) int __stdcall my_sum(double * d_arr, int arr_len, double * sum) { int c = 0; *sum = 0.0; for (c = 0; c < arr_len; c++) { *sum += d_arr[c]; } printf("C >> I will return %f\n", *sum); return 0; } Just in case you hate pointers or are unable to read C I'll explain what happens: - the parameter d_arr is an array of doubles, similar to [3.34, 3.45, 5.22] in Python, except that C has no idea of telling whether or not the values make any sense at all (in fact the could be integers - and if they were the vales in d_arr would be completely wrong). Also C has no idea of the length of the array. - arr_len is the length of the array (or at least we let C think so). - The last item is a pointer to a double - but in this case not an array. Think of it as a "call by reference" instead of a "call by value" (If you don't know what that means then it's like sending a list as the argument in Python: if you do the function can change the list (call by reference). If you pass f.x. a number in Python you are in fact sending a copy of the value (call by value)). - We loop over all elements in the array (we hope) and add the values to sum. - As a debug-print we print the our count before the end of the function. - We return 0 - this is the really old-school way of not throwing an exception (if we had returned 6331 that might have meant: illegal input or something like that (Exceptions aren't part of C.)). The Python code What we need to do in Python to call the c-dll is pretty much the following: - Create an array suitable for C. - Get the adress of a double and sent it to C. - Send a C-integer to C from Python. Create an array of double's for C in Python When I read the tutorial in ctypes I got the impression that this is the easiest way to create what in C is "double * arr". # my_length is a regular python integer here my_arr_class = c_double * my_length arr = my_arr_class() for i in range(len(arr)): arr[i] = c_double(i + 3.13) This pretty much does three things: - We define a new class on the fly (imagine doing that in C). The class is called my_arr_class and is made up of my_length instances of the class c_double. - We call the constructor of this class and create an instance of it in arr. - We fill the array with silly values. Create a C-integer This is pretty easy - call the constructor with an appropriate value. my_length = c_int(my_length) Create a C-double and call by reference. Like for the c_int we call the constructor of the c_double. In the call to our dll we here use addressof(sum). # ret is a c_int sum = c_double() ret = c_double(mydll.my_sum(arr, my_length, addressof(sum))) The whole Python # IO_TEST.PY # # Author # Per Erik Strandberg, 20070406 # see more in [1] # import sys from ctypes import * def io_test(my_length, verbose = 0): """ Purpose Illustrates communication with a c-dll. Send and recieve data. Parameters my_length : length of the array to send to c verbose : for more printing Returns float """ # # Load dll mydll = windll.LoadLibrary("simple_io.dll") # # make array class of fix length if verbose: print "P.io_test >> I will create an array of length %d" % (my_length) #endif my_length = c_int(my_length) my_arr_class = c_double * my_length.value arr = my_arr_class() # # fill array for i in range(len(arr)): arr[i] = c_double(i + 3.13) #endfor if verbose: checksum = 0.0 for f in arr: checksum += f print "P.io_test >> checksum %f" %(checksum) #endif # # create an instance of a c_double and call dll sum = c_double() ret = c_int() ret = c_double(mydll.my_sum(arr, my_length, addressof(sum))) if verbose: print "P.io_test >> return value was %d" % (ret.value) print "P.io_test >> got %f" % (sum.value) #endif return sum #end io_test Use the Python code Enter Python mode and imort io_test from io_test: >C:\temp\module >python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from io_test import io_test >>> help(io_test) Help on function io_test in module io_test: io_test(my_length, verbose=0) Purpose Illustrates communication with a c-dll. Send and recieve data. Parameters my_length : length of the array to send to c verbose : for more printing Returns float Test on a simple case: >>> io_test(3,0) C >> I will return 12.390000 c_double(12.390000000000001) Use the verbose feature: >>> io_test(33,1) P.io_test >> I will create an array of length 33 P.io_test >> checksum 631.290000 C >> I will return 631.290000 P.io_test >> return value was 0 P.io_test >> got 631.290000 c_double(631.28999999999996) 4 Python and C Part IV: Call-backs in Python What is a callback? Since a call-back is pretty abstract I will start with explaining what a callback and giving an example in Python. This code-snippet defines two silly functions: mini and one_and_one and then a third function caller. The function caller prints a little hello and then calls the function that was passed to it as a parameter. def mini(): print "This is mini me!" def one_and_one(): print "%d + %d = %d" % (1, 1, 1+1) def caller(func): print "This is me!" func() print print "now calling caller with mini:" caller(mini) print print "now calling caller with one_and_one:" caller(one_and_one) As you can see we all caller first with the name of the function and then with the name of the second function. Can you guess the output? Well, one you get the hang of callbacks it's not at all hard. - First we let the user know we will call caller with mini. - Then caller is executed. - Then caller calls mini. - When mini is done we return to caller - but there is nothing more to do here and we return to the main script. - We let the user know we will call caller with one_and_one. - The silly print in caller is printed. - caller calls one_and_one. - one_and_one exits, caller exits, and we are back in the main function that exits. The output is thus: now calling caller with mini: This is me! This is mini me! now calling caller with one_and_one: This is me! 1 + 1 = 2 "Call backs are stupid - why should I use them?" Call backs can be a little abstract at first. Call backs are excellent for using algorithms that does something in a more generic way. Somewhat similar to how recursion works - you do a general program that can work in many situations instead of writing too much code. One example of when call backs are good is for mathematical optimization. Imagine a very complex optimization-engine. It has to be able to find the minima (or maxima) of any function you send to it. And to be able to send it you need a callback. In the next subsection I'll give an example from mathematics that uses a "mathematical" function to find the root of any function (given that the function is "nice"). Root-finding with the bisection method in Python I wrote a function that implements the bisection method. Details on what the bisection is and how it works can be found in English Wikipedia here: [2]. I call the method find_root and here is the code of it: def find_root(func, x_left, x_right, epsilon, maxit): """Returns the root of the function func(x). Find_root is a function that takes another function func and searches for an x such that func(x) and func(x+epsilon) have different sings, but performs at most maxit iternations. If a root is to be found it must be within the interval x_left to x_right. Initially func(x_left) and func(x_right) must have different signs. Find_root is an implementation of the bisection method. Details are found here: [3] Returns float.""" # to avoid bad inputs x_left = float(x_left) x_right = float(x_right) maxit = float(maxit) epsilon = fabs(float(epsilon)) f_left = func(x_left) f_right = func(x_right) # extra variables x_middle = 0.0 global ctr ctr = 0 # must have different signs if f_left * f_right > 0: raise Exception("BAD: f(left) and f(right) have the same sign.") # while the interval is large # and we have not done a "large" number of iterations while fabs(x_left - x_right) > epsilon and maxit > ctr: ctr += 1 # fix midpoint x_middle = (x_left + x_right) / 2.0 # Find func(x_middle) if ((func(x_left) * func(x_middle)) > 0): # Throw away left half # (since func(x_left) and func(x_middle) have the same sign) x_left = x_middle else: # throw away right half x_right = x_middle # endif #end while return x_left #end def I hope the code explains itself. The main part here is that a function func is passed in just like above and this function can be evaluated with a float x and returns a float. To test my interval halvation method (an alias of bisection method) I will need to test it on a function. Why not implement the old and very unholy sinc: # Sinc is a function we later will pass as an argument to another function # in other wirds: sinc will later be a callback. def sinc(x): """Sinc is a classic function in transform-theory. sinc(x) = 0 (if x == 0) sinc(x) = sin(x)/x (if x != 0) Returns a float.""" x = float(x) if x == 0.0: return 0.0 else: return sin(x)/x # endif # end sinc I test the program with the following code: x_left = 3.2 x_right = 8 epsilon = 1e-6 maxit = 100 ctr = 0 print "starting interval is", print "[%f,%f]" % (x_left, x_right) x_root = find_root(sinc, x_left, x_right, epsilon, maxit) print "after %d iterations %f was found" % (ctr, x_root) print "Sinc(%f) = %g" % (x_root, sinc(x_root)) and the root found is 2*pi: starting interval is [3.200000,8.000000] after 23 iterations 6.283185 was found Sinc(6.283185) = -7.84199e-008 (I used a dirty trick do get the number of iterations - of course this could be improved but would then not be consistent with the following C-example.) 5 Python and C Part V: Call-backs in C An identical example but in pure C is as follows: #include <stdio.h> #include <math.h> /* * sinc */ double sinc(double x) { if (x == 0.0) return 1.0; else return sin(x)/x; } /* * my_func = sinc + exp + x + 10 */ double my_func(double x) { return sinc(x) - exp(x) + x + 10; } /* * Returns the x where func(x) approx 0.0 using the bisection method * From [4] . * Stops when abs(x_left - x_right) <= epsilon or after maxit iterations. */ float find_root(double (F)(double), double x_left, double x_right, double epsilon, int maxit) { /* * Extra variables */ double x_middle = 0.0; int ctr = 0; double f_left, f_right; epsilon = fabs(epsilon); f_left = F(x_left); f_right = F(x_right); if (f_left * f_right > 0) /* * here it would be nice to throw an exception */ return f_left; while ((fabs(x_left - x_right) > epsilon) && (maxit > ctr)) { ctr += 1; /* * fix midpoint */ x_middle = (x_left + x_right) / 2.0; /* * Find f(xM) */ if ((F(x_left) * F(x_middle)) > 0) /* * Throw away left half */ x_left = x_middle; else /* * throw away right half */ x_right = x_middle; } /* * some diagnostics */ printf("C.find_root >> func(%f) = %g, after %d iterations\n", x_left, F(x_left), ctr); return x_left; } /* * Main function test the root-finder */ void main(int argc, char * argv[]) { double x_root; x_root = find_root(sinc, 3.2, 8, 1e-6, 100); printf("sinc root: %f\n", x_root); x_root = find_root(my_func, 0, 7.7, 1e-12, 100); printf("my_func root: %f\n", x_root); } The output is >c_callback_test.exe C.find_root >> func(6.283185) = -7.84199e-008, after 23 iterations sinc root: 6.283185 C.find_root >> func(2.546852) = 6.51923e-012, after 43 iterations my_func root: 2.546852 6 Python and C Part VI: Python and C Call-back combination Step I: Make a dll of the C-code From the c-file above we create a dll with only the find_root-function like this: __declspec(dllexport) double __stdcall find_root(double (my_func)(double), double x_left, double x_right, double epsilon, int maxit) { /* ... */ } Step II: prepare the call-back function in Python From the class-factory CFUNCTYPE we define a custom class cb_fun (for callback function): cb_fun = CFUNCTYPE(c_double, c_double) That line might seem different to the kind of call-back C is to recieve that looks like this: double (my_func)(double) The reason is simple: the first parameter passed to CFUNTYPE is the return-value from the function to be defined. We can now, in Python, prepare a callback function that C can receive: c_sinc = cb_fun(sinc) Step III: Do it The rest is as before: root_find_lib = windll.LoadLibrary("root_find_lib.dll") find = root_find_lib.find_root find.restype = c_double print find(c_sinc, c_double(3.2), c_double(8.0), c_double(1e-6), c_int(100)) # avoid garbage collection f_temp = c_sinc Here the last line is to prevent Python from garbage-collecting the call back-function. The output looks something like this: C.find_root >> func(6.283185) = -7.84199e-008, after 23 iterations 6.28318481445 7 Read more - [5]: The ctypes infopage ([6] is another ctypes page) - [7]: Extending and Embedding the Python Interpreter, by the man himself: Guido van Rossum ctypes: Great Article From: Yuce Tekol, 2007-05-28, 17:45:29 Thanks for your article called 'Python Cansi Combo', although I've used ctypes before, the article was very useful for me to realize that there is a ctypes function called `addressof`, which killed some of my pains ;) I couldn't find how to linkback in your blog (my Swedish is not that good), so here's my blog post about your article if you're interested: [8] Thanks again :) /yuce [at] gmail [dot] com, [9] This page belongs in Kategori Programmering.
http://pererikstrandberg.se/blog/index.cgi?page=PythonCansiCombo
CC-MAIN-2017-39
refinedweb
2,965
71.34
Before you begin This 25-minute tutorial shows you how to create a Groovy template with interactive Design Time Prompts (DTPs). Background Similar to working with Calculation Scripts, you can create Groovy-based script templates for reusability and maintenance purposes. Templates also enable you to add Design Time Prompts (DTPs) to create interactive wizards for your users. a Groovy template to calculate employee bonuses In this section, you'll create a Groovy template that calculates employee bonuses when an employee's salary has been updated. The template will prompt for a bonus multiplier to use during the calculation. You'll work with the predefined ManageEmployees form, which has been set up to capture employee information such as their Grade, Salary, Bonus, Phone, Email, and Reporting Manager. - Open Calculation Manager and create a template named GT_Calculate Employee Bonuses in the Plan2 cube. - In the Template Editor, change the Designer option to Edit Script and set the Script Type to Groovy Script. - Select the Design Time Prompt tab. - Click (Insert Row) to add a DTP. Select Insert Row at End. - Define the prompt with the following values: - On the toolbar, click (Create/Edit Wizard) to open the Template Wizard Designer. - Click (Add Step). For the Name, enter Enter a Bonus Multiplier, then click OK. - Add the BonusMultiplier DTP to the Selected DTPs list, then click OK. - Select the Template Designer tab again. Copy this script and paste it into the editor. /*RTPS: {BonusMultiplier} */ def BonusMultiplier = rtps.BonusMultiplier; def mbUs = messageBundle(["validation.invalidbonusmultiplier": "Bonus multiplier must be between 0 and 8: {0}"]) def mbl = messageBundleLoader(["en" : mbUs]); //Validate the RTP values validateRtp(rtps.BonusMultiplier, {(0..8).contains(it.enteredValue as int) }, mbl, "validation.invalidbonusmultiplier", rtps.BonusMultiplier); // Capture the edited employees Set employees = [] operation.grid.dataCellIterator("Salary").each { DataCell cell -> if(cell.edited) { employees << cell.getMemberName("Employee") } } if(employees.size() == 0) { println("No employee's bonus has been updated") return } // Generate the calc script to calculate bonuses for the employees whose salaries were edited List povMemberNames = operation.grid.pov*.essbaseMbrName String calcScript = """ Fix("${povMemberNames.join('", "')}", "${employees.join('", "')}") "Bonus" = "Salary" * (${BonusMultiplier}/100); EndFix;""" println("The following calc script was executed by $operation.user.fullName: \n $calcScript") return calcScript.toString() Define the run time prompts and variables used by this rule. Check if the value entered for BonusMultiplier is between 0 and 8. If not, veto the operation. Use a dataCellIteratorto iterator over the grid and capture the edited employees in the form. If no employees have been edited, return a message and exit the script. Generate the calculation script to calculate bonuses for edited salaries. - On the toolbar, click (Save) to save the script. - Click (Validate and Deploy). - Click OK when prompted, then close Calculation Manager. For more complicated user input situations, you can create multiple wizard steps and choose which DTPs to present on each step. Adding templates to forms In this section, you add your Groovy template to the ManageEmployees form so that it runs automatically when the form is saved. - From the Planning Home page, navigate to Forms (located under Create and Manage) and edit the ManageEmployees form. - On the Business Rules tab, associate the GT - Calculate Employee Bonuses template to be run After Save. Save the form and close the Form Manager window. Testing the Groovy template In this step, you test your template in the ManageEmployees form. - From the Planning Home page, click Data to display data entry forms. Click ManageEmployees to open the form. - For Employee 1, enter a salary of 40000, then click Save. The prompt to enter a bonus percent multiplier is displayed. - To check the data validation, enter 9 and click Launch. The validation error message is displayed. - Click OK to close the error message. Enter 5, then click Launch. - The Salary information is saved, and the employee bonus is calculated as 5% of the entered salary. - To see the calculation script that was generated, close the data entry form and navigate to Jobs. Notice that there are two entries in the Recent Activity list for the calculation: the completed calculation, and the error condition from entering an invalid multiplier. - Click the first entry in the list, then click the Completed link to view the executed calculation script. Notice that the calculation is limited to Employee 1, the edited employee, and the entered bonus multiplier, 5, appears in the Bonus calculation. - Close the Job Details, and click on the second entry in the list. Click the Error link to view the error message. Notice that the validation error message is printed here, along with the invalid entry (9).
https://www.oracle.com/webfolder/technetwork/tutorials/obe/cloud/epm/Groovy/Templates/index.html
CC-MAIN-2021-39
refinedweb
762
50.63
Created on 2013-10-18 07:45 by kousu, last changed 2014-03-08 17:54 by python-dev. This issue is now closed. This code doesn't work. I think it should. import dbm with dbm.open("what is box.db", "c") as db: db["Bpoind"] = Boing Indeed, there is nothing supporting PEP 343 for dbm on my system: [kousu@galleon ~]$ grep -r __exit__ /usr/lib/python3.3/dbm [kousu@galleon ~]$ Working on a patch for this. Here's a patch. I agree with the revised title. Test_context_manager() should also test that db is actually closed after the with statement. I presume you can use self.assertRaises and try to do something with db that will fail if it is properly closed. with self.assertRaises(<NotOpenError>): db['a'] = 'a' # or whatever I haven't looked at the C code. Attached patch checks that the db is actually closed after the `with`. Also, I noticed that dbm.dumb doesn't behave like the rest of the variants, as seen in the following: >>> import dbm.dumb as d >>> db = d.open('test.dat', 'c') >>> db.close() >>> db.keys() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tank/libs/cpython/Lib/dbm/dumb.py", line 212, in keys return list(self._index.keys()) AttributeError: 'NoneType' object has no attribute 'keys' >>> vs >>> import dbm.gnu as g >>> db = g.open('test.dat', 'c') >>> db.close() >>> db.keys() Traceback (most recent call last): File "<stdin>", line 1, in <module> _gdbm.error: GDBM object has already been closed >>> This seems like a reasonable request. There is issue19385 for the inconsistency of dbm.dumb, with a patch. Patch looks reasonable to me - if nobody beats me to it, I'll commit this before beta 1 :) New changeset c2f1bb56760d by Nick Coghlan in branch 'default': Close #19282: Native context management in dbm Thanks) I also changed the signature of the enter/exit methods to just use PyObject * (rather than dbmobject *), since that allowed a bunch of casts to be removed and eliminated a couple of compiler warnings about type mismatches. Cool, thanks! New changeset 200207e50cbf by R David Murray in branch 'default': whatsnew: dbm.open is context manager. (#19282)
https://bugs.python.org/issue19282
CC-MAIN-2017-22
refinedweb
366
69.68
Provided by: libdpm-dev_1.13.0-1_amd64 NAME rfio_chmod, rfio_fchmod - change access mode of a directory/file SYNOPSIS #include <sys/types.h> #include "rfio_api.h" int rfio_chmod (const char *path, mode_t mode); int rfio_fchmod (int s, mode_t mode); DESCRIPTION rfio_chmod sets the access permission portion of the mode of a directory/file to the bit pattern in mode. rfio_fchmod is identical to rfio_chmod but works on the file descriptor s returned by rfio_open. path specifies the logical pathname relative to the current directory or the full pathname. mode is constructed by OR'ing the bits defined in <sys/stat.h> under Unix or "statbits.h" under Windows/NT: be super-user. is super-user. RETURN VALUE This routine returns 0 if the operation was successful or -1 if the operation failed. In the latter case, serrno is set appropriately. ERRORS EPERM The effective user ID does not match the owner of the file and is not super- user. ENOENT The named file/directory does not exist or is a null pathname. EBADF s is not a valid file descriptor. EACCES Search permission is denied on a component of the path prefix or write permission on the file itself is. SEE ALSO Castor_limits(4) AUTHOR LCG Grid Deployment Team
http://manpages.ubuntu.com/manpages/eoan/man3/rfio_fchmod.3.html
CC-MAIN-2020-40
refinedweb
208
59.4
Flavor the focus at annual food trade show. - From: ba_ba_b00ie@xxxxxxxxx (ba ba booie) - Date: Sun, 5 Feb 2006 02:04:03 -0500 Fancy that Health, flavor the focus at annual food trade show. By Jolene Thym, FOOD WRITER Some of the food trends included flavored sea salts, and products made with them, Urban Zen green tea flavored with fruit juice. Dunk it in antioxidants, sprinkle it with salt, splash it with green tea and pomegranate juice and there you have it ? the 2006 San Francisco Fancy Food Show on a plate. The annual trade show, a magnet for West Coast retailers who want to stock their shelves with the newest and best food products, is a massive showcase for more than 80,000 products spanning every food group, in every imaginable flavor. Despite the variety, there is no mistaking this year's food trends. The buzz word for 2006 is antioxidant ? lots of foods lay claim to the term, but the definitive antioxidant darlings are green tea, acai and pomegranate, all of which can be found in everything from appetizers to desserts, drinks to energy bars. On the flip side of the health spectrum is a growing interest in gourmet salt ? dozens of companies sell mounds of very expensive gourmet salt flavored with everything from truffles to tea. Many of the products on the exhibition floor will be on grocery and supermarket shelves within coming months, but in the interest of giving you a sneak peek at the flavors in your future, I methodically nibbled my way through the show in search of deliciousness. Here are details on some of the bites that gave me pause: After sampling several flavored salts that tasted like plain salt to me, I encountered Ritrovo Truffle Salt, ($18-$22, 3.5 ounces) an Italian import that delivers an intoxicating hit of black truffle. The company also makes anaromatic Saffron Salt and a Fennel Salt, both of which beg to be sprinkled on rice, pasta, fish or eggs. The salts are available at The Pasta Shop in Oakland, Whole Foods in Walnut Creek and Dean & Deluca. It's hard to compete with California's artisan cheesemakers, but Kerrygold's new blue cheese from Ireland is outstanding. The cheese, headed for specialty shops next month, is a rich cheddar laced with mild blue cheese flavor. The cheese will sell for $15-$18 per pound. Healthy treats: I am not entirely convinced that antioxidants will change my life, but I was happy to try some of the good-tasting anti-oxidant-laden foods on hand. The best, no contest, was the Sharffen Berger Chocolate-flavored gelato made by Ciao Bella. The gelato is served in shops all over the Bay Area, and sold by the pint in some stores. It's also available online for $33 plus shipping for four pints. Go to. Inspiring new products for the bartender or dessert chef in the family include the dizzying lineup of Sonoma Syrups, all-natural, small-batch syrups that deliver a big flavor punch. Keeping up with the trends, the company just added pomegranate, which seemed a little insipid in flavor next to other amazing flavors ? Meyer lemon, Eureka lemon, vanilla, chocolate, lavender, black currant, cinnamon. The syrups are about $10 at Williams-Sonoma. The intoxicating aroma of fresh mole demanded a stop at Native Kjalii Foods, a San Francisco company that makes at least 12 salsas and dips, eight hummus products, chips of all kinds and mole sauces that are sold in Costco stores. The chocolate mole was incredible, but the new green mole is the one I want to douse my next chicken with. It's fresh and rich at the same time. The jars of sauce will be in Costco stores and other markets within eight weeks. Prices will range from $3.49 to $5.99. ~~~~~~~~~~~ Don't forget the chocolate: Those who consider chocolate a main food group were not disappointed. Some of the delicious offerings included out-of-control-rich fudge and sauces by Fudge Fatale in Los Angeles. I loved the chocolate espresso, chocolate and caramel sauces way too much to even pay attention to the small jars. I priced the big, 74-ouncer, the one she really, really wants, trust me. It's $50, and the perfect Valentine's Day gift. Go to. If $50 is not in the budget, consider a pair of caramel-dipped, chocolate-covered apples from V Chocolates in Salt Lake City,. They sell for $5.95 each plus shipping. Shipping for two apples will run roughly $5. Call (801) 376-8028. If you would prefer to drink your indulgence, get your hands on a cup of Holy Chocolate, an intense chocolate produced by the Rev. Stan Smith of Triumphant Christ Church in Campbell. The ultra-rich European-style chocolate is packaged by Independent Way in Oakland, an organization that employs people with special needs. The cocoa mixes come in a lineup of flavors and sell for $1.75 for a single serving; or $8.75 for 5 packets. Shipping is free for orders over $35. Profits all go to support local charities. Call (408) 374-0531 or go to. A perfect pairing with that chocolate would be a bag of Dale & Thomas' dessert popcorn ? in caramel, chocolate chunk, dreamy chocolate and peanut butter drizzle flavors ($4.25 per 5-cup bag). Each cluster of popcorn is coated in irresistible candy ? this treat can be addictive. The popcorn is available at some specialty stores or go to. If your Valentine prefers slightly more traditional chocolates ? with a twist ? don't overlook the prize-winning Smokey Salt Caramels made by Fran's Chocolates, a Seattle-based company that specializes in inventive flavor combinations. The smoked salt and buttery caramel delivers a yin-yang across the palate, ultimately much more satisfying than a basic caramel. The caramels are $22 for a 15-piece box. Call (800) 422-FRAN or go to. Those who prefer to bake up their own treats will enjoy the canned pastes ? called Schmears ? by Love 'N Bake. Until now, the products were available only to commercial bakeries. My favorite is the pistachio, mainly because I do not have the energy to shell my own when I am in the mood to bake. But I also like the cinnamon, because the smell of it makes me happy. The pastes are about $4 per 12-ounce can and are available at Cost Plus and Sur La Table. ~~~~~~~~~~~~~~~ Variety, the spice of life: On the savory side, adventurous cooks may want to order up a bag full of dried black limes from Nirmala's Advertisement Kitchen in New York ($5 per 1.5 ounces.) The limes are used in Middle Eastern stews. Or maybe consider the absolute latest in the salt realm ? 4-ounce crystals that come with a special grater. You grate the salt on the food just as you would hard cheese. The product is due to be released later this year. The price of the crystal salts is not set yet, but Nirmala's Australian salt with bush tomato, Guerande Fleur de Sel with Piment D'Espelette and Japanese Sea Salt with Matcha green tea are about $20 per 4-5 ounces. Call (718) 361-7807 or go to. Some of the fun of covering a show this size is allowing it to unfold as an adventure, making a decision not only to taste, but to listen to the personal stories behind those who are making and selling the products. My adventure included a lovely conversation with Pam Kraemer from Lake Oswego, Ore., a former flight attendant who is expanding her line of Dulcet Cuisine sauces and dressings to include exotic dry spice mixes that can be used as rubs or seasonings for everything from prawns to soup. "I decided to do this last year and it has been a lot of fun," she says. "I started out with the sauces and people liked them a lot. But the competition is so tough that I've expanded." Her spice mixes come in tasteful brown paper cylinders that have recipes hand-tied across the top. "I do all of the tying myself. I must be crazy," she says. She hopes her mixes will be picked up by Whole Foods in Walnut Creek. They can also be ordered online at. My favorites were the Asian Dressing and the Madras Curry spice blend ($6.50 to $7.75). ~~~~~~~~~~~~~~~~ Crisps to coffee: My mouth full of I-don't-recall-what, I was stopped by a young man who begged me to nibble the cheese crisps developed by The Kitchen Table Bakers ? he and his father, Barry Novick. "Try it," Novick encouraged. I tried one. The toasty Parmesan cheese flavor convinced me to try another, this one laced with poppy seeds. Other crisps were flavored with The Fancy Food Show at the Moscone Center in San Francisco is a magnet for West Coast retailers, showcasing 80,000 products. Some of the food trends included flavored sea salts, and products made with them. (D. Ross Cameron - Staff) garlic or jalapeo. "Until two years ago, I was a hospital administrator who hated going to work," Novick says. "It was such a negative business that I decided to do something new." He now oversees a growing New York business that caters to people who love cheese and big flavor. The Parmesan crisps are $6 for a 3-ounce package. The father and son duo are still looking for distribution here on the West Coast. Until then, call (800) 486-4582 or go to. Seeking a libation of any kind, I stumbled across Novato's Republic of Tea, which was pouring cups of Man Kind Tea, Blueberry Green Tea ($10, 50 bags), and the Jerry Garcia Cherry Tea, one in the line of just-released, limited-edition J. Garcia artisan teas in tins decorated with Garcia's art. A few aisles away, I grabbed a cup of Sweet and Sour Orange Sencha Tea by Two Leaves and a Bud ? $8.99, 15 bags;. The search for a mid-afternoon coffee fix led me to stop for a cup of Caffe Sanora Organic, a Texas-based roaster that claims to roast the coffee in such a way as to preserve the natural antioxidants in coffee. It's a patented process that's highly secret ? and since you can't actually taste antioxidants, it's a bit of a faith issue. Drink to your health! Caffe Sanora Organic is $11 to $13 per pound. It is available at some stores and health food stores and via. Funny finds include Jelly Belly's new Sport Beans, coming in two flavors, Lemon Lime and Orange. They have added electrolytes for those who jump around a lot. The beans are $6 for six 1-ounce bags and are widely available. Another product that made me smile was Hint and Hint Kids, bottles of unsweetened water with a hint of berry, orange, mint, or cucumber. Some children might welcome the water in their lunchbox, but the kids I know would opt for juice, hands-down. Hint is widely available at natural food stores. The water is about $2 for 15 ounces. And the winner is ... The Fancy Food Show organizers do give out awards, but if I was in charge, the categories would be different. For example, the award for Coolest Product would go to rick's picks, a New York company that sells pint-sized jars of unusual pickled vegetables of every ilk for about $8. Rick Fields' Windy City Wasa Beans and Spears of Influence are all about flavor and crunch. You can get them at Dean & Deluca in St. Helena. Strangest Product Award would go to Himalania Goji Berries, pinkish-colored oblong berries that look more like incense than something you eat. They aren't bad tasting ? slightly sweet and fruity ? and they are guaranteed to spark conversation. But exactly what else you would do with them besides eat them out of hand, I'm not sure. Goji Berries are $12.99 per 8 ounces. Go to. The Most Heartwarming Award would go to ToteBagsDirect, a Glendale company that imports handmade jute bags. The bags are fair trade, and are made in India by women who would otherwise have to make their living as prostitutes. The bags come in all shapes, sizes and colors, and can be imprinted with a logo. For more information, talk to Raj Madhavan at (818) 543-3238. You can e-mail Jolene Thym, food writer at jthym@xxxxxxxxxxxxxxxxx bbb writes: I would love to go to a trade show like this! This sounded like a lot of fun. Anyone here go? booie........ .. .. Have you checked these sites out today? .. Find out where your favorite band is playing. Pollstar (The concert hotwire) . - Prev by Date: Re: Republicans SUCK (was Re: Reid's Lying, Arrogant Ass is FRIED!!) - Next by Date: Re: Jerry Garcia's limited edition line of tea. - Previous by thread: Tonight's Weather Report (B&P) - Next by thread: Chris Whitley - Index(es):
http://newsgroups.derkeiler.com/Archive/Rec/rec.music.gdead/2006-02/msg01256.html
crawl-002
refinedweb
2,184
73.98
Show Preview - thecontinium Hi. I have looked high and low with no luck but this feels like it should be simple. I am trying to programmatically emulate swiping left in the editor to show the preview of a markdown file. Is there a way to open a file in preview using a url or is there a workflow / python interface to show the file in preview ? Cheers There is no built-in “Show Preview” action, and there isn’t really a Python interface for this either. The good news is that Editorial can call native Objective-C code, using the objc_utilmodule, so this hack should work (via a “Run Python Script” action): from objc_util import UIApplication, on_main_thread @on_main_thread def main(): app=UIApplication.sharedApplication() vc=app.keyWindow().rootViewController() vc.showAccessoryWithAnimationDuration_(0.3) avc = vc.accessoryViewController() avc.showPreview() main() Caveat: This might break at some point, when I change the internals. It should be possible to adapt it though. Super cool. Can I ask how you’d display the file list (left slider) of the current open document? Thanks in advance. ...dave
https://forum.omz-software.com/topic/4472/show-preview
CC-MAIN-2020-40
refinedweb
180
56.15
How to version Jupyter notebooks¶ Introduction¶ This guide will show you how to: Install neptune-notebook extension for Jupyter Notebook or JupyterLab Connect Neptune to your Jupyter environment Log your first notebook checkpoint to Neptune and see it in the UI By the end of it, you will see your first notebook checkpoint in Neptune! Before you start¶ Make sure you meet the following prerequisites before starting: Have Python 3.x installed Have Jupyter Notebook or JupyterLab installed Have node.js installed if you are using JupyterLab Note If you are using conda you can install node with: conda install -c conda-forge nodejs Step 1 - Install neptune-notebooks¶ Jupyter Notebook To install neptune-notebooks on Jupyter Notebook: Install neptune-notebooks extension: pip install neptune-notebooks Enable the extension for Jupyter Notebook: jupyter nbextension enable --py neptune-notebooks JupyterLab To install neptune-notebooks on JupyterLab go to your terminal and run: jupyter labextension install neptune-notebooks Note Remember that you need to have node.js installed to use JupyterLab extensions. Step 2 - Create some Notebook¶ Create a notebook with some analysis in it. For example, you can use this code to create an interactive Altair chart of the cars dataset: Add installation command in the first cell pip install altair vega_datasets Create Altair chart in the second cell import altair as alt from vega_datasets import data source = data.cars() brush = alt.selection(type='interval') points = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color=alt.condition(brush, 'Origin:N', alt.value('lightgray')) ).add_selection( brush ) bars = alt.Chart(source).mark_bar().encode( y='Origin:N', color='Origin:N', x='count(Origin):Q' ).transform_filter( brush ) chart = points & bars chart Run both cells and see the interactive Altair visualization. Step 3 - Configure Neptune API token¶ Now, you need to connect your notebook to Neptune. Copy your Neptune API token. Click on the Neptune icon and paste your API token there. Step 4 - Save Notebook Checkpoint to Neptune¶ Click on the Upload button. You will be prompted to: Choose which project you want to send this notebook to Add a description of the notebook Step 5 - See your notebook checkpoint in Neptune¶ Click on the green link that was created at the bottom of your notebook or go directly to the Notebooks section of your Neptune project. Your notebook checkpoint was tracked and you can explore it now or later. Conclusion¶ You’ve learned how to: Install neptune-notebook extension for Jupyter Notebook or JupyterLab Connect Neptune to your Jupyter environment Log your first notebook checkpoint to Neptune and see it in the UI What’s next¶ Now that you know how to save notebook checkpoints to Neptune you can learn:
https://docs-legacy.neptune.ai/getting-started/quick-starts/how-to-version-notebooks.html
CC-MAIN-2021-17
refinedweb
449
51.89
Plone 3.0 (Aug 21, 2007) This release is no longer supported! If you are using this release, please upgrade to a newer version if possible. Aims to make Plone more efficient to work with. This release adds versioning, locking, inline editing and validation, link integrity, intranet/extranet workflows, wiki support, OpenID support, and full-text indexing of Word/PDF. (If you're not using the installers, please note that this release requires Zope 2.10.4 and Python 2.4.4 — earlier versions will not work) For additional information about this project, please visit the project page . Available downloads For Windows (23376kB) For Mac OS X (36132kB) For Mac OS X (36336kB) For Linux (24.3MB) For SUSE Linux (40018975) For all platforms (11.7MB) Release Notes For a list of the features in this release, have a look at the Features in Plone 3.0 document. Feature enhancements in this release The following features are associated with this release: - Versioning - Plone needs to have a consistent, core solution for simple versioning tasks. This is expected of modern CMS packages. This PLIP outlines the needs and a proposed solution for versioning. Another PLIP will cover staging and multisite usage. - Ship Plone with additional workflows and a workflow control panel - Plone currently ships with one workflow, we propose to ship it with four pre-defined workflows and a control panel that cover most of the use cases people normally have: Community, Intranet, Web Publishing and Extranets. - Portlets engine based on PlonePortlets and Viewlets - Currently, the portlet mechanism in Plone is very crude. A proper structure to handle third-party portlets, individual caching policies and even asynchronous portlet updates is desirable. - Edit-in-place mode for all basic field types - A lot of the time you just want to change a single attribute on an existing item. We want to enable an "advanced users" feature to make this quicker and more efficient. - Ensuring link/reference integrity (removing 404 links) - One of Plone's weaknesses at the moment is the lack of resource tracking. If you delete a picture, and another document references this picture, you won't know before you look at the other document. - Move properties to Edit screen using pre-loaded fieldsets - Clean up the UI a bit by moving the Properties to a grouped schemata on the edit screen. - Return to Icon Flexibility - It is much more flexible to use the "getIcon" method to display icons via CSS in Plone than using the "portal_type". If the portal type is used, then there can only be a single icon for a content type, which makes it impossible to change the icon depending on what is contained in the content type. This is a proposal to get some of the flexibility back that was lost while going from Plone 2.0 to Plone 2.1. - Reader and Editor roles - It is too difficult to share a private or restricted document with another person or group. By introducing Reader and Editor roles, the Sharing tab can be used to let any given user or group the right to read or edit any object. - Componentise the global content menu - The global content menu, the green one with 'actions', 'add item' and 'state' drop-downs, is one beastly monolithic page template with a lot of logic. Worse, whilst it is possible to use actions to add new items to the 'actions' menu, if you want to add a new menu (e.g. for versioning or staging) you have to override the template wholesale. This proposal aims to change that by using views, adapters and utilities. - Generalized Next / Previous navigation - There is a need for a feature that allows a user to navigate easily between content items stored in a container such as a folder. - Locking - Prevent concurrent through-the-web editing in Plone. Trigger WebDAV locking on edit. Make it possible to borrow locks easily. - Improve sharing page - The sharing page has to be simplified significantly. - Move to CMF 2.1 - Require CMF 2.1. - Improved Markup Support - Creating a mechanism for adding support for additional markup languages such as Markdown and Textile for TextField fields and a site-wide policy for defining available and default formats. - Dashboard - We want to create a page where the user can add portlets/widgets showing summaries with content of the portal. The idea is to provide an overview/summery over the content. The criteria which content and wich portlettype can be set/chosen by the user. The personal google page is a very good example. - Portal type configlet in plone setup - Proposal for a configlet in Plone ui to control various settings related to portal types. - Content rules engine - With the introduction of Zope 3 events, it becomes possible to react to events such as "object added" or "object modified". Plone should enable site administrators to set up rules that are invoked when these events occur under certain conditions. For example, it could be possible to move all Events added to a particular folder to the /events folder automatically. - Remove migration code for old releases - Don't support migrating to Plone 3 from versions earlier then Plone 2.1.0-final. - Minimize page weight - Plone as it is per Plone 2.5 is unnecessarily heavy when it comes to downloaded CSS, JS etc. - integrate iterate for checkin/checkout/staging - builds on top of cmfeditions, to allow for explicit checkin/checkout and staging, without the overhead of site stages. - Include KSS in Plone - KSS is an AJAX framework with Zope and Plone support. We propose inclusion of the framework core as part of Plone, together with the implementation of some UI improvements with Ajax. - Wiki syntax support for all content - "wicked" provides usable wiki-like linking and content creation within AT based content. This proposal recommend the inclusion of this behavior as an option for Plone's content. - OpenID support - Add support for the OpenID decentralized identify system to Plone - More configurable and reusable i18n features - Move code for normalizing of ids out of CMFPlone and make it optionally configurable per language. Also consolidate all the three availablelanguage.py files currently found in AT, CMFPlone and PloneLanguageTool into an external package and hook these up using utilities instead. - Expose more settings in the Control Panel - There are a lot of common settings that you still have to reach for the ZMI to adjust. - New visual design for Plone - The existing Plone look is getting a bit long in the tooth — seeing as it essentially is the same as when it was conceived 5 years ago, it's time for an update. - Return to using getIcon for content type icons - Aka. as "the un-PLIP", this proposal advocates changing back to the earlier approach used for content type icons in Plone. - Add a RichText field to Smart Folders - Smart Folders would be much more flexible in real-world deployments if there was a RichText field before the results listing. Change log Plone 3.0 - released August 17, 2007 - Remove usage of login.js and Deprecate it. [ree, wichert] - Update migration code for final release. [wichert] - Remove keywords/category listing from document byline and instead render it as a viewlet right below that. [maurits] - Make workflow history visible again, as viewlet just below the body of the content. Fixes [maurits] - Let the "manage portlets" fallback link (for when no columns are shown) use the canonical object (i.e. object without default view), in the same way that the column would have done. Fixes [optilude] - Sort the configlets in the control panel by their translated title instead of their English title. [hannosch] - Fixed erroneous message when publishing multiple items and a subfolder with no items was present. Also synced status message with the content_status_modify script, so only one message is shown. This closes. [hannosch] - Fixed a few status messages to work with content item titles with non-ascii characters in them. [hannosch] - Plone 3.0 has an ID "content" that only includes the actual content, not everything in the content well. Adjusted the getContentArea() method in register_function.js to prefer this if it's present. This fixes [limi] - Fixed incorrect redirect when pressing the cancel button on the sharing tab. For Files it would cause you to download the file. This fixes Fixed in plone.app.workflow. [maurits] - Fix incorrect use of getActionById that caused an error when sending someone a link to an item in the site. This fixes [maurits] - The wiki syntax support now supports both the [[link]] and ((link)) syntax variations by default. Removed the preference for selecting between them, since it no longer does anything. [limi] - Adding a mini-login form to the login failure screen. This fixes [limi] - Since the CSS isn't recalculated if you switch to https mid-flight, we need to add https version of portal_url to the blacklist to avoid getting the lock icon on local links. This fixes: [limi] - Fixed permissions for iterate check-in/check-out so that non-manager users can use it. Fixes [optilude] - Corrected broken Javascript regular expression that caused almost arbitrary stuff in the query string to cause 'searchterm'-highlighting. Thanks to Claytron for patch. Fixes [elvix] - Reformatted the workflow descriptions in order to prevent insane amount of whitespace to show up in the translations. [hannosch] - Added i18n markup to the workflow descriptions in GenericSetup profiles. [hannosch] - Remapping the "(Default)" workflow to No Workflow didn't work. Fixes [optilude] - Remapping to "No Workflow" resulted in an error, fixed. Thanks to rsantos for the patch. Fixes [limi] - Author profile template was showing left/right portlets, removed these. [limi] - Removed httpresponse patch, which is obsolete with Zope 2.10.4 which we do require now. [hannosch] Plone 3.0-rc2 - released July 27, 2007 - Added a description to the no-workflow information in the types control panel. This fixes [wichert] - Added in markup for the IDs #contentTopLeft, #contentTopRight, #contentBottomLeft, #contentBottomRight to allow rounded corners on the content well using the same technique as the portlets. [limi] - Updated componentregisty.xml to new style. As the object handler only supports registering objects in the site itself now, we can remove all the slashes. [hannosch] - Updated the migration tool to use the "upgrade" terminology, to be consistent with the recent documentation. Also removed useless tab, all information is on one screen now. [limi] - Move login and logout-handling code into the membership tool and add sending of events when a user logs in or logs out. For Plone 3.5 we can move most of the code into event handlers. [wichert] - Harmonized the link classes for wiki links with the Plone standard, made pages that haven't been created yet red, made the entire link clickable, made the "+" superscript. [limi] - The protocol-specific links should only be applied inside the content area. [limi] - Fixed inline editing for dates in event_view [spliter] - Fullscreen view for images has a title of it's parent now [spliter] Plone 3.0-rc1 - released July 13, 2007 - CMF has renamed getToolByInterfaceName to getUtilityByInterfaceName. Update our scripts accordingly. [wichert] - validate_email is stored on the portal root, not in site_properties. Make all scripts and templates aware of that. [wichert] - No longer do portlet and action calculations on error pages. This will make them less resource intensive, and less likely to throw their own errors (which resulted in an XSS issue). Additionally, this means that there is now a means for any template to avoid portlet and action processing as needed. [alecm] - Remove hard-to-cache recent portlet from the default front page. It's on the default dashboard. [optilude] - Changed the behaviour of the "Allow comments" to be a checkbox instead of having three settings. It now respects the global setting unless you made a manual change on that particular document. This closes [hannosch, limi] - Moved the login.js script to only trigger on the login_form page, since that's where the login portlet posts to anyway. Carrying it around on every page doesn't make sense. [limi] - The mark_special_links javascript is no longer hooked up, since we use CSS to do the various protocol-specific markers now. It's not removed from existing sites that use it, but new sites will not have it enabled. The CSS approach works in all modern browsers, but not Internet Explorer 6. It works fine in IE7, however. If you are upgrading from an earlier Plone release, you might want to remove the script manually to reduce page weight. [limi] - Moved several javascripts to be rendered for logged-in users only to reduce the weight of the anonymous page load. [limi] - If we failed to send the user registration email but the user selected his own password to not remove the newly created user but just warn him that the email failed. [wichert] - Do not allow user registration if the site is configured to emai password but no mail configuration has been set. [wichert] - Escape userids and groupnames in all templates so we can handle ids with unfriendly characters. [wichert] - Cleanup handling of userids and loginnames: consistently use userids to key all user information. [wichert] - Disable the mobile style sheet by default, since very few people use it, and we're planning to re-work this in 3.5 anyway. If you need it, simply turn it back on in portal_css. [limi] - Deprecated presentation.css since the presentation code uses the dedicated S5 CSS files now. This closes [limi] - Images and Files no longer have a workflow in the new default setup, making them always visible. This closes [limi] - Workflow states now have a description. This closes [limi, hannosch] - Remove the community workflow and re-title the Plone workflow to "Community workflow". [wichert] - In the simple publication workflow, the author can now edit a published item. He cannot edit it while it is pending, though. [limi] - Blacklist the layoutid to prevent conflicts with the layout property on dynamic view capable content. This fixes [wichert] - Allow form tabbing using other elements than forms. This allows tabbing between multiple forms, which is needed by the content rules config panel. [wichert] - Factored most of the "add menu" functionality out of plone.app.contentmenu into plone.app.content.browser.folderfactories. This contains a view which powers the folder_factories view. The old template-based version is moved to plone_deprecated and is renamed old_folder_factories. Closes. [optilude] - Made the home link on the login success page link to the navigation root rather than always linking to the site root. Fixes. [optilude] - Made all portlet management functions use explicit referer URLs, rather than relying on HTTP_REFERER. Hopefully this fixes problems with IE7 not passing this value properly. Should fix and. [optilude] - Added an event handler to create a default dashboard when a new user is created. This can be overridden using an adapter from IBasicUser to IDefaultDashboard from plone.app.portlets. Closes most of. [optilude] - Added a message to the dashboard when it is empty, instructing users to add some portlets. Refers to. [optilude] - Made the cut and delete items in the actionsmenu fail with a status message explaining the error, rather than an exception, when the context is locked. [optilude] - Ensured that the rulestab is not displayed if content rules are disabled globally. Fixes. [optilude] - Show the locked icon to any user (including the one who holds the lock) so long as they would normally have the "Modify portal content" permission. This makes it easier to realise when you inadvertently locked an object. [optilude] - Fixed _at_creation_flag on initial content. This closes. [hannosch] - Remove the properties action from all FTIs. [wichert] - Corrected status messages emitted by the join form and personalize validators. This closes. [hannosch, wichert] - Unregister tools which are no longer action providers. This fixes [wichert] - Added tests for sending mails via the contact form with Unicode input. The actual bug was fixed in SecureMailHost. This closes. [hannosch] - Added migration to the new five.localsitemanager lookup class. [hannosch] - Added proper byline on search results, optimized layout. [limi] - Adding support for the rel="tag" microformat. This closes [limi] - Separate the kss resources to a development and production version, and change portal_javascript entries to switch to the new resources. Modes can be switched by setting portal_javascript to debug mode, or by visiting the view @@kss_devel_mode/ui (this works with client side cookies, and thus enables changing the development mode of kss without touching the server). [ree] - Use the PlonePAS way of setting member properties [wichert] - Removed utility registrations for tools that are not utilities anymore. [hannosch, wichert] - Updated the factory and migration_util code to use the new GenericSetup methods for directly loading profiles, without setting the context. [hannosch] - Small i18n markup fix in the control panel overview. Dynamic content inside a message has to be quoted by using i18n:name. [hannosch] - The persistent type information of the Topic type was not updated to its new name Collection. This closes. [hannosch] - Reformatted the migration registrations for less excessive whitespace use. [hannosch] - Added migration registrations for the 2.5.3 rc1 and final releases. Corrected the history. This closes. [hannosch] - Added the selected year to the options in the calendar date picker box if it was not in the available range, so you can always keep the year. This closes. [hannosch] - No longer migrate the deprecated related and language portlets to classic portlet assignments in the portal root. This closes. [hannosch] - Made the user preference for which editor to use translatable. This closes. [hannosch] - Consistently bicapitalized JavaScript. This closes. [hannosch] - Fixed explanation on the navigation control panel. This closes. [hannosch] - Updated the language control panel to a new formlib-based version which shows all the language names localized to your language. This refs. [hannosch] - Added migration to move the kupu (core) and CMFPlacefulWorkflow (add-on) control panels to the right categories. This closes. [hannosch] - In plone.app.viewletmanager GenericSetup handler: Added support for based-onand make-defaultparameters in <order /> and <hidden /> nodes, value for skinnamecan be "*" (means all). Added support for insert-before, insert-after(value can be "*") and removeparameters in <viewlet /> node. Viewlets ordering and hiding are now additive. This closes. [davconvent] - Made prefs_user_detailspull its form from personalize_formto minimize duplicated code. If you have customized any of these templates, you should probably revisit them and update your templates accordingly. [limi] - Moved footer.pt, colophon.pt and global_contentviews.pt to viewlets, found in plone.app.layout.viewlets. The original templates are now in the plone_deprecated layer. [optilude] - Users aren't invited to contact the site admin anymore if mail settings are not set. This closes. [hannosch] - Changed the global section (tab) navigation so that it shows non- folderish items as well as folderis ones by default (for migrated the sites, the default is not to display them). Also changed the navigation tree so that it start at level 1, not the site root by default (again does not affect migrated sites). This makes it easier to have a separate front page, and lets the tabs act as first-order navigation with the navtree acting as second-order-and-below. [optilude, limi] - Added a persistent zope.app.cache based RAMCache, which is used for caching the portlets by default. Configuration is available via. [hannosch] - Allow user ids that are substrings of existing user ids. This fixes [nouri] - Fix `RegistrationTool.mailPassword` by passing the results of `reset_tool.requestReset` to it, instead of having the template call the tool's function. Also take care about encoding, since the template returns unicode now. This makes e-mailing forgotten passwords work again, and fixes [nouri] - Added an opt-out for multi-submit protection. Add a class to the input tag called "allowMultiSubmit". [optilude, ree, fschulze] - Adjusted our RegistrationTool's mailPassword method not to use the method from the base tool anymore, as that has changed in incompatible ways. Reverted the method to use the same logic as in CMF 1.6. This refs. [hannosch] - Corrected inconsistent slashing of URLs in folder listings, fixes - Fixed migration from Plone < 2.5. The portal_setup tool needs to be installed before installing CMFPlacefulWorkflow now. This closes. [hannosch] - Added ZPT-like i18n markup to GenericSetup profiles, which is used for automatic message extraction by i18ndude. [hannosch] - Cleaned and speed up ulocalized_time functions. Added request to the method signature which was implicitly acquired so far. Now you can optionally provide it directly. [hannosch] - Corrected spelling error in validate_folder_constraintypes.vpy. This closes. [hannosch] - Fixed duplicate class definitions in some templates. [hannosch] - Fixed lots of small i18n markup errors. Mostly using different message ids for messages whose text has changed significantly. [hannosch] - Link to the users dashboard from password_form and personalize_form, instead of to the plone_memberprefs_panel. [hannosch] Plone 3.0-beta3 - released May 5, 2007 - Allowed any non-structural folders and non-folderish items be eligible as default view types. Structural folders can still be listed if they are added to the default_page_types property. This closes [optilude] - Gave the Editor role a few additional permissions: "Modify view template", "Request review" and "Modify properties". This closes [optilude] - Moved sharing action to a global action and removed from standard types. This closes [optilude] - Fixed migration code for CMFEditions. This closes [hannosch] - Fixed member_search_results to work for users without a fullname. [hannosch] - Added plone.app.viewletmanager. This allows you to hide and order the viewlets per skin via a GenericSetup profile. Plone 3.0-beta2 - released May 2, 2007 - Extended support for creation of translated initial content to include all titles and descriptions of all initial content. [hannosch] - Add getChainFor method in WorkflowTool from CMFPlacefulWorkflow monkey-patch and disable this one. [encolpe] - Hide CMFPlone on the add-on product installation control panel. This fixes. [hannosch] - Fix bad links between templates prefs_users_overview, prefs_user_details and prefs_user_membership (remove starting space and force portal_url) [encolpe] - Separated the Editor role into Editor and Contributor, the latter with responsibility for adding content. This is necessary in order to support the (most common?) use case of wanting to have a folder in which people can add content, but not edit the folder itself! [optilude] - Moved global_logo, global_pathbar, global_personalbar, global_searchbox, global_sections and global_siteactions to viewlets in plone.app.layout. [fschulze] - Add POST-only protections to security critical methods (see). [mj, bloodbare, alecm] - Switched to the simple_publication_workflow as the default workflow. Note that the tests still assume plone_workflow is the default (see the previous change message below). [optilude] - Made an extension profile for the default Plone test fixture in profiles/testfixture. For now, this explicitly sets the test fixture workflow. This profile should be used with care - deviate too far from the base profile and tests become meaningless! However, some deviation may be inevitable in order to have sane and predictable tests. [optilude] - Deprecate Products.CMFPlone.utils.BrowserView. Its users should use Products.Five.BrowserView directly. [wichert] - Removed presentation.css, as the presentation mode has moved to use the S5 presentation mode. [limi] - Cleaned up the ID mess around which ID/class that wraps the actual content (without the UI elements in the content well). The official approach is now to use #content for the actual content, and to use #portal-column-content for the entire content region. Also made it possible to get rid of some !important statements. If you have CSS that depends on either of these two selectors, you might want to make sure that the output is still as expected. It should work the same way in most cases, but since the scope is narrower for #content now, you might need to update your styles (and main_template needs to be updated too, if you have customized that). Fixes [limi] - Let users with the Editor local role add content in folders. Note that this will only work for third party content types and custom workflows if they either use one of the standard "add content" permissions or explicitly give Editor the Add portal content role. Fixes [optilude] - Deprecated ploneifyActions.py and moved the functionality to the @@plone view. As part of this, removed the use_folder_tabs property. All structural folders now use folder tabs; this property pre-dates the concept of non-structural folders. [optilude] - Reindex security recursively after group name update in stripGRUFLocalRolePrefix. Fixes [alecm] - Add back user skin cookie deletion on logout. Fixes [alecm] - Added visual styles and updated markup for the new "Info", "Warning" and "Error" status message levels. [limi] - Made the error page much friendlier, it essentially just prints a log entry number now and explains that the error has been logged. If you are logged in as an administrator, you have access to the full error log. This fixes [limi] - Ensured that templates missing the initial h1 class "documentFirstHeading" got it applied, since it makes a difference with the header styling. If you see additional space above your headlines in your own products or add-on products, please insert this class. It would have been nice if IE supported :first-child selectors, but since it doesn't, this is the workaround. [limi] - Add a migration utility function to load (parts of) GenericSetup profiles during migration. This allows us to write configuration changes in the form of GenericSetup extension profiles instead of python code. Use this to load a new 3.0b1-3.0b2 migration profile. [wichert] Newsand Eventsare no longer "Smart Folders" (or "Collections") in new created portals. Instead, they are now "Large Folders" with a "Collection" default page named aggregator. This closes. [davconvent, nouri, optilude] - Remove the default_charset property on the portal object during migration if it is set to an empty string. This makes sure we do not try to use an invalid (ie empty) encoding when exporting GenericSetup profiles. [wichert] - Register the tool inteface for the membership and workflow tools using the CMFCore interface, overriding the CMFDefault registration. [wichert] - Enabled search-current-folder-only option for the quicksearch box. [optilude] - Make the navigation root affect searches (including live searches). By default, you will not get search results from outside the navigation root. [optilude] - Merged patch from olivluca to properly support the uniqueItemIndex iterator. [optilude] - Set the current instance version on site creation so we can migrate properly. [wichert] - Added new arguments to the action tools API which allow querying for a specific action category or exclude certain action categories or action providers from the results in an efficient way. [hannosch] We exclude all actions from the workflow tool and those in the folder_buttons and object_buttons categories by default from the dictionary available from the ploneview. [hannosch] - Removed lots of unused actions and the entire object_tabs and global action categories. This closes. [hannosch] - Cleaned up code in unicodehacks.py so we don't have a performance penality for mixed unicode/non-unicode pages. [hannosch] - Micro optimization: Use a truly local variable for language lookup, which is faster than getting the value from the globals. [hannosch] - Stop calculating the body text of a document twice in document_view. [hannosch] - Changed order of action providers to fit the way we want to see content tabs. [davconvent, nouri] Plone 3.0-beta1 - released March 26, 2007 - Use plone.session for authentication. [wichert] - Replaced getToolByName calls with getUtility/queryUtility for placeful workflow tool. [encolpe] - Changed all mail related templates and methods to use the email_charset property. This closes. [hannosch] - Added email_charset property, which should be used as the charset to send mail, so you are not restricted to the default_charset which has to be utf-8 right now. This refs. [hannosch] - Opera 9 is now a supported browser for the rich text editor. [duncan] - Removed computeRoleMap.py, as it can't be deprecated in a safe manner. If your product depended on this, you need to update it. [limi] - id="relatedItems" is now a class="relatedItems". This closes. [limi] - Removed references to specific workflow states from the publishing process explanation in content_status_history.cpt. This closes. [hannosch] - Increased the calendar_starting_year property to 2001, so the available calendar range doesn't end in 2010, which is quite soon ;) [hannosch] - Made the content menu (in plone.app.contentmenu) only show up on the main view of an object; on other tabs, it makes less sense, especially on the edit tab where it may cause confusion and lead users to accidentally cancel their edit operation by clicking a content menu link. [optilude] - Removed all mail templates which are part of PasswordResetTool and weren't used anymore. [hannosch] - Replaced a few last occurrences of the term member with user. This closes. [hannosch] - Added temporary monkey-patch for GenericSetup's components handler. We need to ensure we store Acquisition free tools as utilities. [hannosch] - Properly install PloneLanguageTool during site setup and migrations. [hannosch] - Updated setup code. Archetypes and all its dependencies are installed based on GenericSetup extension profiles now. [hannosch] - Add migration code to remove the PlonePAS PloneTool from the site and replace it with a standard PloneTool. [wichert] - Improve the test for GRUF presence; it also considered a PlonePAS monkeyed PAS as GRUF. [wichert] - Remove GRUF usage for local role handling in PloneTool [wichert] - Updated language dependend portal creation step. We set the default language of the portal, the allowed languages and if necessary the combined languages support option. If we get a territory code in the locale we also set the visible_ids setting to true for non-latin-scripts, for which we don't have a IURLNormalizer registered. This closes. [hannosch] - Removed tests/runalltests.py and tests/framework.py as they have outlived their usefulness. To run tests use Zope's testrunner: ./bin/zopectl test --nowarn -s Products.CMFPlone [stefan] - Added missing migration step addPortletManagers, to add the new portlet manager adapters. [hannosch] - Fixed various bugs in the migration code. We need to register additional GenericSetup import steps manually or the componentregistry step is not available, which new products like CMFEditions depend on. When add-ons use this step we need to make sure they are allowed to run all the dependent steps, so we needed to make the plone-site step available for all extension profiles, by not requiring a flag file anymore. We also need to call the enableZope3Site and registerToolsAsUtilities migration steps as the first step in every possible version migration, as the migration code itself depends on these to be present. Otherwise migrating from older versions would fail with ComponentLookupErrors. [hannosch] - Location is now a standard metadata field available for categorizing content. This means that you can geotag images, display content with location data on a map, etc. [limi, nouri] - Extended the timeout on password resets from 1 day to 1 week by default. [limi] - Fix bug #6227 : Batch-workflowing objects would erroneously give them the effective date of the portal object or their container. [elvix] - Registered all standard CMF and Plone tools as local utilities and replaced most getToolByName calls with getUtility/queryUtility. [hannosch] - Registered the portal itself as a utility providing IPloneSiteRoot and as one providing CMF's ISiteRoot. [hannosch] - Replaced our local component registry with one from five.localsitemanager. There is no migration path for existing Plone 3.0 alpha sites, so make sure to throw them away and recreate new ones. Migration from Plone < 3.0 is of course supported. [hannosch] - Optimized the calendar_macros template. Trying to translate integers like years or hours wasn't very helpful. [hannosch] - Optimized code in the translation service tool for the calendar_macros use case, so we can get rid of the explicit call of the deprecated utranslate script. [hannosch] - Added new user/group settings control panel. [hannosch] - Moved version overview and server debug mode to the maintenance control panel. Added warning message about missing mail host or email from adress to the main control panel view. [hannosch] - Added external_links_open_new_window to site properties which controls the behavior of mark_special_links.js. [hannosch] - Only show the user friendly types on the navigation control panel. [hannosch] - Excluded x-web-intelligenttext from the list of activated mimetypes. [hannosch] - Remove the folder user action, and re-point the author profile user action to point to the users dashboard instead. [wichert] - Add an object_provides index to the catalog. This indexes all interfaces provided by an object with their dotted names. [wichert] - Made it possible to look up the ExtensibleIndexableObjectWrapper using a multi-adapter on (context, portal). The wrapper now has an additional method update() which can update with workflow variables and the like. This allows a particular wrapper to be registered for a particular type of object, allowing more careful control over the indexing process. [optilude] - Removed ids from portlet templates and turned into classes. This makes sure we do not get duplicate ids in our html when multiple instances of the same portlet type are created, while still allowing different styling of different portlet types [wichert] - Undeprecated the toLocalizedTime script. We are probably going to change the approach to be based on Zope3 locales in the next release, so it doesn't make sense to force everybody to change their products now. [hannosch] - Renamed Keywords to Categories, and included tags/labels/keywords explanation in the help text. User research showed that people understand this term better than the other alternatives. [limi] - Make it easy to include javascript for trackers like Google Analytics via a new control panel-manageable webstats.js file. [mrtopf] - Added an RSS portlet. [mrtopf] - Removed the unsupported Plone Tableless skin. [wichert] - Added class to the navtree: "navTreeItemInPath", which exists on all nodes that are in the current path. [limi] - Added Google/MSN/Yahoo site map support as described on It is disabled by default and can be retrieved via http://<portalroot>/sitemap.xml.gz [mrtopf] - Add migration code for the enable_sitemap site property [wichert] - Removed the Undo action (since we have versioning now) - it's too complex to be useful for normal users, and admin users have the ZMI. Also renamed "Join" action to "Register" and removed the dedicated link to the personal Preferences pending addition of the Dashboard link. We do not migrate existing sites to these values on purpose - if you want these changes, it's easy to fix them in portal_actions on your site. [limi] - Set text-transform property to none, it's not 2001 anymore, and the mix of uppercase and lowercase was hurting me. Also fixed font size for the unreadably small text in Firefox on certain platforms. [limi] - Install kupu via its GenericSetup profile. [wichert] - Renamed the statusmessage of type stop to error and the CSS class from portalStopMessage to portalErrorMessage accordingly. [hannosch] - Removed the forms.txt and rendering.txt functional test - there are covered by AddMoveAndDeleteDocument.txt, which is more sane. Also update the latter to reflect a label change from plone.app.contentmenu. [optilude] - Deprectated viewThreadsAtBottom and getReplyReplies in favour of a viewlet for IBelowContent, defined in plone.app.form. [optilude] - Added all currently used translation domains as PTSTranslationDomains. This makes them available as Zope3 translation domain as well, so they can be used in pure Zope3 page templates for example. [hannosch, philiKON] - Changed plone_control_panel overview to use a three column layout. [hannosch] - Added migration steps for new security and html filter control panels. [hannosch] - Sanitized control panel names. Removed the redundant settings in titles. [hannosch] - Converted site and skins control panels to be formlib based. Moved the Google sitemap option to the site control panel. Fixed migration code for maintenance control panel. This closes. [hannosch] - Hide the PAS folder and its plugins from the breadcrumbs. [wichert] - Fixed cropping of utf8 encoded text. cropText script is marked as deprecated now. This fixes. [naro] - Remove the default language setting from the site control panel. This setting doesn't work anyways right now. [hannosch] - Split the dashboard into four columns. If you have run an earlier version of the alpha, you need to re-run the portlets.xml importhandler or re-create your portal to be able to use the dashboard. [optilude] - Change the default time and date format. This closes. [hannosch] - On site setup the mail host and email address are left empty. This references. [hannosch] - Renamed "Smart Folder" to "Collection" since it better describes the new functionality, made other things more consistent: "Comments" everywhere instead of "Discussion", "Publishing Date" instead of "Effective Date", better help text on these. [limi] - Ignore a bunch of more required products in the install/uninstall control panel form. [hannosch] - Removed last occurrences of portal_status_messages and removed the inclusion code in global_statusmessage. This closes. [hannosch] - Removed the old CMF types from the GenericSetup profiles. This closes. [hannosch] - Removed the news_listing template that hasn't been in use since Plone 2.0 (it wasn't working anyway). It was replaced by the summary view in Plone 2.1, and deprecated then, which means it should be safe to remove. [limi] - Fixed encoding problem when sending out registration emails [jvloothuis, ender] - Deprecated relaxed mode of the normalizeString methods in favour of direct usage of the normalizers in plone.i18n. [hannosch] - Merged plip174-reusable-i18n branch. Normalization logic and language handling are based on plone.i18n / plone.app.i18n now. [hannosch] Plone 3.0-alpha2 - released February 13, 2007 - Deprecated the isRightToLeft method on the ploneview in favour of the is_rtl method on the plone_portal_state view. [hannosch] - Added Google-specific extensions to the robots.txt file to deny it from indexing a gazillion sendo_forms. The standard doesnt allow for wildcards boot Google does. [elvix] - Added robots.txt file. This should remove some unwanted not-found-errors and give fresh Plone-admins something to customise for robots if they want it. more info about robots.txt here: [elvix] - Commented out the IE-specific styling of textarea scrollbars from IEFixes.css. Plone uses standard scrollbars from 3.0 onwards, but if you want them back, they can easily be uncommented. [limi] - Added some classes to document_byline.pt for more flexibility when styling this template. This closes [spliter] - Deprecated skin related methods of the Plone tool. The functionality is provided by the skins tool itself for some time now. [hannosch] - Updated the various mixed Unicode/UTF-8 support patches to be compatible with Zope 2.10.2, which is required now as a minimum Zope version. [hannosch] - Did some minor import locations cleanup. Deprecated i18n related methods in utils.py and importing IndexIterator from ploneview.py. [hannosch] - Added simply optimization to the getReplyReplies script, avoiding some calculations when there are no replies and removed the custom getDiscussionFor method from CMFPlone's DiscussionTool, as it wasn't needed anymore. [hannosch] - Fixed an unsafe usage of hasattr in computeRelatedItems with base_hasattr. [hannosch] - Removed obsolete factory type information for the Plone folder classes. [hannosch] - Deprecated the getOrderedUserActions script. It was only used in the global_personalbar to enforce a certain logical order of the actions, but action categories support ordering themselves now, so the script was obsolete. [hannosch] - Deleted folder_localrole_form and its scripts, since this is now provided in the @@sharing view. That felt good. Added an alias with a deprecation warning in plone.app.layout so that old links still work. The alias will be gone in 3.5. [optilude] - Moved accessibility elements from base.css to invisibles.css, since they should remain even if you do a total customization. [limi] - Removed Five from the core versions overview in the plone control panel. Five will probably evolve as a set of independent packages rather than one monolithic package so its version isn't of any particular interest anymore. [hannosch] - Added Reader and Editor local roles, and merged in support for the new sharing page, at the @@sharing view. [optilude] - Add support for OpenID authentication. [wichert] - Make it possible to use the plone.session PAS plugin. This provides a scalable method to use session authentication in Plone sites. [wichert] - Converted PlonePAS installation to be GenericSetup based and moved all user/group related setup functions there as well. Also removed explicit GroupUserFolder installation as it isn't needed anymore. [hannosch] - Added new SiteManagerCreatedEvent that is called right after the portal is enabled as a site. We can use this to call the setHooks and setSite functions which are mandatory during test runs, before any other GenericSetup import step tries to call any local component. [hannosch] - Decoupled some more of the GenericSetup import steps. The plone-site step only creates the local component registry and enables the portal object as a site manager. This is needed as steps using local components depend on this step while not much else in the site may have been configured yet. The plone-content step adjusts the initial content and is run last as it depends on everything else in the portal having been already set up. [hannosch] - Added an alias view login(aka @@login) to let people use /login to get to login_form (it perform a redirect). This is also now a reserved id. [optilude] - Merged plone.app.contentrules, your friendly content rules engine [wayworn, optilude] - Moved deprecated zcml declarations to its own file deprecated.zcml in order to make it easy to spot those or turn them off. [hannosch] - Add a new interface INonInstallable for which you can register named utilites that provide a list of profiles that should not be available as installable during site creation. We exclude certain products that are installed anyways by Plone from the config screen this way. [hannosch] - Use the INonInstallable interface in CMFQuickInstallerTool to exclude some products from the list of installable products in the ZMI and install/uninstall control panel screen. Otherwise CMFDefault, CMFUid, etc. would show up in the list. [hannosch] - Added support for plone.app.redirector to the 404 template. This enables automatic redirects when an objet has been moved or renamed, and offers suggested search results on the 404 page otherwise. [optilude] - Merged changes necessary to support PLIP125 Link Integrity, mostly found in the plone.app.linkintegrity package. [witsch, optilude] - Removed the setup tab from the migration tool. It wasn't working anymore and the functionality can be found on the controlpanel tool anyways. [hannosch] - Fixed a bug in the require_login script calling a non-existent method on the migration tool. [hannosch] - The controlpanel and migration tools are registered as local utilities now as well. [hannosch] - Merged in kss. [ree] - Finished multilingual front-page support code. The front page which is created at portal creation time is now localized to the browser language used while creating the portal, as long as there is a complete translation of the page. [hannosch] - Merged generalised next/previous navigation into plone.app.layout (interfaces, viewlet), CMFPlone (rel links in header.pt, tests) and ATContentTypes (adapter for IATFolder). [henri, pelle_, trollfot, optilude] - The interface and translation service tools are registered as local utilities now. [hannosch] - Exposed the member preference panels in the prefs portlet. This closes. [hannosch] - Added javascript and css to switch between schemas in edit page. [fschulze] - Removed properties tab for all ATCT types. [fschulze] - Moved Products.CMFPlone.browser.contentmenu to plone.app.contentmenu. Note that the tests remain in CMFPlone for now (so that they get run more often, and to avoid having to replicate dummies etc in the new location). [optilude] - Moved date/time formatting related messages to it's own domain called plonelocales. Message files in this domain are translated directly by the Zope 3 translations service, which results in a major speed increase for date/time formatting. [hannosch] - Moved new controlpanels to its own package (plone.app.controlpanel). [hannosch] - Moved various interfaces and utilities - IDefaultPage, INvigationRoot, INavtreeStrategy, INavigationQueryBuilder and the buildFolderTree() and getNavigationRoot() helper functions - to plone.app.layout. This reduces the dumping-ground feeling of CMFPlone.browser, leaving it free to focus on actual views that implement CMFPlone look-and-feel and policy, and provide a saner dependency/import location for third party components needing these tools. [optilude] - Gave IContentIcon a html_tag() helper method to make rendering the icon one line (<img tal:) rather than ten or so. Also made the properties properties rather than functions. [optilude] - Removed outdated version of listFilteredActionsFor from the actions tool. [hannosch] - Deprecated cache_decorator in browser/ploneview.py (formerly plone.py), in favour of plone.memoize's instance.memoize decorator. Replaced all uses of cache_decorator in CMFPlone with plone.memoize. [optilude] - Renamed Products.CMFPlone.browser.plone (plone.py) to Products.CMFPlone.browser.ploneview (ploneview.py). The naming was causing conflicts with the plonenamespace package. A module alias remains during the deprecation period (i.e. it will be removed in Plone 4.0). [optilude] - Use img tags instead of css classes for icons (PLIP 178). [fschulze] - Added missing ATRelativePathCriterion to the default profile. [stefan] - Some minor code modernizations in the FactoryTool. [hannosch] - Added formlib based mail and search control panels. ] Plone 3.0-alpha1 - released November 24, 2006 - Update installation instructions for the new Plone release. [wichert] - Added calendar control panel based on formlib. This is related to. [hannosch] - Moved global_contentmenu to plone_deprecated [optilude] - Injected Plone 2.1.4 into the migration chain. [stefan] - Removed bogus scripts from workflow actions, and introduced some BBB code to ensure that if people are using those scripts and they don't exist, the old fallback (content_status_modify) is still used. [optilude] - Plone 3.5 will introduce the role "Power User" to make it possible to hide advanced functionality from casual users. It you have any deployments that use this role name, now would be a good time to rename that role and stop using it in product code. - Update migrations for portlets, and kick the meta.zcml in plone.app.portlets. [optilude] - First day of week in the calendar is Monday now in Plone by default. This closes. [hannosch] - Added option to choose different base profile while creating a new Plone site. This closes. [hannosch] - Deal with CMFDefault renaming _checkEmail to checkEmailAddress. [wichert] - Removed unused scripts from the extensions folder. [hannosch] - Added some notes about CMFEditions and CMFDiffTool installation. [hannosch] - Added first part of multilingual front-page support code. [hannosch] - livesearch_reply.py wrote quotes (") in the title-attribute. misformed XML was generated. replaced quotes by ". [jensens] - Merged plip142-componentised-content-menu. [optilude, hannosch] - Merged plip148-cmf21 bundle. This implements and. [hannosch] - Merged PLIP 8 versioning bundle. [wichert] - Converted some tests to inline doctests and some others to real unit tests as opposed to integration tests. [hannosch] - Changed the logo template global_logoto not use the image replacement approach, but use a straightforward link/image approach instead. Sometimes Plone tries to be too smart for its own good. ;) This also fixes the horizontal scrollbar problem in IE6 for RTL layouts. [limi] - Silenced the utf-8 / Unicode DeprecationWarning. We should only emit warnings once we fixed this in all standard cases ourselves. [hannosch] - Added migration for the css files added by limi in the previous entry. [jladage] - Split up the CSS into a couple of new modules to ease customization. [limi] - Added an optional keyword argument to the date_components_support script that allows to specify the minute steps. It still defaults to five. This closes. [hannosch] - Deprecated some more unused skins scripts: extract_date_components, getPersonalFolderFor, navigationCurrent, navigationLocalRelated and rejectAnonymous. [hannosch] - Deprecated the never used nor functional prefs_workflow* control panels, we are better of with a fresh start on these anyways. [hannosch] - Do not set initial descriptions for the member folders, as these often ended up in a translation the user did not want or understand. We only use the simply username as a title now, which is language independent. This fixes. [hannosch] - Updated the text on the member search form to be more user friendly. This closes. [hannosch] - Deprecated our unmaintainable how-to enable cookieinstructions. This closes. [hannosch] - Added error tolerant version of FasterStringIO to unicodeFallbackPatch. This is monkey patched into the Zope3 tal and pagetemplate modules and replaces the monkey patch found in PlacelessTranslationService so far. [ree, hannosch] - Deprecated PloneContent. Use (marker) interfaces instead to get a way to check for a functionality that is common to some types. [hannosch] - Deprecated the CMFPlone implementation of LargePloneFolder. Use ATBTreeFolder from ATContentTypes instead. [hannosch] - Added unicodeFallbackPatch that allows to use utf-8 encoded strings to be used inside the Zope3 TAL engine. [ree, hannosch] - Fixed the 'Unauthorized: You are not allowed to access Creatorin this context' error that was raised in the testCookieAuth tests. [hannosch] - Using new visualIconcss class to allow much smaller generated.css and RTL.css. When new content types are installed, then generated.css will grow much less then before and RTL.css will not grow at all anymore. The footprint of action icons is also smaller now. [fschulze] - The portal object is set up as a Zope3 site with a local site manager. [hannosch] - Removed CMFPlone.MemberData. This class is never used, and the future is with PAS-based objects instead of membership/memberdata tools. [wichert] - Fixed deprecation warnings for the ZCML content directive. [hannosch] - Removed deprecated createTopLevelTabs from PloneTool and utils. Use the topLevelTabs method of the INavigationTabs view instead. [hannosch] - Removed deprecated CustomizationPolicy and old site creation machinery. [hannosch] - Removed deprecated CSS styles from deprecated.css. [hannosch] - Removed deprecated scripts from the plone_deprecated skins layer. [hannosch] - Removed lots of deprecated values from the PloneView. [hannosch] - Removed deprecated FolderWorkflow, PloneWorkflow and PloneUtilities classes. Removed aliases for base_hasattr and transaction_note from CMFPlone. Import these from CMFPlone.utils. Removed security declarations for zLOG levels. zLOG usage was replaced by Python's logging module. [hannosch] - Removed five:traversable from configure.zcml as it is not needed anymore for Zope 2.10. [hannosch] - Removed bbb code for MessageIDFactory, queryMultiAdapter, transaction and CatalogTool._initIndexes. [hannosch]
http://plone.org/products/plone/releases/3.0
crawl-002
refinedweb
8,175
57.98
Java Concurrency, Part 3: Synchronization With Intrinsic Locks Learn more about Java synchronization with intrinsic locks. Join the DZone community and get the full member experience.Join For Free After learning how to create threads and manipulate them, it’s time to go to one of the most important things: synchronization. Synchronization is a way to make some code thread-safe. Code that can be accessed by multiple threads must be made thread-safe. Thread-safe describes some code that can be called from multiple threads without corrupting the state of the object or simply doing the thing that the code must do in the right order. Disclaimer: This article was originally published in August 2010. The code shown below has been updated and tested in Java 12. You may also like: How to Avoid Deadlock in Java Threads For example, we can take this little class : public class Example { private int value = 0; public int getNextValue(){ return value++; } } It’s really simple and works well with one thread, but absolutely not with multiple threads. An incrementation like this is not a simple action, but three actions: - Read the current value of value - Add one to the current value - Write that new value to value Normally, if you have two threads invoking the getNextValue(), you might think that the first will get 1 and the next will get 2, but it is possible that the two threads get the value 1. Imagine this scenario: describes the possible situations of several threads executing some statements. Even when we only consider three operations and two threads, there are still a lot of possible interleavings. So, we must make the operations atomic to work with multiple threads. In Java, the first way to make that is to use a lock. All Java objects containactor the getNextValue() method using the synchronized keyword: public class Example { private int value = 0; public synchronized int getNextValue(){ return value++; } } With that, you have a guarantee that only one thread can execute the method at the same time. The used lock is the intrinsic lock of the instance. If the method is static, the used lock is the Class object of Example.++; } } } This is exactly the same as using the synchronized keyword on the method signature. Using synchronized blocks, you can choose the lock to block on. For example, if you don’t want to use the intrinsic lock of the current object but another object, you can use another object just as a lock: public class Example { private int value = 0; private final Object lock = new Object(); public int getNextValue() { synchronized (lock) { return value++; } } } The result is the same but has one difference, the lock is internal to the object so no other code can use the lock. With complex classes, it's not rare to use several locks to provide thread safety in the class. There is another issue with multiple threads: the visibility of the variables. This happens when a change made by a thread is visible by another thread. For performance improvements, the Java compiler and virtual machines can make some improvements using registers and a cache. By default, you have no guarantee that a change made by a thread is visible to another thread. To make a change visible to another thread, you must use synchronized blocks to ensure the visibility of the change. You must use synchronized blocks for the read and for the write of the shared values. You must do that for every read/write of a value shared between multiple threads. You can also use the volatile keyword in the field to ensure the visibility of read/write between multiple threads. The volatile keyword ensures only visibility, not atomicity. The synchronized blocks ensure both visibility and atomicity. So, you can use the volatile keyword on fields that don’t need atomicity (if you make only read and write to the field without depending on the current value of the field by example). Pay attention when trying to solve thread safety on a problem that can add new issues of deadlock. For example, if thread A owns the lock 1 and is waiting for the lock 2, and if lock 2 is acquired by thread B who waits on lock 1, there is a deadlock. Your program is dead. So you have to pay great attention to the locks. There are several rules that we must keep in mind when using locks: - Every mutable field shared between multiple threads must be guarded with a lock or made volatile, if you only need visibility - Synchronize only the operations that must be synchronized, this improves performance. But don’t synchronize too few operations. Try to keep the lock only for short operations. - Always know which locks are acquired and when they are acquired and by which thread - An immutable object is always thread-safe. Well, here we are. I hope that this post helps you to better understand thread safety and how to achieve it using intrinsic locks. In our next post, we’ll see more on synchronization methods. Stay tuned! Further Reading How Synchronization Works in Java (Part 1) How to Avoid Deadlock in Java Threads [DZone Refcard] Core Java Concurrency Published at DZone with permission of Baptiste Wicht, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/dnp-java-concurrency-%E2%80%93-part-3
CC-MAIN-2021-04
refinedweb
892
60.55
I have installed the Panda3D-1.6.0-pre.dmg package under MacOS X (Leopard). My application consists of two windows - the Panda3D and a TkinterGUI. When starting the application both windows appear, but it’s hardly possible to interact with the Tk GUI. It seems that not all events on the Tk window are processed. Example code: import direct.directbase.DirectStart import Pmw import Tkinter def sayhello(): print "hello" root = Pmw.initialise() b = Tkinter.Button(root,text="hit me",command=sayhello) b.pack() base.startTk() run() When executing this code two windows appear - the Panda3D and a TkInter GUI with one button “hit me”. Events on the Panda3D window are processed immediately, but not the activites on the Tk window. Try to switch between the windows and you will recognize the problem. The problem occurs only under MacOS, not under Windows. Versions: Mac OS X: 10.5.5 (Leopard) Panda3D: 1.6.0pre Python: 2.5.1 Has anybody a solution for this problem?
https://discourse.panda3d.org/t/panda3d-and-tk-event-scheduling-problem-under-mac-os-x/5211
CC-MAIN-2022-27
refinedweb
165
54.49
If you're interested in writing analysis and source-rewriting tools with Clang's libTooling, you may have run into the following ominous error while trying to invoke a tool on some code: $ clang-check -analyze div0.c LLVM ERROR: Could not auto-detect compilation database for file "div0.c" No compilation database found in /tmp or any parent directory json-compilation-database: Error while opening JSON database: No such file or directory So what's a compilation database, why do Clang tools need it, and how do you go about creating one? Motivation - faithfully reproducing a compilation Unlike many other source analysis tools (for example - syntax coloring in editors) which only provide approximate parsing of C++ source, Clang tools are the real thing. The same compiler frontend that's used to actually parse and compile source is used to build the AST for analysis. This is great because it means you never get false positives; but it also means the analysis tools need the complete information available to the compiler when looking at source files. When we compile code we pass all kinds of flags to the compiler. Warning flags, language-version flags, etc. But most importantly - macro definitions (-D)) and include directories (-I). Without the latter, it's not even possible to parse the source code properly. Historically, a "classical" C compiler pipeline used to run the preprocessor (cpp) to take care of these before the compiler would even see the file. These days modern compilers like Clang combine preprocessing with parsing, but the fundamentals remain in place. OK then, we need to know which flags the code was compiled with. How do we pass this information to tools? Fixed compilation database This is where the concept of "compilation database" comes in. In simple terms, it's a collection of exact compilation commands for a set of files. I'll discuss it in more detail shortly, but first a brief detour into specifying the commands in a simple way that doesn't require a special file. A "fixed" compilation database allows us to pass the compilation flags to a tool on the command-line, following a special token --. Here's a complete example that will demonstrate what I mean. Consider this code: #define DODIV(a, b) ((a) / (b)) int test(int z) { if (z == 0) { #ifdef FOO return DODIV(1, z); #else return 1 - z; #endif } return 1 + z; } Running clang-check simply as shown in the beginning of the post results in an error message. If we tack a -- to the end of the command-line, however, it works: $ clang-check -analyze div0.c -- By "works" here I mean "does not die with an error". But it doesn't report anything either, while I'd expect it to detect a division by zero in the if (z == 0) case [1]. This is because we didn't provide any compiler flags. So the analysis assumed the file is compiled like so: $ clang -c div0.c Indeed, note that the "divide by 0" error happens only if the FOO macro is defined. It's not defined here, so the analyzer is quiet [2]. Let's define it then: $ $clang-check -analyze div0.c -- -DFOO /tmp/div0.c:6:12: warning: Division by zero return DODIV(1, z); ^~~~~~~~~~~ /tmp/div0.c:1:26: note: expanded from macro 'DODIV' #define DODIV(a, b) ((a) / (b)) ~~~~^~~~~ 1 warning generated. So providing compilation commands to tools on the command-line is easy. However, if you want to run analyses/transformations over larger projects for which some sort of build system already exists, you'll probably find a real compilation database more useful. JSON compilation database When Clang tools complain they can't find a compilation database, what they actually mean is a specially named JSON file in either the same directory as the file being processed or in one of its parent directories. The JSON compilation database is very simple. Here's an example: [ { "directory": "/tmp", "command": "gcc div0.c", "file": "/tmp/div0.c" }, { "directory": "/tmp", "command": "gcc -DFOO div0.c", "file": "/tmp/div0.c" } ] It's just a list of entries, each of which consists of these fields: - File: the file to which the compilation applies - Command: the exact compilation command used - Directory: the directory from which the compilation is executed [3] As you can see above, there may be multiple entries for the same file. This is not a mistake - it's entirely plausible that the same file gets compiled multiple times inside a project, each time with different options. If you paste this into a file name compile_commands.json and place it in the same directory (or any of its parents) with the file you want to run the analysis on, the tool will work without requiring the -- part, because it can find the file in the compilation database and infer the compilation command on its own. If the tool finds more than one entry for a file, it just runs multiple times, once per entry. As far as the tool is concerned, two compilations of the same file can be entirely different due to differences in flags. Compilation database for transformation tools Source transformation tools use a compilation database similarly to analysis tools. Consider this contrived example: #include <stdlib.h> int* foo() { #ifdef FOO return 0; #else return NULL; #endif } Let's save this file as nullptr.cpp and run clang-modernize -use-nullptr on it to transform all "NULL-pointer like" constants to an actual nullptr: $ $LLVMGH/clang-modernize -use-nullptr -summary nullptr.cpp -- Transform: UseNullptr - Accepted: 1 $ cat nullptr.cpp #include <stdlib.h> int* foo() { #ifdef FOO return 0; #else return nullptr; #endif } As expected, clang-modernize only replaced within the #else clause because FOO is not defined. We already know how to define it on the command line. We also know that a hypothetical compilation database could provide two entries for nullptr.cpp - one with and one without -DFOO. In this case, clang-modernize would actually run twice over the same file and replace both the 0 and the NULL. Creating a compilation database for your project By now we have a good understanding of how to provide Clang tools with compilation flags for simple files. What about whole projects, however? Assume you have a large existing project and you want to run tools on its source code. You already have a build system of some sort that compiles all the files. How do you tell Clang tools which flags are suitable for any file in the project? There are a few good options. A reasonably recent version of the CMake build tool supports emitting compilation databases [4]. All you need is to run the cmake step with the -DCMAKE_EXPORT_COMPILE_COMMANDS flag, and CMake will take it from there, emitting a compile_commands.json file into your build directory. If you're not using CMake, there are other options. The Ninja build tool can also emit a compilation database since version 1.2, so a Gyp/Ninja combination should be good too. If your project doesn't use either, you should be able to roll your own without too much difficulty. Tools like Build EAR may be helpful here. By the way, it should be clear that large projects is precisely the raison d'être of compilation databases. A single "database" file contains complete information about all the source files in the project, providing Clang tools with the compilation commands required to do their tasks. A custom compilation database It may be the case that you have a very specialized build system that already keeps some sort of record of the flags used to build each file. This is sometimes the case in large companies with monolithic code bases. For such scenarios, you'll be happy to find out that this aspect of Clang tools is fully customizable, because compilation database readers are based on a plugin system. The CompilationDatabase interface (clang/include/clang/Tooling/CompilationDatabase.h) is something you can implement on your own. The same header file that defines the interface also defines CompilationDatabasePlugin, which can be used to link your own compilation database readers to Clang tools. The existing JSON compilation database implementation (clang/lib/Tooling/JSONCompilationDatabase.cpp) is implemented as such a plugin, so there's a handy in-tree example for rolling your own. Final words For most users of Clang tools and people interested in writing custom tools, this post contains way too much information. Most chances are you won't need all of this. But I felt it's important, for the sake of completeness, to describe in full detail what compilation databases are, and how they tie into the large picture. This will help me focus on more internals and examples of Clang tooling in future posts without worrying about compilation databases again.
http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools
CC-MAIN-2017-13
refinedweb
1,473
54.83
Java Switch Statement – Learn its Working with Coding Examples We all use electrical switches in our regular lives to control the electrical equipment. For each particular electrical equipment, there is a unique switch to operate them. And, each switch can activate or deactivate only one item. Similarly, switches in Java are like these electrical switches only. Have you ever wondered how switch statement in Java helps us in decision-making? The answer is switch statements help us with decision making in Java. They are useful to execute one statement from multiple conditions or expressions. In this article, we are going to purely discuss and implement the switch case or switch statement in Java with examples. Before that, let’s take a quick sneak peek of Decision Making in Java with Techvidvan. Keeping you updated with latest technology trends, Join TechVidvan on Telegram Switch Statement in Java A Java switch statement is a multiple-branch statement that executes one statement from multiple conditions. The switch statement successively checks the value of an expression with a list of integer (int, byte, short, long), character (char) constants, String (Since Java 7), or enum types. It also works with some Java Wrapper Classes like Byte, Short, Integer, and Long. When it finds a match, the statements associated with that test expression are executed. A Switch statement is like an if-else-if statement of Java. In other words, the switch statement checks the equality of a variable against multiple values. The syntax or general form of a switch statement is: switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; } Working of a Switch Statement The switch statement evaluates the conditional expression and matches the values against the constant values specified in the case statements. When it finds a match, the statement associated with that case is executed until it encounters a break statement. When there is no match, the default statement gets executed. If there is no break statement, the control flow moves to the next case below the matching case and this is called the fall-through. Some Important points about Switch Statements in Java These are some important rules of the Java switch case: - There is no limit for the number of cases in a switch statement. There can be one or ‘N’ number of cases in a switch statement. - The case values should be unique and can’t be duplicated. If there is a duplicate value, then it is a compilation error. - The data type of the values for a case must be the same as the data type of the variable in the switch test expression. - The values for a case must be constant or literal types. The values can be int, byte, short, int, long or char. - We can also wrapper classes as the values of the cases that is, Integer, Long, Short, and Byte. Also, we can use the Strings and enums for the value of case statements. - We use the break statement inside the switch case to end a statement. - The break statement is optional, and in the absence of the break statement, the condition will continue to the next case. - The default statement in the switch case is also not mandatory, but if there is no expression matching the case (or if all the matches fail), then nothing will execute. There is no need for a break statement in the default case. - We can not use variables in a switch statement. Enhance your knowledge and get to know about Data Types in Java in detail with Techvidvan. Examples of Switch Statement in Java package com.techvidvan.switchstatement; //A Java program to demonstrate the use of switch case public class SwitchCaseDemo1 { public static void main(String[] args) { int day = 5; switch (day) {"); } } } Output: Skipping the break statement in Java Switch: Fall-Through The break statement is optional in the switch case. But, the program will still continue to execute if we don’t use any break statement. You can consider the below code for the same. package com.techvidvan.switchstatement; public class SwitchCaseDemo2 { //Switch case example in Java where we are omitting the break statement public static void main(String[] args) { int number = 20; //switch expression with integer value switch(number) { //switch cases without break statements case 10: System.out.println("Ten"); case 20: System.out.println("Twenty"); case 30: System.out.println("Thirty"); default: System.out.println("Not in 10, 20 or 30"); } } } Output: Thirty Not in 10, 20 or 30 Multiple Case Statements for the same Operation If there are multiple cases in the switch statement and you don’t want to write any operation in a case statement, then the control moves to the next case until it encounters the break statement. For example: package com.techvidvan.switchstatement; public class Test { public static void main(String args[]) { int number = 10; switch(number) { case 5 : //writing no operations for case 5 case 10 : System.out.println("The number is " +number); break; default: System.out.println("The number is not 10"); } } } Output: yield Instruction in Java Switch Statement We can use the Java switch yield instruction from Java 13. It returns a value from a Java switch expression. Code to understand yield in Java switch: package com.techvidvan.switchstatement; public class YieldInstruction { public static void main(String args[ ]) { String token = "TechVidvan"; int tokenType = switch(token) { case "TechVidvan": yield 0 ; case "Java": yield 1 ; default: yield -1 ; }; System.out.println(tokenType); } } Output: Nested Switch Statements in Java When a switch statement has another switch statement inside it, it is called a nested switch statement. Let’s see an example to understand the nested switch statements in Java. package com.techvidvan.switchstatement; public class NestedSwitchCaseDemo { //Java Switch Example where we are skipping the break statement public static void main(String args[ ]) { String branch="CSE"; //Declaring string int year=2; //Declaring integer //switch expression //Outer Switch switch(year) { //case statement case 1: System.out.println("Optional courses for first year: Engineering Drawing, Learning C"); break; case 2: { //Inner switch switch(branch) { case "CSE": System.out.println("Optional Courses for second year CSE branch: Cyber Security, Big Data and Hadoop"); break; case "CCE": System.out.println("Optional Courses for second year CCE branch: Machine Learning, Big Data and Hadoop"); break; case "IT": System.out.println("Optional Courses for second year IT branch: Cloud Computing, Artificial Intelligence"); break; default: System.out.println("Optional Courses: Optimization"); } } } } } Output: Using Strings with Java Switch Statement Since Java SE 7, we can use the strings in a switch expression. The case statement should be a string literal. Dive a little deep into the concept of Java Strings with Techvidvan. Code to understand the switch case with String: package com.techvidvan.switchstatement; public class SwitchStringExample { public static void main(String[ ] args) { //Declaring a String variable String operation = "Addition"; int result = 0; int number1 = 20, number2 = 10; //Using String in switch expression switch(operation) { //Using String Literal in switch case case "Addition": result = number1 + number2; break; case "Subtraction": result = number1 - number2; break; case "Multiplication": result = number1 * number2; break; default: result = 0; break; } System.out.println("The result is: " +result); } } Output: Using Character Literals with Java Switch Statement We can use the data type ‘char’ with the switch statement. The following code explains the switch statement using the character literal. Code to understand the switch case with Character Literals: package com.techvidvan.switchstatement; public class SwitchCharExample { public static void main(String[] args) { //Declaring char variable char courseId = 'C'; //Using char in switch expression switch(courseId) { //Using Character Literal in the switch case case 'A': System.out.println("Techvidvan's Python Course"); break; case 'B': System.out.println("Techvidvan's Big Data and Hadoop Course"); break; case 'C': System.out.println("Techvidvan's Java Course"); break; default: System.out.println("Invalid course id"); } } } Output: Using Enum with Java Switch Statement It is also possible to use Java enums with a switch statement. Below is a Java example that creates a Java enum and then uses it in a switch statement. Code to understand the switch case with the Java enums: package com.techvidvan.switchstatement; public class SwitchOnEnum { private static enum Size { SMALL, MEDIUM, LARGE, X_LARGE } void switchOnEnum(Size size) { switch(size) { case SMALL: System.out.println("Size is small"); break; case MEDIUM: System.out.println("Size is medium"); break; case LARGE: System.out.println("Size is large"); break; case X_LARGE: System.out.println("Size is X-large"); break; default: System.out.println(Size is not S, M, L, or XL”); } } public static void main(String args[]) { SwitchOnEnum obj = new SwitchOnEnum(); obj.switchOnEnum(Size.LARGE); } } Output: Use Cases of Java Switch Statement - The Java switch expressions are useful where you have multiple choices, cases, or options and you need to test these values against a single value. - Switch statements are mainly useful when we want to resolve one value to another. For example, when we need to convert the weekday (number) to a weekday (String), or vice versa. - Switch expressions in Java are also useful in parsing String tokens into integer token types or, character types into numbers. Summary With this, we have come to an end of this tutorial on switch case statement in Java. And now you are well familiar with the switch statement in Java. We learned to implement it in many different scenarios according to our needs. A switch statement can help you with better decision making in Java. They are also very useful for parsing one type of value to the other. As a Java beginner, you should master this concept to become an expert in Java programming. Thank you for reading our article. Do share our article on Social Media. Happy Learning 🙂
https://techvidvan.com/tutorials/java-switch-statement/
CC-MAIN-2021-17
refinedweb
1,615
54.83
Originally posted by David Harkness: This was just discussed one or two weeks ago either in this forum or one of the Java in General ones -- probably this one I'd hope. Actually, I assume you're talking about using static methods instead of a DAO instance, correct? The main problem with this is that you can't ever swap out your DAO for something else: either a different implementation or a mock object for testing. You're much better off creating an interface and implementation. Go ahead and use a singleton instance of the DAO; tools like the Spring Framework make this a snap. Check out the ORM forum for recent discussions on using Spring for this. Static methods should be reserved for things that won't ever change. While it's conceivable that you may want to swap out a different implementation of the java.util.Math methods, it's pretty unlikely. But to test a business object that uses a DAO, it is much nicer to use a mock DAO (jMock or EasyMock; I slightly prefer the former) so you can test the business object in isolation (this is the whole point of unit testing). If you use static methods, all your tests have to run against a real database or you need to swap in a different JAR with a different class that has the same static methods. Ouch! So turn it around: what specific reasons do you have for using static methods? What do they buy you? Maybe we can give you other ways to get the same benefits without them. Originally posted by David Harkness: I certainly didn't mean to imply there aren't valid reasons. I'm not badgering the witness, honestly! Now that I'm using Spring I no longer use the Singleton pattern in the following form, but my DAOs are effectively singletons. All of the business objects that use the DAOs reference a single instance, but that doesn't preclude having multiple instances for different BOs or instiating a new one for each request (Spring supports this model too). But if you're not using a similar framework, the old standby Singleton pattern works pretty well.public interface Dao { ... } public interface UserDao extends Dao { ... } public class UserDaoJdbc implements UserDao ( ... ) public class UserDaoFactory { private static UserDao instance = null; public static UserDao inst() { return instance; } public static void setInst(UserDao dao) { if ( instance != null ) { throw new IllegalStateException("Hey, only one instance, buddy!"); } instance = dao; } }A common anti-pattern is to have the factory create the DAO in the inst() method if it hasn't been created yet, but then you're limiting yourself to a single implementation (though you could have it instantiate the default implementation I suppose). Instead, you'll need to bootstrap your DAOs in a startup servlet or some other way. To use it is nearly as easy as static methods:User user = UserDaoFactory.inst().findUserByEmail("bob@bob.com");You can of course make the instance available in a context object or anywhere else you like from there. Originally posted by Gregg Bolinger: Question, in the UserDaoFactory, when/how does getInst get called so that the instance is created? Instead, you'll need to bootstrap your DAOs in a startup servlet or some other way. If this is the answer, could you explain that a bit more? Thanks. Originally posted by Gregg Bolinger: I am not going to use Spring. I've been wanting to understand DAO's and using a framework won't help me. However, I have done enough JDBC and SQL to last me a lifetime so I am using Hibernate. Does anyting you suggested change with regards to the above statement? If you are in a CMT environment, you should no longer need Spring. AFAICT, people use spring here for four things: (1) session handling/flushing (2) transaction management (3) SQLException mapping (4) Runtime exceptions model Well, with hibernate.transaction.flush_before_completion and hibernate.transaction.auto_close_session, (1) is now much, much easier. (2) is handled by CMT. (3) is implemented in the Hibernate Dialect. And Hibernate3 has an unchecked exception model, so (4) is no longer relevant. I'm currently working on a project with Spring + hibernate 3. I started with Hibernate 2.1 but had too many issues with collections and composite keys so I switched to Hibernate 3 and everything worked out of the box. Originally posted by Gregg Bolinger: So what advantage does the suggested UserDAOFactory have? How does it help me? Originally posted by Paul Wheaton: I prefer TG: Martin Fowler's "Table Gateway Pattern". This is the DAO with the one-to-one mapping. Unlike Mr. Harkness, I prefer to use static methods for anything that does not make for an object (no state means no object). My solution is that a class provides static methods, but those methods will call an instance of an inner class called "Implementation". Originally posted by Paul Wheaton: Jenny uses multiple data sources. Sorry, I don't know what CGLIB is. Jenny generates everything you need. Jenny essentially generates what many people call a "DAO".
http://www.coderanch.com/t/301716/JDBC/databases/Data-Access-Objects-static-methods
CC-MAIN-2014-52
refinedweb
851
65.01
At 11:20 AM 11/1/2006 -0600, Ian Bicking wrote: >So I've got a couple specs out there that build on WSGI, and hopefully >other people will be introducing more. These specs are (or should be) >fairly light and optional, suggesting useful compatibilities between >WSGI components rather than anything that changes WSGI itself. So I >don't think we need a very heavy process, but we need some process. > >Does anyone have a suggestion? My suggestion is that WSGI extensions should be proposed using a proposer-owned namespace (e.g. "selector.vars" in the url_vars case), and simply published by the proposer, with an announcement to the Web-SIG For actualy *standardization*, I think that there should be some *positive* action from other people required. Standardization implies that something is useful and reasonably non-problematic, but I'm not convinced that e.g. the POST parsing stuff that's currently on the table is non-problematic. I'd want to see actual *implementations* of the proposal in a couple of widely-used frameworks before I'd consider it standards-worthy. Frankly, I'd like to err on the side of TOO MUCH process for WSGI extensions than too little. There is very little need for many of the extensions that get proposed, and often the proposals come with too high a price tag attached. Meanwhile, if a proposal is something useful, it can *easily* become a defacto standard. In fact, I think that further protocol standardization in WSGI is mostly bad design at the community level. We should encourage sharing *implementations* first, before sharing interfaces. So, I'm at a very strong -1 on having a simple process for defining WSGI extensions; the whole point of namespaced environ variables is to allow you to define your *own*; there is really no reason for everything to be named 'wsgi.something'. >Like I said, I don't want to make this a big complicated process, I do. :) Well, actually, I suggest that there be a *really* simple process: just publish your own specs under your own package namespace, announce it to Web-SIG, and let other people use it if they like it. But if you want to play in the wsgi.* namespace, it *should* be a big complicated process. >People are always free to >ignore these specifications, so it's really just as much a matter of >getting a couple people to agree on some useful compatibility, Great. But let's please do it *outside* the wsgi.* namespace, and remember that if you share *implementations*, you don't need to duplicate any code, or have as much discussion about how stuff works inside. People will either like it or not, and use it or not. That's as low of a process bar as can be managed. It's probably the case that some people don't feel that their extension is as valued by the community if it doesn't go in wsgi.*. But that's just their lack of self-esteem talking. If I ever come up with WSGI extensions, they're going to go under my name or a framework name. If two or three other frameworks copy me, *then* I might talk about proposing adding it to the wsgi.* space, and I still wouldn't expect the proposal to get a free pass from the Web-SIG just because it's me. To be honest, I don't think that the routing_args thing is *really* worthy of a wsgi.* namespace, it's just that with its problems fixed, it's not so much of a threat that it's worth fighting over. And to some extent, I'm giving it a pass because it's you. ;) But if this is just the start of a wave of people demanding that *their* extensions get in too, then I'm all in favor of slamming the door on it to help keep the rest out. IMO, wsgi.* standardization needs a PEP-sized or stdlib-inclusion-sized bar to it, since everyone is perfectly free to use their own namespaces for extensions, even ones they intend to offer as published interfaces for others to conform to. >and not >everything has to be universally applicable or useful. If you're going to put it in 'wsgi.*', I think it must at least "do no harm". I'm okay with the wsgi.routing_args thing, because at worst it's superfluous. The POST stuff, I still think is dangerously likely to be overused. Overenthusiasm for standardization is dangerous at this stage of WSGI's adoption. WSGI itself is still not well-understood by the Python developer audience at large; for example, a recent IBM Developerworks article about WSGI contained some *serious* errors in its example middleware, which was terribly non-compliant, as the author would've seen if he'd run it with wsgiref.validate or paste.lint on both sides of it. I guess what I'm saying is, it's bloody hard enough sometimes just to get people to write things that actually conform to the spec we have now, without adding a bunch of new ones. (Hell, we should probably require that proposed "standard" extensions include patches to wsgiref.validate that verify correct operation of the extensions!)
http://mail.python.org/pipermail/web-sig/2006-November/002324.html
crawl-002
refinedweb
879
62.27
AS3 Tutorials Novice Contents 1 Introduction This article is part of the Actionscript 3 tutorial series. Make sure you also run through the section on Compiling a program. You may want to print that page and keep it at hand as you will need to repeat the process for each example given in these tutorials. 2 Stage 1 : (Absolute) Novice I don't know for you. I tend to learn best by doing. What gets me through complex learning is the desire to realize things. Of course, it is very important to take the time to understand complex notions thoroughly. However if you are too much worried about understanding every single aspect of the programming language before writing your first line of code, chances are high that you will give up before reaching that point. If you reach that point, the risk is that your head will be so full of unfamiliar concepts that you will completely unsure about what you should be doing next, what option to take. Something that I find to work for me is to take a tutorial or book about the language, read it through without trying to understand everything. I do my best to understand the introductory paragraph of each chapter and to browse through the code trying to grasp the gist of how things get done. That's absolute novice stage. I would wait for Beginner stage to read each chapter in details. I will read chapters one by one and not move to the next chapter until I feel that I understand all concepts well enough. I will also take the time to hand code (rather than copy and paste) the simple examples proposed in that chapter. I will start to explore and attempt to write variants of these simple examples, adding a new element each time or trying to merge two examples together to produce a more complex result. I will then move to the next chapter. If I chapter is too difficult or the content of limited interest, I go through it rapidly and move on. Then Intermediate stage. Once I become familiar enough with the basics I try to come up with an idea of a little program that I could write that would make use of many of these basic elements. I attempt write the program... I don't give up before I have finished writing it. I don't read the book sequentially anymore. I mostly use the index at the back of the book to try and locate the information I need to solve the problems that I set to myself. Once I am okay with writing an original program, I try and come up of ideas of various types of games, learning activities or mini-apps that I would like to become able to realize. I evaluate which one I can write successfully with what I already know. I evaluate what new concepts I need to master and the likelihood that I can get to learn these concepts in a short enough amount of time. I go for the most realistic options. For now, we are at novice stage. The priority here is to develop your familiarity with actionscript code. You are not expected to be able to write a program from scratch, only to give a try at modifying a few values or slightly reorganizing a few lines of code. In this view, what we will do next is : - provide a simple program that is guaranteed to work (copy/paste/compile/run). - invite you to try and write variants - introduce a small number of examples that each introduce a specific technique Then we will move onto Beginner level and give you an understanding of how things work as well as provide you with the minimal skills you need to write your own code. 2.1 First words We mentioned that ActionScript has become a serious Object Oriented language with version 3. The problem then, for an absolute newbie, is that the use of Object Oriented constructs are not optional. They are mandatory. The consequence of this is that any ActionScript programs contains elements that are somehow puzzling for the person who only started programming. Don't worry about this. For now, at this complete novice stage, consider them as magical incantations. In the age of Harry Potter or Eragon, we all know that magical incantations need to be precisely reproduced, each bit must be correctly spelt. Otherwise you have the risk of unwelcome results. In a programming set up, the awkward results are called errors. They pop on the screen to tell you that your program didn't work and these error messages won't get away until you incantation is correct in every way. Sometimes they let your program run but with completely unexpected results. You wanted a rabbit to pop out of your hat and you got a snake instead! Yuk! Sometimes they prevent your program from running altogether. That's the major difficulty when learning a serious programming language. You need to get these incantations correct or your program won't run. Any person who has followed a bit of training in magic however knows that magical incantations are not in fact unbreakable constructs. They are made of parts that can be combined in different ways to give various results. It goes the same with programming. As soon as beginner stage, we will start to explain what the parts are and how they work. For now, what matters is to get you started. It's a bit like arriving in a new city, for example to go to University. The first week is spent wandering around to try and locate the grocerer, the bank, the post office and other facilities. At Novice level, we will invite you to do exactly this. Wander about, get some kind of global mental map of the new environment you will get to live in for the next few months and perhaps the next few years. If you were to go to live to London, Australia, or Japan, you would need to get used to driving on the left side of the road. When you program in ActionScript 3, what you have to get used to is declaring classes and packages, as explained below. Like riding on the left side of the road, this sounds *very* weird and *completely* unnatural at first. You will progressively get used to it, though. 2.1.1 Everything needs to be organized into classes In ActionScript 3 *Everything* needs to be organized into classes. You must have at least one class in your program. This can appear quite obscure at first. But because the class definition always uses the same format, that's simply a question of getting used to add these extra lines in your code. Initially you will write short programs that don't justify the use of more than a single class. Don't worry if you don't understand that class concept yet. What matters is that you start going, start writing a bit of code and become able to play around. We will explain the concept of class soon enough. // The class definition public class Game { // instance variable of type integer var score:int // The constructor method public function Game () { // code that initialize Game instances } // instance method public function updateScore ():void { // code to execute when updateScore () is invoked } } 2.1.2 Classes need to be placed in a package With the class-based organisation comes another concept, the one of package. A package is a conceptual container. It is used to group classes that operate together within a physical region of their own. Its main function is to help organize the code for large applications. The recommendation here is the same as for classes. In a first time, simply use the syntax without worrying too much about not understanding what it is for. For a few days or weeks, you are likely to write programs that stand within a single package. All you need to know, therefore, is that for a program to run, you must enclose each class in a package. You can provide a pathname to point to a given region in your codespace. If you don't need different regions, you can simply use the package declaration on its own. package { // The class definition public class Game { // instance variable of type integer var score:int // The constructor method public function Game () { // code that initialize Game instances } // instance method public function updateScore ():void { // code to execute when updateScore () is invoked } } } 2.2 Requirements Make sure you first run through the section on Compiling a program. You may want to print that page and keep it at hand as you will need to repeat the process for each example given in these tutorials. 2.3 Tips Don't forget that there is a list of AS3 Useful links you can consult at any point. 2.4 Let's go exploring! - AS3 simple examples: introduce a small number of examples that each introduce a specific technique. You should follow these example tutorials in the same order. - AS3 example Drawing graphics - AS3 example Message Box, mixing graphics and text on the screen - AS3 example Button - AS3 example Positioning - AS3 example Drag and Drop - AS3 example Keyboard control - Video: Learn The Basics of setting up a project in AS3/Flash Enjoy !
http://edutechwiki.unige.ch/en/AS3_Tutorials_Novice
CC-MAIN-2018-30
refinedweb
1,564
70.73
MATLAB’s Mersenne Twister Random Number Generator: Seed 0 gives the same numbers as Seed 5489 This shows one way of dealing with the need for many independent streams Skipping Ahead the Mersenne Twister Random Number Generator Reading your post I checked the C version of Mersenne Twister: I commented the code in main, and set succesively the two seeds and printed 5 values for each. As expected the two seeds led to different sequences of random numbers. but with these lines: int i; init_genrand(5489);//set the seed for(i=0;i<10;i++) printf("\n %1.15lf ", genrand_real2()); I've seen that compared with the 5 values returned by MATLAB rand function (and np.random.random) it appears that MATLAB (Numpy) returns vals[2*i], i=0, … from those given by C code ~/AA2014$ gcc mt19937ar.c -o mersenne ~/AA2014$ ./mersenne 0.814723691903055 0.135477004107088 0.905791934113950 0.835008589783683 0.126986811868846 0.968867771094665 0.913375855656341 0.221034042770043 0.632359249982983 0.308167050359771 @Themos Say I use that routine to produce independent streams by skipping ahead by 2^N. I now know for sure that if I generate more than 2^N numbers in a stream, I am going to have problems. So, I just need to make sure I generate less than 2^N. All good stuff. I have a question, however. Does the routine keep track of the number of calls I’ve made to it, and warn if I’ve made too many, or do I need to do it manually? Hello Mike, the answer is “manually”, we don’t track consumption. But it should be pretty straightforward to encapsulate the underlying functionality in a module that does. By the way, I recently came across a case where a RNG user unwittingly “sabotaged” the RNG by selecting a starting state (a “seed”) with extremely low entropy. In modern very-long-period RNGs this is something users need to be educated about. As a colleague put it “[setting the seed] is useful for restarting the generator with the same sequence it had before, unless you are an expert in THAT PARTICULAR GENERATOR the only possible result of [starting the generator] with a user-specified seed is to make things worse.” @Themos – which RNG was that for? In the implementations of MT used in MATLAB, Python etc, the entire state is encoded in just one integer. How this maps onto the actual state, I have no idea. @Mike, the Mersenne Twister inside NAG’s Fortran compiler. It provides full access to the entire RNG state, all 634 32-bit integers. What follows is the part of the manpage nagfor(1) RANDOM NUMBER ALGORITHM The random number generator supplied as the intrinsic subroutine RANDOM_NUMBER is the “Mersenne Twister”. Note that this generator has a large state (630 32-bit integers) and an extremely long period (approx 10**6000),). Do you know how those 630 integers get mapped to 1 in the implementations discussed here? Badly? :-) I hope its not too bad since it seems that this mapping is used by several major implementations. Hm afaiu, this is a special matlab behavior that you’ve got nowhere else! Not in ruby, nor in numpy, nor in octave. in octave, the seed function is made by old fortran fuction. will fix it. the result is equal to numpy and ruby than (and for 5489 to matlab too). octave:8> rand(‘twister’,twister_seed(5489)) octave:9> rand(5,1) ans = 0.814723686393179 0.905791937075619 0.126986816293506 0.913375856139019 0.63235924622541 octave:10> rand(‘twister’,twister_seed(0)) octave:11> rand(5,1) ans = 0.548813503927325 0.715189366372419 0.602763376071644 0.544883182996897 0.423654799338905 You can get the 624 (623?) integers that constitute the state of Mersenne-Twister PRNG: ### MATLAB: % rng(1) % seed r = rng; disp(r.State) % 625×1 uint32 array (624 + 1 integer position) ### Python: # import numpy as np np.random.seed(1) # seed np.random.get_state() # tuple contains array of length 624, position, other things .. I tried this in R, but the state is encoded as an array of signed integers, so I’m not sure how to it matches with the unsigned integers from MATLAB and NumPy: ### R # set.seed(1) # seed .Random.seed # state vector of legnth 625 # (I think the second element denotes the current position) As to how we map the seed number into the state vector, the Wikipedia article has a pseudocode for the mapping function: // // Initialize the generator from a seed function initialize_generator(int seed) { index := 0 MT[0] := seed for i from 1 to 623 { // loop over each other element MT[i] := lowest 32 bits of(1812433253 * (MT[i-1] xor (right shift by 30 bits(MT[i-1]))) + i) // 0x6c078965 } }
http://www.walkingrandomly.com/?p=5480
CC-MAIN-2014-52
refinedweb
786
70.73
#include <SimpleModbusSlave.h>/* SimpleModbusSlaveV10 supports function 3, 6 & 16. This example code will receive the adc ch0 value from the arduino master. It will then use this value to adjust the brightness of the led on pin 9. The value received from the master will be stored in address 1 in its own address space namely holdingRegs[]. In addition to this the slaves own adc ch0 value will be stored in address 0 in its own address space holdingRegs[] for the master to be read. The master will use this value to alter the brightness of its own led connected to pin 9. The modbus_update() method updates the holdingRegs register array and checks communication. Note: The Arduino serial ring buffer is 64 bytes or 32 registers. Most of the time you will connect the arduino to a master via serial using a MAX485 or similar. In a function 3 request the master will attempt to read from your slave and since 5 bytes is already used for ID, FUNCTION, NO OF BYTES and two BYTES CRC the master can only request 58 bytes or 29 registers. In a function 16 request the master will attempt to write to your slave and since a 9 bytes is already used for ID, FUNCTION, ADDRESS, NO OF REGISTERS, NO OF BYTES and two BYTES CRC the master can only write 54 bytes or 27 registers. Using a USB to Serial converter the maximum bytes you can send is limited to its internal buffer which differs between manufactures. */#define LED 9 // Using the enum instruction allows for an easy method for adding and // removing registers. Doing it this way saves you #defining the size // of your slaves register array each time you want to add more registers// and at a glimpse informs you of your slaves register layout.//////////////// registers of your slave ///////////////////enum { // just add or remove registers and your good to go... // The first register starts at address 0 AB, AC, HOLDING_REGS_SIZE // leave this one // total number of registers for function 3 and 16 share the same register array // i.e. the same address space};unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array////////////////////////////////////////////////////////////void setup(){ /* parameters(HardwareSerial* SerialPort, long baudrate, unsigned char byteFormat, unsigned char ID, unsigned char transmit enable pin, unsigned int holding registers size, unsigned int* holding register array) */ /* Valid modbus byte formats are: SERIAL_8N2: 1 start bit, 8 data bits, 2 stop bits SERIAL_8E1: 1 start bit, 8 data bits, 1 Even parity bit, 1 stop bit SERIAL_8O1: 1 start bit, 8 data bits, 1 Odd parity bit, 1 stop bit You can obviously use SERIAL_8N1 but this does not adhere to the Modbus specifications. That said, I have tested the SERIAL_8N1 option on various commercial masters and slaves that were suppose to adhere to this specification and was always able to communicate... Go figure. These byte formats are already defined in the Arduino global name space. */ modbus_configure(&Serial3, 9600, SERIAL_8N2, 1, 4, HOLDING_REGS_SIZE, holdingRegs); // modbus_update_comms(baud, byteFormat, id) is not needed but allows for easy update of the // port variables and slave id dynamically in any function. modbus_update_comms(9600, SERIAL_8N2, 1); pinMode(LED, OUTPUT);}void loop(){ // modbus_update() is the only method used in loop(). It returns the total error // count since the slave started. You don't have to use it but it's useful // for fault finding by the modbus master. modbus_update(); holdingRegs[AB] = 45; // update data to be read by the master to adjust the PWM analogWrite(AC, holdingRegs[2]>>2); // constrain adc value from the arduino master to 255 /* Note: The use of the enum instruction is not needed. You could set a maximum allowable size for holdinRegs[] by defining HOLDING_REGS_SIZE using a constant and then access holdingRegs[] by "Index" addressing. I.e. holdingRegs[0] = analogRead(A0); analogWrite(LED, holdingRegs[1]/4); */ } when i set the both side to 9600 baud rate , then i can sucsessfully send the request and give response from slave .but if i chance the parity type or numbers of stop bits in masters side , there will be no difference in results . i mean it works successfully in every situation and every stop bit number and every parity type, In this case I guess you're using an USB to RS485 adapter that uses the CH340/341 chipset. At least the drivers for Windows and Linux simply ignore the parity and stop bits settings. On the Linux side this is because no official documentation for that chipset exists and the current driver got it's information from reverse engineering the Windows driver. Get an adapter with a working chipset (p.e. FTDI) or create your own by using a USB to serial adapter (of course with a different chipset than the CH340/341) together with a UART to RS485 adapter.I eliminated all CH340 version from my toolset because of that undocumented and silently denying functionality. Sending two stop bits is just a timing issue. Any modern UART should still be able to receive either one or two stop bits.It's also very common for devices to ignore parity errors.So it isn't that strange that it still works even when you change those values. There isn't a 9th bit for parity. If parity is used it is the high order 8th bit of the 8 bits of data. 8E1 means 8 data bits #define SERIAL_8E1 0x26 A frame starts with the start bit, followed by the data bits (from five up to nine data bits in total): first theleast significant data bit, then the next data bits ending with the most significant bit. If enabled, the paritybit is inserted after the data bits, before the one or two stop bits.
http://forum.arduino.cc/index.php?topic=553118.msg3772903
CC-MAIN-2018-51
refinedweb
954
57.2
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. On Fri, Nov 30, 2001 at 12:11:30PM -0400, Brad Spencer wrote: > > Even if the off-the-cuff idea above were implemented -- and it /is/ ugly > > as sin :-) -- we couldn't recommend that users make use of names in the > > implementation namespace. They'd have to be wrapped and exposed somehow. > > Perhaps in ext? Oh, definitely in the ext directory. But we also need to choose a namespace, and type names inside that namespace, and then maintain them. (Although perhaps we don't need to be as careful about maintain extensions as we must be about maintaining the standard ABI.) The only drawback to putting extensions in namespace __gnu_cxx is that it /also/ has the leading-underscore name, and thus screams "stay away" to smart programmers. :-) Maybe "namespace gnu_ext" or "namespace gnu_ext = __gnu_cxx". >. Ah. Good point,
http://gcc.gnu.org/ml/libstdc++/2001-11/msg00341.html
crawl-001
refinedweb
154
73.88
OpenCV cv2.minMaxLoc() is often used to find the maximum and minimum value in a numpy array. In this tutorial, we will use an example to show you how to use this function. Look at this example: import numpy as np import cv2 a=np.array([[1,2,3,4],[5,67,8,9]]) We have created a numpy array a, which is 2*4. In order to find the maximum and minimum value in a, we can do like this: min_val,max_val,min_indx,max_indx=cv2.minMaxLoc(a) print(min_val,max_val,min_indx,max_indx) cv2.minMaxLoc() will return four values: min_val: the minimum value max_val: the maximum value min_index: the index of minimum value in a max_indx: the index of maximum value in a Run this code, you will get: 1.0 67.0 (0, 0) (1, 1)
https://www.tutorialexample.com/learn-python-opencv-cv2-minmaxloc-by-examples-opencv-tutorial/
CC-MAIN-2020-45
refinedweb
137
65.73
All of our programs so far have lived entirely inside the main() function. In other words, all the code was in one big pile. So far this has not been much of a problem because our programs were small. But we did use functions that others have written. For example, we have used cmath’s pow() and sqrt() functions. Even cout and cin are functions, though they are quite a bit more complicated and a little bit special (actually, the stream operators << and >> are functions too, as we’ll see several weeks from now). If we did not have, say, sqrt(), at our disposal as a function, we would need to include our own code for sqrt() (using an approximation method like Newton’s) in our big pile of code in main(). This is undesirable. Functions allow the programmer to modularize and isolate code, so that in any single function, only one task is being performed. This generally makes code more understandable. Additionally, writing a function allows one to potentially hide code. A function can be compiled and provided (in machine-readable form, but not human-readable form) to other programmers. This is very common; e.g., Microsoft provides many functions specific to Windows that others can use (to write their own Windows programs) but that others cannot read. You can think of a function as simply code that has a name. The name of some chunk of code is what the code does. For example, the sqrt() function contains only enough code to find the square root of a number. Where to write your own functions For now, we will write functions in the same file as main() so that our programs still consist of just one file. Programs need not be just one file, however, and in the future we will explore ways to split up code into multiple files (by putting functions in different files). Functions can be defined above main(), or they can have just a prototype (or signature) above main() with the function definition below main(). (Function definitions cannot be placed inside other functions, although prototypes can.) Here are examples: #include <iostream> using namespace std; // this is an example of a function fully defined above main() double timesTwo(double x) { return 2*x; } int main() { cout << timesTwo(4.5) << endl; } #include <iostream> using namespace std; // this is an example of just a prototype above main() // the function code itself is below main() double timesTwo(double); int main() { cout << timesTwo(4.5) << endl; } double timesTwo(double x) { return 2*x; } The importance of where the function is defined and defined (above main() or not) is that the compiler requires that either the function prototype or the whole function itself is found above the code that uses the function. If you try to use a function called timesTwo() but the compiler has not seen any function by that name yet (either as a prototype or definition), then you get a compiler error. Function return types and parameter types Every function must have a return type (e.g. int, double, etc.), or the function could be a void function, which means we write void instead of a return type ( void is not technically a type). The return type goes before the function name. If the function is not a void function, then the code inside the function must use return somewhere, returning a value of the proper type. A void function does not need the return command; it can include the return command (this causes the function to terminate) but cannot use return to return a value. A function may have parameters. But it need not. A function that has no parameters has empty parentheses. A function that has two int parameters would have int x, int y in the parentheses. The x and y names are usually not written in the function prototype (though they can be). The x and y should be included, however, when the function is being defined. The x and y names exist only inside the function. Assume a function is called add and it has two int parameters. This is what it looks like: int add(int a, int b) { return a+b; } Then when the function is called (say, from some code in main()), two integer values must be provided as arguments: add(4, 12) (the result of that function call is 16, naturally). Inside the function, the 4 is assigned to the variable name a and the 12 is assigned to b. This a and b exist only inside the function. Consider this example: #include <iostream> using namespace std; int add(int a, int b) { return a+b; } int main() { int a = 15; int b = 20; cout << add(a, b) << endl; } The a and b inside main() are different variables than those inside add(). Even if the code inside the function add() decided to change the values of a and b, it would only change the values for the variables known by those names inside the add() function, not those known by those names inside main(). The function add() cannot access the variables declared inside main(). Since the variables inside a function are not the same as those inside a different function, they need not have the same names: #include <iostream> using namespace std; int add(int someSillyNameX, int someSillyNameY) { return (someSillyNameX + someSillyNameY); } int main() { int a = 15; int b = 20; cout << add(a, b) << endl; } Note that function names (e.g. add) have the same restrictions as variable names (i.e. they cannot start with a number or special symbol, etc.). Function calling & parameter passing The functions demonstrated above use call-by-value, which means only the value of the arguments is provided to the function. Here is the textbook’s explanation of how call-by-value works: It is the values of the arguments that are plugged in for the formal parameters. If the arguments are variables, the values of the variables, not the variables themselves, are plugged in. The first argument is plugged in the for the first parameter, the second argument is plugged in for the second parameter, and so forth. Functions can also use call-by-reference. If a function uses call-by-reference, then it receives not just the value of an argument but also the memory location of the original variable. All variables keep track of their memory location so they know where their value is stored in memory. When a variable is updated or assigned, the value in the variable’s memory location is changed. When a function uses call-by-reference, it also has access to the memory locations that the original variables (in the calling function) used. So the function can change the values in those memory locations. Here is an example of a function that uses call-by-reference. It’s the “increment” function, which means it takes an integer parameter and increases that integer by one. #include <iostream> using namespace std; void increment(int &x) { x++; } int main() { int a = 5; increment(a); cout << a << endl; return 0; } You know the increment() function uses call-by-reference for its single parameter because that parameter has an & in front of it. When main() calls increment(), the variable a (inside main()) is passed by reference to the function. The function does not name this variable (and its memory location) “a” but instead names it x. Otherwise, they are the same variable. Any changes to x inside the function cause the same changes to a inside the calling function (i.e. main()) because x and a use the same memory location to store their value. We say this is a case of “call-by-reference” because it’s not the value of a that is being provided to the function (like it would be if we left out the & and therefore had a call-by-value parameter) but rather the memory location to which a refers. A function can have a mix of call-by-reference (or “pass-by-reference”) and call-by-value parameters. For example, this function updates two variables w0 and w1 (which are passed by reference, so that they can be updated) depending on the value of another variable y (which is just passed by value): void updateXYZ(double &w0, double &w1, double y) { if(y < 0.0) { w0 = w1 = 0; } else { w0 = pow(w0+w1, 2.0); w1 = pow(w0-w1, 2.0); } } Pointers as parameters to functions The C language (which came before C++) didn’t have “call-by-reference,” so in order to make a function that could change the values of its arguments, pointers were used: void changeValues(int *px, int *py) { // add one to each variable pointed to by the parameters *px = *px + 1; *py = *py + 1; } C++ can do the same thing (although how the function is used must change): void changeValues2(int &x, int &y) { // add one to each variable x = x + 1; y = y + 1; } These are equivalent except in how they are used. Here is how the C version (which uses pointers) is used: int x = 5, y = 8; changeValues(&x, &y); Note that you have to provide the “memory location” of the variables x and y to use the function that has pointer parameters. The C++ version (call-by-reference) can be used in a more straight-forward manner: int x = 5, y = 8; changeValues2(x, y); This is why call-by-reference is useful; it makes the code a little simpler, but has the same effect. An example from class: TimeAdder // This program adds a specified number of minutes // to a specified time (given in 24-hour format), // and displays the result, after converting // the resulting time to 12-hour format. #include <iostream> using namespace std; // convert a 24-hour time to a 12-hour time, // and set ampm equal to P or A void to_am_pm(int &hour, int minute, char &m) { if(hour > 12) { ampm = 'P'; hour -= 12; } else { ampm = 'A'; } } // add a specified number of minutes to // a time; set hour and minute to the // resulting time; note that hour may // become greater than 12, and in cases // when adding lots of minutes, may become // greater than 23 // // refer to the to_am_pm() function to // convert the result from 24-hour time // to 12-hour time void add_min(int &hour, int &minute, int min_to_add, char &m) { int plus_hours = min_to_add / 60; min_to_add %= 60; hour += plus_hours; minute += min_to_add; to_am_pm(hour, minute, ampm); } int main() { int h, m; cout << "Enter hour (0-23) followed by space " << "followed by minutes (0-59): "; cin >> h >> m; int min_to_add; cout << "Enter minutes to add: "; cin >> min_to_add; char ampm; add_min(h, m, min_to_add, ampm); cout << "Final time is " << h << ":" << m << " " << ampm << "M" << endl; return 0; } Functions inside classes (“methods”) We can put a function inside a class; in this case, the function can only be used on an existing object of that class. Recall the Person class: class Person { public: string name; int age; // in years int height; // in cm int weight; // in kg }; Let’s add a function that prints the person’s weight: class Person { public: string name; int age; // in years double height; // in cm double weight; // in kg void printWeight() { cout << name << " weighs " << weight << " kg." << endl; } }; Suppose we have an object: Person vignesh; vignesh.name = "Vignesh S."; vignesh.age = 25; vignesh.height = 177; vignesh.weight = 68; We can use the printWeight() function in the following way, using the object as the prefix (just like when we set values like weight): vignesh.printWeight(); Or, we can add a function that returns the weight in pounds: class Person { public: // ... double getWeightPounds() { return (2.204 * weight); } }; And we can use it like so: double pounds = vignesh.getWeightPounds(); A final word It is surely time to recover the original sense of “argument” (via Latin arguere, to put in a clear light) as “clarification, proof.” The depressing confusion over name/value calling, between real/formal arguments and/or parameters, and how/when/where they are initialized and/or assigned must be resolved here and now. Remember: if you pass by name, the function can corrupt your actual argument, but if you pass by value, the function can only corrupt a copy of your argument. Some sophisticated languages let you pass explicit pointers, pointers-to-pointers, references, references-to-pointers, pointers-to-references, and so on to any depth (whence the phrase “beyond fathomage”), allowing the function to corrupt not only your arguments and their copies, but also those of your erstwhile friends running in distant parts of the system. It’s your call, as they say. – The computer contradictionary
http://csci221.artifice.cc/lecture/functions.html
CC-MAIN-2020-05
refinedweb
2,106
66.17
This to load image from local disk, and how to load image from Internet. First example is how to load an image from disk, then I’ll show how to modify it, to load image from Internet. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; import javafx.stage.Stage; /** * * @author zoranpavlovic.blogspot.com */ public class LoadImage extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Load Image"); StackPane sp = new StackPane(); Image img = new Image("javafx.jpg"); ImageView imgView = new ImageView(img); sp.getChildren().add(imgView); //Adding HBox to the scene Scene scene = new Scene(sp); primaryStage.setScene(scene); primaryStage.show(); } } Okay, what if you want to load a image from some Internet location? Well, that can be also easily done, just modify this line of code. The result will be same. Image img = new Image(""); What if I want to dynamically choose the file from filechooser and upload it in the imageview if you want show from specified file ,you can use Image me = new Image(” file://”+fileway.toString); a lot of tutorial doesn’t show where to put the image file ?! so where :)
https://www.javacodegeeks.com/2013/10/javafx-2-how-to-load-image.html
CC-MAIN-2017-22
refinedweb
216
52.97
Image: from the 1989 annual report. From 1983 to 2015, every woman, man, kid, and baby received an Alaska Permanent Fund Dividend check with an amount calculated by a 1982 law. It was rarely questioned publicly until the last five years because of ample petroleum revenues and several years of cushion thanks to the billions in the Constitutional Budget Reserve (now just fumes.) A former APFC website via waybackmachine. Thanks in part to a booming stock market that prescribes a big dividend (around $3,000 per citizen), a reckoning for the 1982 calculation has begun. Maybe. By many descriptions, it’s “full,”, “lawful,” and “traditional” payout. Others call the same statutory dividend going forward is “unsustainable”, or “irresponsible”. In testimony to an Alaska House committee this year, after admonishing the legislature, a citizen in seven words laid the foundation for what I want to explore. “Do NOT mess with the Permanent Fund!,” wrote the Soldotna resident. “The original formula has worked just fine.” Educational materials from the 1990 annual report Does the statutory dividend serve “all generations of Alaskans”? Putting aside the use of the fund’s earnings for non-dividend purposes, my primary interest is about how the 1982 dividend calculation affects the funds’ long term health and earnings power. Does this reliance on a rolling five-year average result in a measured withdrawal? Or can it push it to its limit, where successive draws lead to a shrinking or disappearing fund? Because it’s called the “Permanent Fund,” and the founding legislation of the fund calls for the fund to “benefit all generations of Alaskans,” I wanted to dig into how this statutory dividend has worked over the years and ask about its relevance in the long term, given the fund’s dual role laid out in state law as both a “savings device” that is managed to “allow the maximum use of disposable income.” (AS 37.13.020). Or more specifically, should a $65 billion fund that now has billions in tech stocks, Asian venture capital funds, biotech startups, and Snapchat be expected to grow while paying out a dividend formula designed when the fund was essentially $3 billion in bonds and government treasury bills? Image: APFC office in the 1984 annual report Alaskans have gotten to know the Permanent Fund through nearly four decades of dividends. With the exception of the first year and the last three, all dividends have been determined by the 1982 calculation. Since the mid 1990s, rarely has the dividend been below $1,000. The fund overall has grown from royalty payments in the early years and from stock market gains in recent years. The Formula Feel free to skip this section if you know it like the back of your hand. In a very simplified manner the amount is calculated based on a five-year average of the fund’s earnings, which sounds simple and downright sensible (to be dissected later). To be precise, it’s half of 21% of the fund’s realized earnings and interest over the past five years, minus expenses and previously owed dividends. It’s finally divided by the number of eligible Alaskans. Earnings are Volatile This is what annual statutory net income looks like since 1982. The traditional calculation’s five-year rolling average serves to dampen the peaks and troughs. If the dividend formula were based only on the current year’s earnings, there would be years of feast and famine, including nothing in 2009. Beneath these earnings has been a quiet four-decade transformation from a young oil savings account to a globally significant sovereign wealth fund with investments, earnings patterns, and risk strategies the 1982 Alaska Legislature could not have imagined. 1984 Annual Report The 2019 Permanent Fund Looks Nothing Like the 1983 Permanent Fund At the time of the dividend calculation law’s passage, the Permanent Fund was basically a $3.3 billion in U.S. treasury bills, government bonds, and CDs. Fund managers were first allowed to invest in the stock market in 1982, but they did it with a slow ramp up. The 1982 annual report described the cautious approach of the early days of the fund. “Confronted by high inflation, highly volatile markets, and significant economic uncertainty, the trustees chose to adopt a conservative investment approach…as a result of the invest emphasis being placed on very short maturities, the Permanent Fund was essentially operated as a ‘money market fund’ until 1982.” A decade after its founding, only 12% of the fund was invested in the stock market in 1988. A full 83% was in bonds and treasuries, with the remainder in real estate. It wasn’t until 1990 that the fund was legally allowed to buy foreign stocks and bonds. But the 1990s saw both a roaring stock market and an appetite for more risk. By 2000 the target equity allocation was up to 54%. Starting in 2004, the fund had begun to invest millions into alternative assets that require sophistication, patience, and the willingness to stomach risk. The fund put money into absolute return strategy funds (hedge funds) and private equity: non-listed, often distressed companies that managers seek to reinvent after slashing costs. (What Mitt Romney used to do). They also gave the fund entry into venture capital funds that invest in early stage startups. As the housing market peaked in 2007 and the US stock market reached all-time highs, the fund’s target asset allocation dedicated 6% to private equity and 6% absolute return (hedge funds). The 2019 portfolio is a vast web of active stock managers, funds of funds, complex debt instruments, tech startups, infrastructure bets, and foreign real estate, in addition to a lot of stocks and bonds. The days of predictable earnings from bonds are long over. Earnings are Getting More Volatile You can see a bit of an inflection point in the mid 90’s when a surging stock market (followed by the bursting of the tech bubble, a downturn, and the leadup to the 2008 financial crisis). The latter years should be expected to show a larger standard deviation due to growing assets . Below I have divided the five-year standard deviation by the fund value for a better comparison. Volatility should be expected in an investment account that is saving for the long term. It’s the price of admission for assets that you expect to beat inflation and hope to reward you a premium for the risk you bear. But the Permanent Fund’s owners (Alaskans) also expect to be paid on an annual basis with the dividend. What Sort of Draw is Sustainable? In the personal finance world, people talk about their “safe withdrawl rate,” the annual percentage of one’s funds that they can reasonably expect to last them through a 30 or 40 year retirement. The generally acccepted rule is 4 percent. It fails (goes to zero) in some bad market outcomes and does great in many market simulations. As of last year, Alaska has a law that caps spending at 5.25% of a rolling fund value, but there has been no real limit in place up until now. (For simplicity, I show the draw as a percentage of the respective year value). Here’s how the past dividends compared After several years of lawsuits, when the first dividend appeared in 1982, it was by far the biggest draw relative to fund value. The $470 million spend on dividends ($1,000 per Alaskan) represented 14.3 percent of the fund’s value, however it was not paid from the fund, but rather from general fund dollars the legislature appropriated. In the above chart, 1982’s dividend sucks all of the air out of the room. Here are the dividends without the first year: There is huge variation in the percent of market value of each year’s dividend, ranging from more than 4% to 1%. After 1982, the next largest is 1988’s draw at 4.5% for a $826.93 dividend. In 2001, the $1,850.28 dividend represented a 4.3 percent chunk of the fund. While the median draw is 3.2 percent, for seven years the draw was above 4 percent. The draw was below two percent in another seven years. The lowest draw as a percentage of the fund was 2017’s dividend, representing just 1.1 percent of the fund’s value. While the fund has not faced a massive draw in the nearly 40 years of dividends, the relative instability of draw size complicates life for managers trying to protect principal (and maximize earnings) as well as legislators thinking about how to budget. Dividend Size Does Not Predict Payout Percentage The chart below is not adjusted for inflation/state population/or fund size, but we can see that similarly sized dividends (from the resident perspective) can represent vastly different draws. In 2014, the $1,884 divided captured 2.3% of the fund, while the similarly sized 2000 dividend of $1,963 represented 4.3% of the fund’s entire assets. The former would not rattle many endowment managers, while the latter may push them to the edge of their comfort. While the corpus is protected under the constitution, sustained overdraws that drain the earnings reserve dramatically lower the fund’s earnings power and viability of dividends. As the fund has grown in value, we’ve seen a decoupling of fund value and dividend size, beginning in the last half of the 1990s. (2016, 2017, and 2018 dividend amounts were decided by the Governor and Legislature, not the 1982 formula.) Under the Hood on SNI Stock dividends and bond interest count as income under the 1982 law. But there’s a human factor too: for earnings to be realized (for example, shares of Amazon stock that have gone up 1,000% over the past several years)the manager must actually sell it. There are billions in unrealized gains sitting the fund’s principal that don’t affect the statutory earnings calculation. A 2007 Commonwealth North report highlighted the conflict that arises from the 1982 payout calculation. “The realized earnings of the Fund—and therefore the payout for dividends—are disconnected from the value of the Fund. As the market is going up, the amount of the Dividend often goes down, and vice versa….In short, the current method for calculating income is outdated.” Image: 1983 annual report Earnings amounts are linked to fund spending (dividend calculation), but don’t necessarily fully reflect the health or standing of the overall fund. This sounds like a footnote, but it’s important to the fund’s long term health for a couple of reasons. The alternative to the earnings based payout is the endowment style, Percent of Market Value (POMV) approach that limits draws to a small portion of the fund, like the “safe withdrawal amount”. Marc Langland, former APFC chair wrote in the 2002 Trustees Papers that POMV would “free Permanent Fund managers from the need to cash out investments in order to fund the dividend at a time when holding the investments would maximize long term earnings.” Langland pointed out that using a percentage could have a stabilizing effect, by “severing its tie to the realized income of the fund and by dampening its connection to fluctuations in the stock and bond market.” POMV: Problem Solved? or Conflicting Laws The 2018 Alaska Legislature passed a law that limits the total draw (funding for government as well as dividends) to 5.25% of its rolling fund value now and going down to 5% in 2021. This POMV-based law is in line what the Permanent Fund Trustees have been seeking for decades, although critically it is not a constitutional amendment, as they requested in 2001 and many times since then. While I am not a lawyer, this statute has the same standing as the 1982 law that sets dividends. The Supreme Court ruled a couple years ago that the legislature’s appropriation powers extend to the dividend. By the same margin that the Alaska Legislature designated Marmot Day and established the new license plates with a bear, it can spend the entirety of the earnings reserve and go far beyond sustainable spending rates. While the principal of the fund can’t be spent, the earnings from the fund can be spent with a simple majority vote. Under several scenarios (see post script), big drawdowns could undercut the earnings reserve, fund earning potential, and the entire dividend program. Image: Cryptic projection from the 1989 Annual Report POMV should largely protect against overspending, however, there are scenarios that were presented to the Legislature in which the 5% (or 4%) annual spend drains the earnings reserve to nothing over the course of a handful of years. To paraphrase the last several months of Alaska politics, a POMV draw, while likely sustainable in the long term, is incompatible with the large 2019 statutory dividend (thanks to a long bull market and a huge year of realized earnings in 2018) unless the state cuts the budget very deeply or raises money through taxes. I’ll leave that one for another day though. Post Script: Nightmare scenarios for the Permanent Fund: Anticipating a downturn, managers sell stocks and build a couple years of massive statutory net income. The fund plunges 50%, and the successive statutory dividend draws erode the earnings reserve. Inflation roars back and the legislature declines to put funds towards inflation-proofing the principal, instead dedicating Permanent Fund revenues to cover ever-growing expenses. The Governor or Legislature decide to “pay back” previous dividends in concert with a large current year dividend, leading to a draw that massive drains the earnings reserve Account, forcing managers to sell assets to refill the earnings reserve for spending on government operations and dividends. Amid a global recession, oil drops to $25 per barrel (it was above $100 for years prior to the current decline), further increasing the Alaska’s dependence on permanent fund earnings while ignoring POMV legislation and continuing to draw from the fund through its appropriation powers Voters pass a new constitutional amendment requiring the 1982 statutory draw with no POMV backstops. While the principal is protected under the constitution, the case reaches the Alaska Supreme Court when the legislature attempts to pay dividends from the corpus A constitutional amendment that requires a “floor” on the dividend (say, $2,000) requires tapping the corpus after Alaska’s population surges to 2 million amid a decade-long drought in California About: The data used in this comes from the Alaska Permanent Fund Division and the Alaska Permanent Fund Corporation. The Alaska Legislature (in most years) has put up money to inflation-proof the principal of the fund. The code and raw data are available on this GitHub repo Analysis done in Python with plots in R/ggplot2.
https://benmatheson.github.io/blog/pfdincome/
CC-MAIN-2019-47
refinedweb
2,483
58.92
server. Start by downloading the Jetty distribution files, at the time of writing the latest version was jetty-distribution-9.0.5.v20130815. Unzip this file and copy the lib directory to a place where your Java application (which we will build in a moment) can find it. Now create a Java project and start with the WebSocketTest class file: import org.eclipse.jetty.server.Server; import org.eclipse.jetty.websocket.server.WebSocketHandler; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; public class WebSocketTest { public static void main(String[] args) throws Exception { Server server = new Server(8080); WebSocketHandler wsHandler = new WebSocketHandler() { @Override public void configure(WebSocketServletFactory factory) { factory.register(MyWebSocketHandler.class); } }; server.setHandler(wsHandler); server.start(); server.join(); } } Now create the MyWebSocketHandler class: import java.io.IOException;; @WebSocket public class MyWebSocketHandler { @OnWebSocketClose public void onClose(int statusCode, String reason) { System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason); } @OnWebSocketError public void onError(Throwable t) { System.out.println("Error: " + t.getMessage()); } @OnWebSocketConnect public void onConnect(Session session) { System.out.println("Connect: " + session.getRemoteAddress().getAddress()); try { session.getRemote().sendString("Hello Webbrowser"); } catch (IOException e) { e.printStackTrace(); } } @OnWebSocketMessage public void onMessage(String message) { System.out.println("Message: " + message); } } The server side of things is now done. The client is written in Javascript with some HTML to make it work. The index.html file looks like this: <!DOCTYPE html> <html> <body> <h1>WebSocket test</h1> <script src="index.js"></script> </body> </html> And the referenced index.js looks like this: var ws = new WebSocket("ws://127.0.0.1:8080/"); ws.onopen = function() { alert("Opened!"); ws.send("Hello Server"); }; ws.onmessage = function (evt) { alert("Message: " + evt.data); }; ws.onclose = function() { alert("Closed!"); }; ws.onerror = function(err) { alert("Error: " + err); }; Now startup the server side by running the main of the WebSocketTest class and startup the client by pointing your webbrowser to the index.html file. If your browser is new enough to support WebSocket, you should see that the client and the server connect with each other and that the server sends a message to the client and vice versa. On the client: On the server: If we wait long enough, a timeout will occur, resulting in the following message on the client: and this on the server: StevenMarch 30, 2014 at 11:27am Thanks for sharing! There are a couple of examples for seting up a websocket server, but your’s is pretty simple and easy to begin with. SeanApril 15, 2014 at 5:21am can you mail me you example full android project file? l try form your example code, but I finally crash in phone. Thank you. Kamesh PalaniApril 22, 2014 at 1:11pm Hi, I just followed the above instruction but, I’m getting below exception, ” WebSocket connection to ‘ws://localhost:8989/WS/’ failed: Error during WebSocket handshake: Unexpected response code: 200 ” Could some one please help me regarding the same? Thanks in Advance, -Kamesh monkryMay 7, 2014 at 6:49pm MY GOODNESSSSS Thank you so very much Sir! I’ve searched for something like this for god knows how long… many websocket and jetty example out there, but for me who’s total newbie in web programming and fucked up understanding in backend programming, a neat simple example and up-to-date (thank you very much for using Jetty 9.x…) like this is so… *sobs* Again, thank you so very much Sir! ( TvT) vamshiJune 13, 2014 at 12:20pm not working for android mobile(4.4 version, chrome browser). DylanAugust 25, 2014 at 1:01pm Got it working eventually by changing the port to 8081. Its as if Jetty was listening on 8080 and doing nothing with the client connection (like jetty didnt not get told of a handler). I wasnt running Jetty by specifying a main class, but using the “java -jar start.jar” and deploying a webapp. How do I run it main class method + as well as have the webapp with index.html etc deployed? Or do I have to split it up? Tutorial makes it sound like one deployable artefact should work. Still confused…unless I split it into two. Netbeans Jetty Override Added and RemovedSeptember 20, 2014 at 4:23pm […] So I try follow this: […] RuwenDecember 19, 2014 at 5:26pm Thanks for the tutorial. It’s working for me with Chrome but not with Firefox / IE. Both browsers are using WebSocket Version 13. In FF the connection is immediately closed after it is established (@OnWebSocketConnect is called, @OnWebSocketClose immediately after it). The close reason is 1001 or sth. 1005. Any ideas? thx for help. Andy C.January 2, 2015 at 12:08pm Thank you very much for your tutorial: it’s valuable and effective. Good job indeed! Andy C. Andy C.February 11, 2015 at 2:13pm I’m experimenting with your code: it is very instructive, thank you again. A question regarding “MyWebSocketHandler” class: in your code, the Server sends a msg back to the Client inside the “onConnect” method, using “session”. Instead, how can I send a msg back to the Client inside the “onMessage” method? In this method, “session” seems not to be available. Any suggestion? Thank you very much for your help. Bye, Andy C.
https://jansipke.nl/websocket-tutorial-with-java-server-jetty-and-javascript-client/
CC-MAIN-2019-22
refinedweb
865
58.28
Robert Femi689 Points This one should be short and sweet. Challenge Task 1 of 1 Why isn't the code accepted if I put ("True") and ("False") but it's accepted if remove brackets and quotation marks? Spent a LONG time figuring that out and would like to learn why so at least it won't be a complete waste of time. Would appreciate if someone can explain that to me. Many thanks. def even_odd(number): if number % 2 == 0: return ("True") else: return ("False") 1 Answer Alex KoumparosPython Development Techdegree Student 36,857 Points Hi Robert, Strictly, the problem is just with the quotation marks, not with the parens. return (True) will pass but return ("True") will not. This is because True and "True" are completely different data types. True is a boolean (a data type that can only ever be True or False, and Python can understand semantically what true and false mean) and "True" is a string (and Python doesn't generally have any way to understand what is semantically in a string, just that it is a sequence of characters). As for the parentheses, they are completely redundant and should be removed. Cheers Alex Robert Femi689 Points Robert Femi689 Points Thanks Alex.
https://teamtreehouse.com/community/this-one-should-be-short-and-sweet-challenge-task-1-of-1
CC-MAIN-2021-25
refinedweb
206
68.1
java.lang.Object javax.jms.QueueRequestorjavax.jms.QueueRequestor public class QueueRequestor The QueueRequestor helper class simplifies making service requests. The QueueRequestor constructor is given a non-transacted QueueSession and a destination Queue. It creates a TemporaryQueue for the responses and provides a request method that sends the request message and waits for its reply. This is a basic request/reply abstraction that should be sufficient for most uses. JMS providers and clients are free to create more sophisticated versions. TopicRequestorMSMSMS provider fails to close the QueueRequestordue to some internal error. Copyright © 2009-2011, Oracle Corporation and/or its affiliates. All Rights Reserved. Use is subject to license terms. Generated on 10-February-2011 12:41
http://docs.oracle.com/javaee/6/api/javax/jms/QueueRequestor.html
CC-MAIN-2017-30
refinedweb
115
52.66
Array::Group - Convert an array into array of arrayrefs of uniform size N. use Array::Group qw( :all ); @sample = ( 1 .. 10 ); $rowsize = 3; ngroup $rowsize => \@sample ; # yields ( [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ); dissect $rowsize => \@sample ; # yields ( [ 1, 5, 9 ], [ 2, 6, 10 ], [ 3, 7 ], [ 4, 8 ] );. The ongoing saga between princepawn, davorg and kilinrax over who did when in terms of getting this out is rather long-winded. They have their side of the story and I have mine. As is usual, it is princepawn versus some other majority. But what more could you expect from the black sheep of the Perl community? One thing is for certain there is a bug in Array::Reform and two months have passed and the author has done nothing about my RT bug patch submitted 1/21/06: Not to mention that I held the Array::Reform namespace and when I turned it overto him, he did not even acknowledge this. The test suite for HTML::Element::Library depends on this functionality and since I have people complaining about the wacky errors coming out of kilinrax's version of this module, and since he does not respond to emails, it is clear it is time to drop any reliance on his module. So, I wont say who the author is of what... this is free software anyway.
http://search.cpan.org/dist/Array-Group/lib/Array/Group.pm
crawl-003
refinedweb
229
76.66
In my role as a web developer who sits at the intersection of design and code,. In my experience, however, there is an outlier where many developers believe that custom elements don’t work, specifically those who work with React, which is, arguably, the most popular front-end library out there right now. And it’s true, React does have some definite opportunities for increased compatibility with the web components specifications; however, the idea that React cannot integrate deeply with Web Components is a myth. In this article, I am going to walk through how to integrate a React application with Web Components to create a (nearly) seamless developer experience. We will look at React best practices its and limitations, then create generic wrappers and custom JSX pragmas in order to more tightly couple our custom elements and today’s most popular framework. Coloring in the lines If React is a coloring book — forgive the metaphor, I have two small children who love to color — there are definitely ways to stay within the lines to work with custom elements. To start, we’ll write a very simple custom element that attaches a text input to the shadow DOM and emits an event when the value changes. For the sake of simplicity, we’ll be using LitElement as a base, but you can certainly write your own custom element from scratch if you’d like. Our super-cool-input element is basically a wrapper with some styles for a plain ol’ <input> element that emits a custom event. It has a reportValue method for letting users know the current value in the most obnoxious way possible. While this element might not be the most useful, the techniques we will illustrate while plugging it into React will be helpful for working with other custom elements. Approach 1: Use ref According to React’s documentation for Web Components, “[t]o access the imperative APIs of a Web Component, you will need to use a ref to interact with the DOM node directly.” This is necessary because React currently doesn’t have a way to listen to native DOM events (preferring, instead, to use it’s own proprietary SyntheticEvent system), nor does it have a way to declaratively access the current DOM element without using a ref. We will make use of React’s useRef hook to create a reference to the native DOM element we have defined. We will also use React’s useEffect and useState hooks to gain access to the input’s value and render it to our app. We will also use the ref to call our super-cool-input’s reportValue method if the value is ever a variant of the word “rad.” One thing to take note of in the example above is our React component’s useEffect block. useEffect(() => { coolInput.current.addEventListener('custom-input', eventListener); return () => { coolInput.current.removeEventListener('custom-input', eventListener); } }); The useEffect block creates a side effect (adding an event listener not managed by React), so we have to be careful to remove the event listener when the component needs a change so that we don’t have any unintentional memory leaks. While the above example simply binds an event listener, this is also a technique that can be employed to bind to DOM properties (defined as entries on the DOM object, rather than React props or DOM attributes). This isn’t too bad. We have our custom element working in React, and we’re able to bind to our custom event, access the value from it, and call our custom element’s methods as well. While this does work, it is verbose and doesn’t really look like React. Approach 2: Use a wrapper Our next attempt at using our custom element in our React application is to create a wrapper for the element. Our wrapper is simply a React component that passes down props to our element and creates an API for interfacing with the parts of our element that aren’t typically available in React. Here, we have moved the complexity into a wrapper component for our custom element. The new CoolInput React component manages creating a ref while adding and removing event listeners for us so that any consuming component can pass props in like any other React component. function CoolInput(props) { const ref = useRef(); const { children, onCustomInput, ...rest } = props; function invokeCallback(event) { if (onCustomInput) { onCustomInput(event, ref.current); } } useEffect(() => { const { current } = ref; current.addEventListener('custom-input', invokeCallback); return () => { current.removeEventListener('custom-input', invokeCallback); } }); return <super-cool-input ref={ref} {...rest}>{children}</super-cool-input>; } On this component, we have created a prop, onCustomInput, that, when present, triggers an event callback from the parent component. Unlike a normal event callback, we chose to add a second argument that passes along the current value of the CoolInput’s internal ref. Using these same techniques, it is possible to create a generic wrapper for a custom element, such as this reactifyLitElement component from Mathieu Puech. This particular component takes on defining the React component and managing the entire lifecycle. Approach 3: Use a JSX pragma One other option is to use a JSX pragma, which is sort of like hijacking React’s JSX parser and adding our own features to the language. In the example below, we import the package jsx-native-events from Skypack. This pragma adds an additional prop type to React elements, and any prop that is prefixed with onEvent adds an event listener to the host. To invoke a pragma, we need to import it into the file we are using and call it using the /** @jsx <PRAGMA_NAME> */ comment at the top of the file. Your JSX compiler will generally know what to do with this comment (and Babel can be configured to make this global). You might have seen this in libraries like Emotion. An <input> element with the onEventInput={callback} prop will run the callback function whenever an event with the name 'input' is dispatched. Let’s see how that looks for our super-cool-input. The code for the pragma is available on GitHub. If you want to bind to native properties instead of React props, you can use react-bind-properties. Let’s take a quick look at that: import React from 'react' /** * Convert a string from camelCase to kebab-case * @param {string} string - The base string (ostensibly camelCase) * @return {string} - A kebab-case string */ const toKebabCase = string => string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$ 1-$ 2').toLowerCase() /** @type {Symbol} - Used to save reference to active listeners */ const listeners = Symbol('jsx-native-events/event-listeners') const eventPattern = /^onEvent/ export default function jsx (type, props, ...children) { // Make a copy of the props object const newProps = { ...props } if (typeof type === 'string') { newProps.ref = (element) => { // Merge existing ref prop if (props && props.ref) { if (typeof props.ref === 'function') { props.ref(element) } else if (typeof props.ref === 'object') { props.ref.current = element } } if (element) { if (props) { const keys = Object.keys(props) /** Get all keys that have the `onEvent` prefix */ keys .filter(key => key.match(eventPattern)) .map(key => ({ key, eventName: toKebabCase( key.replace('onEvent', '') ).replace('-', '') }) ) .map(({ eventName, key }) => { /** Add the listeners Map if not present */ if (!element[listeners]) { element[listeners] = new Map() } /** If the listener hasn't be attached, attach it */ if (!element[listeners].has(eventName)) { element.addEventListener(eventName, props[key]) /** Save a reference to avoid listening to the same value twice */ element[listeners].set(eventName, props[key]) } }) } } } } return React.createElement.apply(null, [type, newProps, ...children]) } Essentially, this code converts any existing props with the onEvent prefix and transforms them to an event name, taking the value passed to that prop (ostensibly a function with the signature (e: Event) => void) and adding it as an event listener on the element instance. Looking forward As of the time of this writing, React recently released version 17. The React team had initially planned to release improvements for compatibility with custom elements; unfortunately, those plans seem to have been pushed back to version 18. Until then it will take a little extra work to use all the features custom elements offer with React. Hopefully, the React team will continue to improve support to bridge the gap between React and the web platform. The post 3 Approaches to Integrate React with Custom Elements appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.
http://design-lance.com/3-approaches-to-integrate-react-with-custom-elements/
CC-MAIN-2021-10
refinedweb
1,397
53.1
Built-in Global Variables When an instance of the ShowBase class is created, many of its member variables are written to the built-in scope of the Python interpreter, making them available to any Python module without the need for extra imports. While these are handy for prototyping, we do not recommend using them in bigger projects as it can make the code confusing to read to other Python developers to whom it may not be obvious from where these variables are originating. Many of these built-in variables are alternatively accessible as members of the global base instance, or can instead be imported from the ShowBaseGlobal module. The variables written to the built-in scope are: - base A global instance of the ShowBaseclass is available to any Python scope as base. This allows access to the graphical display, the scene graph, the input devices, the task and event managers, and all the other things that ShowBase is responsible for setting up and managing. Although it is not a required component, most Panda3D applications are created using the ShowBase abstraction layer, because it sets up nearly everything needed by most games and simulations, with only a minimal amount of set up required. In fact, to start up a ShowBase application, it is only necessary to call: from direct.showbase.ShowBase import ShowBase base = ShowBase() base.run() There can only be one ShowBase instance at a time; call destroy()to get rid of it, which will allow another instance to be created. - Type .ShowBase - render A NodePath created as the root of the default 3-D scene graph. Parent models to this node to make them show up in the 3-D display region. - Type - - render2d Like render, but created as root of the 2-D scene graph. The coordinate system of this node runs from -1 to 1, with the X axis running from left to right and the Z axis from bottom to top. - Type - - aspect2d. - Type - - pixel2d This is a variant of aspect2dthat is scaled up such that one Panda unit is equal to one pixel on screen. It can be used if pixel-perfect layout of UI elements is desired. Its pixel origin is also in the top-left corner of the screen. Because Panda uses a Z-up coordinate system, however, please note that the Z direction goes up the screen rather than down, and therefore it is necessary to use negative instead of positive coordinates in the Z direction. - Type - This is a scene graph that is not used for anything, to which nodes can be parented that should not appear anywhere. This is esoteric and rarely needs to be used; the use of stash()will suffice in most situations wherein a node needs to be temporarily removed from the scene graph. - Type - - camera A node that is set up with the camera used to render the default 3-D scene graph ( render) attached to it. This is the node that should be used to manipulate this camera, but please note that it is necessary to first call base.disableMouse()to ensure that the default mouse controller releases its control of the camera. - Type - - loader This is the primary interface through which assets such as models, textures, sounds, shaders and fonts are loaded. See Model Files and Simple Texture Replacement. - Type - - taskMgr The global task manager, as imported from direct.task.TaskManagerGlobal. - Type - - jobMgr The global job manager, as imported from direct.showbase.JobManagerGlobal. - Type - - eventMgr The global event manager, as imported from direct.showbase.EventManagerGlobal. - Type - - messenger The global messenger, imported from direct.showbase.MessengerGlobal, is responsible for event handling. The most commonly used method of this object is perhaps messenger.send("event"), which dispatches a custom event. - Type - - bboard The global bulletin board, as imported from direct.showbase.BulletinBoardGlobal. - Type - - ostream The default Panda3D output stream for notifications and logging, as a short-hand for Notify.out(). - Type - - globalClock The clock object used by default for timing information, a short-hand for ClockObject.getGlobalClock(). The most common use is to obtain the time elapsed since the last frame (for calculations in movement code), using globalClock.dt. The value is given in seconds. Another useful function is to get the frame time (in seconds, since the program started): frameTime = globalClock.getFrameTime() - Type - - vfs A global instance of the virtual file system, as a short-hand for VirtualFileSystem.getGlobalPtr(). - Type - - cpMgr Provides access to the loaded configuration files. Short-hand for ConfigPageManager.getGlobalPtr(). - Type - - cvMgr Provides access to configuration variables. Short-hand for ConfigVariableManager.getGlobalPtr(). - Type - - pandaSystem Provides information about the Panda3D distribution, such as the version, compiler information and build settings. Short-hand for PandaSystem.getGlobalPtr(). - Type - - inspect(obj)[source] Short-hand for direct.tkpanels.Inspector.inspect(), which opens up a GUI panel for inspecting an object’s properties. See Inspection Utilities. - config The deprecated DConfiginterface for accessing config variables. - run() Calls the task manager main loop, which runs indefinitely. This is a deprecated short-hand for base.run().
https://docs.panda3d.org/1.10/python/reference/builtins#the-global-clock
CC-MAIN-2022-33
refinedweb
835
55.64
- NAME - VERSION - SYNOPSIS - DESCRIPTION - USAGE - EXPORTED FUNCTIONS - AUTHOR NAME Test::Roo::Role - Composable role for Test::Roo VERSION version 1.004 SYNOPSIS A testing role: # t/lib/MyTestRole.pm package MyTestRole; use Test::Roo::Role; # loads Moo::Role and Test::More requires 'class'; test 'object creation' => sub { my $self = shift; require_ok( $self->class ); my $obj = new_ok( $self->class ); }; 1; DESCRIPTION This module defines test behaviors as a Moo::Role. USAGE Importing Test::Roo::Role also loads Moo::Role (which gives you strictures with fatal warnings and other goodies). Importing also loads Test::More. Any import arguments are passed through to Test::More's import method. Creating and requiring fixtures You can create fixtures with normal Moo syntax. You can even make them lazy if you want and require the composing class to provide the builder: has fixture => ( is => 'lazy' ); requires '_build_fixture'; Because this is a Moo::Role, you can require any method you like, not just builders. See Moo::Role and Role::Tiny for everything you can do with roles. Setup and teardown ) }; EXPORTED FUNCTIONS Loading Test::Roo::Role exports a single subroutine into the calling package to declare tests. test. AUTHOR David Golden <dagolden@cpan.org> This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004
https://metacpan.org/pod/Test::Roo::Role
CC-MAIN-2017-04
refinedweb
220
57.57
In the previous two articles in this series, I explained the rationale and design considerations for an XML/RDF vocabulary to describe open source projects. The Description of a Project (DOAP) vocabulary will meet the needs of project maintainers who find they must register their software at myriad Web sites, and for anyone seeking to exchange such data. Part 1 outlined existing work in this area, and defined the boundaries of the project. Part 2 presented candidate terms for the vocabulary, and mentioned some design concerns. In this article, I present the first draft of the DOAP vocabulary along with some example descriptions of projects. A lot of this article is example-based: You are encouraged to experiment with and create your own DOAP descriptions as you read. I'll use the language of RDF schemas to talk about DOAP. Although DOAP will be pretty easy to use as XML, you'll see that it is fundamentally an RDF vocabulary. Be aware of two main concepts in RDF schemas as used in this article: the class and the property. A class is a type of resource in RDF, similar to the way that a class is a type of object in Java programming. A property is a relationship between one resource and either another resource or a literal value. For additional developerWorks articles explaining RDF schemas, see Resources. Before I start explaining the terms of the DOAP vocabulary, take a look at this simple example DOAP file -- Listing 1 shows a minimal description of the DOAP project itself: Listing 1. A minimal description of the DOAP project Here are some general rules about writing DOAP files that you can draw from Listing 1: - Classes are labeled with capitalized terms, such as "Project" and "Person." This convention in writing RDF vocabularies is a general one that seems to work well. Properties are written in lower case. - The outer element of a DOAP document is <Project>. The February 2004 RDF syntax specification (see Resources) allows the omission of the <rdf:RDF>container where the description can be written with one outer node. - The Friend-of-a-Friend (FOAF) vocabulary is used to describe people. I have written several articles on this topic (see Resources). - The DOAP namespace is. - The standard xml:langattribute denotes the language of textual properties. The DOAP vocabulary currently contains three kinds of classes: - Project: The main project resource - Version: An instance of released software - Repository: A source code repository In fact, Repository has several subclasses, which I will describe later. Now, I'll examine each of the classes in turn. As you might expect, a Project is the main class in DOAP. Each Project is uniquely identified by its home page URI (I outlined the reasons for this in the previous article). Additionally, a project description should also list all of its old home page URIs, as they are still valid unique identifiers that others may still use to refer to the project. Table 1 shows the permissible properties for a Project. A description can contain an unlimited number of instances of each property. It is probably common sense to have only one name for a Project, but this is not a necessity. Additionally, a Project description can have as few properties as the author desires. The only minimum requirement to be useful is the homepage property. Table 1. Properties of the Project class (an asterisk denotes an identifying property) Listing 2 shows some properties that can be used to extend Listing 1 when you insert them before the </Project> tag: Listing 2. Some additional properties of the Project class Listing 2 demonstrates several more principles of the DOAP vocabulary, such as: - Properties whose values are URIs use the RDF construct rdf:resourceto contain the URI. - DOAP passes the buck on categorization schemes. Of the many categorization schemes, each has different advantages. Specialist communities may well have their own schemes. The approach taken in DOAP is simply to mandate that the category must be a URI. Listing 2 shows the use of two category schemes -- for Freshmeat and OSDIR.com. In each case, the category was derived from the URI of the page for the corresponding category on the Web site. Take care with canonicalization, however, as the Web sites often allow different forms of a URL, all pointing to the same page. DOAP needs to standardize these for the common sites. - The common software licenses will each have a well-known URI assigned to them by DOAP, as described in Part 2 of this series. However, as maintainer of the DOAP project, I have no desire to own identifiers for licenses and will put in place a mechanism to allow arbitrary URIs. For license URIs that processing software doesn't already know, it should be possible to retrieve a small RDF description of the license to provide software with human-readable license descriptions. As I mentioned earlier, the xml:lang attribute can be used to implement internationalization of a DOAP description. The permissible values of xml:lang are the standard codes for languages as defined in RFC 3066 (see Resources). Figure 1 shows a screenshot of an excerpt from the full DOAP description of DOAP itself (see Resources). I took a screenshot because not all readers will have the right fonts on hand to view the text. Figure 1. Internationalized description properties The DOAP schema defines a Repository class, a general class used to describe source code repositories. In itself this is not very useful, so DOAP has four more concrete subclasses of Repository, for the Subversion, BitKeeper, CVS, and GNU Arch source revision control systems. Table 2 shows each of the subclasses and the properties that are applicable to them: Table 2. Properties applicable to Repository subclasses DOAP is restricted to describing public access versions of the repositories, which are read-only. This removes the need to codify access control information for the writeable repositories, thus simplifying DOAP without much penalty as participant developers will have other ways of discovering this information. To make this clearer, here are some example descriptions for each of these systems. Subversion repositories are simply URLs. For example, the DOAP public repository I set up for this project has the URL. It's also publicly browseable (see Resources). Written using DOAP, these details look like this: DOAP entries for BitKeeper look similar to those for Subversion, as a single URL is enough to identify a repository. Here's a sample description for the Linux 2.6 kernel: CVS is probably the most popular source revision control system used in the open source world. Each repository is identified by a root and a module name. For instance, the Epiphany Web browser for GNOME can be checked out using the command cvs co -d:pserver:anonymous@anoncvs.gnome.org:/cvs/gnome epiphany. A DOAP description for Epiphany's repository looks like: The GNU Arch revision control system is currently gaining popularity. It eschews the idea of a central repository, and works on the principle that every developer has a repository. However, a project still needs to designate one repository as the place where the official released versions of the software are created. Arch has the concepts of archive location and module name. For instance, you can access a version of the "PlanetPlanet" RSS aggregation system using the archive at, with the module name jdub@perkypants.org--projects/planet--devel--0.0. The following example shows how to write this code in DOAP: To embed the repository location in the DOAP description, it must be the value of the repository property. Look at DOAP's own DOAP file (in Resources) to see how this works. Although, as stated in the first article in this series, the tracking of each project release is not part of the first phase of DOAP, you still a need to describe current releases of software projects. The Version class represents an instance of a software release. Table 3 shows its properties. Table 3. Properties of the Version class An example version description for Mac OS X 10.3 might look like the following: Each project may well have more than one current release, hence the need for the branch property. For example, it is not uncommon for projects to maintain a stable branch, while also releasing an unstable branch for testing new features. The formal definition of classes and properties in the DOAP vocabulary can be found in the DOAP schema (see Resources). It is written as an RDF schema, borrowing one term from the OWL ontology language to denote the identifying properties (in OWL-speak, inverse functional properties). Tools that are RDF-schema- or OWL-enabled can use the schema to assist authoring or interpretation of DOAP descriptions. One nice feature of RDF schemas is that if you use them properly, you can transform them into a good source of documentation. Morten Fredriksen has created an online service for doing this. From the Resources section, you can view a fully hyperlinked reference to all of the DOAP terms. Figure 2 shows an excerpt: Figure 2. DOAP schema transformed with Fredriksen's schema viewer As the examples in this article show, you can also process DOAP as straight XML. I do not encourage this approach to DOAP. RDF is best processed as RDF, and you will find no shortage of tools for doing this. However, one large advantage to DOAP having a reasonably regular XML syntax is the ability to create an XSLT stylesheet to transform a DOAP description into an easy-to-read chunk of HTML. The crucial next step in the DOAP project is to establish a suite of tools for the creation and consumption of the vocabulary. If DOAP is to live up to its promise as an interchange vocabulary for software directories, then it needs some real-world deployment. Secondly, it is plain that DOAP needs to be extended to cover software releases. Making release announcements is a major burden on software projects, and some way of automating this process would help maintainers. - Review the previous articles in this series part 1 introduces the DOAP project while part 2 presents candidate terms for the vocabulary, and identifies several design concerns. - Read "Basic XML and RDF techniques for knowledge management, Part 4" (developerWorks February 2002), in which author Uche Ogbuji explains RDF schemas. - Get the latest in the RDF/XML Syntax Specification (Revised), published in February 2004. - Check out the author's description of the FOAF vocabulary in "Finding friends with XML and RDF" (developerWorks June 2002) and "Support online communities with FOAF (developerWorks August 2002). - Review RFC 3066 to define the language codes used with the xml:langattribute. - Use Morten Fredriksen's RDF Schema viewer to produce a pleasingly human-readable version of the DOAP schema. - Find hundreds more XML resources on the developerWorks XML technology zone. Read previous installments in the XML Watch column series. - Browse for books on these and other technical topics. - Learn how you can become an IBM Certified Developer in XML and related technologies. Edd Dumbill is managing editor of XML.com and program chair of the XML Europe conference. He is co-author of the forthcoming O'Reilly book Mono: A Developer's Notebook." You can contact him at edd@xml.com.
http://www.ibm.com/developerworks/xml/library/x-osproj3/
crawl-003
refinedweb
1,883
53.81
CS::Mesh::iAnimatedMesh Struct Reference [Mesh plugins] State and setting for an instance of an animated mesh. More... #include <imesh/animesh.h> Detailed Description State and setting for an instance of an animated mesh. These meshes are animated by the skeletal animation system (see CS::Animation::iSkeleton) and by morphing (see CS::Mesh::iAnimatedMeshMorphTarget). Definition at line 629 of file animesh.h. Member Function Documentation Clear the weight of all active morph targets. Convenient accessor method for the CS::Mesh::iAnimatedMeshFactory of this animesh. Get the bounding box of the bone with the given ID. The corners of the box are expressed in bone space. If no bounding box has been defined for this bone on the animated mesh, then the one from the factory will be returned instead. If the factory has no box neither, then a default, empty one will be returned. It is valid to use CS::Animation::InvalidBoneID as a parameter, in this case it will return the bounding box of the vertices that aren't influenced by any bone. Get the weight for the blending of a given morph target. Get the render buffer accessor of this mesh. Get the skeleton to use for this mesh. Get a specific socket instance. Get the number of sockets in the factory. Get a submesh by index. Get the total number of submeshes. Set the bounding box of the given bone. Bone bounding boxes are used to update the global bounding box of the animated mesh, and to speed up hitbeam tests. Each bounding box should enclose all the vertices that are influenced by the given bone, even when the morph targets are active. If you don't specify a bounding box, then the one from the factory will be used instead. - Parameters: - Set the weight for the blending of a given morph target. Set the skeleton to use for this mesh. The skeleton must have at least enough bones for all references made to it in the vertex influences. - Parameters: - Unset the custom bounding box of this animated mesh. It will now be again computed and updated automatically. At the inverse, using iObjectModel::SetObjectBoundingBox() on this mesh will force a given box to be used. The documentation for this struct was generated from the following file: Generated for Crystal Space 2.1 by doxygen 1.6.1
http://www.crystalspace3d.org/docs/online/api/structCS_1_1Mesh_1_1iAnimatedMesh.html
CC-MAIN-2013-48
refinedweb
390
58.89
Classical OpenGL Gears running in GLW framework. Welcome to GLW – OpenGL Window! As the title says, GLW is a very simple to use OpenGL framework. You can use it as a drop-in framework in your applications to open an OpenGL window. As drop-in, I mean just copy source and header files into your own code and skip any library linking and loading. GLW consists of only one header and one source file so it is just to include gwl.h, and you are good to go. Alternatively if you wish to use it as a shared library, you can compile it as a dll as well. Included is solution with sources and two projects. One uses static GLW (drop-in source) and another links to shared library. I have adapted standard GL Gears from GLUT 3.6 source as a demo for this article. Just to experiment with size, there are 3 different configurations of project, among which, one is extremely optimized for size (not meant for real use). It turns that in static build, GLW adds approximately around 3 kb to exe. Dll weights in around 6.5 kb (7 on disk): Compiled binaries compared in build folder GLW abstracts away windowing and input in a friendlier, c-like, manner than what you see in standard Win32 API. Actually to use it you don’t have to dig into win32 at all to use it. If you have ever used GLUT, GLFW, or something similar, you will be at home with GLW at once. GLW is written as a very small and tiny subset of GLUT. However, it is GLUT-like, but it is not GLUT-clone, so don’t expect 1 : 1 correspondence to GLUT in GLW API. Long time ago I have written myself a library I called GLW that was much more of a GLUT clone. I was always interested about how such frameworks are done, so I put together my own. I alse had handling for several keyboards, mice and gamepads/gamejoysticks at once (with raw_input). I have used it in my own projects, but it was too messy in some detail to be put it in front of public eyes. Also I never got to Linux part . Since then I have moved to other stuff in my life and game programming at all have been on the shelf for few years for my part. Anyway few days ago I felt for doing something for the fun, so naturally playing with OpenGL comes first on my list. So I picked up my old library, and realized I don’t need really most of the stuff from it for simple tests and demos, so I have cleaned out unnecessary stuff, and left is very minimal but still usable framework to write simple demos or games. My goal is not to make smallest possible in terms of kilobytes; but small in terms of usage and learning curve. Certainly it is not very difficult to program Win32, but at same time it is unnecessary ugly and involved. Also you are tying your code into Windows platform and making it hard to port to some other platform if you ever want to. I believe that it is always better to abstract those (ugly) platform details away, and create yourself a clean API you are working against. Even if it is for personal use. If you need a serious framework, as mentioned there are GLUT and its clones, there are Qt, SDL and numerous other libraries and frameworks. Almost any 3d engine or toolkit will come with platform independent and more programmer-friendly windowing API then what one have to work when coding plain Win32 or MFC. If you need a simple to use and learn framework with basic functionality than GLW might be for you. GLW is meant to be used in small, personal demos and projects, if you wish to throw together some small test or demo fast. If you are using Visual Studio (I use VS2008 Express), create Win32 empty console project (exe). In your main source file, include glw.h and you are good to go. Be sure you also copy over glw.c, otherwise your linker won’t be happy. Visual Studio 2008 Project Settings for an GLW application. As shown above, make an empty console app if you are starting a new project in Visual Studio. I suggest you drop in GLW source directly in your code, since you will anyway use almost all of its stuff in any program that opens a window. If you anyway wish to link against dll you have to define preprocessor directive USEGLWDLL. To open a window for rendering just call glwMainLoop() from your main: #include "glw.h" int main(int argc, char** argv){ return glwMainLoop(); } The result is a simple window on the screen: Default window from GLW If you wish to remove console window that starts in the background you may add to your source (or change linker settings in project properties): #pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") Don’t disable console windows in gears1 or gears2 tests; it is used for printing some information. To dismiss window and exit application press escape. Well that is not much of stuff, just an empty window; but it has OpenGL up and initiated with reasonable default 3d projection (first person camera). Drawing is done in glwUpdateFunc callback (GLUTs glutRenderFunc). Draw a simple triangle: static void draw(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3f(0,1,0); glBegin(GL_TRIANGLES); glVertex3f( 0, 1,0); glVertex3f(-1,-1,0); glVertex3f( 1,-1,0); glEnd(); } To set up that function as glw rendering callback use glwSetUpdateFunc(draw): int main(int argc, char** argv){ glwSetUpdateFunc(draw); return glwMainLoop(); } Just for the fun, here is the output: GLW Window with a triangle in it Generally for any callback that GLW uses, there is a setter in form of: glwSetCallbacknameFunc( glwCallbackFuncf ). All callback funtions have name in form of glwCallbacknameFunc( … ). There are not many callbacks defined; glw only does a window and input, so naturally there are only callbacks to handle those aspects. By the way; I am using “old ways” to send data to OpenGL, just for the purpose of demonstration for this demo. GLW works fine with shaders, vbos and all other nice modern OpenGL stuff you may wish to use. glwResizeFunc(int width, int height) glwSetResizeFunc callback. Width and height are off course with and height of window used. For example you might do something like: void reshape(int w, int h){ float a; if (h==0) h=1; a = (GLfloat) h / (GLfloat) w; glViewport(0, 0, (GLint) w, (GLint) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -a, a, 5.0, 500.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -10.0); } and set it up in main: int main(int argc, char** argv){ glwSetResizeFunc(reshape); glwSetUpdateFunc(draw); return glwMainLoop(); } If you run same app now, you will see no change . It is just because I have pasted here the resize function glw uses as default for 3d perspective anyway. Now you know what defaults are if you don’t plan on setting up your own perspective. There is default 2d setup as well. To switch between 3d and 2d mode, use glwSet2DMode() and glwSet3DMode(). To draw same triangle, but in 2d, try this: void draw(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3f(0,1,0); glBegin(GL_TRIANGLES); glVertex2f(320,0); glVertex2f(0,480); glVertex2f(640,480); glEnd(); } int main(int argc, char** argv){ glwSet2DMode(); glwSetUpdateFunc(draw); return glwMainLoop(); } And same triangle is up and running again. If you resize the window, triangle will stay at same spot and same size. The reason is that viewport of OpenGL is configured to have origin (0,0) at top left and max at lower right corner of the window, but triangle is configured to draw in fixed coordinates and does not account for change in window size. To update triangle when window size changes, you need window width and height. You get those with glwGetWindowSize(int* w, int* h); It will put width and height of the window into parameters you give it: void draw(){ int w, h; glClearColor(1,1,1,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glwGetWindowSize(&w,&h); glColor3f(0,1,0); glBegin(GL_TRIANGLES); glVertex2f((float)w*0.5f,0); glVertex2i(0,h); glVertex2i(w,h); glEnd();} } Now the triangle resizes with the window (with white background this time). There is also corresponding glwSetWindowSize(int width, int height) to set width and height of the window. However it is only meaningful in context of creation. It means you can use it before you enter main loop to request initial size of the window. You cannot use it later on to change size of the window (use your mouse). In same spirit there are no positioning functions. I just don’t found those very useful for a dirty and simple do-some-quick-drawing-and-close style work. I wanted to keep this simple, not to make it a Swiss-knife of everything. Let’s go back to our 3d triangle and add rotation about y-axis: void draw(){ glClearColor(1,1,1,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glRotatef(1,0,1,0); glColor3f(0,1,0); glBegin(GL_TRIANGLES); glVertex3f(0,1,0); glVertex3f(-1,-1,0); glVertex3f(1,-1,0); glEnd(); } glwSetUpdateMode(GLW_CONTINOUS_LOOP); glwSetUpdateMode(GLW_EVENT_LOOP); int main(int argc, char** argv){ glwSetUpdateMode(GLW_CONTINOUS_LOOP); glwSetUpdateFunc(draw); return glwMainLoop(); } Triangle rotating around Y-axis. To trigger rendering while in event mode use: glwRedisplay() This function does nothing when you are not in event-driven mode so it’s ok to have it in code that works in both modes. To test updating modes in gears app, press ‘E’ to put GLW in event-mode or ‘C’ to go back to continuous rendering. To recap, these are all windowing functions available (see header file for more details): glwMainLoop glwSetResizeFunc glwSetUpdateMode glwSetUpdateFunc glwSet2DMode glwSet3DMode glwSetWindowSize glwGetWindowSize Well I could go on with just a green triangle, but it is more fun to see something more complex. As mentioned I have adaptated Gears app as found in GLUT 3.6 code. Both gears1 and gears2 projects found in solution, are 100% identical with each other. Only reason I have two projects, was to test size of executable when linked with dll versus static linking with source code. So you may peek in either one, but you don’t have to look at both. OpenGL gears running in a GLW window I have tried to do input as simple as I could too. I use input just occasionally to manipulate objects in the scene, and it reflects in capabilities of GLW. Keyboard handling is limited to physical keys. It means you can listen to what keys are pressed, like Enter, PageUp, PageDown, A, B, C and so on. But you can’t get things like ‘@,$,a-z’ (ascii characters). I just didn’t found it very usefull to move stuff around in a 3d scene with say ‘@’. If you really wish to be able to write advanced text with glw, you will have to add code to handle WM_CHAR yourself, I am afraid. So for instance glw is *not* the app you would do your text editor on (but maybe a shooter?). Mouse is handled quite well; you can listen on left, middle and right buttons, mouse motion and wheel motion. Signature for keyboard callback is void glwKeyboardFunc(short key, short event) Usually you would ignore key up, and turn all keyboard handling into “keypress” kind-a model. But if you wish to do some more advanced stuff like doing something while you hold down a key, possibility is there. I am using shorts instead of ints in hope it will be little less pushing and popping on stack (2 shorts are 4 bytes, 2 ints are 8 bytes). Well I guess it does not save much, but I always try to get away with as little as possible. In gears I do keyboard like this: void key(short k, short event){ if(event == GLW_KEYUP) // act only on keydown return; switch (k) { case 'A': showfps = ~showfps; break; case 'X': view_rotz += 5.0; break; case 'Z': view_rotz -= 5.0; break; case 'E': glwSetUpdateMode(GLW_EVENT_LOOP); break; case 'C': glwSetUpdateMode(GLW_CONTINOUS_LOOP); break; case 'F': glwToggleFullscreen(); break; case 'V': vsync = !vsync; glwSetVSync(vsync); break; case 'H': view_movx = 0; view_movy = 0; view_movz = 0; break; case 27: /* Escape */ case 'Q': glwExit(); break; } } GLW_DELETE GLW_INSERT GLW_ESCAPE GLW_SHIFT GLW_ALT GLW_CTRL ( ... ) Key-up event is called GLW_KEYUP, and key-down event is called GLW_KEYDOWN. There is almost no key processing in GLW; keys are pretty much mapped 1:1 to their counterparts in win32 (VK_). Alt and “extended keys” handling in windows is a bit miss moaner that needed some special care, but aside from that, keys are just passed through to the application. Well fastest processing is one you don’t have to do . That’s about it; you can’t do stuff like case ‘q’ or case ‘a’ - it won’t work. ASCII A-Z (as used in example) and 0-9 works only because OS assigns same values as ASCII to corresponding virtual keys. Mouse is a little bit more versatile than keyboard. For starter, left, right and middle mouse buttons are handled just like keyboard. Signature for the callback is: void glwMouseFunc(short x, short y, short event, short modifiers) Usually one is rather interested in deltas (amount of movement) between last read and current one. For that reason it does not matter if they are in screen or window coordinates. If you for some reason need screen space coordinates, it is trivial to provide conversion; either calculate it yourself or by calling ScreenToClient and ClientToScreen from Win32 api. Both solutions require you to modify glw itself (code is found in sglw.c). Another twist is that windows calculate coordinates relative to upper left corner, while GLW uses lower left corner as origin, so if you need to translate position of the mouse in window, to GLW you need to take that in account, also be aware that cursor coordinates are in 2d space of window, while OpenGL thinks in origin of you 3D scene (world). Event means same as for keyboard, either a button was up or down. To find which button is pressed you have to look into modifiers. Possibilities are: GLW_LBUTTON GLW_RBUTTON GLW_MBUTTON if(modifiers & GLW_KEY) /do something here / void mpdbg(short x, short y, short e, short m){ if(e == GLW_KEYDOWN) puts("Event: mouse key down"); if(e == GLW_KEYUP) puts("Event: mouse key up"); printf("Modifiers: "); if(m & GLW_ALT) printf("alt "); if(m & GLW_CTRL) printf("ctrl "); if(m & GLW_SHIFT) printf("shift "); printf("\nButtons: "); if(m & GLW_LBUTTON) printf("left "); if(m & GLW_RBUTTON) printf("right "); if(m & GLW_MBUTTON) printf("middle "); puts(""); } Mouse motion is called when mouse moves inside the window. The signature is somewhat simpler than previous one: void glwMouseMoveFunc(short x,short y, short modifiers); Here is what I do in gears to enable simple translation and rotation with mouse: void onmousemove(short x, short y, short m){ int dx, dy; if(oldx == 0) oldx = x; if(oldy == 0) oldy = y; dx = (x-oldx), dy = (y-oldy); if(m & GLW_ALT){ if(m & GLW_LBUTTON){ view_rotx += dx; view_roty += dy; } else if(m & GLW_RBUTTON){ view_movx += dx*0.01f; view_movy -= dy*0.01f; }else if(m & GLW_MBUTTON){ view_movz += (dx+dy)*0.5f*0.1f; } glwRedisplay(); } oldx = x; oldy = y; } Don’t hang–up on that code, it is there just to illustrate how to read buttons from the mouse not to show how to implement a camera in OpenGL. Mouse wheel function is called when you turn mouse wheel. Unlike x and y coordinate for the cursor, the wheel is not sending coordinates. It sends ticks. So when you turn wheel a bit, you get one tick and a windowing event. When you turn it a bit more you get another tick and so on. Continuous moving of wheel will also not produce continuous coordinates, but a discrete value on every event. Tick has size and name. Its name is WHEEL_DELTA, a term you can google on to learn more about how wheel events are handled. Size is either +120 or -120, depending on the direction of movement (+ from you and – towards you). So you will never get something like 240, 360 and so on. Instead of 360; you get 3 updates a 120 each. It means that we really are interested just in sign of the movement, not amount. For that reason, our z will always be either +1, or -1. Here is an example of usage from gears: void onmousewheel(short x, short y, short z, short m){ float amount = 10*(float)z; if(m & GLW_CTRL) view_rotz += amount; if(m & GLW_SHIFT) view_roty += amount; if(m & GLW_ALT) view_rotx += amount; glwRedisplay(); } Usually you will need to load textures and maybe some other resources for which you need OpenGL context. Well until main loop has started there is no context. Instead you may register a function to be called once the OpenGL is created and ready for use. Function signature is void glwInit() void glwSetInitFunc(glwInitFunc cb) Analogous to initialization you need to perform cleanup when you are done. For that purpose there is glwExitFunc set with glwSetExitFunc. Just like init is safe place to initiate gl stuff, so is exit safe place to clean it up. Exit function is called while OpenGL context is still active. Doing any cleanup after main loop has exited will most likely result in a crash, since GL context will be destroyed at that point. Finally there is glwExit() It should not be confused with glwExitFunc. glwExit is GLWs API function that in turn will call your callback glwExitFunc to clean up resources allocated by the applicaiton. It also brings issue of terminating an glw app: don’t call exit(0), call glwExit to make sure OpenGL resources are properly released. For same reason, don’t rely on atexit() to clean up any of OpenGL. Instead register your callback with glwSetExitFunc() and GLW will call it when appropriate. As known OpenGL board has changed a lot how OpengGL API works. I don’t really agree with all changes they introduce, mostly those about deprecation, but who am I to judge? I have thrown in support for initialization of modern context (3.xx and later). If you believe new ways are better, you might do something like this: int main(int argc, char** argv) { int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0 }; glwSetGLAttribs(attribs); glwSetInitFunc(init); glwSetExitFunc(clean); glwSetKeyboardFunc(key); glwSetUpdateFunc(render); return glwMainLoop(); } As a note, if I ask for GL version from driver I will always get latest at least on my card (Nvidia 560ti), no matter what attributes I pass to OpenGL. I get latest even with “old ways”, so why would I bother? Well just because it works that way on my card does not mean it will work same on some other driver. That was pretty much the whole framework , but there are few extras I haven’t touched yet. GLW window can be set in and out of full screen mode with call to glwToggleFullscreen() Note it does not trigger real video-mode change. It just puts window on top and hides all window decorations. Yeah – I know, it is old GLUT ‘game-mode’, but I am quite fine with it. Switch is fast and almost for free in terms of code. To add real video-mode handling would require much more code and would be a bloat for something as simple as GLW. There is issue with full screen. Sometimes, but just sometimes, when an app is switching into full screen for the very first time, the screen may go black (window is not updated). I have seen it only very few times, and cannot reproduce it on-demand actually, so I can’t hunt down the cause. Switch out and in again fixes problem; maybe some other update of the screen would solve it as well, but as said I am unable to reproduce it so it is difficult for me to say. Last function is glwSetVsync() As a funny note – did you know you could set graphics card to half of the monitor refresh rate? I didn’t, but I found out by mistake. Pass in ~1 to vsync, and the fps will go half the rate (at least does for me, Gf560 ti,24’’ flatscreen at 60hz refresh rate). Well I know that vsync means that graphics card can only refresh in multiples of monitor refresh rate, but I didn’t know I can turn it off or on in those multiples manually. I am not going to write much about internals; it is so small and simple framework, that discussion would probably turn into introductive Win32 tutorial . However for those that are used to windows programming, there are few notes to mention. For the first GLW gets rid of WinMain. You don’t need WinMain in windows application; it is just a convention, and it is myth that this convention is useful. Really ; winmain just makes your code less portable and adds additional idiom to remember, while not giving you any special value. You can obtain all arguments passed to WinMain through Win32 API if you need them, and you can configure your linker to produce windowed application anyway. Maybe there is something deeper about WinMain I miss, in that case please inform me. Main loop is done little differently than normal. Usually frameworks implement one or another kind of loop (either GetMessage or PeekMessage); but I have coded it in a way that makes it possible to switch between those. Included with this framework is a high-resolution timer code that I have found and adapted from an article on Intel's site. It is found in etimer.h and etimer.c. I believe that code was free, but I include link to both original article and to licence in etimer.h. It is also a drop-in code you can use independently of this library. 2012-04-23 Article and source published 2012-04-25 Fixed a bug with initial window size in glw.
http://www.codeproject.com/script/Articles/View.aspx?aid=371849
CC-MAIN-2015-06
refinedweb
3,710
69.41
Crawlers written in Java Looking for help Looking for help I am looking for a valid helper to solve flex 4 problems I have found after switching from flex 3. We would work directly on my code with team viewer in the beginning. Thanks for your help Paolo Open Source E-mail Server code for complete control. POPFile: Open Source E-Mail... Expense Submittal System (ESS) is an open source Web-based expense reporting system...Open Source E-mail Server MailWasher Server Open Source code for complete control. POPFile: Open Source E-Mail... web server. Open-source server software Sun... and services. Adisoft's Expense Submittal System (ESS) is an open source Web Open Source web mail Open Source web mail Open Web Mail Project Open WebMail... is fully skinnable using XHTML and CSS 2. Open-source Web software... as well. Open source Web mail Server The software can source code - JSP-Servlet source code please i want source code for online examination project (web technologies) Hi Friend, Send some details of your project. Thanks want source code for Online shopping Cart... Rakesh, I am sending a link where u will found complete source code... functional application. System Scope Shopping Cart is a web application intended Open Source web Templates Open Source web Templates Open Source Web Templates A web site... to reference methods defined in Java code. Velocity can be used to generate web... as a standalone utility for generating source code and reports Open Source CD the largest number of software packages. Open source code... to contain source code from the open-source project LAME, an MP3 encoder and player...Open Source CD TheOpenCD TheOpenCD is a collection of high quality Need source code - Swing AWT image in database, try the following code: import java.sql.*; import...Need source code Hai, In java swing, How can upload and retrieve...(); JOptionPane.showMessageDialog(null,"image is successfully inserted."); } catch(Exception ex Microsoft Open source . says it is looking to turn over more of its programs to open-source software... at the breadth of source code that we have, the breadth of software that we have... is inferior. Open Source Code Finds Way into Microsoft Java - looking for a tool to force-kill a child process (Windows) source code, I cannot program it to better handle termination requests. I have...Java - looking for a tool to force-kill a child process (Windows) hello I am looking for a Java tool/package/library that will allow me to force Image Steganography Image Steganography SOURCE CODE FOR IMAGE STEGANOGRAPHY Open Source Images Open Source Images Open Source Image analysis Environment TINA... and stretched and rotated. ImageMagick is free software delivered with full source code...; Open Source Digital Image Management Took As the technical Open Source CMS , and by having access to the source code, developers can do things like add support... distributions, but only one Linux. There are over a dozen open-source Web servers..., by the way, that Byrne is an open-source Luddite. CMS Watch, the leading Web-based Open Source Exchange ; DDN Open Source Code Exchange The DDN site... macro source code subject to the terms outlined below. All of the source code...Open Source Exchange Exchange targeted open source help desk Open Source Web Help Desk Software Liberum Help Desk is a web-based... a modular, web-based, open-source helpdesk system that would meet a variety... modify their source code. For those reasons, they've gained popularity How to download JDK source code? are looking for the source code to see the working of Java API. You can see...How to download JDK source code? This articles explains you how you can download the source code of JDK. You will learn how to download JDK source code Open Source software written in Java for short is software which is available with the source code. Users can read, modify... Frameworks Automated Test Tools Web Crawlers... Code Coverage Open Source Java Collections API Open Source Hardware Open Source Image GNU Image...; Open Source Image Analysis Environment... delivered with full source code and can be freely used, copied, modified Open Source Jobs ; Open Source Applications Foundation OSAF is looking... looking for someone with a passion for building great web applications.  ... the source code is available to the general public for use and/or modification from Looking to Hire Magento Website Developer? Looking to Hire Magento Website Developer? Are you searching.... We are amongst the top Magneto web development company in India. Perform high quality ecommerce solution from our knowledgeable Magento Web Developers Open Source Content Management code for open-source CMSes is freely available so it is possible to customize... new Web pages.Etomite is OpenSource (GPL), which makes it free to use. If you...; ATutor Learning Content Management System ATutor is an Open Source Web-based source code source code how to get the fields from one page to another page in struts by using JSTL Directory architecture includes source code for both directory client access and directory servers... for those looking for an open source directory server. But with OpenLDAP well... unveiled the Red Hat Directory Server and simultaneous release of the source code source code source code how to use nested for to print char in java language? Hello Friend, Try the following code: class UseNestedLoops{ public static void main(String[] args){ char[][] letters = { {'A', 'B'}, {'C','D Image Processing Java Image Processing Java Using This Code I Compressed A JPEG Image... How Can I Decompress It Please Give Me The "SOURCE CODE" And Hee is my Source Code...:// Open Source Web Page Open Source Web Page The Open Source Page Open Source Initiative..., redistribute, and modify the source code for a piece of software, the software evolves... and is open source GPL. Open Source Web Designs Empire Elements j2ee source code - Design concepts & design patterns j2ee source code am developing n-tier clien server e-commerce web application project but i don have much time please help me to get source code of the project Open Source Code Open Source Code What is SOAP SOAP is a protocol for exchanging... that the actual program code that the developer created, known as the source code.... Open source code in Linux If the Chinese have IT, get View source code of a html page using java .. View source code of a html page using java .. I could find the html source code of a web page using the following program, i could get the html code image image how to add the image in servlet code Open Source Project Management or low-cost project management We're looking for an open source or low-cost...Open Source Project Management Open Source Project Management... on a production site or if you are not willing to have to do some work at the code image Processing image Processing Please give Me a JPEG or GIf "LOSS LESS" Image Compression and Decompression Source Code Please Help Me I don't want links Kindly help me Compression ratio not matter Open Source Media Center time, the front-end JavaScript is not scrambled, which means the source code...Open Source Media Center Open source media center for Windows Why buy.../nothing/nada/nopes and best of all it is open source. This means anyone can Open Source Download of the free/open source GNU Image Manipulation Program (GIMP), intended... Buzz. Netscape Communicator Open Source Code White... unprecedented move, Netscape announced that it would make the source code to its flagship Open Source Browser to standardize on a single Web browser, Nokia on Wednesday released the source code...-source browser A new Web browser with a socially conscious streak was released... building open-source browser Apple's Safari web browser may not be available VoIP PBX Open Source members can contribute to writing open source code, similar to the Linux development... VoIP PBX Open Source Open Source IP PBX Digium has released Open Source Router -source router company, released the first beta version of its WAN router code... as an open-source router software project. Vyatta's code combines a modified Linux... based on the code) and is licensed under a similar license as the open source Problem with Java Source Code - Java Beginners Problem with Java Source Code Dear Sir I have Following Source Code ,But There is Problem with classes, plz Help Me. package mes.gui; import...(" ", ii ,JLabel.CENTER);//---default image MAINPANEL.add(ImageLabel Web Services Tutorials and Links ; Web Services primer: Looking... of features for programmers looking to create and edit Web Services: Intuitive... for Web Services standards, tools for testing code, support for XML Schema source code for the following question source code for the following question source code for the fuzzy c-means Java source code Java source code How are Java source code files named Web Services - Web Services Tutorials to the remote source. One can access Web services using nothing but HTTP. Of all..., read a data source, etc.) for the consumer and wait for the next request. Web... an HTTP success code and a SOAP response or an HTTP error code. Open Source means Open Source Accounting Software A web based, open source accounting and inventory program called NOLA has been... and additions to the software without releasing the source code. Pepers expects Quasar... currently looking for a simple web based accounting application. The system should source code in jsp source code in jsp i need the source code for online payment in jsp. Hiding Source Code - WebSevices Hiding Source Code Is there any way to prevent viewing source code in browser java/j2ee source code java/j2ee source code java/j2ee source code for online food purchasing service with my sql database java source code java source code java source code to create mail server using struts2 Source Code - Java Beginners Source Code What do I have to add to my original code to make it work source code in jsp source code in jsp how to insert multiple images in jsp page of product catalog Java Source code Java Source Code for text chat application using jsp and servlets Code for text chat application using jsp and servlets request for java source code request for java source code I need source code for graphical password using cued-click points enabled with sound signature in java and oracle 9i as soon as possible... Plz send to my mail Web Designing Cost : Firebug: Firebug is a free, open source in-browser web development tool... View - which shows a preview of your source code. Dreamweaver is tightly... Web Designing Cost Roseindia provides you complete packages Open Source XML Editor external editors work with web logs.) Using this XML-RPC code has other benefits: it?s Open Source, so you can see the code. As a set of Cocoa classes it?s...Open Source XML Editor Open source Extensible XML Editor source code - JSP-Servlet source code i need source code for client server application in jsp to access multiple clients Hi Friend, Please visit the following link: Here you will get lot of examples web service call in jsp page with source code...web service call in jsp page I am wandering on internet for hours looking for a simple and good example on how to create a simple JSP page to call source code - JSP-Servlet source code i want source code for my project online examination it includes two modules user and administrator so if user want to write exam first he register his details and then select the topics on which he want to write AWT Image AWT Image I have loaded two images using toolkit in java.one is concentric rectangle and other is concentric circle.kindly someone send me the source code of interchanging the inner most rectangle with the inner most circle Developing Axis Web services with XML Schemas. : If you are looking for RESTful web services, please refer Axis2 ) with Axis1.4... files are included in the tutorial source code project. Step1: Identify... exception. Download Source code Open Source Servers Open Source Servers Open Source Streaming Server the open source... and RTSP protocols. Based on the same code base as QuickTime Streaming Server... on a variety of platforms allowing you to manipulate the code to fit your needs Open Source Encryption Open Source Encryption Open Source encryption module loses FIPS... certification of the open-source encryption tool OpenSSL under the Federal Information Processing Standard. OpenSSL in January became one of the first open-source source code of java source code of java how to create an application using applets is front end and back end is sqlwith jdbc application is enter the student details and teaching & non teaching staff details and front end is enter in internet Open Source Intelligence community to refer to programs whose source code is publicly available (and modifiable... years of open source intelligence conferences. They're all available on my Web...Open Source Intelligence Open source Intelligence The Open Source Source Code - Java Beginners Source Code How to clear screen on command line coding like cls in DOS? Hi Friend, Here is the code to execute cls command of DOS through the java file but only one restriction is that it will execute Developer Open Source Library handles the rest. Swat is an open-source web application...-source software at silver orange, building many of our websites and web... with the release of the Swat Web Application Toolkit. Swat is an open-source web application Open Source Defination Open Source Defination The Open Source Definition Open source doesn't just mean access to the source code. The distribution terms of open-source... Strategy Against Open Source These Open Source consultants do not sell software source code - Java Beginners source code Hi...i`m new in java..please help me to write program that stores the following numbers in an array named price: 9.92, 6.32, 12,63... message dialog box. Hi Friend, Try the following code: import loading image give me a source code to add any wallpaer of my PC as a background image to jpanel on a jframe Retrieve image from mysql database through jsp to retrieve image from mysql database through jsp code. First create a database.... mysql> create database mahendra; Note : In the jsp code given below, image... image with 'id' value 11. So before running this jsp code first check whether image Open Source GPS Open Source GPS Open Source GPSToolKit The goal of the GPSTk project is to provide a world class, open source computing suite to the satellite.... The principles of object-oriented programming are used throughout the GPSTk code base Open Source Shopping Cart shopping cart can be downloaded from their websites. The source code... distribution websites. Availability of source code is a big advantage of using any open source shopping cart. You can download and modify the source code regarding designing of web search engine - Development process regarding designing of web search engine we want to design a web search engine in java. so, how to get started with our coding...can i get sample code for web crawlers or similar requirements... help us Show Image Reader and Image Writer by image format : Download source code... Show Image Reader and Image Writer by image format... to display the Image Reader and Image Writer by the image format. To show Open Source RFID source 'will solve RFID's image problem The public image of RFID... is looking to develop a suite of open-source RFID software that conforms...Open Source RFID RFID RFID systems can be used just about anywhere Linux Open Source the GNU General Public License , the source code for Linux is freely available... Public License and its source code is freely available to everyone.  ... commitment: Sun has opened more lines of source code than any other company HTML - Image link code. HTML - Image link code. Description : HTML image link is a combination of two HTML tags. One is anchor and another is image tag. Image tag image is used as a text of anchor tag. Code : <!DOCTYPE html PUBLIC Open Source Software Software Open source doesn't just mean access to the source code. The program must include source code, and must allow distribution in source code... with source code, there must be a well-publicized means of obtaining the source code Open Source Accounting but play with code. With easy access to an open source application, the techie can...; Open Source Accounting and Inventory Program Launched A web... pace for your own needs. Because source code is shared openly, you can freely use Best Open Source Software (and sometimes incorrectly) called freeware, shareware, and "source code," open... of intellectual property assets in the form of source code for both reference... and modify source code as opposed to proprietary software such as that made HTML Editor Open Source such as image editors and access to underlying source code. There are pros... sites, while enabling Web authors to stay in total control of their HTML code. ..., Application. Powerful Open Source Web Editor The emergence and now
http://www.roseindia.net/tutorialhelp/comment/21639
CC-MAIN-2014-10
refinedweb
2,862
63.19
FILE * fopen ( const char * filename, const char * mode ); <cstdio> Open file Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE object whose pointer is returned. The operations that are allowed on the stream and how these are performed are defined by the mode parameter.The running environment supports at least FOPEN_MAX files open simultaneously; FOPEN_MAX is a macro constant defined in <cstdio>. /* fopen example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen ("myfile.txt","w"); if (pFile!=NULL) { fputs ("fopen example",pFile); fclose (pFile); } return 0; }
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
crawl-002
refinedweb
105
65.62
On Sun, Oct 01, 2000 at 08:31:10AM -0700, Me wrote: > As for the subject, I have noticed that ne2000 card > support was compiled > into gnumach for the 2000-03 hurd tarball, but I can > only get the card > detected if the card is on io=0x300. Is there a place > to change this so > that multiple ne2000 cards could be supported by > gnumach? Ah, yes. We haven't talked about GNU Mach yet. Here is what is required: As GNU Mach doesn't support such boot time options, you need to hack the kernel, but it isn't hard: In gnumach-1.2/linux/dev/drivers/net/Space.c, you'll find this: /* In Mach, by default allow at least 2 interfaces. */ #ifdef MACH #ifndef ETH1_ADDR # define ETH1_ADDR 0 #endif #ifndef ETH1_IRQ # define ETH1_IRQ 0 #endif #endif You need to fill those in. If you want to override everything, you do this: Replace: #ifdef MACH static struct device eth1_dev = { "eth1", 0, 0, 0, 0, ETH1_ADDR, ETH1_IRQ, 0, 0, 0, ð2_dev, ethif_probe }; #else static struct device eth1_dev = { "eth1", 0,0,0,0,0xffe0 /* I/O base*/, 0,0,0,0, ð2_dev, ethif_probe }; #endif With: static struct device eth1_dev = { "eth1", 0, 0, 0, 0, 0x300, 10, 0, 0, 0, ð2_dev, ne_probe }; This will FORCE the probe for a NE2000 card (and no other second chard is recognized) at the specified address. I think you should be able to specify ETH1_ADDR and _IRQ at compile time, but I can't find
https://lists.debian.org/debian-hurd/2000/10/msg00025.html
CC-MAIN-2017-30
refinedweb
250
68.33
This site uses strictly necessary cookies. More Information How can i set mouse cursor position? Answer by Ashkan_gc · Dec 24, 2009 at 01:42 PM in mono you can use the system.windows.form.cursor.position but it needs the windows.form.dll and you need to add this assembly to your project. for mouse clicks you should use external APIs witch are in user32.dll but i don't know anything about OSX. in web players you can use javascript to do mouse movement and click. note: you can not use external native code in web players. how do you add this assembly to your project? I referenced it in mono, but it keeps dereferancing when I compile in unity? You can't modify a generated file. The mono solution is generated by Unity. You can add the dll file into your Unity asset folder and write "using namespaceOfTheDll;" at the beginning of your script to be able to use it. $$anonymous$$ine is a $$anonymous$$oving UI, So it is must for me to reset cursor to centre of screen every time user hits a button or returns to $$anonymous$$ain $$anonymous$$enu. So plzz help. If you need help with anything, then DON'T ask for it in a comment to a question that is 7 years old. Please be sure to read the user guide and watch this video: If you need help, google your question and if you can't find an answer, ask a new question. Properly formulate your problem and explain what you tried and what doesn't work. Don't do that here, ask a new question. But only if you can't find an answer on the internet. problem is you also have to add System.Drawing in order the Point method to change System.Windows.Form.Cursor.Position. Answer by duck · Dec 24, 2009 at 10:10 AM I don't think it's possible to directly set the mouse cursor position with Unity's own API (although it's likely possible if you use a custom DLL in a standalone build). However, if your goal is to set the mouse cursor position in order to achieve a "mouse look" effect, there's a lockCursor command to do just this. Answer by Benproductions1 · Jul 04, 2012 at 10:33 AM You can work around this problem, by basically manually implementing a GUI based mouse and moving it through the mouse delta given by Unity. You could then set the position of this mouse and just use static variables to access it from every script. Wish unity would fix it, so we don't have to do these stupid workarounds. I don't see this. Where can I get this mouse delta? Assuming it's Input.mousePosition from this and previous frame subtracted, then what, when real mouse will touch the screen edge? All deltas will become 0, even if GUI cursor will be on the center of the screen. Edit: Oh, ok. I can do this with an axis. Answer by NightmarexGR · Apr 30, 2014 at 11:16 AM Hello guys it seems this problem is still active, for this reason i created a unity API that lets you set the cursor's position on screen "SetCursorPosition(x : int,y : int)" Answer by amisane · Nov 01, 2016 at 04:32 PM I was able to create an implementation for this that works (in my 2D game running on Windows at least...) Add this struct in to your project: [StructLayout(LayoutKind.Sequential)] public struct Point { public int X; public int Y; public static implicit operator Vector2(Point p) { return new Vector2(p.X, p.Y); } } And add the following to some script: [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetCursorPos(out Point pos); private void MoveCursorToNearbyObject(GameObject objToFocus) { float targetWidth = 1920f; float targetHeight = 1080f; Vector2 inputCursor = Input.mousePosition; inputCursor.y = Screen.height - 1 - inputCursor.y; Point p; GetCursorPos(out p); var renderRegionOffset = p - inputCursor; var renderRegionScale = new Vector2(targetWidth / Screen.width, targetHeight / Screen.height); var objPos = objToFocus.transform.position; var newXPos = (int)(Camera.main.WorldToScreenPoint(objPos).x + renderRegionOffset.x); var newYPos = (int)(Screen.height - (Camera.main.WorldToScreenPoint(objPos).y) + renderRegionOffset.y); SetCursorPos(newXPos, newYPos); } I'm getting: The type or namespace name 'DllImport' could not be found (are you missing a using directive or an assembly reference?) when I try the above; do I need to add a 'using'? Duh, ignore that. It was just 'using System.Runtime.InteropServ. Enable scrolling the page in WebGL 1 Answer Making an AirPlane follow mouse 1 Answer Convert GetAxis (mouse) to VR head movement 1 Answer Double Click Speed? 1 Answer Unity Check if gameobject is clicked 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/9408/set-cursor-position.html?sort=oldest
CC-MAIN-2021-25
refinedweb
804
66.33
24C04 is a two-wire serial EEPROM which is an abbreviation of Electrically Erasable Programmable Read-Only Memory. This EEPROM IC provides an I2C communication interface. It is basically a memory device which stores information and retains it even when we remove the power. It has a memory capacity of 512 words. Each word has 8-bits. The memory consists of 32 pages of 16 bytes each and uses a word address of 9-bit data for random word addressing from memory. The module uses the I2C communication protocol to communicate with other microcontrollers or digital devices. 24C04 EEPROM Pinout It consists of 8 pins. This diagram shows the pinout of 24C04 Pin Description Pin#01, 02, 03: A0, A1, A2 These three pins are address inputs. The pins A2 and A1 are for hardwire addressing. You can address four 4K devices on a single bus system whereas the A0 pin is a no connect pin and normally, we connect this pin to ground. Pin#04: GND Connect this terminal to the main ground. Pin#05: SDA The serial data pin allows the bidirectional transfer of serial data and addresses. Pin#06: SCL It is a clock input pin that injects the data into each EEPROM device on positive edge of a clock and on a negative transition, it sends data out on the output pin of each device. Pin#07: WP As the name implies, the write-protect pin protects the hardware data. It enables read/write operation by connecting it to the ground pin. Only write operation is enabled, when applied with Vcc. Pin#08: Vcc Apply a voltage signal in a range of 1.7V to 5.5V at this pin. Features - Low and standard-voltage operation - Vcc = 1.7V to 5.5V. - The memory has a capacity of 512 x 8 (4K) bits. - The EEPROM device provides bidirectional data transfer and this communication takes place through a 2-wire serial interface - Schmitt triggered inputs which can suppress noise. - It is a highly reliable device with an endurance of 1 million write cycles and the limit of data retention is almost 100 years. - Maximum clock frequency = 1MHz. - Hardware data protection through write Protect Pin Where to use 24C04 EEPROM? This device is well-suited for use in applications which require low-voltage and power for operation. Many industrial and commercial applications use this device as it provides noise immunity and you can expand it by cascading 8 similar devices. You can easily interface with other microcontrollers. Computers and other electronic devices use this device to store data and avoid data loss when the power is turned off. How to use it? As already mentioned above, this device uses an I2C interface which consists of two wires named SDA and SCL. As it is a bidirectional bus, therefore, it can act as a transmitter or receiver. The SDA input pin is pulled high with a microcontroller or any other device. The data on SDA pin changes on a high to low transition of the SCL signal. The low to high transition of the clock pulse signal indicates a start or stop condition. When a positive transition occurs at the SDA input pin with SCL high, it is a start condition. Stop condition occurs when a negative transition of the input signal takes place at SDA with SCL input being high. It puts the device in a standby power mode. The EEPROM sends or receives addresses and data words serially in the form of 8-bit words and sends a zero as an acknowledgment that it has received each word. The figure below illustrates the effect on output on changing SDA and SCL inputs. Data In is SDA input. 24C04 Interfacing with Arduino This is a connection diagram of 24C04 EEPROM interfacing with Arduino UNO. Connect the SCL pin of Arduino with the SCL pin of EEPROM. Similarly, SDA pin ( Arduino ) with SDA pin of EEPROM IC. Also, connect pull-up resistors with SDA/SCL wires. - Copy this code and paste it in Arduino IDE - Upload this code to your Arduino board. - This code will just read a value from address 0x00 You can modify this code according to your requirements. #include "Wire.h" #define EEPROM_I2C_ADDRESS 0x50 void setup() { Wire.begin(); Serial.begin(9600); int address = 0; byte val = 110; writeAddress(address, val); byte readVal = readAddress(address); Serial.print("The returned value is "); Serial.println(readVal); } void loop() { } void writeAddress(int address, byte val) { Wire.beginTransmission(EEPROM_I2C_ADDRESS); Wire.write((int)(address >> 8)); // MSB Wire.write((int)(address & 0xFF)); // LSB Wire.write(val); Wire.endTransmission(); delay(5); } byte readAddress(int address) { byte rData = 0xFF; Wire.beginTransmission(EEPROM_I2C_ADDRESS); Wire.write((int)(address >> 8)); // MSB Wire.write((int)(address & 0xFF)); // LSB Wire.endTransmission(); Wire.requestFrom(EEPROM_I2C_ADDRESS, 1); rData = Wire.read(); return rData; } Example Application You can easily interface this device with other microcontrollers. The figure below shows the connections. The microcontroller sends the data to EEPROM 24C04 which stores the data. You can use this circuit for designing smart car parking systems. Every customer who enters the parking area enters his CNIC number through a keypad. Microcontroller stores this CNIC number into the EEPROM device. Now, if the customer wants to open that lock, the LCD will display “Enter your CNIC number” command. If the CNIC entered is matched with the stored CNIC in the EEPROM, it will open the lock where the car of a user is parked.
https://microcontrollerslab.com/24c04-two-wire-serial-eeprom-interrfacing-arduino/
CC-MAIN-2021-39
refinedweb
907
58.58
>>. Sad that you consider abandoning this project... I'd like to use it in my game, but pyBox2D seems a little bit hard and non-pythonic. Maybe I'm just too lazy. Anyway, the BoxCutter example is great! But it crashes sometime with that message: Assertion failed: d.y >= 0.0f, file Collision/Shapes/b2PolygonShape.cpp, line 225 I am sorry to hear that you are considering dropping it. Please check out Mekanimo (mekanimo.net). Currently I am using a custom DLL using box2d but was considering using pybox2d in the near future. Thanks for the feedback, guys. I don't know, perhaps I'm expecting too much. But for the 6 months or so that I've maintained the project, thotep's bug is probably the 2nd I've gotten from a user. Is the code just that good? Of course not. Oh, and those degenerate shapes should be caught by the checkValues() function. I'll take a look into it... I can understand the issues with it being non-Pythonic, and have considered restructuring the API in the past. However, given the huge amount of support you can receive from the Box2D forums for the standard API, and the support of only one person for the Python API, ... well, the choice was obvious. fahri: Your Mekanimo project looks very nice! I think box2d has much more functionality than chipmunk and I would really like to see your project continued. Maybe you want a contributor to the project? here is my first patch: Index: Python/testbed/pyglet/convert-from-pygame.py =================================================================== --- Python/testbed/pyglet/convert-from-pygame.py (revision 104) +++ Python/testbed/pyglet/convert-from-pygame.py (working copy) @@ -5,7 +5,7 @@ import re print "Running this will overwrite files." -os.system("pause") +raw_input() def checkFile(file): if file[-3:]==".py" and file[:5]=="test_": as in osx you don't have the pause command. I want to help in improving the packaging and the testbed of pybox2d, that is, if you want help. Leonardo: Thanks for the fix; I didn't test the OS X version as well as I should have. I would love some help with the project. Show me a bit more of what you can do to contribute (in some non-trivial cases) and I'd be happy to add you onto the project. Ok I will be posting patches on the issue tracker. @thotep: It was a very simple error on the size checking code, I fixed it and will be posting the patch on the issue tracker. I hope you don't abandon the project! I understand that the lack of feedback and projects using pybox2d put down the motivation for mantaining your project, and no one can blame you! I don't know if this helps, but I'm using pybox2d in a project, and it's working very well. This project is still no big deal, but I expect releasing something until the end of October. I'll post a comment when I put it online. Meanwhile, thank you for the very good work! Hey, just wanted to let you know that I've only begun following PyBox2D and think it's great. I looked at Chipmunk but thought it would be perfect to fit PyBox2D into my game--I can see how it'll save me a lot of time and effort. The only bug I could find was in the Python testbed test_SensorTest.py which dies when I try to run it on Kubuntu 8.04, Python 2.5.2, pygame 1.7.1: File "test_SensorTest.py", line 85, in Step center = ground.GetWorldPoint(circle.GetLocalPosition()) AttributeError: 'b2PolygonShape' object has no attribute 'GetLocalPosition' Thanks for the input, michael. Perhaps with Santagada's help and a bit of cheering on from you guys, the project will be able to continue. :) re: your bug, it's actually fixed in the latest SVN. Hi, I've "released" my project. It's still full of bugs and missing features, but take a look! =) Looks interesting! Hope to see it developed more. (Added it to the projects page here) Thank you! I'll surely develop it more, as I start creating my games and see missing features... NOOOOOO don't leave us! D= Granted, I haven't used pybox2d yet, but I plan to in the very near future! Seems like lots of people are abandoning their projects... bet you didn't know that I'm using pyBox2d in conjunction with Opioid2d for a side-scroller? Seems like Shang has better things to do, so O2d is not being worked on at the moment. Please don't follow in his footsteps! Looking forward to the implementation of planetary physics and something that will allow for top-view collision systems (eg. original Grand Theft Auto). Know anything about these? Zorbicon, you should take a look at the new controllers on pybox2d. I think you can simulate planetary physics with them. Thanks for your comments. Zorbicon, you can use it for overhead views with no problem -- just set gravity to (0,0). And as Santagada said, controllers should take care of the gravity. I look forward to seeing your projects. That's the main thing that will keep me interested in maintaining pybox2d. Thanks for the advice. I guess the finer point I'm getting at is simulating the resistance to changes in the inertia vector of an object traveling on different substances (like asphalt for cars and water for boats). After a certain threshold, a car skids, so the behavior is dynamic. Also boats turn more easily about their axis at lower speeds.... Anyway, keep up the good work. Sorry, just noticed the cartop demo. Nice! Sad that you are considering abandoning the project, I just discovered it and I like it better then pymunk. What about a module that offers a more pythonic interface but uses pybox2d on the inside? Re Pythonic API see issue 5: Glad to hear that you like it, but it would appear that you are in the minority. :)
http://pybox2d.blogspot.com/2008/10/202b0-released.html
CC-MAIN-2017-34
refinedweb
1,011
76.62
For this assignment, you may work alone or with a partner of your choice. If you work with a partner, both partners should contribute equally to the assignment and both partners must fully understand everything you submit. Remember to follow the pledge you read and signed at the beginning of the semester. For this assignment, you may consult any outside resources, including books, papers, web sites and people. If you use resources other than the class materials, lectures and course staff, explain what you used in a comment at the top of your submission or next to the relevant question. If you haven't figured out to start early and take advantage of the scheduled help hours and office hours by now, probably it won't do any good to remind you to do so again on this assignment. The main purpose of this assignment is to understand static typing and how to implement type checking in an interpreter, and to provide additional experience using Java to be well prepared to take cs2110 in the Spring. As introduced in Chapter 5, a type defines a possibly infinite set of values and the operations that can be performed on them. For example, Number is a type. Addition, multiplication, and comparisons can be performed on Numbers. In Scheme (and in Charme and the current Aazda interpreter before you modify it), types are latent: they are not explicitly denoted in the program text. Nevertheless, they are very important for the correct execution of a Scheme program. If the value passed as an operand is not of the correct type, an error will result. For example, evaluating (+ 1 true) produces a type error in Scheme and Aazda. Scheme has fairly strong type checking. If the types of operands do not match the expected types, it reports an error. Python has weaker type checking. Evaluating 1 + True in Python does not produce a type error. (Try guessing what the result will be before evaluating it in the Python interpreter to see what the actual result is.) One advantage of stronger type checking is it is often better to get errors than to get mysterious result. (See Martin Rinard's papers on the acceptability envelope for an alternate view.)Both Scheme and Python have dynamic type checking. This means types are checked only when an expression is evaluated. For example, evaluating (define (badtype a b) (+ (> a b) b))does not produce a type error even though their are no possible inputs for which badtype evaluates to a value: any application of badtype must produce a run-time type error. Expressions that are not well-typed produce errors when those expressions are evaluated, but not earlier. Your goal for the rest of this assignment is to add static type checking to Aazda. Static type checking checks that expressions are well-typed when they are defined, rather than waiting until they are evaluated. Static type checking reduces the expressiveness of our programming language; some expressions that would have values with dynamic type checking are no longer valid expressions. If a correct static type checker deduces the program is well-typed, there is no input on which it could produce a run-time type error. In many cases, it is much better to detect an error early, than to detect it later when a program is running. This is especially true in safety-critical software (such as flight avionics software) where a program failure can have disastrous results (such as a plane crashing). As with Java (but unlike Scheme and Python), Aazda will use manifest types: every definition and parameter will include explicit type information that describes the expected type of the variable or parameter. This increases the length of the program text and sacrifices expressiveness, but makes it easier to understand and reason about programs. To provide manifest types, we change the language grammar to support explicit type declarations. /* Modified for Question [N] */ your changed code /* End Modifications for Question [N]*/ To provide manifest types, we modify the grammar for Aazda to include type declarations. Two rules need to change: definitions and lambda expressions. We replace the original definition rule, Definition → (define Name Expression)with a rule that includes a type specification after the name (we will define the Type nonterminal for denoting a type later): Definition → (define Name : Type Expression) We modify the lambda expression grammar rule similarly to include a type specification for each parameter: Expression → ProcedureExpression ProcedureExpression → (lambda (Parameters)Expression) Parameters → ε Parameters → Name : Type Parameters The new nonterminal, Type, is used to describe a type specification. A type specification can specify a primitive type. Like a primitive value, a primitive expression is pre-defined by the language and its meaning cannot be broken into smaller parts. Aazda supports only two primitive types: Number (for representing numbers), and Boolean (for representing the Boolean values true and false). (Adding support for Pair types is not required for this assignment, so the cons, car, cdr, and list primitives are not part of static Aazda.) We also need constructs for specifying procedure types. The type of a procedure is specified by the type of its inputs (that is, a list of the input types), and the type of its results (an Aazda procedure can only return one value, so the result type is a singleton). The arrow symbol, -> symbol is used to denote a procedure type, with the operand type list on the left side of the arrow and the result type on the right side of the arrow. To avoid ambiguity when specifying procedures that have procedure result types, we use parentheses around the procedure type specification. The grammar for type specifications is: Type → PrimitiveType | ProcedureType PrimitiveType → Number | Boolean ProcedureType → ( ProductType -> Type) ProductType → (TypeList) TypeList → Type TypeList | ε For example, (define x : Number 3)defines x as a Number and initializes its value to 3. The definition, (define square : ((Number) -> Number) (lambda ((x : Number)) (* x x)))defines square as a procedure that takes one Number input and produces a Number as its output. Here is a definition of a compose procedure that takes two procedures as inputs and produces a procedure as its output: (define compose : ((((Number) -> Number) ((Number) -> Number)) -> ((Number) -> Number)) (lambda ((f : ((Number) -> Number)) (g : ((Number) -> Number))) (lambda ((x : Number)) (g (f x))))) The compose example reveals two important disadvantages of static, manifest types. The first is that manifest types add a lot to the size of a program. You will notice this in your Java programs also. The second is that static types reduce expressiveness of Aazda compared with Charme. This procedure only works on a small subset of the inputs for which the typeless compose procedure works, namely procedures that take Number inputs and produce a Number output. If we want to compose procedures that operate on Boolean inputs, we would need to define a separate procedure with a different type specification. To support type definitions without spaces, we also modify the Tokenizer to treat : as a separate token (like ( and ) in the original Tokenizer. The first step in adding static type checking to our interpreter is to define classes for representing types. We will use inheritance to define the APrimitiveType and AProcedureType classes as subtypes of the AType class (we prefix our names with A for Aazda, to avoid confusion with the other type names). There are three classes (included in taazda.zip): AType.java, APrimitiveType.java, and AProcedureType.java. AType is the supertype class; all of the types we represent are AType objects. The APrimitiveType and AProcedureType are subclasses that inherit from AType. The APrimitiveType class provides a specialized class for representing primtive types (Boolean and Number); the AProcedureType is for representing procedure types which have a return type and parameter types. The AType class is an abstract class. This means that it provides no constructors. Hence, there is no way to construct an AType directly, only to create its subtypes. The AType class defines one abstract method: public abstract boolean match(AType p_t);An abstract method is not implemented, but it specifies a method that must be implemented by subtypes of AType. The match method takes an AType as its input, and outputs a boolean that indicates if this type matches the input type. The APrimitiveType class is a subtype of AType for representing the primitive types. In Java, this is done using extends in the class declaration. We use a String to represent each type: package aazda; public class APrimitiveType extends AType { private String tname; public APrimitiveType(String p_name) { tname = p_name; }Since APrimitiveType is a concrete type, it must implement the abstract match(AType t) method from the superclass: public boolean match(AType t) { if (t instanceof APrimitiveType) { APrimitiveType pt = (APrimitiveType) t; return tname.equals(pt.tname); } else { return false; } }This method needs to work for any AType input, not just for other APrimitiveTypes. So, the first thing it does is check if the input is a primitive type (that is, is its type APrimitiveType) by using t instanceof APrimitiveType). If the predicate is false, the input is some other kind of type, so it cannot match and it returns false. If it is a primitive type, we check if the type names are the same using equals. The APrimitiveType class also implements a toString() method that overrides the toString() method provided by the java.lang.Object class (which every Java class inherits from). This will produce a human-readable String that represents the type. Representing procedure types is more complicated since they have both a return type (an AType) and parameters (an ArrayList<AType>). The AProcedureType class does this using the result and params private instance variables. Look at the provided code in AProcedureType.java to understand how procedure types are represented, and how the match method works for procedure types. The AType class provide a method AType parseType(SExpr) that converts a type expressed as an s-expression (that is, the result of Parser.parse(String)) into an AType. You should be able to read and understand the code for parseType(SExpr) in AType.java, but will not need to modify this code. The AType class includes a main method for testing the type implementation. The provided code includes some simple tests. For the next exercise, you should modify this code. With static typing, each place has an associated type. In Java, a variable declaration introduces a new name and gives that name a type. For example, int a;declares a place named a that can only hold values of type int. To support typed places, we need to modify the Environment type to associate types with places. We do this by defining a Place class that packages a type (AType) and a value (SVal): class Place { // Place has a type and value AType type; SVal val; public Place(AType p_type, SVal p_val) { type = p_type; val = p_val; } }Then, we change the frame to be a HashMap<String, Place> so there is both a type and value associated with a name in the frame. The lookup methods are changed accordingly to support both looking up the type and value associcated with a name. The main change to the evaluator is adding a method, public static AType typeCheck(SExpr expr, Environment env)that performs static type checking and returns the type of expr in the environment env. The meval method is modified to call typeCheck before evaluating an expression: public static SVal meval(SExpr expr, Environment env) throws EvalError, TypeError { typeCheck(expr, env); if (isPrimitive(expr)) { ...If the expression is not well-typed, typeCheck will throw a TypeError exception and exection of meval will terminate. The typeCheck method (defined in Evaluator.java) is very similar to meval except instead of calling evalRule it calls typeRule: public static AType typeCheck(SExpr expr, Environment env) { if (isPrimitive(expr)) { return typePrimitive(expr); } else if (isName(expr)) { return typeName(expr, env); } else if (isIf(expr)) { return typeIf(expr, env); } else if (isCond(expr)) { return typeCond(expr, env); } else if (isAssignment(expr)) { typeAssignment(expr, env); return AType.Void; } else if (isDefinition(expr)) { typeDefinition(expr, env); return AType.Void; } else if (isLambda(expr)) { return typeLambda(expr, env); } else if (isBegin(expr)) { return typeBegin(expr, env); } else if (isApplication(expr)) { return typeApplication(expr, env); } else { throw new TypeError("Unknown expression type: " + expr.toString()); } }Each of the typeRule methods takes an expression and environment as its inputs, and returns the type of that expression (or throws an exception if it is not well-typed). For the expression that have no type, we use the AType.Void to represent a non-value. For example, below is the definition of typeIf (with some error checking removed, see the full code in Evaluator.java). It first checks that the type of the predicate expression is a Boolean. This uses typeCheck recursively, similarly to the way evalIf uses meval to evaluate the value of the predicate expression. (Indeed, the typeRule methods were created by starting from a copy of the code for the corresponding evalRule.) The key difference, though, is that the type checker does not actually evaluate any expression, it just determines its type. public static AType typeIf(SExpr expr, Environment env) throws EvalError { ... SExpr pred = ifExpr.get(1); // error checking code removed SExpr consequent = ifExpr.get(2); SExpr alternate = ifExpr.get(3); // Check the predicate is a Boolean AType predType = typeCheck(pred, env); if (!predType.isBoolean()) { throw new TypeError( "Predicate for an in expression must be a Boolean. Type is: " + predType); } // Check both clauses have the same type AType consequentType = typeCheck(consequent, env); AType alternateType = typeCheck(alternate, env); if (consequentType.match(alternateType)) { return consequentType; } else { throw new TypeError( "Clauses for if must have matching types. Types are: " + consequentType.toString() + " / " + alternateType.toString()); } } We have provided a testing class, TestAazda.java, for testing taazda. You can run this by selecting the TestAazda main method for running.As provided, not all of the tests pass. Your assignment is to finish the taazda implementation; after this, all of the tests in TestAazda.java should pass. As provided, the Taazda interpreter cannot handle recursive definitions! For example, when we try to define factorial in Taazda (this is TestAazda.testFactorial()) we get an Undefined name factorial error. This is a serious problem, since without recursive definition we do not have a universal programming language. Note that meval is not an algorithm. It (hopefully) correctly always produces the value of any Taazda expression, but it is not guaranteed to terminate. Indeed, it is impossible to produce an algorithm for this, since that would require solving the Halting Problem. Since Taazda is a universal programming language, we can implement any mechanical computation in Taazda, including simulating a universal Turing Machine. Hence, we know the Taazda-Value problem described below is noncomputable:. Taazda-ValueInput: A string, expr, that is an expression in the Taazda language.Output: The value of expr in the standard global environment, or Void if expr has no value. def halts(s): return taazdaValue(rewriteNoValue(s)) != VoidFor the last problem, consider the Taazda-Well-Typed problem described below: Taazda-Well-TypedInput: A string, expr, that is an expression in the Taazda language.Output: If expr is well-typed according to the Taazda type checking rules, output true. Otherwise, output false. Your answer should either (1) argue that type-checking is computable, supporting that argument by explaining why typeCheck always terminates; or (2) prove that type checking is noncomputable by showing how halts could be implemented using an algorithm that solves the type checking problem. (define identity : ((E) -> E) (lambda ((x: E)) x)) Supporting Lists also requires a special solution for null (what type should null have?) and if you want to support the list procedure for making arbitrarily long lists, a way to have parameter lists that can be any size. Is there a reason all the test passed in my TestAzzada class? I haven’t edited any code yet and the instructions indicate that not all the test should pass initially. In the distributed code, the failing tests are commented out. The main method in TestAazda.java is: public static void main(String[] args) { testIf(); testCompose(); // These tests are commented out for now, since they will fail with the provided interpreter. // As you answer the problems, uncomment each test. // testAssignment(); // will fail until Problem 1 // testBegin(); // will fail until Problem 2 // testCond(); // will fail until Problem 3 // testFactorial(); // will fail until Problem 4 } When you start, it should pass the first two tests. As you make progress in the assignment, you should uncomment the other tests by removing the // in front of testX();. For typeBegin and typeCond, is the return expression currently there (AType.Error) only a placeholder for our input, or should that remain there after we add code? Yes, that is just there so the code compiles before you implement those methods. You should replace them with your code. Is the Alonzo Bot ready for us? I’ve tried to submit the ps8 about three times over the course of today, and it always claims the page cannot be found. (the ubiquitous 404 error) Sorry about that. It is up now. Please try again and let me know if you run into any problems. Thank you. The bot is there now… although it gives me this error “Zipfile is not complete. Missing Evaluator.java. Are you sure you zipped all the files in your /taazda/src/taazda directory?” I am positive Evaluator.java is there. I tried it several times. It takes the zip nonetheless, so I’m good :-). The problem is your zipfile is the taazda directory, not the files in it. When your file unzips, it produces the directory taazda which contains all the source files. The tester expects the zip file to just be the files, not contained in any directories. You should be able to create it by just selecting all the files in your taazda/src/taazda directory and zipping them. Now, that’s embarrassing. Done.
https://www.cs.virginia.edu/~evans/cs1120-f11/problem-sets/problem-set-8-part-2-typed-aazda
CC-MAIN-2018-05
refinedweb
2,989
54.22
I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment. Here is as a code I use: #include <iostream> #include <string> #include <fstream> #include <sys/time.h> #include <sys/wait.h> using namespace std; struct timeval first, second, lapsed; struct timezone tzp; int main(int argc, char* argv[])// query, file, num. of processes. { int pCount = 5; // process count gettimeofday (&first, &tzp); //start time pid_t* pID = new pid_t[pCount]; for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++) { pID[indexOfProcess]= fork(); if (pID[indexOfProcess] == 0) // child { // code only executed by child process //magic here exit(0);// The End } else if (pID[indexOfProcess] < 0) // failed to fork { cerr << "Failed to fork" << endl; exit(1); } else // parent { // if(indexOfProcess==pCount-1) and a loop with waitpid?? gettimeofday (&second, &tzp); //stop time if (first.tv_usec > second.tv_usec) { second.tv_usec += 1000000; second.tv_sec--; } lapsed.tv_usec = second.tv_usec - first.tv_usec; lapsed.tv_sec = second.tv_sec - first.tv_sec; cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl; } }//for }//main I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest: for (int i = 0; i < pidCount; ++i) { int status; while (-1 == waitpid(pids[i], &status, 0)); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl; exit(1); } } gettimeofday (&second, &tzp); //stop time I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are supposed to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly. An alternative using wait: while (true) { int status; pid_t done = wait(&status); if (done == -1) { if (errno == ECHILD) break; // no more child processes } else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { cerr << "pid " << done << " failed" << endl; exit(1); } } } This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.
https://codedump.io/share/lYZCCEjYq1ww/1/how-to-wait-untill-all-child-processes-called-by-fork-complete
CC-MAIN-2017-04
refinedweb
414
66.37
This is the mail archive of the cygwin mailing list for the Cygwin project. Hi, Sinan, Please don't send personal mail with Cygwin questions unless specifically requested. All Cygwin-related queries should go to an appropriate Cygwin mailing list (see <>). The lists can also be accessed as newsgroups via <> (see the "Unofficial newsgroup" link on the Cygwin homepage). That way not only do you get access to the combined expertise of the community, which is more than any one person can provide, but your query and the answers also get into the archives, where they could be later found by others with the same problem. For your convenience, I'm directing this reply to the main Cygwin mailing list, and setting the Reply-To: field accordingly. Please send any follow-up messages to the mailing list. More replies inline below. On Thu, 1 Apr 2004, Sinan Yalcin wrote: > hello.. I took your mail address from cygwin.com.. I am a graduate > student at Sabanci University, Turkey.. > I want to ask a question to you about cygwin package installation.. I > will be glad if you can answer... > > During installation, I chose all packages(full) installation. But, 4 > packages were absent at the intranet server > of our university: these were... > libdb2 ............ The Sleepycat Berkeley DB Library v2 - runtime > libdb2-devel ... The Sleepycat Berkeley DB Library v2 - devel > libdb3.1.......... The Sleepycat Berkeley DB Library v3.1 - runtime > libdb3.1-devel..The Sleepycat Berkeley DB Library v3.1 - devel > > libltdl3 Libtool's dynamic loader (runtime) > > So, I unchecked only above packages from full installation and completed > the installation successfully... > I want to ask you what those unchecked packages are, and whether any > problems their absence cause > or not.. > Thank you very much... As far as I know, Berkeley DB is required by some other packages, e.g., cvs. Explicitly unchecking them will mean that you essentially override the dependencies from other packages, and those packages will probably not work. If your server doesn't have them, then it's a broken mirror, and you would be well advised to select another one. Also, for the future, the best way to report the state of your Cygwin installation is by attaching (as an uncompressed text attachment, not inline) the output of "cygcheck -svr", as requested in the Cygwin problem reporting guidelines at <> (a good read in any case). > Also I want to mention that, I faced with g++3 iostream (cout, main(), > etc...) problem, and solved by your > existing mail ("using namespace std;").. I want to ask that: is this > solution must for all .cpp files for g++3, and > do I face with any more problems about g++3? which version of g++ does > not have such problems? > and what is the latest version of g++? To find out which packages are available in Cygwin, see the Cygwin package list/search page at <>. The "using namespace std;" approach is just one of the possible fixes (another would be to prefix all occurrences of "cout" and others by "std::"), and it will be necessary everywhere due to the more stringent syntax of g++-3.*. > Thanks a lot for your help... On Thu, 1 Apr 2004, Sinan Yalcin wrote: > Pardon.. I forgat to say that: > By full installation of cygwin, my download folder is 250MB, and > installed folder is 870MB... > Isn't it too much? Is there too much unnecessary applications? > I have seen 170MB installed folder.. > Thank you... > With my best regards.... I suggest looking at the package descriptions to find out which ones you do and don't need. It's generally advised to install at least the "Base" category (which is selected by default in new installations) and then select individual packages that you feel you will need. Setup should automatically select other packages that the ones you selected depend on, but it doesn't check these dependencies once the selection is made, so don't unselect anything once you've selected it (or start over if you feel you've made a mistake). See also <>.:
http://cygwin.com/ml/cygwin/2004-04/msg00030.html
CC-MAIN-2015-35
refinedweb
675
65.42
It's probably an easy program to fix but as a newbie I'm having trouble understanding the concept of class. I'm supposed to create a person class to represent a person. (You may call the class personType.) To simplify things, have the class have 2 variable members for the person's first and last name. Include 2 constructors. One should be a default constructor and the other should be one with parameters. Include respective functions for: setting the name, getting the name, and printing the name on the screen. This is what I did so far, but I'm having trouble running it. If anyone can explain what I'm doing wrong I would greatly appreciate it.If anyone can explain what I'm doing wrong I would greatly appreciate it.Code:#include <iostream> #include <cstring> #include <cstdlib> using std::cout; using std::cin; using std::endl; using namespace std; class personType { public: void print() const; void setName(string first, string last); void getName(string& first, string& last); personType(string first, string last); //Constructor with parameters private: string firstName; //store the first name string lastName; //store the last name}; }; int Main () { personType(); //Default constructor; { string firstName; //store the first name string lastName; //store the last name } void personType::print() { cout<<firstName<<" "<<lastName; } void personType::setName(string first, string last) { firstName = first; lastName = last; } return 0; } Thanks
http://cboard.cprogramming.com/cplusplus-programming/71262-need-help-get-working.html
CC-MAIN-2015-11
refinedweb
228
60.75
In this presentation from GOTO Conference CPH 2015, Marin shows how to create animations in UIKit with Swift that work with Auto Layout UIs. He looks into using existing constraints in animations, as well as replacing those constraints to create better animations. He also touches on how and when to trigger animated and static layout updates, discussing how and why those animations work like a breeze. Then a bonus! - a demo of animating with iOS 9’s UIStackView. Introduction (0:00) My name is Marin Todorov and I’m an independent developer and author. I split my time between my own studio for making iPhone apps and a website called raywenderlich.com. At the beginning of 2015, I published a book called iOS Animations by Tutorials, a fantastic book about animations on iOS. I also write a monthly animations newsletter. I’m here today to talk about Auto Layout and stack views. Animations are fantastic in iOS 7, 8 and 9 because we no longer have rich user interfaces that have wood backgrounds or steel concrete gutters. Today, iOS is mostly text and color. You have to find new ways to put your brand up in the front of everyone and make your app distinguishable from the others. For example, this screenshot could be one of Apple’s built-in apps, or it could be a custom app that somebody invested hundreds of hours designing. Animations are an amazing way to make your app unique. The above example is the built-in contacts app in iOS, but it may have been difficult to tell because it’s about white space, text and color. If you have ever written an app on iOS you have done at least one animation. Most animation tutorials start with the red square. The square moves along with a single line of code using animateWithDuration. You specify how long you want the animation to go and define the final values for the target animation. In this example, the UIKit API will take the current values and current position of the red square and create an animation over one second moving it on the x-axis to value of 200—looking something like this. UIView.animateWithDuration(1.0, animations: { redSquare.center.x = 200.0 }) This was fantastic with iOS 3, 4 and 5, but then we were introducted to new screens. Things changed. Moving the red square to the point 200 on the x-axis didn’t mean much anymore. Before having different screen sizes, you knew where the screen started; point 0. Then, you moved it 200 points to the right. With the iPhone 6, 6+ or 5S, for example, you no longer know what it means to move to point 200. It might be close to the edge of the screen, straight in the center, or anywhere. Get more development news like this Before going further, I want to say it’s better to understand how things work and why they happen so you know what to do the next time you encounter a similar problem. Do not run off to Stack Overflow and accept the first answer without an understanding of the solution. Auto Layout is Different Than Pre–Auto Layout (6:17) Auto Layout is different than pre–Auto Layout. I’ll demonstrate with a quick demo. My hope is that you’ll know how create animations with Auto Layout by the end, or at least know how to approach them. Here is my storyboard in a present day application. I’m using Auto Layout. I have a login screen for an imaginary app and I have a username and password field at the top. I want to animate them towards the center of the screen when a user opens the app. I laid out everything in Interface Builder, centered the fields and put constraints on username and password. Then, let’s imagine I go to Stack Overflow to see how I can create an animation. Super Awesome Ninja Dev has answered my question, “Call your animation with duration and then change the center property and that should work.” I go to my code and put in UIView.animationWithDuration, with half a second duration. I have two outlets, username and password. I’m going to try to animate their center property. They’re still not entirely visible because I didn’t make them fully opaque, so I’m going to make them opaque as well. override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.5, animations: { self.fldPassword.center.y += 200 self.fldUsername.alpha = 1.0 self.fldPassword.alpha = 1.0 }) UIView.animateWithDuration(0.5, delay: 0.1, options: [], animations: { self.fldUsername.center.y += 200 }, completion: nil) } I run into a problem when I enter the username. Everything jumps up as soon as I focus on the text field. Two things are happening. First, the fields repositioned to where they were originally. Second, they did not fade out as they were originally. Auto Layout makes your layout for you automatically, but here you went over its head and changed the position of these views manually. That’s not good. The first moral of this talk is not everything about animation changes with Auto Layout. It’s fine if you animate the alpha or a background call or something like that—that still works the old way. What does not work in the old way is changing the center manually. The question is why did it jump back like this when I tapped into the text field? When you lay down buttons, labels, images, etc. in Interface Builder and set up your constraints, you’re attaching a list of constraints on those views that explain the relationship between them. In the end, everything depends on the size of the screen. For example, when the keyboard jumps up or when a call is incoming, the size of the container or view controller changes. NSLayoutConstraint subclasses NSObject. It’s not a kind of visual class. It doesn’t have the tremendous logic behind it; it’s just a model. It contains few properties that define an equation so that you can set rules. For example, buttons should be always centered. It’s important to know that the constraints you design in Interface Builder are models—data objects that contain few pieces of information. They don’t draw anything with UIKit or move your views, but Auto Layout does. When things need to appear on screen or find their spot on the screen, Auto Layout grabs the list of constraints, solves the equations and finds where the views should appear on screen. There are all kind of constraints. There’s width, height, center X, margin Y, ratio between width and height, vertical space and vertical to margins, and more. But, when Auto Layout solves all these rules that you set up, it changes the position of your views and their size. That’s all it does. Auto Layout reacts to internal and external changes to a layout. Examples of internal changes are changes in constraints, removal of constraints or a changes in code. An example of an external change is rotating the device, which changes the size of the view controller. Let’s say that you push a view controller when you load up an app. First, the app loads the view from the story board. Auto Layout needs to solve the layout so that it knows where to show things on screen. It solves all your constraints and finds the position of all the views. However, if you tap on a text field, for example, the keyboard will pop up and change the size of the view controller margins. This will trigger another pass on the layout and Auto Layout will have the orientation change. Auto Layout will again get the list of constraints, calculate them based on the container size, and then reposition. How can we do proper animations? Any changes made within the following closure will be animated. UIView.animateWithDuration(1.0, animations: { view.center.x -= 10 }) There’s a list of the animatable properties such as alpha, background caller, position, size, etc. that you can change within the closure and they will be automatically automated by UIKit. Now, we need to connect a pass on the Auto Layout that takes all the constraints, recalculates them and changes center and bounds which are animatable properties. We’re getting really close to what was happening before, but we need to change the constraints and force a pass on the layout from within the animation block. Let me quickly show how to do it from code. This my next example for showing constraints and how to animate them. I have a little to-do list app and I have this top bar that I want to dynamically resize. To show you the premise, let me open the story board file. There’s one view on the top and one table view on the bottom. The top view is pinned to the top, the table view is pinned to the bottom, and they’re pinned to each other. I have the height constraint of this one that says it’s going to be height 60 points. There are two ways to animate constraints. The first is when you want to change the constant of a constraint. You can do this by opening the properties and editing the height, for example. I know which constraint I want to animate so I’m going to go to my view controller and I’m going to make an outlet. Since constraints are something that you lay down in Interface Builder, you can also make outlets and use them to access constraint in real time. I’m going to put in an IBOutlet called menu height, and it’s going to be of type NSLayoutConstraint. @IBOutlet weak var menuHeight: NSLayoutConstraint! Then, any other button view, text view, etc. that you’re used to doing by using by outlets, you can go to the story board, find the height constraint, come to the Connections Inspector and drag from the new referencing outlet back to view controller, connecting your outlet to the constraint. @IBAction func actionToggleMenu(sender: AnyObject) { menuHeight.constant = 200 } I changed the constraint, and this is a change that will not be undone randomly because now the constraint says that it’s going to be a height of 200. Since we can control the constraint now, the animations are really easy to do. Wrap it up with an animateWithDuration call or a spring animation. I’m going to use a spring animation. This is the default UIKit API, again. Nothing really crazy going on. UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0, options: [], animations: { self.view.layoutIfNeeded() }, completion: nil) What I said on my slide and I’m going to stick to it, was changing the constraints anywhere in code, and then force a pass on that Auto Layout from within the animation block. The layout pass is the one that changes the center and the bounds and so forth. Changing the constraints doesn’t do anything. It does not do anything. Having a pass on the layout and layout changing center and bounds, this is what does something. Let’s do exactly this. My constraint here is updated, and here from the animations block I’m just going to say, view.layoutIfNeeded(), which will force Auto Layout to immediately consider all constraints, and if anything changed, then recalculate everything and change the position and size of views. That’s why it’s called layoutIfNeeded(). Because maybe you didn’t change anything, then it will not do anything. This time, when I click it, then this change in the constraint is already animated. What is really important here to note is that I don’t animate anything on the table view. I have only one line that changes the constraint on the top bar. I don’t really tell the table view to do anything, but… since the top view and the table view are pinned together, changing the height of the one also changes the height of the other. I don’t really do this explicitly, I leave Auto Layout to solve all the rules that I laid down. And since the rules that I did was so that they stay together, that changes both. Also the changes to both are animated because their bounds were changed from within the animation block. This is really easy and now you can do all kinds of other stuff further from here. The second thing I want to show is changing the multiplier on a constraint. The multiplier is read-only. To change a multiplier, you must loop over all the constraints, find the one you want to change, kill it, and then put a new one in its place. for c in titleLabel.superview!.constraints { print(c) if c.identifier == "Center" { c.active = false let nc = NSLayoutConstraint( item: titleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: titleLabel.superview!, attribute: .CenterX, multiplier: 1.5, constant: 0) nc.active = true } } In Xcode 7, there is a new field when you are editing your constraints called Identifier. Identifier is a way to give your constraint a name. This property also existed in iOS 8, but Xcode 6 did not have a text box for it. Everything I say is valid if you’re using Xcode 6, but you will need to use the user definer and time attributes to set identifier. In Cocoa, you have to set delegates and build relationships and things like this, but not with this API. With this API, as long as you set active property on your constraint to false, next time Auto Layout does a pass, it will say, “This constraint is not active, I don’t need it.” The same thing goes for when you are adding new constraints. When you set active, the next time Auto Layout does a pass, it will say, “This is active” and will add it to the list of constraints. There is an API that is a static method on NSLayoutConstraint where you can add more constraints at the same time, but what it does is go over all of them and set active to true. And those are the two easy ways to animate constraints. Make an outlet and change a constant and change a multiplier by removing a constraint and adding a new one. And most importantly, call layoutIfNeeded() from within an animation block if needed. Stack Views (38:12) Stack views are “Auto Layout without constraints.” This is a way to create Auto Layout animations without having to animate constraints. I have a third sample project to demonstrate stack views. Its premise is a shop application. It will show you the list of all books that are worked on that you can purchase also. The app consists of a list of books and when you click on the detail view controller, you will see the cover of the book with additional details. import UIKit class DetailViewController: UIViewController { var book: MasterViewController.Book! @IBOutlet weak var cover: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var year: UILabel! @IBOutlet weak var topStack: UIStackView! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) configureView() view.addGestureRecognizer( UITapGestureRecognizer(target: self, action: "didTap") ) } func didTap () { UIView.animateWithDuration(0.4, animations: { self.topStack.arrangedSubviews.last!.hidden = !self.topStack.arrangedSubviews.last!.hidden }) } func configureView() { //set the views if cover != nil { cover.image = UIImage(named: "\(book.imageName).jpg") } if name != nil { name.text = book.title } if year != nil { year.text = book.year } } } What I want to have is some text that will show the name of the book, year of release, etc. I’m going to call this Title using one label. Then, I’m going to call another one Book Title. Stack views are a way to group views and we have some views we want to group together forever. There’s a property called axis, which defines whether the stack view is horizontal or vertical. And there’s an alignment property that you can change from top, bottom or center. The stack view only keeps reference to the views that are arranged in there, and will take all the properties into consideration. All it does is manage the constraints for the arranged views so you don’t have to change the constraint of those views. It will create the constraints for you so that they’re aligned the way you want them. About the content This talk was delivered live in October 2015 at goto; Copenhagen. The video was transcribed by Realm and is published here with the permission of the conference organizers.
https://academy.realm.io/posts/gotocph-marin-todorov-auto-layout-animations-ios/
CC-MAIN-2021-17
refinedweb
2,791
65.83
Objective like. Note - I recommend that everyone read Chapter 2, "More About C Variables." In my experience, many who should be familiar with the material it contains are not familiar with that material. There are many books on C. The original Kernighan and Ritchie book, The C Programming Language, is still one of the best.1 It is the book most following. This chapter begins by looking at some structural aspects of a C program: the main routine, formatting issues, comments, names and naming conventions, and file types.: // This is a comment. /* This is the other style of comment */ This type of comment may extend over multiple lines. For example: /* This is a longer comment. */ It can be used to temporarily "comment out" blocks of code during the development process. This style of comment cannot be nested: /* /* WRONG - won't compile */ */ However, the following is legal: /* // OK - can nest end of line comment */ Variable and function names in C consist of letters, numbers, and the underscore character ( _ ): Here are some legal names: j taxesForYear2010 bananas_per_bunch bananasPerBunch These names are not legal: 2010YearTaxes rock&roll bananas per bunch As a kindness to yourself and anyone else. The code for a plain C program is placed in one or more files that have a .c filename extension: ACProgram.c Note - Mac OS X filenames are not case sensitive. The file system will remember the case you used to name a file, but it treats myfile.c, MYFILE.c, and MyFile.c as the same filename. Code that uses the Objective-C objects (the material covered starting in Chapter 3, "An Introduction to Object-Oriented Programming") is placed in one or more files that have a .m filename extension: AnObjectiveCProgram.m Note - Because C is a proper subset of Objective-C, it's OK to put a plain C program in a .m file. a #include or #import preprocessor directive. (See Preprocessor, later in this chapter.) Header files have a .h filename extension as shown here: AHeaderFile.h Note - The topic is beyond the scope of this book, but it is possible to mix Objective-C and C++ code in the same program. The result is called Objective-C++. Objective-C++ code must be placed in a file with a .mm filename extension: AnObjectiveCPlusPlusProgram.mm For more information, see Using C++ With Objective-C. A variable is a name for some bytes of memory in a program. When you assign a value to a variable, what you are really doing is storing that value in those bytes. Variables in a computer language are like the nouns in a natural language. They represent items or quantities in the problem space of your program. C requires that you tell the compiler about any variables that you are going to use by declaring them. A variable declaration has the form: variabletype name; C allows multiple variables in a single declaration: variabletype name1, name2, name3; A variable declaration causes the compiler to reserve storage (memory) for that variable. The value of a variable is the contents of its memory location. The next chapter describes variable declarations in more detail. It covers where variable declarations are placed, where the variables are created in memory, and the lifetimes of different classes of variables. C provides the following types to hold integers: char, short, int, long, and long long. Table 1.1 shows the size in bytes of the integer types on 32- and 64-bit Mac OS X executables. (32-bit and 64-bit executables are discussed in Appendix C, "32-Bit and 64-Bit.") The char type is named char because it was originally intended to hold characters; but it is frequently used as an 8-bit integer type. An integer type can be declared to be unsigned: unsigned char a; unsigned short b; unsigned int c; unsigned long d; unsigned long long e; When used alone, unsigned is taken to mean unsigned int: unsigned a; // a is an unsigned int An unsigned variable's bit pattern is always interpreted as a positive number. If you assign a negative quantity to an unsigned variable, the result is a very large positive number. This is almost always a mistake. C's floating-point types are float, double, and long double. The sizes of the floating-point types are the same in both 32- and 64-bit executables: float aFloat; // floats are 4 bytes double aDouble; // doubles are 8 bytes long double aLongDouble; // long doubles are 16 bytes Floating-point values are always signed. Ordinary expressions are commonly used for truth values. Expressions that evaluate to zero are considered false, and expressions that evaluate to non-zero are considered true (see the following sidebar). _Bool, bool, and BOOL - Early versions of C did not have a defined Boolean type. Ordinary expressions were (and still are) used for Boolean values (truth values). As noted in the text, an expression that evaluates to zero is considered false and one that evaluates to non-zero is considered true. A majority of C code is still written this way. C99, the current standard for C, introduced a _Bool type. _Bool is an integer type with only two allowed values, 0 and 1. Assigning any non-zero value to a _Bool results in 1: _Bool b = 35; // b is now 1 If you include the file stdbool.h in your source code files, you can use bool as an alias for _Bool and the Boolean constants true and false. (true and false are just defined as 1 and 0, respectively.) #include <stdbool.h> bool b = true; You will rarely see either _Bool or bool in Objective-C code, because Objective-C defines its own Boolean type, BOOL. BOOL is covered in Chapter 3. Variables can be initialized when they are declared: int a = 9; int b = 2*4; float c = 3.14159; char d = 'a'; A character enclosed in single quotes is a character constant. It is numerically equal to the encoding value of the character. Here, the variable d has the numeric value of 97, which is the ASCII value of the character a. A pointer is a variable whose value is a memory address. It "points" to a location in memory. You declare a variable to be a pointer by preceding the variable name with an * in the declaration. The following code declares pointerVar to be a variable pointing to a location in memory that holds an integer: int *pointerVar; The unary & operator ("address of" operator) is used to get the address of a variable so it can be stored in a pointer variable. The following code sets the value of the pointer variable b to be the address of the integer variable a: 1 int a = 9; 2 3 int *b; 4 5 b = &a; Now let's take a look at that example line by line: Figure 1.1 illustrates the process. (Assume that the compiler has located a beginning at memory address 1048880.) The arrow in the figure shows the concept of pointing. The unary * operator (called the "contents of" or "dereferencing" operator) is used to set or retrieve the contents of a memory location by using a pointer variable that points to that location. One way to think of this is to consider the expression *pointerVar to be an alias, another name, for whatever memory location is stored in the contents of pointerVar. The expression *pointerVar can be used to either set or retrieve the contents of that memory location. In the following code, b is set to the address of a, so *b becomes an alias for a: int a; int c; int *b; a = 9; b = &a; c = *b; // c is now 9 *b = 10; // a is now 10 Pointers are used in C to reference dynamically allocated memory (Chapter 2). Pointers are also used to avoid copying large chunks of memory, such as arrays and structures (discussed later in this chapter), from one part of a program to another. For example, instead of passing a large structure to a function, you pass the function a pointer to the structure. The function then uses the pointer to access the structure. As you will see later in the book, Objective-C objects are always referenced by pointer. A variable declared as a pointer to void is a generic pointer: void *genericPointer; A generic pointer may be set to the address of any variable type: int a = 9; void *genericPointer; genericPointer = &a; However, trying to obtain a value from a generic pointer is an error because the compiler has no way of knowing how to interpret the bytes at the address indicated by the generic pointer: int a = 9; int b; void *genericPointer; genericPointer = &a; b = *genericPointer; // WRONG - won't compile To obtain a value through a void* pointer, you must cast it to a pointer to a known type: int a = 9; int b; void *genericPointer; genericPointer = &a; b = *((int*) genericPointer) ; // OK - b is now 9 The cast operator (int*) forces the compiler to consider genericPointer to be a pointer to an integer. (See Conversion and Casting, later in the chapter.) C does not check to see that a pointer variable points to a valid area of memory. Incorrect use of pointers has probably caused more crashes than any other aspect of C programming. C arrays are declared by adding the number of elements in the array, enclosed in square brackets ([]), to the declaration, after the type and array name: int a[100]; Individual elements of the array are accessed by placing the index of the element in [] after the array name: a[6] = 9; The index is zero-based. In the previous example, the legitimate indices run from 0 to 99. Access to C arrays is not bounds checked on either end. C will blithely let you do the following: int a[100]; a[200] = 25; a[-100] = 30; Using an index outside of the array's bounds lets you trash memory belonging to other variables resulting in either crashes or corrupted data. Taking advantage of the lack of checking is one of the pillars of mischievous malware. The bracket notation is just a nicer syntax for pointer arithmetic. The name of an array, without the array brackets, is a pointer variable pointing to the beginning of the array. These two lines are completely equivalent: a[6] = 9; *(a + 6) = 9; When compiling expression using pointer arithmetic, the compiler takes into account the size of the type the pointer is pointing to. If a is an array of int, the expression *(a + 2) refers to the contents of the four bytes (one int worth) of memory at an address eight bytes (two int) beyond the beginning of the array a. However, if a is an array of char, the expression *(a + 2) refers to the contents of one byte (one char worth) of memory at an address two bytes (two char) beyond the beginning of the array a. Multidimensional arrays are declared as follows: int b[4][10]; Multidimensional arrays are stored linearly in memory by rows. Here, b[0][0] is the first element, b[0][1] is the second element, and b[1][0] is the eleventh element. Using pointer notation: b[i][j] may be written as: *(b + i*10 + j) A C string is a one-dimensional array of bytes (type char) terminated by a zero byte. A constant C string is coded by placing the characters of the string between double quotes (""): "A constant string" When the compiler creates a constant string in memory, it automatically adds the zero byte at the end. But if you declare an array of char that will be used to hold a string, you must remember to include the zero byte when deciding how much space you need. The following line of code copies the five characters of the constant string "Hello" and its terminating zero byte to the array aString: char aString[6] = "Hello"; As with any other array, arrays representing strings are not bounds checked. Overrunning string buffers used for program input is a favorite trick of hackers. A variable of type char* can be initialized with a constant string. You can set such a variable to point at a different string, but you can't use it to modify a constant string: char *aString = "Hello"; aString = "World"; aString[4] = 'q'; // WRONG - causes a crash The first line points aString at the constant string "Hello". The second line changes aString to point at the constant string "World". The third line causes a crash, because constant strings are stored in a region of protected read-only memory. A structure groups a collection of related variables so they may be referred to as a single entity. The following is an example of a structure declaration: struct dailyTemperatures { float high; float low; int year; int dayOfYear; }; The individual variables in a structure are called member variables or just members for short. The name following the keyword struct is a structure tag. A structure tag identifies the structure. It can be used to declare variables typed to the structure: struct dailyTemperatures today; struct dailyTemperatures *todayPtr; In the preceding example, today is a dailyTemperatures structure, whereas todayPtr is a pointer to a dailyTemperatures structure. The dot operator (.) is used to access individual members of a structure from a structure variable. The pointer operator (->) is used to access structure members from a variable that is a pointer to a structure: todayPtr = &today; today.high = 68.0; todayPtr->high = 68.0; The last two statements do the same thing. Structures can have other structures as members. The previous example could have been written like this: struct hiLow { float high; float low; }; struct dailyTemperatures { struct hiLow tempExtremes; int year; int dayOfYear; }; Setting the high temperature for today would then look like this: struct dailyTemperatures today; today.tempExtremes.high = 68.0; Note - The compiler is free to insert padding into a structure to force structure members to be aligned on a particular boundary in memory. You shouldn't try to access structure members by calculating their offset from the beginning of the structure or do anything else that depends on the structure's binary layout. The typedef declaration provides a means for creating aliases for variable types: typedef float Temperature; Temperature can now be used to declare variables, just as if it were one of the built in types: Temperature high, low; typedefs just provide alternate names variable for types. Here, high and low are still floats. The term typedef is often used as a verb when talking about C code, as in "Temperature is typedef'd to float." An enum statement lets you define a set of integer constants: enum woodwind { oboe, flute, clarinet, bassoon }; The result of the previous statement is that oboe, flute, clarinet, and bassoon are constants with values of 0, 1, 2, and 3, respectively. If you don't like going in order from zero, you can assign the values of the constant yourself. Any constant without an assignment has a value one higher than the previous constant: enum woodwind { oboe=100, flute=150, clarinet, bassoon=200 }; The preceding statement makes oboe, flute, clarinet, and bassoon are now 100, 150, 151, and 200, respectively. The name after the keyword enum is called an enumeration tag. Enumeration tags are optional. Enumeration tags can be used to declare variables: enum woodwind soloist; soloist = oboe; Enumerations are useful for defining multiple constants, and for helping to make your code self-documenting, but they aren't distinct types and they don't receive much support from the compiler. The declaration enum woodwind soloist; shows your intent that soloist should be restricted to one of oboe, flute, clarinet, or bassoon, but unfortunately, the compiler does nothing to enforce the restriction. The compiler considers soloist to be an int and it lets you assign any integer value to soloist without generating a warning: enum woodwind { oboe, flute, clarinet, bassoon }; enum woodwind soloist; soloist = 5280; // No complaint from the compiler! Note - Enumeration constants occupy the same name space as variable names. You can't have a variable and enumeration constant with the same name. Operators are like verbs. They cause things to happen to your variables. C has the usual binary operators +, -, *, / for addition, subtraction, multiplication, and division, respectively. Note - If both operands to the division operator (/) are integer types, C does integer division. Integer division truncates the result of doing the division. The value of 7 / 3 is 2. The remainder or modulus operator (%) calculates the remainder from an integer division. The result of the following expression is 1: int a = 7; int b = 3; int c = a%b; // c is now 1 Both operands of the remainder operator must be integer types. C provides operators for incrementing and decrementing variables: a++; ++a; Both lines add 1 to the value of a. However, there is a difference between the two expressions variables value before it is used in the rest of the expression. In the example, the values of both c and d are 10. The decrement operators a-- and --a behave in a similar manner. Code that depends on the difference between the prefix and postfix versions of the operator is likely to be confusing to anyone but its creator.. Note - C defines a complicated table of precedence for all its operators (see). But specifying the exact order of evaluation that you want by using parentheses is much easier than trying to remember operator precedences. The unary minus sign (-) changes an arithmetic value to its negative: int a = 9; int b; b = -a; // b is now -9 Note - As with any language, testing for floating-point equality is risky because of rounding errors, and such a comparison is likely to give an incorrect result. The logical operators for AND and OR have the following form: [__em__): expression1 expression2 CheckSomething() if (b < a && CheckSomething()) { ... } The unary exclamation point (!) is the logical negation operator. After the following line of code is executed, a has the value 0 if expression is true (non-zero), and the value 1 if expression is false (zero): expression a = ! expression; If the two sides of an assignment are of different variable types, the type of the right side is converted to the type of the left side. Conversions from shorter types to longer types or from integer types to floating-point types don't present a problem. Going the other way, from a longer type to a shorter type can cause loss of significant figures, truncation, or complete nonsense. For example: int a = 14; float b; b = a; // OK, b is now 14.0 float c = 12.5; int d; d = c; // Truncation, d is now 12 char e = 128; int f; f = e; // OK, f is now 128 int g = 333; char h; h = g; // Nonsense, h is now 77. C also has shorthand operators that combine arithmetic and assignment: a += b; a -= b; a *= b; a /= b; These are equivalent to the following, respectively: a = a + b; a = a - b; a = a * b; a = a / b; Expressions and statements in C are the equivalent of phrases and sentences in a natural language. The simplest expressions are just single constants or variables: 14 bananasPerBunch Every expression has a value. The value of an expression that is a constant is just the constant itself: the value of 14 is 14. The value of a variable expression is whatever value the variable is holding: the value of bananasPerBunch is whatever value it was given when it was last set by initialization or assignment. Expressions can be combined to create other expressions. The following are also expressions: j + 14 a < b distance = rate * time The value of an arithmetic or logical expression is just whatever you would get by doing the arithmetic or logic. The value of an assignment expression is the value given to the variable that is the target of the assignment. Function calls are also expressions: SomeFunction() The value of a function call expression is the return value of the function. When the compiler encounters an expression, it creates binary code to evaluate the expression and find its value. For primitive expressions, there is nothing to do: Their values are just what they are. For more complicated expressions, the compiler generates binary code that performs the specified arithmetic, logic, function calls, and assignments. Evaluating an expression can cause side effects. The most common side effects are the change in the value of a variable due to an assignment, or the execution of the code in a function due to a function call. Expressions are used for their value in various control constructs to determine the flow of a program (see Program Flow). In other situations, expressions may be evaluated only for the side effects caused by evaluating them. Typically, the point of an assignment expression is that the assignment takes place. In a few situations, both the value and the side effect are important. When you add a semicolon (;) to the end of an expression, it becomes a statement. This is similar to adding a period to a phrase to make a sentence in a natural language. A statement is the code equivalent of a complete thought. A statement is finished executing when all of the machine language instructions that result from the compilation of the statement have been executed, and all of the changes to any memory locations the statement affects have been completed. You can use a sequence of statements, enclosed by a pair of curly brackets, any place where you can use a single statement: { timeDelta = time2 — time1; distanceDelta = distance2 — distance1; averageSpeed = distanceDelta / timeDelta; } There is no semicolon after the closing bracket. A group like this is called a compound statement or a block. Compound statements are very commonly used with the control statements covered in the next sections of the chapter. Note - The use of the word block as a synonym for compound statement is pervasive in the C literature and dates back to the beginnings of C. Unfortunately, Apple has adopted the name block for its addition of closures to C (see Chapter 16, "Blocks"). To avoid confusion, the rest of this book uses the slightly more awkward name compound statement. The statements in a program are executed in sequence, except when directed to do otherwise by a for, while, do-while, if, switch, or goto statement or a function call. These control statements are covered in more detail in the following sections. Note - As you read the next sections, remember that every place it says statement, you can use a compound statement. An if statement conditionally executes code depending on the truth value of an expression. It has the following form: if ( expression ) statement If expression evaluates to true (non-zero), statement is executed; otherwise, execution continues with the next statement after the if statement. An if statement may be extended by adding an else section : statement if ( expression ) statement1 else statement2 If expression evaluates to true (non-zero), statement1 is executed; otherwise, statement2 is executed. statement1 statement2 An if statement may also be extended by adding else if sections, as shown here: if ( expression1 ) statement1 else if ( expression2 ) statement2 else if ( expression3 ) statement3 ... else statementN The expressions are evaluated in sequence. When an expression evaluates to non-zero, the corresponding statement is executed and execution continues with the next statement following the if statement. If the expressions are all false, the statement following the else clause is executed. (As with a simple if statement, the else clause is optional and may be omitted.) A conditional expression is made up of three sub-expressions and has the following form: expression1 ? expression2 : expression3 When a conditional expression is evaluated, expression1 is evaluated for its truth value. If it is true, expression2 is evaluated and the value of the entire expression is the value of expression2. expression3 is not evaluated. expression3 If expression1 evaluates to false, expression3 is evaluated and the value of the conditional expression is the value of expression3. expression2 is not evaluated. A conditional expression is often used as a shorthand for a simple if statement. For example: a = ( b > 0 ) ? c : d; is equivalent to: if ( b > 0 ) a = c; else a = d; The while statement is used to form loops as follows: while ( expression ) statement When the while statement is executed, expression is evaluated. If it evaluates to true, statement is executed and the condition is evaluated again. This sequence is repeated until expression evaluates to false, at which point execution continues with the next statement after the while. You will occasionally see this construction: while ( 1 ) { ... } The preceding is an infinite loop from the while's point of view. Presumably, something in the body of the loop checks for a condition and breaks out of the loop when that condition is met. The do-while statement is similar to the while, with the difference that the test comes after the statement rather than before: do statement while ( expression ); One consequence of this is that statement is always executed once, independent of the value of expression. Situations where the program logic dictates that a loop body be executed at least once, even if the condition is false, are uncommon. As a consequence, do-while statements are rarely encountered in practice. The for statement is the most general looping construct. It has the following form: for (expression1; expression2; expression3) statement When a for statement is executed, the following sequence occurs: expression1 and expression3 are evaluated only for their side effects. Their values are discarded. They are typically used to initialize and increment a loop counter variable: int j; for ( j=0; j < 10; j++ ) { // Something that needs doing 10 times } Any of the expressions may be omitted (the semicolons must remain). If expression2 is omitted, the loop is an infinite loop, similar to while( 1 ): for ( i=0; ; i++ ) { ... // Check something and exit if the condition is met } Note - When you use a loop to iterate over the elements of an array, remember that array indices go from zero to one less than the number of elements in the array: int j; int a[25]; for (j=0; j < 25; j++ ) { // Do something with a[j] } Writing the for statement in the preceding example as for (j=1; j <= 25; j++) is a common mistake. The break statement is used to break out of a loop or a switch statement. int j; for (j=0; j < 100; j++ ) { ... if ( someConditionMet ) break; //Execution continues after the loop } Execution continues with the next statement after the enclosing while, do, for, or switch statement. When used inside nested loops, break only breaks out of the innermost loop. Coding a break statement that is not enclosed by a loop or a switch causes a compiler error: error: break statement not within loop or switch continue is used inside a while, do, or for loop to abandon execution of the current loop iteration. For example: int j; for (j=0; j < 100; j++ ) { ... if ( doneWithIteration ) continue; // Skip to the next iteration ... } When the continue statement is executed, control passes to the next iteration of the loop. In a while or do loop, the control expression is evaluated for the next iteration. In a for loop, the iteration (third) expression is evaluated and then the control (second) expression is evaluated. Coding a continue statement that is not enclosed by a loop causes a compiler error. A comma expression consists of two or more expressions separated by commas: expression1, expression2, ..., expressionN The expressions are evaluated in order from left to right and the value of the entire expression is the value of the right-most sub-expression. The principal use of the comma operator is to initialize and update multiple loop variables in a for statement. As the loop in the following example iterates, j goes from 0 to MAX-1 and k goes from MAX-1 to 0: for ( j=0, k=MAX-1; j < MAX; j++, k--) { // Do something } When a comma expression is used in a for loop, only the side effects of evaluating the sub-expressions (initializing and incrementing or decrementing j and k in the preceding example) are important. The value of the comma expression is discarded. A switch branches to different statements based on the value of an integer expression. The form of a switch statement is shown here: switch ( integer_expression ) { case value1: statement break; case value2: statement break; ... default: statement break; } In a slight inconsistency with the rest of C, each case may have multiple statements without the requirement of a compound statement. value1, value2, ... must be either integers, character constants, or constant expressions that evaluate to an integer. (In other words, they must be reducible to an integer at compile time.) Duplicate cases with the same integer are not allowed. When a switch statement is executed, integer_expression is evaluated and the switch compares the result with the integer case labels. If a match is found, execution jumps to the statement after the matching case label. Execution continues in sequence until either a break statement or the end of the switch is encountered. A break causes the execution to jump out to the first statement following the switch. integer A break statement is not required after a case. If it is omitted, execution falls through to the following case. If you see the break omitted in existing code, it can be either a mistake (it is an easy one to make) or intentional (if the coder wanted a case and the following case to execute the same code). If integer_expression doesn't match any of the case labels, execution jumps to the statement following the optional default: label, if one is present. If there is no match and no default:, the switch does nothing, and execution continues with the first statement after the switch. integer_expression C provides a goto statement: goto label; When the goto is executed, control is unconditionally transferred to the statement marked with label: label: statement Using goto statements with abandon can lead to tangled, confusing code (often referred to as spaghetti code). The usual boilerplate advice is "Don't use goto statements." Despite this, goto statements are useful in certain situations, such as breaking out of nested loops (a break statement only breaks out of the innermost loop): for ( i=0; i < MAX_I; i++ ) for ( j=0; j < MAX_J; j++ ) { ... if ( finished ) goto moreStuff; } moreStuff: statement // more statements Note - Whether to use goto statements is one of the longest running debates in computer science. For a summary of the debate, see. Functions typically have the following form: [__em__]returnType functionName( arg1Type arg1, ..., argNType argN ) { statements } An example of a simple function looks like this: float salesTax( float purchasePrice, float taxRate ) { float tax = purchasePrice * taxRate; return tax; } A function is called by coding the function name followed by a parenthesized list of expressions, one for each of the function's arguments. Each expression type must match the type declared for the corresponding function argument. The following example shows a simple function call: float carPrice = 20000.00; float stateTaxRate = 0.05; float carSalesTax = salesTax( carPrice, stateTaxRate ); When the line with the function call is executed, control jumps to the first statement in the function body. Execution continues until a return statement is encountered or the end of the function is reached. Execution then returns to the calling context. The value of the function expression in the calling context is the value set by the return statement. Note - Functions are not required to have any arguments or to return a value. Functions that do not return a value are typed void: void FunctionThatReturnsNothing( int arg1 ) You may omit the return statement from a function that does not return a value. Functions that don't take any arguments are indicated by using empty parentheses for the argument list: int FunctionWithNoArguments() Functions are sometimes executed solely for their side effects. This function prints out the sales tax, but changes nothing in the program's state: void printSalesTax ( float purchasePrice, float taxRate ) { float tax = purchasePrice * taxRate; printf( "The sales tax is: %f.2\n", tax ); } C functions are call by value. When a function is called, the expressions in the argument list of the calling statement are evaluated and their values are passed to the function. A function cannot directly change the value of any of the variables in the calling context. This function has no effect on anything in the calling context: void salesTax( float purchasePrice, float taxRate, float carSalesTax) { // Changes the local variable calculateTax but not the value of // the variable in the calling context carSalesTax = purchasePrice * taxRate; return; } To change the value of a variable in the calling context, you must pass a pointer to the variable and use that pointer to manipulate the variable's value: void salesTax( float purchasePrice, float taxRate, float *carSalesTax) { *carSalesTax = purchasePrice * taxRate; // this will work return; } Note - The preceding example is still call by value. The value of a pointer to a variable in the calling context is passed to the function. The function then uses that pointer (which it doesn't alter) to set the value of the variable it points to. When you call a function, the compiler needs to know the types of the function's arguments and return value. It uses this information to set up the communication between the function and its caller. If the code for the function comes before the function call (in the source code file), you don't have to do anything else. If the function is coded after the function call or in a different file, you must declare the function before you use it. A function declaration repeats the first line of the function, with a semicolon added at the end: void printSalesTax ( float purchasePrice, float taxRate ); It is a common practice to put function declarations in a header file. The header file is then included (see the next section) in any file that uses the function. Note - Forgetting to declare functions can lead to insidious errors. If you call a function that is coded in another file (or in the same file after the function call), and you don't declare the function, neither the compiler nor the linker will complain. But the function will receive garbage for any floating-point argument and return garbage if the function's return type is floating-point. When C (and Objective-C) code files are compiled, they are first sent through an initial program, called the preprocessor, before being sent to the compiler proper. Lines that begin with a # character are directives to the preprocessor. Using preprocessor directives you can: The following line: #include "HeaderFile.h" causes the preprocessor to insert the text of the file HeaderFile.h into the file being compiled at the point of the #include line. The effect is the same as if you had used a text editor to copy and paste the text from HeaderFile.h into the file being compiled. If the included filename is enclosed in quotations (""): the preprocessor will look for HeaderFile.h in the same directory as the file being compiled, then in a list of locations that you can supply as arguments to the compiler, and finally in a series of system locations. If the included file is enclosed in angle brackets (<>): #include <HeaderFile.h> the preprocessor will look for the included file only in the standard system locations. Note - In Objective-C, #include is superseded by #import, which produces the same result, except that it prevents the named file from being imported more than once. If the preprocessor encounters further #import directives for the same header file, they are ignored. #define is used for textual replacement. The most common use of #define is to define constants, such as: #define MAX_VOLUME 11 The preprocessor will replace every occurrence of MAX_VOLUME in the file being compiled with an 11. A #define can be continued on multiple lines by placing a backslash (\) at the end of all but the last line in the definition. Note - If you do this, the \ must be the last thing on the line. Following the \ with something else (such as a comment beginning with "//") results in an error. A frequently used pattern is to place the #define in a header file, which is then included by various source files. You can then change the value of the constant in all the source files by changing the single definition in the header file. The traditional C naming convention for defined constants is to use all capital letters. A traditional Apple naming convention is to begin the constant name with a k and CamelCase the rest of the name: #define kMaximumVolume 11 You will encounter both styles, sometimes in the same code. The preprocessor allows for conditional compilation: #if condition statements #else otherStatements #endif Here, condition must be a constant expression that can be evaluated for a truth value at compile time. If condition evaluates to true (non-zero), statements are compiled, but otherStatements are not. If condition is false, statements are skipped and otherStatements are compiled. condition statements otherStatements The #endif is required, but the #else and the alternative code are optional. A conditional compilation block can also begin with an #ifdef directive: #ifdef name statements #endif The behavior is the same as the previous example, except that the truth value of #ifdef is determined by whether name has been #define'd. name One use of #if is to easily remove and replace blocks of code during debugging: #if 1 statements #endif By changing the 1 to a 0, statements can be temporarily left out for a test. They can then be replaced by changing the 0 back to a 1. #if and #ifdef directives can be nested, as shown here: #if 0 #if 1 statements #endif #endif In the preceding example, the compiler ignores all the code, including the other compiler directives, between the #if 0 and its matching #endif. statements are not compiled. If you need to disable and re-enable multiple statement blocks, you can code each block like this: #if _DEBUG statements #endif The defined constant _DEBUG can be added or removed in a header file or by using a —D flag to the compiler. printf Input and output (I/O) are not a part of the C language. Character and binary I/O are handled by functions in the C standard I/O library. Note - The standard I/O library is one of a set of libraries of functions that is provided with every C environment. To use the functions in the standard I/O library, you must include the library's header file in your program: #include <stdio.h> The only function covered here is printf, which prints a formatted string to your terminal window (or to the Xcode console window if you are using Xcode). The printf function takes a variable number of arguments. The first argument to printf is a format string. Any remaining arguments are quantities that are printed out in a manner specified by the format string: printf( formatString, argument1, argument2, ... argumentN ); The format string consists of ordinary characters and conversion specifiers: The only conversion specifiers used in this book are %d, for char and int, %f for float and double, and %s for C strings. C strings are typed as char*. Here is a simple example: int myInt = 9; float myFloat = 3.145926; char* myString = "a C string"; printf( "This is an Integer: %d, a float: %f, and a string: %s.\n", myInt, myFloat, myString ); Note - The \n is the newline character. It advances the output so that any subsequent output appears on the next line. The result of the preceding example is: This is an Integer: 9, a float: 3.145926, and a string: a C string. If the number of arguments following the format string doesn't match the number of conversion specifications, printf ignores the excess arguments or prints garbage for the excess specifications. Note - This book uses printf only for logging and debugging non-object variables, not for the output of a polished program, so this section presents only a cursory look at format strings and conversion specifiers. printf handles a large number of types and it provides very fine control over the appearance of the output. A complete discussion of the available types of conversion specifications and how to control the details of formatting is available via the Unix man command. To see them, type the following at a terminal window: man 3 printf Note - The Foundation framework provides NSLog, another logging function. It is similar to printf, but it adds the capability to print out object variables. It also adds the program name, the date, and the time in hours, minutes, seconds, and milliseconds to the output. This additional information can be visually distracting if all you want to know is the value of a variable or two, so this book uses printf in some cases where NSLog's additional capability is not required. NSLog is covered in Chapter 3. When you write programs for Mac OS X or iOS, you should write and compile your programs using Xcode, Apple's Integrated Development Environment (IDE). You'll learn how to set up a simple Xcode Project in Chapter 4, "Your First Objective-C Program." However, for the simple C programs required in the exercises in this chapter and the next chapter, you may find it easier to write the programs in your favorite text editor and then compile and run them from a command line, using gcc, the GNU compiler. To do this, you will need: You are now ready to compile. If your source code file is named MyCProgram.c, you can compile it by typing the following at the command prompt: gcc -o MyCProgram MyCProgram.c The -o flag allows you to give the compiler a name for your final executable. If the compiler complains that you have made a mistake or two, go back and fix them, then try again. When your program compiles successfully, you can run it by typing the executable name at the command prompt: MyCProgram If you want to debug your program using gdb, the GNU debugger, you must use the -g flag when you compile: gcc -g -o MyCProgram MyCProgram.c The -g flag causes gcc to attach debugging information for gdb to the final executable. To use gdb to debug a program, type gdb followed by the executable name: gdb MyCProgram Documentation for gdb is available at the GNU website, or from Apple at. In addition, there are many websites with instructions for using gdb. Search for "gdb tutorial". This chapter has been a review of the basic parts of the C language. The review continues in Chapter 2, which covers the memory layout of a C program, declaring variables, variable scope and lifetimes, and dynamic allocation of memory. Chapter 3 begins the real business of this book: object-oriented programming and the object part of Objective-C. void average( float a, float b, float average ) Write a small test program and verify that your function doesn't work. You can't affect a variable in the calling context by setting the value of a function parameter. Now change the function and its call to pass a pointer to a variable in the calling context. Verify that the function can use the pointer to modify a variable in the calling context. int flipResult; if ( flipResult = FlipCoin() ) printf("Heads is represented by %d\n", flipResult ); else printf("Tails is represented by %d\n", flipResult ); As you will see in Chapter 6, "Classes and Objects," an if condition similar to the one in the preceding example is used in the course of initializing an Objective-C object. Write a program that calculates and stores the 4x4 identity matrix. When your program is finished calculating the matrix, it should output the result as a nicely formatted square array. F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub> Write a program that calculates and stores the first 20 Fibonacci numbers. After calculating the numbers, your program should output them, one on a line, along with their index. The output lines should be something like: Fibonacci Number 2 is: 1 Use a #define to control the number of Fibonacci numbers your program produces, so that it can be easily changed. Using the conversion specification %.2f instead of %f will limit the check and tip output to two decimal places. Using %% in the format string will cause printf to output a single % character. Write a function that takes two rectangle structure arguments. (Use the structures that you defined in the previous exercise.) Your function should return 1 if there is a non-zero overlap between the two rectangles, and 0 otherwise. Write a test program that creates some rectangles and verify that your function works. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Second Edition. (Englewood Cliffs: Prentice Hall, 1988). Samuel P. Harbison and Guy L. Steele, C: A Reference Manual, Fifth Edition. (Upper Saddle River: Prentice Hall,.
https://www.codeproject.com/Articles/111970/Excerpt-from-Learning-Objective-C-A-Hands-On-G
CC-MAIN-2018-13
refinedweb
7,545
60.24