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
3rd Party Client Library for Manipulating Go Daddy DNS Records. Project description PyGoDaddy is a 3rd-party client library, written in Python, for site admins(devs), to make GoDaddy suck less. Currently, Only A-Record manipulation is supported Features - Login with a USERNAME and a PASSWORD - CREATE, READ, UPDATE, DELETE your domain’s DNS Records (A-Record only for now) INSTALL To install pygodaddy, simply: pip install pygodaddy QUICKSTART from pygodaddy import GoDaddyClient client = GoDaddyClient() if client.login(username, password): print client.find_domains() client.update_dns_record('sub.example.com', '1.2.3.4') DOCS Or you can always refer to docstrings and tests TESTING Create a file in tests/accounts.py Put settings in this file: accounts = [ { 'username': 'USERNAME', 'password': 'PASSWORD', 'test_domain': 'DOMAIN.NAME', }, ] run nosetests tests in root directory 0.2.0 (2015-03-11) - Added logging messages to add, delete, edit, save, and update methods 0.1.9 (2015-03-11) - Fix _split_hostname() method (thanks to @artoleus and @sjpengelly) 0.1.8 (2015-02-28) - Fix “.co.uk” type of domain (thanks to @sjpengelly) 0.1.7 (2015-02-02) - Fix CSRF (thanks to @DanChianucci) 0.1.1-0.1.6 (2013-07-12) - Fix a lot pypi stuff 0.1.0 (2013-07-12) - Birth! 0.0.1 (2011-07-12) - Frustration - Conception Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pygodaddy/
CC-MAIN-2018-26
refinedweb
242
50.94
7 Interview Questions on JavaScript Closures. Can You Answer Them? Every JavaScript developer must know what a closure is. During a JavaScript coding interview there’s a good chance you’ll get asked about the concept of closures. I compiled a list of 7 interesting and increasingly challenging questions on JavaScript closures. Take a pencil and a piece of paper, and try to answer the questions without looking at the answers, or running the code. In my estimation, you would need about 30 minutes. Have fun! If you need a refresh on closures, I recommend checking the post A Simple Explanation of JavaScript Closures. Table of Contents Questions 1: Closures raise your hand Consider the following functions clickHandler, immediate, and delayedReload: let countClicks = 0; button.addEventListener('click', function clickHandler() { countClicks++; }); const result = (function immediate(number) { const message = `number is: ${number}`; return message; })(100); setTimeout(function delayedReload() { location.reload(); }, 1000); Which of these 3 functions access outer scope variables? Expand answer clickHandleraccesses the variable countClicksfrom the outer scope. immediatedoesn’t access any variables from the outer scope. delayedReloadaccesses the global variable locationfrom the global scope (aka the outermost scope). Questions 2: Lost in parameters What will log to console the following code snippet: (function immediateA(a) { return (function immediateB(b) { console.log(a); // What is logged? })(1); })(0); Expand answer 0 is logged to the console. Try the demo. immediateA is called with the argument 0, thus a parameter is 0. immediateB function, being nested into immediateA function, is a closure that captures a variable from the outer immediateA scope, where a is 0. Thus console.log(a) logs 0. Questions 3: Who’s who What will log to console the following code snippet: let count = 0; (function immediate() { if (count === 0) { let count = 1; console.log(count); // What is logged? } console.log(count); // What is logged? })(); Expand answer 1 and 0 is logged to the console. Try the demo. The first statement let count = 0 declares a variable count. immediate() is a closure that captures the count variable from the outer scope. Inside of the immediate() function scope count is 0. However, inside the conditional, another let count = 1 declares a local variable count, which overwrites count from outer the scope. The first console.log(count) logs 1. The second console.log(count) logs 0, since here count variable is accessed from the outer scope. Questions 4: Tricky closure What will log to console the following code snippet: for (var i = 0; i < 3; i++) { setTimeout(function log() { console.log(i); // What is logged? }, 1000); } Expand answer 3, 3, 3 is logged to console. Try the demo. The code snippet executes in 2 phases. Phase 1 for()iterating 3 times. During each iteration a new function log()is created, which captures the variable i. setTimout()schedules log()for execution after 1000ms. - When for()cycle completes, ivariable has value 3. Phase 2 The second phase happens after 1000ms: setTimeout()executes the scheduled log()functions. log()reads the current value of variable i, which is 3, and logs to console 3. That’s why 3, 3, 3 is logged to the console. Side challenge: how would you fix this example to log 0, 1, 2 values? Write your solution in a comment below! Questions 5: Right or wrong message What will log to console the following code snippet: function createIncrement() { let count = 0; function increment() { count++; } let message = `Count is ${count}`; function log() { console.log(message); } return [increment, log]; } const [increment, log] = createIncrement(); increment(); increment(); increment(); log(); // What is logged? Expand answer 'Count is 0' is logged to console. Try the demo. increment() function has been called 3 times, effectively incrementing count to value 3. message variable exists within the scope of createIncrement() function. Its initial value is 'Count is 0'. However, even if count variable has been incremented a few times, message variable always holds 'Count is 0'. log() function is a closure that captures message variable from the createIncrement() scope. console.log(message) logs 'Count is 0' to console. Side challenge: how would you fix log() function to return the message having the actual count value? Write your solution in a comment below! Questions 6: Restore encapsulation The following function createStack() creates instances of stack data structure: function createStack() { return { items: [], push(item) { this.items.push(item); }, pop() { return this.items.pop(); } }; } const stack = createStack(); stack.push(10); stack.push(5); stack.pop(); // => 5 stack.items; // => [10] stack.items = [10, 100, 1000]; // Encapsulation broken! The stack works as expected, but with one small problem. Anyone can modify items array directly because stack.items property is exposed. That’s an issue since it breaks the encapsulation of the stack: only push() and pop() methods should be public, but stack.items or any other details shouldn’t be accessible. Refactor the above stack implementation, using the concept of closure, such that there is no way to access items array outside of createStack() function scope: function createStack() { // Write your code here... } const stack = createStack(); stack.push(10); stack.push(5); stack.pop(); // => 5 stack.items; // => undefined Expand answer Here’s a possible refactoring of createStack(): function createStack() { const items = []; return { push(item) { items.push(item); }, pop() { return items.pop(); } }; } const stack = createStack(); stack.push(10); stack.push(5); stack.pop(); // => 5 stack.items; // => undefined items has been moved to a variable inside createStack() scope. Thanks to this change, from the outside of createStack() scope, there is no way to access or modify items array. items is now a private variable, and the stack is encapsulated: only push() and pop() method are public. push() and pop() methods, being closures, capture items variable from createStack() function scope. Questions 7: Smart multiplication Write a function multiply() that multiples 2 numbers: function multiply(num1, num2) { // Write your code here... } If multiply(num1, numb2) is invoked with 2 arguments, it should return the multiplication of the 2 arguments. But if invoked with 1 argument const anotherFunc = multiply(num1), the function should return another function. The returned function when called anotherFunc(num2) performs the multiplication num1 * num2. multiply(4, 5); // => 20 multiply(3, 3); // => 9 const double = multiply(2); double(5); // => 10 double(11); // => 22 Expand answer Here’s a possible implementation of multiply() function: function multiply(number1, number2) { if (number2 !== undefined) { return number1 * number2; } return function doMultiply(number2) { return number1 * number2; }; } multiply(4, 5); // => 20 multiply(3, 3); // => 9 const double = multiply(2); double(5); // => 10 double(11); // => 22 If number2 parameter is not undefined, then the function simply returns number1 * number2. But if number2 is undefined, it means that multiply() function has been called with one argument. In such a case let’s return a function doMultiply() that when later invoked performs the actual multiplication. doMultiply() is a closure because it captures number1 variable from multiply() scope. Summary Compare your answers with the answers in the post: - You have a good understanding of closures if you answered correctly 5 or more questions - But you need a good refresher on closures if you answered correctly less than 5 questions. I recommend checking my post A Simple Explanation of JavaScript Closures. Ready for a new challenge? Try to solve the 7 Interview Questions on “this” keyword in JavaScript. About Dmitri Pavlutin About Dmitri Pavlutin Your JavaScript Coach I know how cumbersome are closures, scopes, prototypes, inheritance, async functions, this in JavaScript. I'm excited to start my coaching program to help you advance your JavaScript knowledge. You can have direct access to me through: - 1 hour, one-to-one, video or chat coaching sessions - JavaScript, TypeScript, React, Next teaching, workshops, or interview preparation (you choose!) - Conversational and friendly format
https://dmitripavlutin.com/javascript-closures-interview-questions/
CC-MAIN-2021-17
refinedweb
1,270
50.94
Obtaining the JDK Kernel Support For Java JDK Java Beans Swing Java Accessibility Utilities JSDK Documentation Java Tutorial Sun's HotJava Browser Next Month This article is intended to help those new to either Linux or Java set their machines up to run Java applications, as well as providing an effective environment for developing new Java applications. Specifically I shall explain how to set up Sun's 1.1.x JDK and other related packages. This is not the only way to run Java on Linux. Blackdown.org now offers the new 1.2.x JDK for Linux (at the time of writting this is still a pre-release version). I only recommend using this if you are also using the new 2.2.x Linux kernel. If you choose to install the 1.2.x JDK then please note that you do not need to obtain the Swing and JSDK packages, since they are already included. Also you may find some compatibility problems if you use older Java applications with the 1.2.x JDK. In particular if you intend to implement the javapache extensions to Apache you will need to use JDK 1.1.x. In addition there exist other third party Java environments and Java compilers such as IBM's jikes. Use these at your own peril! IMHO Sun have defined and developed the Java language so I expect their Java environments to be the most standard. Other environments may be of interest, but I cannot cover them here. Unfortunately the development of the Java language for Linux lags the development for other operating systems. Having said that there are still many advantages to using Java on Linux, not least of which is the easy availability of sophisticated development tools. If you have not seen a recent version of DDD (The Dynamic Display De-bugger), you may not realise that it now supports Java. If you write any programs under Linux DDD is a must have utility. Why use Java at all? Java's greatest advantage is also its greatest disadvantage. For reasons given below, the fact that the same Java code can be run on any platform without re-compiling is responsible for the fact that Java applications can appear slow. It is this slowness that has lead some to question the need to use Java at all. It is true that if speed in loading and running an application is the only criteria for choosing a programming language then I would never consider using Java at all. Although applications such as jedit and the Java cd player described in earlier editions of this e-zine are functionaly equivalent to applications written in C they are very slow to start up and I am loath to use them when I have much faster alternatives. But Java is not meant for such applications. Java excells in what it was originally designed for, which is to provide a means of making applications available over the Internet. Over the Internet the speed of loading an application is not really important when compared to the time it takes to download the application. Now consider your friendly ISP, and the servers that provide you with Internet access. Your ISP (even your local Intranet) needs the fastest machines possible given certain criteria (cost etc). The cost of the actual server may not be important when compared to the software investment of server-side applications. Using Java to implement server-side applications leaves your ISP free to choose the best machine architecture and operating system without having to worry about the cost and feasibility of re-implementing such applications. They can simply be copied from one machine to another. Perhaps one day Microsoft will develop a reliable operating system that is superior to a *NIX operating system. If that day ever comes I will want to change from Linux, using Java will allow me to do that and keep exactly the same server-side applications I am running now. If you only want to use a stand-alone computer, with no network access, either locally or over the Internet, then you probably do not need or want to consider using Java. But if your machine is going to be part of a local network or the Internet then the use of Java should be taken very seriously. Java is not the only way to develop network applications. For instance Perl can be used in a very similar way. But Java is a very attractive option. Please do not obtain your JDK directly from Sun. They provide support only for Microsoft Windows, Solaris etc. Instead go to Blackdown.org and find the version you require. All other packages mentioned here should be obtained from Sun. The Linux port of the JDK can either be found on a Linux distribution disk, or can be found at. You will find you have a bewildering choice of files to install. There is the JRE as well as the JDK. I recommend you get the full JDK package since it contains everything in the others. Linux was possibly the first operating system to provide direct kernel support for Java. This allows Linux to run both Java applications and Java applets directly, without the need for a browser such as Netscape. But if you think direct kernel support means that the kernel has anything to do with actually running Java code you are sadly mistaken. To understand what is happening you need to realize that Java is really only one step removed from running interpreted programs rather than compiled programs. In the early days of computing, it was common to use an interpreted language, such as GW-BASIC, to write simple applications. The code that was written was never compiled into a program, rather the code would be parsed by an interpreter which would perform the actual execution of instructions. This is a very inefficient way of doing things and the results will always be slow. Java differs from an interpreted language, such as early versions of BASIC, in that the source code is compiled. But the source is not compiled into something a computer can directly execute as would be the case if you compiled a C program with gcc. Instead the source code is byte-compiled into a standard format. The reason that the same Java application can be run on any platform is precisely because this byte-code is in a standard format. The programs java and appletviewer, provided by Sun or Blackdown.org perform the function of parsing this byte-code and executing the instructions. This is the reason Java applications can appear slow, the byte-code must be parsed by an interpreter before it can be executed, though the situation is not nearly as bad as it was with early BASIC programs, since the byte-code has already been optimized by the java compiler. When you compile Java support into the Linux kernel what you are really doing is telling the operating system to invoke either java or appletviewer when a request is made to execute a java application. Linux is simply giving you a shorthand way of saying 'appletviewer myapplication'. For this reason you need to tell the kernel where your Java executables are kept. If you obtain the JDK from Blackdown.org then the chances are that java and appletviewer will be placed in /usr/local/java/bin. If you install the JDK from a S.u.S.E. distribution disk then they will be in /usr/lib/java/bin. Of course you might have installed the JDK to some non-standard location. Before you re-compile your Linux kernel, edit the file /usr/src/linux/fs/binfmt_java.c to reflect the situation you actually have. #include <linux/malloc.h> #include <linux/binfmts.h> #define _PATH_JAVA "/usr/local/java/bin/java" // Replace with correct location for your system. #define _PATH_APPLET "/usr/local/java/bin/appletviewer" // Replace with correct location for your system. #define _PATH_SH "/bin/bash" char binfmt_java_interpreter[65] = _PATH_JAVA; char binfmt_java_appletviewer[65] = _PATH_APPLET; Please note that the references to java and appletviewer should be to the actual location of the binaries and not to any symbolic link you might have created. In the example above the directory /usr/local/java might be a symbolic link to /usr/lib/java-1.1.7, but the actual file refereed to is not a symbolic link, it actually exists in /usr/lib/java-1.1.7/bin. Now you can decide if you want to compile Java support directly into the kernel, or have it as a module. I choose to use a module. The only comment I feel necessary is that when I try to execute a html file kernld will not automatically load the binfmt_java module, so I must "insmod binfmt_java" first. Execute a HTML file? Yes, Linux will allow you to execute certain HTML files as though they are applications. To understand why you would want to do this you need to understand the difference between a Java applet and a full blown Java application. Whilst a Java application provides all the resources it needs itself, an applet does not. Normally an applet needs to be included in a web page which is viewed by a Java enabled browser such as Netscape or HotJava because it has no top level window of its own. An alternative is to use the appletviewer program to view the applet. Linux gives you a further option. if you add the line <!--applet--> to a HTML file (and '<' must be the first character in the file), and chmod the file to be executable, then you will be able to launch the applet(s) embedded in the file directly. In a similar manner a Java application is made up of one or more class files. To make the application executable by linux simply chmod the top level class file so it is executable. Reading the documentation that comes with the JDK, we find that there is no need to set the CLASSPATH or JDK_HOME environments. Whilst this is true for the JDK itself, I have found that there are some applications that expect these environments to be set. In any case setting them will not cause you any harm and I recommend you take the following steps to install the JDK correctly: Where {JDK_HOME} is the top-level directory to which you installed the JDK. The JavaBeans API allows you to create component software in the Java programming language. Components are complete, self-contained, reusable software items that can be visually linked into any Java program, applet or servlet. Such software items are refereed to as Beans. Many Java IDE's are available, such as NetBeans or Visarj, that use this technology to provide application builder tools. Included in the package is BeanBox, a simple JavaBean IDE to get you started. When you startup BeanBox, by running bin.sh in the BDK/beanbox sub-directory, three windows will open for you: The BeanBox window A ToolBox window A Properties window The ToolBox initially contains a number of example beans, you can add your own to create your own visual programming environment. Select a bean by clicking your mouse on it. Then click somewhere in the BeanBox. The javaBean will appear and a list of its properties will appear in the Properties window. You may then use the Properties window to customize the JavaBean for your application. When you have finished adding Beans, and are happy with the appearance of your application in the BeanBox you can select File/Make applet from the BeanBox windows menu and an applet complete with example html file will be generated for you. As should now be clear, JavaBeans provide a means to develop applications without writing a single line of code. Of course you need to write the Beans themselves but many third party vendors make Beans available and the Internet is a fine place to look for new components. A feature of JavaBeans is that they are packed into the JAR file format. This format has many advantages over java class files including: File Compression A JAR file may optionally be compressed for more efficient storage and faster download times. Decreased Download Times An entire applet may be bundled into a single JAR file. This means a users browser only needs to open a single connection to download your applet rather than a connection for each class file your applet requires. Security A JAR file can be digitally signed. This gives users the opportunity to grant your software security privileges it would not normally have, so long as the user is able to recognize your signature. Additional features are included in JDK 1.2.x including package versioning, package sealing and packaging for extensions. INSTALLATION Not all Java applications are equal! Some look better than others. Swing provides several enhancements to the Java language. Whilst you do not need Swing to develop and run Java applications and applets, you may well need it to compile or run certain Java applications (such as jedit) that are freely available on the Internet. The Java Foundation Classes (JFC, this is included in the Swing package), together with Swing, provide a set of "lightweight" components that work the same on all platforms. Effectively they provide GUI extensions to the Java language that can provide many enhancements to the look and feel of your applications. The screen-shot above shows the initial screen when you start the swingset application. This can be used to demonstrate the enhancements Swing provides. by selecting a category such as ListBox you will be able to display and alter the various options that are available and so become familiar with the effects that Swing can provide. An application I can recommend that makes full use of Swing is jedit, a very nice editor. This is available in full source code, and is suitable for editing plain text files such as HTML, Java source, Perl scripts, LaTeX documents, etc. The editor supports the inclusion of plug-ins and a couple of trivial examples are included to get you started. INSTALLATION Where {SWING_HOME} is the directory under which you unpacked Swing. Actually, there are two packages here: The Java Accessibility API and the Java Accessibility Utilities themselves. The Java Accessibility API defines a contract between individual user-interface components that make up a Java application and an assistive technology that is providing access to that Java application. If a Java application fully supports the Java Accessibility API, then it should be compatible with, and friendly toward, assistive technologies such as screen readers, screen magnifiers, etc. With a Java application that fully supports the Java Accessibility API, no off screen model would be necessary because the API provides all of the information normally contained in an off screen model. In order to provide access to a Java application, an assistive technology requires more than the Java Accessibility API: it also requires support in locating the objects that implement the API as well as support for being loaded into the Java virtual machine, tracking events, etc. The Java Accessibility utility classes provide this assistance. As you may have guessed from the screen-shot above, the Java Accessibility Utilities require that you have installed the Swing package. Several example utilities are provided in the package. The screen-shot above shows the Java Monitor which allows you to obtain information about objects being displayed on the screen by a Java Virtual Machine. Also included are: AWT Monitor This is the same as the Java Monitor but does not require or support the Java Foundation Classes. Explorer Explorer uses the Java Accessibility Utilities to examine accessible information about the objects in the Java Virtual Machine. It allows the user to select different methods for selecting the object to be examined: by following focus, by following the mouse, by following caret position, or by pressing the F1 when the pointer is over an object. Once an object has been selected for examination, Explorer displays the results of calling Java Accessibility API methods on that object. Monkey Like a monkey, Monkey "swings" through the component trees in a particular Java Virtual Machine and presents the hierarchy in two different ways. The first is the actual Component hierarchy and the second is the hierarchy viewed as Accessible objects. In addition, if the user clicks the right mouse button over a tree node in Monkey, Monkey will present the user with a pop-up menu containing options for manipulating the object. Accessibility Monitor Accessibility Monitor will monitor all accessible property change events on all of the non-transient objects in the virtual machine. In addition, if the user clicks the right mouse over the events presented in the table provided by AccessibilityMonitor, AccessibilityMonitor will present the user with a pop-up menu containing options for manipulating the associated object. Linker Linker captures the Accessible hypertext information contained in the object underneath the mouse (the user the presses the F1 key), and displays a list of the the Accessible hyperlinks within that object in a table. Selecting one of the links and clicking "Activate Selected Link" will cause the hypertext object to follow the link selected (to update the display, move the mouse over the object and press F1 again). INSTALLATION This is a little different to the other packages mentioned here, since the different utilities included have to be explicitly enabled by you. When you start any Java application you will also be able to automatically stat one of the utilities mentioned above by following the steps below: AWT.EventQueueClass=com.sun.java.accessibility.util.EventQueueMonitor AWT.assistive_technologies=JavaMonitor The Java Servlet API is a standard extension to the Java Development Kit. Servlet's are bodies of code that run inside servers to extend their functionality. For example, servlet's offer an efficient platform-independent replacement for CGI scripts. Servers that can host servlet's are java-enabled servers that respond to client requests. The diagram above shows a typical use of a Java servlet. A HTTP server is running a servlet that is responsible for taking data from a HTML order-entry form and applies a companies rules for updating their order database. Simply put, a java servlet is a servers version of a java applet. As one might expect, since the server will be running remotely and unattended (from a users viewpoint at least) servlet's have no graphical user interface. Servlet's provide a way to generate dynamic documents that is both easier to write and faster to run. Servlet's also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension. So use servlet's to handle HTTP client requests. For example, have servlet's process data POSTed over HTTP using an HTML form, including purchase order or credit card data. A servlet like this could be part of an order-entry and processing system, working with product and inventory databases, and perhaps an on-line payment system. Amongst the many other possible uses for servlet's are the following: Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlet's to support systems such as on-line conferencing. Forwarding requests. Servlet's can forward requests to other servers and servlet's. Thus servlet's can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. If you use Apache then you will be interested in the javapache project, available from. To use this you will need to use the 1.1x JDK, and must use version 2.0 of the JSDK. Next month I hope to make an introduction to this project available. The JSDK is available for download from If you are using the newer 1.2.x JDK please remember you do not need to download this package, since the JSDK is already included. INSTALLATION export PATH=$PATH:/usr/lib/JSDK/binto your /etc/profile file. Add the JSDK Classes to your CLASSPATH, e.g. export CLASSPATH=$CLASSPATH:/usr/lib/JSDK/lib/jsdk.jar Again you can add this line to your /etc/profile file. Each package includes its own documentation in HTML format. However, since you need to get your JDK from Blackdown.org, rather than from Sun, the documentation for the JDK will be missing from the package. Sun provides full documentation for both 1.1.x and 1.2.x versions of the JDK. Documentation for the 1.1.x version exists for version 1.1.3. I do not think it has been updated since then. In the demo sub-directory you will find many examples. Find the HTML files that launch java applets and make them executable in the manner I have described above so you can run them as conventional programs. The docs subdirectory contains a complete programmers guide to the Java language. This is further enhanced by the Java Tutorial. Sun have a comprehensive Java tutorial which can get you up to speed programming in Java very quickly. Both the entire tutorial and specific parts of it are available for download: Alternatively you can read the tutorial on-line at. Please note: Whilst you are free to mirror this tutorial on a local network or Intranet, Sun request that you do not make it available publicly on the Internet. This is a web browser written entirely in Java. For that reason even on a 133Mhz pentium class processor it is very slow. Its advantage is that it is one of the very few browsers available for Linux that can run Java applets. It is also very interesting for other reasons. HotJava is highly modular, the user interface is easily customizable and has a small footprint (does not take up a large amount of system resources). Well that is what Sun claims. I find in practice that if I try loading java applets whilst running other applications the browser will die on me. I would have thought that if it does have a small footprint this would not happen - whatever. Sun further claim that the browser is ideal for a variety of devices - such as screen phones as well as desktop PC's. All I can say is that until the browser can perform faster (on my pentium class box with 32Meg ram it takes about three minuets to start up and load the default screen), and is more reliable, then it is unlikely to be of much use unless you have a very fast processor. The heart of HotJava is the HotJava HTML Component. This is a JavaBean that parses and renders HTML. This can be embedded into your own applications, anything from a newsreader to a microwave oven (yes there are microwaves and even fridges that give you Internet access now), can make use of it to display information. HotJava supports the following Internet standards:- JDK 1.1 HTTP 1.1 Protocol HTML 3.2 Tables and Frames FTP and Gopher File Transfer Protocols Persistent Cookies GIF and JPEG Media Formats AU audio format SMTP and MIME E-mail Protocols SOCKS Protocol SSL 3.0 Java Archive (jar) Format The following packages are available depending on your needs: HotJava Browser Source Code (including HotJava HTML Component) HotJava Browser Binary HotJava HTML Component Source Code HotJava HTML Component Binary Last month I explained how to set up the Apache HTTP server. Next month I intend to tie these two articles together by showing you how to incorporate the javapache extensions to Apache so you can use Java to create dynamic HTML pages and server side applications to enhance your web site. In a future article I shall give an overview of the available Netscape Plug-ins and show how simple it is to develop your own plug-ins. In the meantime I welcome your comments and suggestions for future articles. Editor's note: October's Linux Journal, in the Strictly On-Line section, contains two articles related to Java:
http://www.redhat.com/mirrors/LDP/LDP/LGNET/issue45/gibbs/Linux_java.html
crawl-003
refinedweb
4,034
53.61
Join the community to find out what other Atlassian users are discussing, debating and creating. Do anyone have a SQL to safely delete a project with all issues? Using delete project with 50k+ issues using http takes forever. This varies by version of Jira, so we can't give you the raw SQL. I'd also consider alternatives to SQL However you choose to do it, keep it simple. Don't try to delete the project - just hit the issues. When you've scrubbed most (or all) of them, then use the UI to delete the (near) empty project. To delete via SQL, you'll need to examine the full database structure for your version of Jira. To get you started though, you'll be using jiraissue as the driver, and the id off there to delete from There are probably more tables you'll need to scan and delete from, I only know the core ones off the top of my head. I don't know about Greenhopper at all either. Also, if you're going to do it with SQL, you *must* follow this process: For a large Jira (e.g. 50k+ issues in a project), you'll find that leaves you with very significant downtime. Make sure you plan that in, and give yourself plenty of reserves. I'm not that familiar with the structure of the database in 5.2, but I don't think it's changed much. The list of core tables you'll need to amend is right. More importantly, you need to understand that although "using http and API takes a few hours", doing it via SQL is probably going to take longer. A lot longer. The execution of the SQL will be a lot faster. But there's no way you should do it without a proven backup. There's no option about keeping Jira running while you run the SQL - you MUST have it offline. You MUST re-index afterwards which takes a while. It's going to take you a while to work out the exact SQL you need to run too. Offline jira is not a problem. The thing what I am tring to do is to create a testing Jira environment on demand in cloud by cloning jira database and rsyncing Jira home from the production env. Spawning cloud machine takes few minutes, however out of 100k+ issues instance I want to leave DEMO project + configuration. This process takes around 3h to complete. I am looking something to speed-up process. Ok, so that means you can dump the backup too (if it goes wrong, you can re-clone). You are not going to get around the fact that the SQL is complex - you need a whole swathe of deletes to get there, and although this is going to run faster than clicking "delete project", you still need to reindex afterwards. It's still going to take some time to do all of this, but I'd not like to guess whether it'll be faster to SQL or delete in the UI. I need to export two projects from our JIRA instance to another JIRA server, the plan is first import the JIRA backup from production server to a sandbox server, delete all other projects except the two, then export it again. here is what I did: import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.ComponentManager def projectManager = ComponentManager.getInstance().getProjectManager() def result=""; new File('/home/jira/scripts/delete_projects/unneeded_projects').eachLine { projectname -> p = projectManager.getProjectObjByKey ( projectname ); result += "Deleting Project: $p.key id $p.id <br>\n"; projectManager.removeProject( p); } return result; 2. the above code only deleted JIRA projects, but all issues and other records are still in database. Then I shut down sandbox JIRA and run delete from jiraissue where project not in ( select id from project ); delete from changegroup where issueid not in ( select id from jiraissue); delete from jiraaction where issueid not in ( select id from jiraissue); delete from worklog where issueid not in ( select id from jiraissue); delete from customfieldvalue where issue not in ( select id from jiraissue); This removed most data. 3. restart Jira, reindex, then do integrity check, this will fix some left data problem. You've missed several tables. Please, go back to your backup, and use the API to do the deletes. Messing around in the database when you don't know what you are doing is NOT a clever thing to do. Well, I should put a disclaimer: This worked perfect for my task, but might not work for you. I only deleted those records on the sandbox, the "data integrity check" step will find some orphaned records and remove them. Then I exported it to xml again, and used JIRA 's "Project import" function to import the two projects into another instance. "Project import" will also do data integrity check and it will not load orphaned data. Since the projects are working fine on new server now, I consider the job is done. Deleting projects one by one from Web UI or API is not acceptable, cause there are more than 100 projects and 300,000 issues, it will take week to delete them. The data integrity check will NOT find orphaned records and even if you think "it's all working now", that could easily be an incorrect assumption. You might be lucky. You might not. I'd keep your backups from before you botched this, you may need them. data integrity check will find orphanes data, not all, but some. also Jira's own "project import" function should be able to filter orphaned data. Keeping backup is definitely a good suggestion. like nic said... i'd tryout the CLI in your case check #59.
https://community.atlassian.com/t5/Jira-questions/How-to-delete-a-Jira-project-from-database-with-all-issues/qaq-p/431539
CC-MAIN-2019-39
refinedweb
962
73.47
Fact. #include #include // reducing numbers from biggest to 2 // 16 -> 2*8 … 8 -> 2*4 … 4 -> 2*2 … void main(int argc, char **argv) { int n = atoi(argv[1]); int *p = (int *) malloc(sizeof(int) * (n + 1)); int i, j, d; for(i = 0; i 1; i–) if(p[i]) { for(j = i + i, d = 2; j <= n; j += i, d++) { if(p[j]) { p[i] += p[j]; p[d] += p[j]; p[j] = 0; } } } printf("1"); for(i = 2; i <= n; i++) if(p[i]) printf(" * %i^%i", i, p[i]); printf("\n"); } Recursivelly adding factorizations import Data.List import Data.Monoid import Data.Numbers.Primes facfac 1 = Factors [(1, 1)] facfac n = factorization n `mappend` facfac (n – 1) — Factorizations Monoid data Factorization a = Factors [(a, a)] deriving Show factorization = Factors . map (\ps -> (head ps, length ps)) . group . primeFactors instance Integral a => Monoid (Factorization a) where mempty = Factors [] mappend (Factors []) fs = fs mappend fs (Factors []) = fs mappend xfs@(Factors (xf@(x, a):xs)) yfs@(Factors (yf@(y, b):ys)) = case x `compare` y of EQ -> Factors ((x, a + b):ms) LT -> Factors (xf:ns) GT -> Factors (yf:os) where Factors ms = mappend (Factors xs) (Factors ys) Factors ns = mappend (Factors xs) yfs Factors os = mappend xfs (Factors ys) (Excuse me, I can’t modify previous post) In C version, we can reduce main loop from “i = n” to “i = n >> 1″. That version has O(n log log n) and are not needed primes calculation nor mul nor div operations (space is O(n)). Did in Go using my Project Euler library. Since it’s designed to solve PE problems everything is done with type uint64. That’s a fun little problem. Here is my solution. It is quick and dirty, not efficient. Assuming `primes` is already implemented, returning a stream of prime numbers in order, in Haskell, Another Python version. The optimization suggested by Will Ness did not work (in Python).
http://programmingpraxis.com/2014/01/24/factoring-factorials/
CC-MAIN-2014-35
refinedweb
323
59.74
int Cgetopt (int argc, char **argv, char *optstring) int Cgetopt_long (int argc, char **argv, char *optstring, Coptions_t *long_options, int *index) The Cgetopt_long function is similar to Cgetopt but it accepts options in two forms: words and characters. The Cgetopt_long function provides a superset of the functionality of Cgetopt. The additional functionality is described in the section CGETOPT_LONG. The option string optstring may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string x recognizes an option x , and an option string x: recognizes an option x taking an argument. It does not matter to Cgetopt if a following argument has leading white space. On return from Cgetopt, Coptarg points to an option argument, if it is anticipated, and the variable Coptind contains the index to the next argv argument for a subsequent call to Cgetopt. The variable Coptopt saves the last known option character returned by Cgetopt. The variables Copterr and Coptind are both initialized to 1. The Coptind variable may be set to another value before a set of calls to Cgetopt in order to skip over more or less argv entries. In order to use Cgetopt to evaluate multiple sets of arguments, or to evaluate a single set of arguments multiple times, the variable Coptreset must be set to 1 before the second and each additional set of calls to Cgetopt and the variable Coptind must be reinitialized. The Cgetopt function returns -1 when the argument list is exhausted, or a non-recognized option is encountered. The interpretation of options in the argument list may be cancelled by the option -- (double dash) which causes Cgetopt to signal the end of argument processing and returns -1. When all options have been processed (i.e., up to the first non-option argument), Cgetopt returns -1. Cgetopt_long can be used in two ways. In the first way, every long option understood by the program has a coresponding short option, and the option structure is only used to translate from long option to short options. When used in this fashion, Cgetopt_long behaves identically to Cgetopt. This is good way to add long option processing to an existing program with the minimum of rewriting. In the second mechanism, a long option set a flag in the Coptions_t structure passed, or will store a pointer to the command line argument in the Coptions_t structure passed to it for options that take arguments. Additionally, the long option's argument may be specified as a single argument with an equal sign, e.g myprogram --myoption=somevalue When a long option is processed the call to Cgetopt_long will return 0. For this reason, long option processing without shortcuts are not backwards compatible with Cgetopt. It is possible to combine these methods, providing for long options processing with short option equivalents for some options. Less frequently used options would be processed as long options only. The Cgetopt_long call requires a structure to be initialized describing the long options. The structure is: Coptions_t { char *name; int has_arg; int *flag; int val; }; The name field should contain the option name without the leading double dash. The has_arg field should be one of: NO_ARGUMENT if no argument to the option is expected, REQUIRED_ARGUMENT if an argument to the option is required or OPTIONAL_ARGUMENT if an argument to the option may be presented. If flag is non-NULL, then the integer pointed to by it will set to the value in the val field. If the flag field is NULL, then the val field will be returned. Setting flag to NULL and setting val to the corresponding short option will make this function act just like Cgetopt. Option arguments are allowed to begin with - ; this is reasonable but reduces the amount of error checking possible. #include <Cgetopt.h> int bflag, ch, fd; Coptind = 1; /* Required */ Copterr = 1; /* Some stderr output if you want */ bflag = 0; while ((ch = Cgetopt(argc, argv, "bf:")) != -1) switch(ch) { case 'b': bflag = 1; break; case 'f': if ((fd = open(Coptarg, O_RDONLY, 0)) < 0) { (void)fprintf(stderr, "myname: %s: %s\n", Coptarg, strerror(errno)); exit(1); } break; case '?': default: usage(); } argc -= Coptind; argv += Coptind; #include <Cgetopt.h> int bflag, ch, fd; int daggerset; /* options descriptor */ Coptions_t longopts[] = { {"buffy", NO_ARGUMENT, NULL, 'b'}, {"floride", REQUIRED_ARGUMENT, NULL, 'f'}, {"daggerset", NO_ARGUMENT, &daggerset, 1}, {NULL, 0, NULL, 0} }; Coptind = 1; /* Required */ Copterr = 1; /* Some stderr output if you want */ bflag = 0; while ((ch = Cgetopt_long(argc, argv, "bf:", longopts, NULL)) != -1) switch(ch) { case 'b': bflag = 1; break; case 'f': if ((fd = open(Coptarg, O_RDONLY, 0)) < 0) { (void)fprintf(stderr, "myname: %s: %s\n", Coptarg, strerror(errno)); exit(1); } break; case 0: if(daggerset) { fprintf(stderr,"Buffy will put use her dagger" "to apply floride to dracula's teeth"); } break; case '?': default: usage(); } argc -= Coptind; argv += Coptind; A single dash - may be specified as an character in optstring, however it should never have an argument associated with it. This allows Cgetopt to be used with programs that expect - as an option flag. This practice is wrong, and should not be used in any current development. It is provided for backward compatibility only. By default, a single dash causes Cgetopt to return -1. This is, we believe, compatible with System V. It is also possible to handle digits as option letters. This allows Cgetopt to be used with programs that expect a number -3 as an option. This practice is wrong, and should not be used in any current development. It is provided for backward compatibility only. The following code fragment works in most cases. int length; char *p; Coptind = 1; /* Required */ Copterr = 1; /* Some stderr output if you want */ while ((c = Cgetopt(argc, argv, "0123456789")) != -1) switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': p = argv[Coptind - 1]; if (p[0] == '-' && p[1] == ch && !p[2]) length = atoi(++p); else length = atoi(argv[Coptind] + 1); break; } } The OPTIONAL_ARGUMENT always eats the following argument unless the argument is included via the --option=argument notation.
http://www.makelinux.net/man/3/C/Cgetopt
CC-MAIN-2014-15
refinedweb
1,018
60.45
list_plot() not working in a terminal session Hello, list_plot() does not produce any plot when I run a script in a terminal (pure text) session. But it does when I run the same script in SAGE's graphical ("notebook()") environment. However, in both ways the execution ends normally (no error messages). Curiously, if I type list_plot(...array name goes here...) in the terminal after the execution of the aforementioned script, a plot is produced. Any explanation for that? The script is quite simple and short as shown below. Thanks for any help. import time from sage.all import * import math n = [19, 31, 61, 127] l=len(n) c = [] for i in range(l-1): for k in range(i+1,l): ai = 2**n[i]-1 ak = 2**n[k]-1 temp = ai*ak print ai, ak, ai*ak start_cpu = time.clock() divs = prime_divisors(temp) cpu_t = time.clock() - start_cpu c.append((math.log10(1.0*ai*ak),cpu_t)) print divs print 'CPU time = %.3e \n' % (cpu_t) list_plot(c) My setup: OS X 10.10.2, Sage 6.5.beta2. With your exact code, I get the plot displayed (an external viewer, Preview, is started and the plot is displayed there). What OS and what version of Sage are you using? Hi, Sorry for taking too long to reply. I had problems signing in and had to create another account. I'm using SAGE 6.4 on a Ubuntu 14.04-64bit machine. Thanks.
https://ask.sagemath.org/question/25674/list_plot-not-working-in-a-terminal-session/
CC-MAIN-2017-22
refinedweb
244
78.85
Configuring Remote Interpreter via and Python Docker plugins are enabled. The plugins are bundled with PyCharm and activated by default. If the plugins are not activated, enable them on the Plugins settings page of the Settings / Preferences Dialog as described in Managing Plugins. Also, for Windows, right-click the Docker whale icon, choose Settings on the context menu, and in the General page select the Expose daemon... checkbox: Preparing an example Create a Python project QuadraticEquation, add the quadratic_equation.py file and enter the following code: import math) Configuring Docker as a remote interpreter Now that we've prepared our example, let's define a Docker-based remote interpreter. To do it, open the Settings dialog (press Ctrl+Alt+S or click on the main toolbar). Next, click the Project Interpreter page, on this page click next to the Project Interpreter field, and choose Add from the drop-down list: In the dialog box 'quadratic_equation.py' command. You see that your script runs in the Docker container: As you can see, the prefix in the Run tool window shows the container ID. Debugging your application in a Docker container Next, let's debug our application. For that, let's put a breakpoint Tool Window as the UI for the Docker command-line client. If you have configured Docker as a remote interpreter, you will see the Docker tool window button at the bottom side of the main PyCharm window: Click this button and see that the Docker tool window opens:.
https://www.jetbrains.com/help/pycharm/2018.2/using-docker-as-a-remote-interpreter.html
CC-MAIN-2019-47
refinedweb
250
51.38
HOME HELP PREFERENCES SearchSubjectsFromDates This is a consequence of how our collection building process works, and because we started off with collections being static rather than continually growing. Data to build the collection on goes into the import directory. This is just so we know which data to use for the collection. Importing creates intermediate files (the doc.xml files) which are then used as source data for indexing. Strictly speaking, the archives are not essential. You can supposedly run buildcol.pl on the import directory. The trouble with that is that there are several passes through the documents to compress the text, index and build up the database. If you haven't generated the archives, then each pass through the documents you are effectively regenerating the doc.xml version. i.e. doing all the conversions and metadata extraction. So this is much slower. The final index directory is where the collection is served from. Both import and archives can be deleted once the index is created. Unfortunately, with our collection building process not being incremental, deleting the import directory means that the collection cannot be rebuilt. In a true incremental system, once you have indexed some documents, their import and archive documents can be deleted. And when you come to add some more documents, they can be imported and built into the collection without needing the source files for the others. This is what we are working towards using Lucene. I am not sure how far we have got towards that goal. For now, here are some ideas: 1. I am hoping that the incremental stuff will be tidied up a bit for the next release, and there will be some documentation about it. You could wait till then, and maybe you will be able to delete import and archives and still add more documents to the collection. I am hoping that will be the case, but whether we will have got there yet I am not sure. 2. do command line building, and each time you import, use import.pl -keepold and only have the new documents in the import directory. The archives directory will not be deleted each time, and will just get the new documents added in each import. This way, you will still have two copies of the associated files, in archives and index, but its better than three copies :-) 3. If you need to keep the archives files around for rebuilding, you could perhaps modify the perl code that handles associated files, so that they are not copied over into the index directory, but are linked to from the archives directory. Now you only have one copy left. This will involve programming though, and I am not sure how much of the system it will affect. Or maybe you could modify the code so that associated files are copied to the index/building directory the first time a document is indexed, and then they are deleted from the archives. Next time a build is done you need to make sure that the associated files directory is not deleted, and so existing associated files stay there. new associated files will be transferred over, but ones that have already gone will not be. Well, thats all. I hope this rambling was useful. Regards, Katherine Lost Samoan (Corporate) wrote: > □gather□ just the HTML files then none > of the associated files are available to the collections pages. If I > □gather□ the complete directory c:storage all the collection pages > embedded and linked files work fine, but: I then have the associated > files located in the c:~{collection_name}importstorage directory > AND in the c:~{collection_name}inexassocHASHxxxx directory, > doubling the storage required. After any □create□ the files are also > archived tripling the storage space. > > > > If I then remove the associated files from > c:~{collection_name}importstorage, the collection pages will not > work after any complete or incremental □create□. > > > > The real library is incrementally built six days per week with 30 new > HTML pages and associated audio files (in three formats) to say 6 of > those. This □triple□ storage acquaints to 54Mb for the audio files in > lieu of the base 18Mb. Over one Year this is an extra 11Gb. > > > > Question 1) Am I doing something wrong with the □gather□, or the files > associations within the HTML pages? > > Question 2) I know I can delete the □archive□ HASHxxxx folders and all > still works- but is there an associated risk doing this? > > > > I have re-read all the manuals and checked the users archive, but cannot > find an answer. > > > > Thank you for your consideration. > > > > > > **Colin J. Murfett** > > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > greenstone-users mailing list > greenstone-users@list.scms.waikato.ac.nz >
http://www.nzdl.org/gsdlmod?e=d-00000-00---off-0gsarch--00-0----0-10-0---0---0direct-10---4-----dfr--0-1l--11-en-50---20-help-Amin+Hedjazi--00-0-1-00-0--4----0-0-11-10-0utfZz-8-00&a=d&c=gsarch&cl=CL1.1.173&d=44C7F07A-1040503-cs-waikato-ac-nz
CC-MAIN-2016-07
refinedweb
776
63.7
I want to extract only the data from Excel in Excel by specifying conditions. Then I want to write the extracted data to Excel. In the middle of that, I was trying to create a data frame with Pandas, and when I tried to change the data to Excel and assign a column name in the data frame definition part, the following error message occurred. It is written in the part of # that i am trying to do, but please also see if the code matches it. Thank you. Applicable source codeApplicable source code The truth value of a Series is ambiguous.Use a.empty, a.bool (), a.item (), a.any () or a.all (). import pandas as pd df_A = pd.read_excel ("pandas_practice.xlsx", sheet_name = "Sheet1", index_col = [0,1]) # pd.read_excel (EXCEL file name, sheet_name = sheet name, index_col = column name/column number specified for index) Columns1 = ["CogDeg", "i", "j", "L", "B", "V"] #Column name df_B = pd.DataFrame (data = df_A, columns = Columns1) #Create a data frame with a named column df_C = df_B [df_B ["i"] == 0 and df_B ["j"] == 0] # Extract all rows where both column names i and j are 0 from the data frame df_C = pd.to_excel ("C: \ Desktop \ Python \ pandas_practice.xlsx", sheet_name = "Sheet2") # pd.to_excel (Destination directory + EXCEL file name, sheet_name = Sheet name) I didn't understand even after examining it.Supplemental information (FW/tool version etc.) Please provide more detailed information here. - Answer # 1 - Answer # 2 ☓ df_C = pd.to_excel (.. .... ◯ df_C.to_excel (...... Related articles - python - i want to sort and extract the top n columns for each "dataframe" index - about the operation of excel using python - python - excel display format using pyhon does not work - line breaks when outputting to excel in python - about external libraries when using multiple versions of python - python - i want to separate by a specific word using the split function - python - image recognition using cnn keras multiple inputs - python3 extract and delete duplicate data of date and time - about batch change of file name using python - extract title and video count with python youtube api - python 3x - i want to get the nth array with an argument using python3 argparse - excel python i want to get the display result instead of the conditional statement - python 3x - how to rename a folder created using jupyternotebook - csv - i want to extract the numerical group of the excel file displayed in matlab as it is - python - pandasdataframe i want to match the time columns of two csv and load them - python 3x - processing to jump to the link destination using chrome driver in python - python - error in image binarization using cv2adaptivethreshold function - python - i want to extract the numerical value at a certain position from bs4elementtab extracted by beautifulsoup by using the - parameter estimation using python's weighted least squares method (wls) - extract from python dat data and output to csv part is incorrect.Please use . Reference [Python] Dealing with errors when multiple conditions are specified in pandas.DataFrame-Qiita What to do when an error like The truth value of ... is ambiguous. occurs in numpy or pandas-A quiet name (拙 Article)
https://www.tutorialfor.com/questions-151127.htm
CC-MAIN-2021-10
refinedweb
515
55.07
Original article was published by Boulevard Consulting on Deep Learning on Medium Deep Learning from Scratch Engineering neural networks from scratch with Python Back in 2018, I first saw The Coding Train’s series on engineering neural networks from scratch with javascript. I felt it was extremely helpful and have since wanted to make my own hacky, from-scratch implementation with python. As I go along, I’ll attempt to explain my thought process using layman’s terms and as little math as possible. # exponential function from math import exp # a very simple iteration operation from itertools import tee # library for n-dimensional arrays... I had made my own classes for vectors and matrices but, without hardware-accelerated operations for dot products and transposition, they relied on very slow loops that proved to be pretty impractical. import numpy as np# some standard helper functions ## example datasets from sklearn.datasets import make_circles, make_blobs ## to randomly split data from sklearn.model_selection import train_test_split ## to shuffle the data randomly from sklearn.utils import shuffle ## to score classification tasks from sklearn.metrics import roc_auc_score, roc_curve, auc # lastly, a nice plotting module for visualizing my rambles import matplotlib.pyplot as plt ## a colormap functio nfrom matplotlib.cm import get_cmap as cmap I like to think of machine learning (specifically supervised learning tasks) as an automatic calculator. It is but a series of mathematical operations on some inputs to provide a targeted output. Machine learning models can be as simple as a linear regression, but sometimes more complex models are needed for more complicated issues. Neural networks are a complicated model that can mimic the functionality of linear regression, but also may also scale up to be far more complicated. A common problem in machine learning is that of nonlinearity. That is, complex interactions among the inputs to a model. Below is a very simple example of what a nonlinear interaction looks like. The meaning of vertical axis in relation to the color is dependent on the horizontal axis. Simply put, there is no line that can separate the two colors. It has linear inseparability. X, y = make_circles(n_samples=500, noise=0.1, factor=0.1) plt.scatter(X.T[0], X.T[1], c=y) plt.axis('off'); plt.show() Neural networks are extremely generalizable and are excellent at learning nonlinear interactions. This does come at a cost though. Neural networks can be quite computationally expensive to train and they are virtually uninterpretable. In other words, there is no easy way to tell how a neural net made a prediction. Neural networks are surprisingly similar to linear regression models. I like to think of a “layer” of a neural networks as just many multiple regression models stacked on top one another, each with their own outputs. A neural network is then just a sequence of these layers. The neural network works by iterating over each layer, propagating the outputs of each of them to the next, until the final layer outputs its own final answers. Before we can get to that, I’m just going to put together some miscellaneous general helper functions: # this is a handy function to go over the pairs within an iterable object def pairwise(iterable): a, b = tee(iterable) next(b, None) return zip(a, b) # for example... for i, j in pairwise(range(1,6)): print(f'{i} precedes {j}')1 precedes 2 2 precedes 3 3 precedes 4 4 precedes 5 Now I need to make a basic activation function. These are used to transform the output of all node. While I am using the sigmoid for uniformity (the output of the final layer is to be constrained between 0 and 1 for my classification problem), the ReLU is much more common these days for many reasons. The purpose of activation functions is to introduce nonlinearity. I think of activation functions, (especially ReLU), as being analogous to the use of options (financial derivatives): having the access to nonlinearity allows a creative mind — in this case, an artificial one — to design extremely complex, nonlinear outputs much in the same way multiple options can be used strategically to create a spread to hedge financial risks. def sigmoid(x): if x >= 0: z = exp(-x) return 1 / (1 + z) else: z = exp(x) return z / (1 + z)# derivative of sigmoid function (needed for calculus in of back-propagation). prime = lambda x: sigmoid(x) * (1 - sigmoid(x)) # vectorizing a function just means that I can now easily apply it element-wise to a numpy ndarray sigmoid = np.vectorize(sigmoid) prime = np.vectorize(prime) x = np.arange(-10,10,0.1) plt.plot(x, sigmoid(x)) plt.title("Sigmoid Function") plt.ylim(top=1.0) plt.show() plt.plot(x, prime(x)) plt.title("Derivative of Sigmoid Function") plt.ylim(top=1.0) plt.show() As I had mentioned above, the essential unit of a neural network is the layer. In my implementation layer holds two key parameters: biases and the weights. In the same way a layer is just a stack of linear regression models, biases are a stack of “y-intercepts” for each model. In other words, I implement biases as a vector of β₀, one for each node in the layer. Similarly, weights is simply a list of coefficients for all the inputs in each linear regression model. Because we have multiple linear models per layer, all of which will have the same number of betas (the number of inputs), weights can be implemented as a matrix! All of the elements in both these objects are initialized to a standard, normal distribution. We also have a “setting” (hyperparameter): the “activation function”. In the same way the output of a logistic regression model is applied to a sigmoid function, we will also apply the sigmoid function to the output of each node in out layer. This is a standard implementation that create additional nonlinearity. The sigmoid function is an arbitrary decision here, and there are far better ones with an easier mathematical implementation (namely ReLU!), but sigmoid is actually easier because it fits the desired range we want for classification (constrained between 0 and 1). For the purposes of correcting errors with calculus, we need to store the derivative of the activation function as well. I’ve found that a really simple but effective Layer class is very important for the technical implementation of a neural network. class Layer: def __init__(self, ncol, nrow): # number of inputs & outputs self.shape = (nrow, ncol) # values of the weights self.weights = np.random.randn(nrow, ncol) # values of biases self.biases = np.random.randn(nrow, 1) # placeholder for unactivated output of layer self.outputs = np.ones((nrow, 1)) # activation function (currently fixed as sigmoid) self.activator = np.vectorize(sigmoid) # derivative of activation function self.primer = np.vectorize(prime) layer = Layer(3, 5) print(f'\n weights: shape = {layer.weights.shape} \n {layer.weights}') print(f'\n biases: shape = {layer.biases.shape} \n {layer.biases}') print(f'\n sigmoid(3) = {layer.activator(3):.4}') weights: shape = (5, 3) [[ 0.58360291 -1.04477239 2.01744448] [ 0.80362262 0.70918266 2.00654262] [ 0.98185151 0.09150979 0.96289542] [ 0.01239768 -0.12943097 0.41800989] [-0.07103671 -0.39461366 0.9333896 ]] biases: shape = (5, 1) [[ 0.97393686] [-1.12518667] [-1.46797602] [ 0.77734602] [ 0.81846104]] sigmoid(3) = 0.9526 The first and last layers of a neural network is always called the input layer and output layer, respectively. All layers in between are called hidden layers as they are beyond our interpretation. As the information flows through them, they exist in latent space. The final step is actually stitching these layers together with the ability to communicate with one another. Layers need to communicate in two key ways: (1) sending forward through our hidden layers & (2) sending back blame to correct themselves. These two processes are called forward propagation and backward propagation, respectively. Forward propagation is simple enough. For each hidden layer, there is our stack of linear regression models. Each linear regression model takes all outputs of the previous layer, multiplies them by its vector of weights, and then adds its bias and is passed through the layer’s activation function. This makes one of the potentially many outputs of that layer, all of which collectively then repeat the same process through the next layer until the output layer is reached. Forward propagation works just like a bunch of linear models hooked up together human-centipede style. Backward propagation is the hard part. Once the final prediction is made from the output layer, that prediction is compared to the real answer. The difference between the two is the error for the final layer. Backward propagation is all about each linear regression model in each layer trying to figure out how responsible it is for this final error, and then, using some calculus, how responsible each of its respective weights (and bias!) is before then sending the aggregated blame back to the previous layer. In layman’s terms, backward propagation is just each layer learning from their own mistakes before telling the previous layer how to learn of their own. class NeuralNetwork: def __init__(self, *shape, epochs = 50, lr = 0.001): # stores number of nodes at each layer self.shape = shape # placeholder to store pairs of layers self.layers = [] # static hyperparameters self.epochs = epochs self.lr = lr # create layers as pairs of inputs for inputs, outputs in pairwise(shape): self.layers.append(Layer(inputs, outputs)) # placeholder to store scores for each epoch self.scores = [] def forward(self, x): # reshape input to fit succeeding layers tensor = np.atleast_2d(x).transpose() # for each layer for layer in self.layers: # multiply inputs by their weights and add their bias tensor = layer.outputs = layer.weights.dot(tensor) + layer.biases # activate output tensor = layer.activator(tensor) # return final activated output return tensor def backward(self, error): # error is already initialized for the final output layer! # for each layer in reverse order for index, layer in reversed(list(enumerate(self.layers))): # find preceding layer predecessor = self.layers[index - 1] # define delta as the partial derivative of layers input with respect to its weights delta = error @ predecessor.activator(predecessor.outputs).transpose() # change weights by their assigned blame dampened by the learning rate layer.weights -= delta * self.lr # change biases by their subsequent node's blame dampened by the learning rate layer.biases -= error * self.lr # update error as the blame for preceding layer error = layer.weights.transpose().dot(error) * predecessor.primer(predecessor.outputs) def predict(self, X): # predict based on each observation in X predictions = [self.forward(obs) for obs in X] # return array of predictions return np.array(predictions).squeeze() def score(self, inputs, answer, verbose=True): # find predictions of all inputs prediction = self.predict(inputs) # find comparison of predictions with the actual answers auc = roc_auc_score(answer, prediction) if verbose: print(f'auc = [{auc:.1%}].') return auc def fit(self, X, y, target = None): self.decision_boundary = np.average(y) # for each epoch for epoch in range(self.epochs): # shuffle data X, y = shuffle(X, y) # append score score = self.score(X, y, verbose=False) self.scores.append(score) if target is not None: if score > target: break # for each record in shuffled data for inputs, answer in zip(X, y): # predict answer prediction = self.forward(inputs) # find error of output layer error = prediction - answer # propagate that backwards self.backward(error) def plot_errors(self, X, y): # this guy plots the first two dimensions of a dataset in a scatterplot # each point is colored green if it was correctly predicted, otherwise it is printed red predictions = self.predict(X) > self.decision_boundary incorrect = np.logical_xor(predictions, y) plt.scatter(X.T[0][incorrect], X.T[1][incorrect], c='red') plt.scatter(X.T[0][~incorrect], X.T[1][~incorrect], c='green') plt.axis('off'); plt.show() def plot_scores(self): # plots the AUC for each epoch x = list(range(len(self.scores))) y = self.scores plt.plot(x, y) plt.ylim(top=1.0, bottom=0.0) plt.title("In-sample AUC score prior to each epoch") plt.show() def graph(self): colormap = cmap('RdYlGn', 2) for index, layer in enumerate(self.layers): # initialize set of nodes nodes = set() output_size, feed_size = layer.shape for output_index, output in enumerate(range(output_size)): # arrows for output layer if index == len(self.layers) - 1: plt.arrow(index + 1.1, output - output_size/2, 0.05, 0, head_width = 0.4, head_length = 0.05, color="steelblue", length_includes_head =True) # add all output nodes (if unique!) nodes.add((index + 1, output - output_size/2)) # plot weights between biases and hidden/output layers height = max(self.shape)/2 value = layer.biases[output_index, 0] plt.plot([index, index+1], [height, output - output_size/2], c = colormap(value > 0), linewidth = min(8, abs(value)+0.25)) # plot biases plt.scatter(index, height, s=150, c='white', edgecolors='black', zorder = 10) plt.text(index, height, s='1', zorder = 100, horizontalalignment='center', verticalalignment='center') for feed_index, feeder in enumerate(range(feed_size)): # arrows for input layer if index == 0: plt.arrow(index - 0.15, feeder - feed_size/2, 0.05, 0, head_width = 0.4, head_length = 0.05, color="steelblue", length_includes_head =True) # add all input nodes (if unique!) nodes.add((index, feeder - feed_size/2)) # plot weights between input and output nodes value = layer.weights[output_index, feed_index] plt.plot([index, index+1], [feeder - feed_size/2, output - output_size/2], c = colormap(value > 0), linewidth = min(8, abs(value)+0.25)) # plot set of nodes for node in nodes: plt.scatter(*node, s=150, c='black', zorder = 10) plt.axis('off') plt.xlim(xmin=-0.2, xmax=len(self.layers) + 0.3) plt.ylim(ymin= -(max(self.shape)/2) - 1) plt.show() Now that the hard part is done, let’s check it out. First, let’s build a neural network with only one hidden layer. nn = NeuralNetwork(2,3,1, epochs=50) nn.graph() Let’s get some (linear) data to play with. This should be easily solvable with the equivalent of a logistic regression model. That being said, because linear models don’t have to worry about nonlinear interactions, they train significantly faster than neural networks with approximately equal performance. Since we’re using a neural network prepared for nonlinear relationships, we still are running over the same data multiple times. This is very computationally inefficient and won’t perform significantly better. It’s good to confirm that my implementation will be able to solve it though. X, y = make_blobs(n_samples=1000, centers=2, cluster_std=3) plt.scatter(X.T[0], X.T[1], c=y) plt.axis('off'); plt.show() X_train, X_test, y_train, y_test = train_test_split(X, y) The data here looks easy enough to solve. It has linear separability. nn.fit(X_train, y_train, target=0.99) nn.plot_errors(X_test, y_test) nn.plot_scores() The neural network learned to use its degrees of freedom to place a decision boundary between the two clusters. With our test data, the neural net was able to predict the colors of almost all the points. Any mistakes it made are now colored in red. An AUC of 100% is perfect. Ours is almost there, but still made a few mistakes. But that is to be expected — some of the colors overlapped. Now let’s look back at our nonlinear problem. X, y = make_circles(n_samples=1000, noise=0.1, factor=0.1) plt.scatter(X.T[0], X.T[1], c=y) plt.axis('off'); plt.show() X_train, X_test, y_train, y_test = train_test_split(X, y) We are using this data generator for the simplicity of visualizing its two dimensions — in practice, data hardly looks like this. Furthermore, because the rings are centered at (0,0), we could simply use some feature engineering to make a very simple third variable equivalent to the euclidean distance of any point to center. This would give a single variable perfectly able to explain the color. X₁ = √(x1² + X₂²) Regardless, without such feature engineering, there is no way to place a line anywhere to divide the two colors using a linear model. A “logistic regression” model, (a neural network without any hidden layers) is doomed to fail here. nn = NeuralNetwork(2, 1, epochs = 20) nn.graph() If we use a neural network without any hidden layers, we won’t be able to pick up on the nonlinear interactions. It tries to place a line between all of the data and will inevitably fail. nn.fit(X_train, y_train) nn.plot_errors(X_test, y_test) nn.plot_scores() An AUC of 50% is equivalent to guessing randomly. This model offers no value. Lets use that exact same data but with a more complex neural network. This neural network has enough degrees of freedom to make latent variables on its own. This means it can learn that the problem is nonlinear and will, of its own accord, learn how to place some nonlinear decision boundary between the colors. nn = NeuralNetwork(2, 9, 6, 1, epochs=500) nn.graph() nn.fit(X_train, y_train, target=0.975) nn.plot_errors(X_test, y_test) nn.plot_scores() The model is significantly better than guessing randomly, but still misses a section of the outer ring. Looks like it formed some sort of slanted parabola around the center, but I cut it off before it had time to tie the parabola into a circle around the center. Based on the high AUC I get the impression it was pretty unsure about those mistakes too. Nice, so the neural network almost learned how to solve this very simple problem. Here are but a few of the many shortcomings of my implementation: - It doesn’t use batch learning. That is, it is running backwards propagation for each record it sees. This is very inefficient and computationally expensive. It is standard to aggregate errors before backpropagating them to save time. - It is dependent on loops and is not able to be compiled to run on GPUs. This is perhaps one of the biggest drawbacks and will slow down computation time by well over 100x… It is a limitation of using Python to write this instead of a lower-level language such as C or Rust. Since neural networks use matrix multiplication for forwards and backwards propagation, they are able to run extremely fast if accelerated. - My learning rate is static — this will lead to diminishing increases in accuracy as the neural network approaches its parameters reach their optimal states. Libraries such as Torch and Tensorflow are built to provide all of this functionality, including a ton more, all of which is way more computationally efficient, accurate and reliable with just a few lines of code. That being said, I feel as though recreating their most basic functions helped me learn alot about what goes on underneath the hood. About the Author Grantham Taylor is a Consultant at Boulevard with a focus in data science. He recently graduated with a Masters in Finance and Quantitative Management from Duke University. His interests focus on deep learning, machine vision, natural language processing, non-linear optimization, and anomaly detection..
https://mc.ai/deep-learning-from-scratch-2/
CC-MAIN-2020-45
refinedweb
3,158
50.02
Cannot find or open PDB file I am running the following code in visual studio 2010 as win32 console application: #include #include #include #include using namespace std; Standard_Integer main() { STEPControl_Reader reader; reader.ReadFile("C:\Users\..\cylinder.stp"); // Loads file MyFile.stp Standard_Integer NbRoots = reader.NbRootsForTransfer(); // gets the number of transferable roots cout } It shows the following error : C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file Loaded 'C:\OpenCASCADE6.5.0\ros\win32\vc8\bin\TKernel.dll', Binary was not built .... .... and the says "The program cannot start because tbbmalloc.dll is missing from your coumputer. try reinstalling the program to fix this problem." The command window appears though without any output. I tried '' but there was no change. The PDB file is a file with debug information, that fact that it is missing is no problem unless you need the debug information (line number, local variable names and so on), when the DLL is compiled a matching PDB file is also created and should be in the same place as the dll. I have no idea about the missing dll. It is possible you might need to rebuild the OCC projects, I don't know how it is today but in the past most demo projects and sometimes the OCC projects was incorrect and needed some modifcations before they would work, they never tested the Visual Studio projects before they released a new version of OCC, but they may have improved on this today. Dear Mikael, We do not appreciate your false statement: "... they never tested the Visual Studio projects before they released a new version of OCC...". We would like to stress that all VC projects before delivery go through certification loop and can't be a part of the coming release without testing by definition. Without doubt it doesn't exclude appearance of bugs in OCCT, but our experience allows to affirm that the most of problems linked with VC projects is raised by incorrectly tuned local environment. We believe that every accusation should be based on facts and proved... Regards Forum supervisor So is there no solution to the problem ??? Should i use mfc instead of win32 ??? strange that it requires tbballoc.dll since it's a dll from threading building blocks. I don't know if OCC binaries are built with it. Anyway, you are probably loading vc8 binaries (ros/vc8/bin/TKernel.dll) while using VC 2010. It won't work that way, binaries must match specific compiler version and service pack level. No i am using vc10 binaries only. Can i do this in mfc, if yes then what modifications i must make in project properties etc. as i have never used it before ?? There is nothing false about the statement, it is possible that they are tested today as I also said, but a number of times when I downloaded OCC (in the past), both OCC itself and sample MFC projects was not possible to compile because a number of reasons, most of the time settings in the project options was incorrect and needed modification, some directories was incorrect and some #defines where missing so there is no chance whatsoever that those project was ever tested. Often the debug version of a VC project worked fine but a lot of things where incorrect in the release version as an example and it was very clear that only one of the project types had ever been tested not the other, so this is not a FALSE statement, this is 100% true. And once again, this was in the past, today they may all be tested and verified, I do not know that but they where not then (maybe 4-5 years ago).
https://www.opencascade.com/comment/6754
CC-MAIN-2020-16
refinedweb
648
62.38
(); //make a request to the REST interface for the data HttpWebRequest webRqst = (HttpWebRequest)WebRequest.Create(endpoint); webRqst.UseDefaultCredentials = true; webRqst.Method = "GET"; webRqst.Accept = "*/*"; webRqst.KeepAlive = true; /; //read the response now HttpWebResponse webResp = webRqst.GetResponse() as HttpWebResponse; //make the request and get the response StreamReader theData = new StreamReader(webResp.GetResponseStream(), true); string payload = theData.ReadToEnd(); theData.Close(); webResp.Close(); /. Hi Steve, Thanks for this post. Is it necessary to use this method when in a Claims-based authentication enabled site? Can't you just use a normal Web Reference and it's context? I'm asking because I've been getting errors with my silverlight web part (which uses listdata.svc) in a claims-based authentication enabled site. Cheers, Yohan Hi, do you have a link to the GetSamlToken() method you're using? Can this method be modified to look into AD instead of a custom or Adfs provider? I want to do this to connect to a site in a web app which is in claims mode (Active Directory only) and FBA (Ldaps). I don't know how to get the cookie. If I copy the cookie using Fiddler (and IE) and set it in the GET call it works. Thanks Do we need to add servcice reference to use this service, the way you have described? this is brutal man! :) it saved me a lot of investigation, thanx. Nice Post !!. Is there any way to get this working using Jquery.ajax() ? Although this article is very old, I hope you still get a notification for this. I got the problem that a site with mixed authentication windows + fba in sharepoint 2013 claims doesn't allow for specific credentials to be handed over. If I use DefaultCredentials everything is fine, if not, 401 Unauthorized is returned. Thanks for your help This seems to be serving my requirements. Thanks to you!However when I copied the code into my windows application in VS 2012, I found VS could not able to locate GetSamlToken() method, I searched in google too but no luck.Could you please help me which namespace I forgot to include in my project.Thanks in Advance.
http://blogs.technet.com/b/speschka/archive/2010/09/25/retrieving-rest-data-in-a-claims-based-auth-site-in-sharepoint-2010.aspx
CC-MAIN-2014-23
refinedweb
359
67.86
Learn Once Use Everywhere: Using JavaScript APIs in Java for Web Browser Last time we saw how we can reuse our Java code in JavaScript from my article “Web Browser Programming in Java”. Today we’ll take a look on how we could call the JavaScript APIs, web apps and frameworks from our Java code and at the end to transpile them back to JavaScript so that it will be runnable on the web browser. To see how we could do this, it is important that we understand the process on how Java with GWT () or J2CL () communicates with JavaScript. For this purpose we have the JsInterop which work as a bridge between Java and JavaScript. In the old version of GWT we had JSNI (JavaScript Native Interface) but this is now deprecated and we should only use JsInterop. In JsInterop you have two cases: Use case 1: the contracts are available in Java and you want to use those contracts in JavaScript. This is shown in our Calculator example from my first article. In this case you want to use the Java apps and APIs from your JavaScript apps. Use case 2: the contracts are available in JavaScript as APIs or apps or frameworks and you want to use them in Java. In this case you need to bridge the JavaScript APIs to your Java apps. At the end you transpile everything back to JavaScript since you want to run your app on the web browser. Following picture shows both use cases for JsInterop. In this article I will show you how to do the use case 2. First of all we need to have a JavaScript app or APIs which we want to use in our Java app. For this simple example I would use a JavaScript Calculator which is implemented in the index.html file as a JavaScript function: <!doctype html> <html> <head> <script type="text/javascript" src="calculator.nocache.js" </script> <script type="text/javascript"> Calculator = function () { this.x; this.y; }; Calculator.prototype.sum = function () { return this.x + this.y; }; </script> </head> <body> ... </body> </html> The Calculator has just two values x and y. It also has a function sum to calculate the sum of x + y. The next step is how we can bridge this Calculator function into our Java world? It’s quite easy, we just write a JsInterop class Calculator.java to map it to our Java world. We use isNative = true to say to our transpiler that the implementation of this class is in the JavaScript world: package com.github.lofi.client;import ...;@JsType(namespace = JsPackage.GLOBAL, name = "Calculator", isNative = true) public class Calculator { public int x public int y; public native int sum(); } In the class above you don’t see any implementations of the Calculator since they reside in the JavaScript function. That’s it. But wait, how can we use this Java class Calculator in our Java web app? For this purpose I extend the HTML file just like following steps: - I add the result of the transpiled JavaScript file: calculator.nocache.js to the HTML file - In the component Button event onclick we can use the CalculatorService and call the calculatePrice method. <!doctype html> <html> <head> <script type="text/javascript" src="calculator.nocache.js" </script> <script type="text/javascript"> Calculator = function () { this.x; this.y; }; Calculator.prototype.sum = function () { return this.x + this.y; }; </script> </head> <body> <button onclick="console.log(new CalculatorService().calculatePrice(41, 2));">Click my Calculator! </button> </body> </html> So the Calculator class can be used directly within the CalculatorService class in Java and at the end the CalculatorService class can be called from the JavaScript component Button within onclick event. For this purpose we need to build CalculatorService and this class should be callable from JavaScript which represents the use case 1 above. Here is the implementation of CalculatorService class which uses the Calculator class: package com.github.lofi.client;import ...;@JsType(namespace = JsPackage.GLOBAL, name = "CalculatorService") public class CalculatorService { public String calculatePrice(int x, int y) { Calculator calculator = new Calculator(); calculator.x = x; calculator.y = y; final int sum = calculator.sum(); return "Price: " + sum; } } That’s all we need. To sum up, in this short article we have seen how we could access JavaScript APIs from Java by creating a JsInterop file which has a “native” implementation. The property “native” means that the implementation lies in JavaScript, which represents the use case 2. In the example above the implementation of the Calculator is done in JavaScript. From CalculatorService we can call the JavaScript APIs easily as they were implemented in Java. In this context I also show you again how we would call the CalculatorService from the JavaScript which shows us the use case 1. Detail information about the use case 1 can be found in my first article. The diagram below shows the dependencies and interactions between Java and JavaScript for both classes CalculatorService and Calculator. Enjoy and have fun with Java on the Web browser! After understanding both use cases for JsInterop, next time I’ll show you how to implement web browser persistence with IndexedDB using Elemental2 APIs — only in Java. All examples can be found at: Padlet for GWT / J2CL modern programming:
https://lofidewanto.medium.com/learn-once-use-everywhere-javascript-in-java-for-web-browser-ec1b9657232c?source=post_page-----ec1b9657232c--------------------------------
CC-MAIN-2021-21
refinedweb
873
64
WikiLeaks founder Julian Assange could be charged under the Espionage Act for making public classified U.S. government documents which he obtained illegally, a media report said here on Tuesday. The U.S. authorities are investigating whether Mr. Assange, also Editor-in-Chief of the whistle-blower website, violated criminal laws by disclosing the classified information, ‘The Washington Post’ reported. The FBI is examining everyone who came into possession of the documents, including those who gave the material to WikiLeaks and also the organisation itself, it said, citing those familiar with the probe. According to the Post, charges against WikiLeaks and Mr. Assange could be filed under the Espionage Act. ,” the daily reported. Under the Espionage Act, anyone who has “unauthorised possession to information relating to the national defence” and has reason to believe it could harm the United States may be prosecuted if he publishes it or “wilfully” retains it when the government has demanded its return, Jeffrey H Smith, a former CIA general counsel, told the paper. However, “no charges are imminent”, sources were quoted as saying, adding it is unclear whether any will be brought. White House Press Secretary Robert Gibbs told reporters that “the stealing of classified information and its dissemination is a crime.” “We have an active, ongoing criminal investigation with regard to this matter. We are not in a position as yet to announce the result of that investigation, but the investigation is ongoing,” U.S. Attorney General Eric Holder said. “To the extent that we can find anybody who was involved in the breaking of American law and who has put at risk the assets and the people ..., they will be held responsible. They will be held accountable,” Mr. Holder said when asked if action could be taken against Julian Assange, the WikiLeaks founder and Editor-in-Chief. Secretary of State Hillary Clinton said the U.S. is taking aggressive steps to hold responsible those who stole this information. “I have directed that specific actions be taken at the State Department in addition to new security safeguards at the Department of Defence and elsewhere to protect State Department information so that this kind of breach cannot and does not ever happen again,” she told reports. Jeffrey H Smith told the post: “I’m confident that the Justice Department is figuring out how to prosecute him (Assange).” Mr. Smith noted that the State Department general counsel Harold H Koh had sent a letter to Mr. Assange on Saturday urging him not to release the cables, return all classified material and destroy all secret records from WikiLeaks databases. “That language is not only the right thing to do policy-wise but puts the government in a position to prosecute him,” he said. Keywords: WikiLeaks, Julian Assange, espionage Act, whistle-blower, U.S. State department documents, Secretary of State, Hillary Clinton
http://www.thehindu.com/news/international/assange-could-be-charged-under-espionage-act-report/article923621.ece
CC-MAIN-2013-48
refinedweb
475
54.12
Free for PREMIUM members Submit [Webinar] Streamline your web hosting managementRegister Today public class Person { // Backing Store varible name added for Property Name private string name; public string Name { get { return name; } set { name = value; } } // Backing Store varible age added for Property Age private int age; public int Age { get { return age; } set { age = value; } } } //public class Person //{ // public string Name { get; set; } // public int Age { get; set; } //} public partial class Form1 : Form { List<Person> Customers; Person newPerson = new Person(); public Form1() { InitializeComponent(); // You need to allocate space on the heap for the Customers list Customers = new List<Person>(); newPerson.Name = "Bob"; newPerson.Age = 30; Customers.Add(newPerson); newPerson.Name = "Mickey"; newPerson.Age = 29; Customers.Add(newPerson); newPerson.Name = "Jan"; newPerson.Age = 29; Customers.Add(newPerson); // You are iterating over the wrong object newPerson which is NOT a collection, // you would need to iterate over Customers but you can not modify the list in this // way. // foreach(Person p in newPerson) // { // p.Age=25; // } // So you can do the following in a single line of code. Customers.ForEach( c => c.Age = 25 ); } } Select all Open in new window foreach(Person p in Customers)... foreach(Person p in newPerson) { p = new Person(); } ...you would need to iterate over Customers but you can not modify the list in this way. $37.50. Premium members get this course for $151.20. Premium members get this course for $143.20. Premium members get this course for $4.00. Premium members get this course for $389.00. Premium members get this course for $79.20. A couple of issues with the code you posted. You can not use the class Person as you have defined it. The form you chave used need ]s the backing store variables for each of the properties as shown below. You could allow the compiler to create these backing store variables on its own as follows the class Person which is commeted out. Inside the Form1 class you declared a List<Person> but that line of code does not allocate memory on the heap so you need to do that before you use it. Open in new window Open in new window What you cannot do is this: Open in new window Attempting to modify the iterator variable itself will yield an exception. Modifying any properties of the object the iterator variable points to...that is OK. You most certainly can modify the age within a foreach loop. That's exactly what you're one-liner is doing ; ) Or am I misunderstanding what you were saying in that line? With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you. I am in agreement with your statement in the your post. What I was trying to state to brgdotnet is that his foreach loop was trying to iterate over a single object and NOT a collection as is needed, a collection as Customers, but what he wanted to do can not be done. Sorry if it confused anyone.
https://www.experts-exchange.com/questions/28151912/How-to-change-items-in-a-list-when-iterating-through-the-list.html
CC-MAIN-2018-09
refinedweb
522
65.32
#include <hallo.h> * Josselin Mouette [Sat, Jul 14 2007, 02:26:55AM]: > Le vendredi 13 juillet 2007 à 17:16 -0700, Steve Langasek a écrit : > > >? > > I'm wondering what is the use case for that entry. Changing another WM on-the-fly when letting somebody use your PC, without restarting the whole X session? Testing other WMs? The fact you are not imagining any use cases does not mean that such ones do not exist. > I can imagine someone dealing with such a case (although I'd personally > start a new session to better match the user's environment) but I don't > think this justifies adding these entries to all users' menus. If you don't like seeing them, move them to the Settings submenu. Eduard. -- <Joey_> Weasel: schreib mal da hinein, daß ich im IRC immer so schroff bin und nur auf die Türen zeige, öffnen und durchgehen müssen die Leute schon selbst. Und wenn sie nicht tun, was ich ihnen sage, endet mein Support an der Stelle.
https://lists.debian.org/debian-devel/2007/07/msg00372.html
CC-MAIN-2015-48
refinedweb
170
78.89
! Where can I download the binary for Python Netbean 7.0 for Windows platform? Currently I download the Python Netbean from the hudson build. Is it the same place for me to download the python Netbean build? I haven't tried the latest build. But the previous release with unittest and code coverage is really awesome. It is really useful for me. Just one problem with me with previous build is when running unittest, it will complain the cannot import my test file. For eg, I am testing c:\work\testfile.py I must added c:\work into the python path in order to run the unit test. If I had another file at c:\work\common\testb.py, I will need to add c:\work\common into python path also. This is a bit annoying but I can live with that. Thanks for the great work on the best IDE! Posted by shin guey on January 05, 2009 at 05:34 PM PST # Hi Shin, thanks for the comment. Yes, is the right place to get the latest Python bits, including for Windows. We'll have proper installers etc. built for the full release when we get to beta, rc1 and final. I'm not sure I fully understand your problem. You -do- have to have all the test files part of your project (e.g. under one of the source directories listed in your source file roots, listed in your project properties dialog (right click on the project in the project explorer)). Is that the problem? Or are you saying there is a problem accessing files in packages? If you can boil this down to a simple self contained project which demonstrates the problem, and file it as a bug report, that would be great: Posted by Tor Norbye on January 05, 2009 at 07:07 PM PST # Based on the explanation of how the testrunner works it seems it is currently not possible to run standalone doctests? What I mean with this is to test separate *.txt files with doctests. The testrunner that I am familiar with solves this by letting you specifiy a function (suite) within your test modules. This function is called and is supposed to return a unittest.TestSuite instance. That means you can have code like: def suite(): s = unittest.TestSuite() s.addTest(doctest.DocFileSuite( 'somefile.txt', 'anotherfile.txt')) Posted by Jeroen on January 24, 2009 at 06:48 AM PST #
http://blogs.sun.com/tor/entry/netbeans_screenshot_of_the_week7
crawl-002
refinedweb
408
83.86
Are you looking for samples in v1.0 or v2.0? The code you quoted below is some version of v2.0 (we're still working on the final tweaks to what will become the new, final, hosting model). From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Joshua J. Pearce Sent: Tuesday, October 16, 2007 2:08 PM To: users at lists.ironpython.com Subject: [IronPython] Need a Good Embedded Example I have been looking for a good example of embedding IronPython in a c# application. I am under the impression that there have been some major changes in the way this is done from version 1.1 to 2.0. This is what I found at the Python Cookbook site: namespace IronPythonScriptHost { class Program { static void Main(string[] args) { string code = "print \"Hello \" + Name"; Script.SetVariable ("Name", "Me"); Script.Execute("py", code); } } } That's nice, but doesn't really help me to know how to get variable output from the script back to my c# code. I also need to know how to call scripts with multiple statements and whether all variables need to be set on the script object, or can their declaration just be part of the script code. Is there a good and simple example anywhere that shows how to host the IronPython engine in a c# app and let users manipulate your program objects via ipy scripts? Thanks! -- Joshua Pearce -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/ironpython-users/2007-October/005759.html
CC-MAIN-2016-40
refinedweb
252
74.69
Trigonometry Archive: Questions from March 27, 2013 - ClammyVillain3911 asked2 answers - DangerousEagle5101 asked?xml:namespace prefix = o ns = "urn:schemas-micros... Show more Please Help!! Be very neat and provide details.<?xml:namespace prefix = o 1. The range for a projectile is defined by the following equation: R=(V2sin2theta)/(g) Where V is the velocity, g is gravity and ? is the elevation angle. For V = 250 ft/sec, g = 32 ft/sec2 (a) If you wish to achieve a range of 1100 ft, what elevation angle ? will be needed? Give your answer to at least 2 decimal places. (b) Calculate the ranges for ? = 20o, 30o, 40o, 50o, 60o then see if you can estimate what elevation angle ? will give you the longest range. 2. The methods presented in your text do not always work and you often have to rely on other method. Try the problem below: Given y=3.2cos0.4x-sin0.1x (a) For x between 0 and 2?, draw the graph of this function. (b) Solve for x in using the Intermediate Zero Theorem. Give you answer to at least 2 decimal places accuracy (i.e., 0.00xx) If you don’t remember what the Intermediate Zero Theorem is, it was covered back in Algebra.• Show less2 answers - ExpressMoney11 askedA ladder, 40 feet long, may be so planted, that it shall reach a window 33 feet from the ground on o... Show more A ladder, 40 feet long, may be so planted, that it shall reach a window 33 feet from the ground on one side of the street; and, by only turning it over, with?out moving the foot out of its place, it will do thesame by a window 21 feet high on the other side: what is the breadth of the street? For some reason, its not ringing a bell to me on how to go about this problem as to how to set this up. if somebody gets me going on this I could probably solve it from there with plugging everything in.• Show less5 answers - Lecter asked4 answers - Lecter asked3 answers - Lecter asked4 answers - Lecter asked3 answers - Lecter asked4 answers - ZBgord asked4 answers
http://www.chegg.com/homework-help/questions-and-answers/trigonometry-archive-2013-march-27
CC-MAIN-2015-22
refinedweb
360
75.1
Again, if you haven’t already done so I suggest reading through Part 1 and Part 2 of the series. I’ll do a quick TL; DR; recap, but it may not do it justice. What feels like ages ago, I started on a journey to implement a clone of Microsoft’s C++ Unit Test Framework Test Adapter, but fix some issues I had with it. These included a better reporting mechanism for standard C++ exceptions, and better error messages when libraries were failing to load. Typically this was due to missing dependencies. Part 1 of the series explained Microsoft’s technique to for exposing a dynamic set of classes and functions, for the test framework to call. This is typically solved with reflection, but given that there is no standard mechanism for reflection in C++, some neat tricks in the binary sections were played. Part 2 explores the second step, after discovery — execution. How can we take the metadata information, and actually have it run some code? It’s essentially a plugin system, in a plugin system. Part 2 left off where we were able to actually execute our test methods, but when an Assertion would fail the entire framework would collapse on itself. I lift my head from my hands, wipe the tears from my eyes, and get real with the situation. I’ve started down this path of re-implementation, why stop now? Among the package that is shipped with Microsoft’s C++ Unit Test Framework, there is a file called Assert.h. This is the header that you’re to include, in order to make assertions in your tests. Asserting is a critical part of Unit Testing. The three portions of a unit test are essentially: - Setup - Act - Assert There’s fancy acronyms describing this (AAA), I prefer mine (SAA). In a general sense, in your test you will do these three things. You setup the test to have your code under test in the state it needs to be. You run the code you want to test. Then you Assert that what was supposed to happen happened, and potentially Assert that other things that weren’t supposed to happen, didn’t. Though this becomes a slippery slope into a rabbit hole. That being said, asserting is a very important part of unit testing, arguably the most important part. So we’ve hit a bit of a conundrum, because negative assertions are the part that tell us when our code isn’t working correctly. Anyone who is experienced with TDD will tell you there is more value in the red lights than the green ones. That means it’s a problem when our framework crashes and burns on a failed Assert. So, to follow suit with re-implementation. I decided that I would just do away with Microsoft’s Assert library, in favour of my own. Obviously this is the best idea possible. Don’t get me wrong, it’s not like I didn’t try to figure out what was happening with their Assert library. The problem is there is less “public” information in it. Meaning that unlike the CppUnitTest.h file where a lot of the work was in the header because it was template code, most of the assertion code, lived in a compiled binary. The only code in the Assert.h file was template code for comparing generic types. It means I had no real way to figure out what they were doing. All I knew is that whatever they were doing, was crashing my application, and it worked for theirs. So I’ll make one that works with my framework. Now, you might be thinking. Of what value is re-implementing the Microsoft C++ Unit Test Framework? Is there any actual value in now re-implementing part of their library. The answer is probably not, but if you’re curious like me, you like to figure out how things work. The way I do this, is I look at something and implement it myself. If I can do that, I typically run into the problems that the original author ran into, and then I can understand why they solved the problem the way they did. I’ve approached software development this way for my entire professional career, and I’d like to think it has paid dividends. In all honesty, how hard could writing an assertion library be? Like, basically you only check a few different things. Are these two things equal? Are these two things not equal? Is this thing null? Is this thing not null? If the test passes, don’t do anything. If the test fails, stop executing and barf out some kind of message. If we ponder this for a moment, can we think of something we could use to halt execution and spit out some form of a message? I know! I’ve written this code a lot. if ( !some_condition ) throw condition_violated_exception("Violated Condition"); Well, exceptions look like a good place to start for our assertion library. So that’s where we’re going to start. The plan is essentially to have a bunch of Assert calls, that when they fail will throw an exception. Easy right? The code could look something like this. // MyAssert.h #include <AssertViolatedException.h> namespace MyAssert { template <typename T> static void AreEqual(const T& expected, const T& actual) { if( expected != actual ) throw AssertViolatedException(fmt::format("{0} != {1}", expected, actual)); } }; By no means is this complete, it’s really just to illustrate the point that when we have two objects that aren’t equal we generate an exception with an appropriate message. God it feels good to be a gangster. Now we can go about our mission, we’ll just use MyAssert.h, and completely disregard Microsoft’s version Assert.h. Given that we’ve implemented so that any escaped standard C++ exception will end up in the framework’s handler. I can guarantee that the assertions will end up there. Right? Given that I didn’t show a snip of AssertViolatedException.h, you can assume that it’s derived from std::exception. If you’re interested in how I actually implemented it, you can find the file here. It has a little bit more complexity, for capturing line information, but largely it’s the same idea. I’m sure this is EXACTLY how Microsoft would’ve done it. After we’ve implemented this, we can use it in the same way that you would if you were to use the Assert library included in Microsoft’s framework. #include <MyAssert.h> #include "calculator.h" TEST_CLASS(TestCalculator) { public: TEST_METHOD(TestAdd) { calculator c; int val = c.add(2, 2); MyAssert::AreEqual(4, val); } }; This is great, and it works, for the most part. It works for this case. Can you see where it falls down? If we recall, we’re using a standard C++ exception for our assertion. Unfortunately, the compiler doesn’t care whether or not the exception begins from our MyAssert class or any other place in the application. This means, that any handler prepared to handle a std::exception, will catch our assertion. Consider this code. #include <functional> class calculator { std::function<int(int, int)> on_add_; public: template <typename AddFnT> void on_add(const AddFnT &on_add) { on_add_ = on_add; } int add(int a, int b) { try { return on_add_(a, b); } catch(const std::exception &e) { return 4; } } }; #include <MyAssert.h> #include "calculator.h" TEST_CLASS(TestCalculator) { public: TEST_METHOD(TestAdd) { calculator c; c.on_add([](int a, int b) { MyAssert::AreEqual(2, a); MyAssert::AreEqual(2, b); return a + b; }); int val = c.add(2, 22); // see the error here? Tyop. MyAssert::AreEqual(4, val); } }; This isn’t by any means good code, nor does it really make sense. Everyone knows developers are notorious for cutting corners to save time, and someone decided 4 was a good error code, and someone made a typo in the test. The unfortunate thing about this, is that it passes. The light is green, but the code is wrong. Now, you’re saying “no one would ever do this in their right mind.” Consider the case where you have a layer between your business logic, and your database. You call the business logic function, it does some work and it passes the values to the store function. A way to test to make sure you’re populating the DB with the right values, is to abstract the database layer and intercept at that level. You also, likely want some error handling there as well. If an exception was to throw from the database. So there you go, at this point our Assert library falls down, hard. It’s been a long read, and you may feel like you’re getting ripped off at this point, because I haven’t really explained much. Realistically, we actually just learned a whole lot. So I encourage you to keep reading. Microsoft has an Assert library that you can use to make assertions about your program. The generally accepted form of “assertions” within an application is an exception. Microsoft can’t use standard exceptions in their framework, because it could interact with the application under test. I just proved that, by trying it. So what the hell did they do? Well the application crashes, that means something is happening. Most modern day programmers are familiar with exceptions, most people just see them as the defacto standard for error handling. (I really want to get into talking about return values vs. exceptions for error handling, but that will take me down a rabbit hole.) To keep it short, exceptions in various languages allow for your normal program flow to be separated (for the most part) from your exceptional program flow. Wikipedia, defines exceptions as “anomalous or exceptional conditions requiring special processing”. If you’re familiar exceptions and handling them, you’ve probably seen try/catch before. If you’re familiar with modern C++, you probably at least know of this concept. What you might not know, is that the C++ standard only define what an exception is, not how it is implemented. This means that the behaviour of exceptions and handling them in C++ is standardized, but the way that compiler vendors implement them is free game. Another thing people might not know is languages like C and older languages, don’t have a concept of exceptions. An exception can come from a custom piece of code, like one above where we throw the exception OR from somewhere deeper down maybe it’s a hardware exception like divide by zero, or out of memory exception. The end result in C++ is the same. Hence why it’s called a “standard” exception. The algorithm is pretty simple. Find an appropriate handler, and unwind the stack until that handler, call the handler. You ever wonder how though? Well, low level errors like divide by zero, will come from the hardware, generally in the form of an interrupt. So how do we go from a hardware level interrupt to our C++ runtime? On Windows, this is called Structured Exception Handling (SEH). It is Windows concept of exceptions, within the OS itself. There’s a good explanation of this in the book Windows Internals – Part 1 by Mark Russinovich. At a high level, the kernel will trap the exception, if it can’t deal with it itself, it passes it on to user code. The user code, can then either A) deal with the exception and report back stating that, or B) tell the kernel to continue the search. Because this is at the OS level, this is not a language specific thing. So runtimes built on Windows, will use this to implement exceptions within the language. This means that MSVC uses SEH to implement C++ exceptions within the C++ runtime. Essentially the runtime generates a Structured Exception Handler for each frame, and within this the runtime can search for the appropriate handler in the C++, unwind the stack and call the destructor of the objects, then resume execution in the handler. Obviously, these generated Structured Exceptions are well known for the C++ runtime, so it can know how to appropriately deal with the exception. What if Microsoft was using a Structured Exception for their assertion? The behaviour lines up with that hypothesis, in that something is generated on failed assertion that crashes the application. In SEH, if there isn’t an appropriate handler found the application will be terminated. How can we prove that? Well it turns out it was easy. Though it’s not recommended. Microsoft recommends if you’re using exceptions in C++ you use standard exceptions, but there is Windows API that you can use in your code to do SEH. #include "Assert.h" TEST_METHOD(AssertFail) { __try { Assert::AreEqual(0,1); } __except(EXCEPTION_EXECUTE_HANDLER) { Logger::WriteLine(L"Gotcha!"); } } After we compile and run this code it’s pretty obvious what’s going on. When the Assert::AreEqual fails, we land smack dab in the handler. So I guess that mystery is solved. We just need to figure out how and where to do the exception handling. Now, the __try/__except/__finally APIs are built into C++ on Windows, and allow us to basically install a frame based exception handler. They work very similar to the way you would expect a try/catch to work. After some research I decided this wasn’t exactly what I wanted. I wanted to be able to catch an exception regardless of stack frame. I stumbled upon Vectored Exception Handling. This is an extension to SEH, that allows you to install a handler that gets called regardless of where you are. So you can globally register The solution then is rather straight-forward. We just need to register an Exception Handler, when the exception throws we can catch it, record the error and continue on our way. If you read the code in the repository, I had to go through a bunch of layers of indirection to actually get the message to pass to the Test Window Framework. That’s because the architecture of the application has a .NET component, a .NET/CLI component and a pure native component. So for sake of simplicity the way that I went about handling the exception was like this, but not exactly this. LONG TestModule::OnException(_EXCEPTION_POINTERS *exceptionInfo) { // if the code is the MS Unit test exception if (exceptionInfo->ExceptionRecord->ExceptionCode == 0xe3530001) { NotifyFailure(reinterpret_cast<const wchar_t*>(exceptionInfo->ExceptionRecord->ExceptionInformation[0])); return EXCEPTION_CONTINUE_EXECUTION; } else return EXCEPTION_CONTINUE_SEARCH; } auto h = ::AddVectoredExceptionHandler(1, &OnException); This is where I had to do a bit of guess work. If you recall, this handler will get called for all exceptions. But we only want to do something when it’s an Assert exception. So I had to make the assumption that Assert threw an exception with the code 0xe3530001. Then I did a bit of sleuthing in the memory, to see that a pointer to the message was stored in the first index of the ExceptionRecord ExceptionInformation. With that I could grab the message and fail appropriately. That being said, I’m not sure if this solution lines up 100% with Microsoft’s functionalities. To summarize this long journey, I set out to set some things right with the behaviour of Microsoft’s CPP Unit Test Framework. It started out as something fun to investigate and it turned out to be a great learning experience. Out of all the projects that I’ve worked on, I’ve probably learned the most about ingenuity from this one. There are a lot of neat tricks, cool uses of obscure APIs, and really just overall an interesting view of how Microsoft engineers their tools. You might be wondering to yourself if it was actually worth it. For me, it was about learning, it was about facing the challenges and working to understand them. It wasn’t every really truly about replacing what ships with Visual Studio. So yes, it was worth it. Though I would love it if Microsoft could fix the issues… If I can do it, they most certainly can do it. Recapping the issues that I ended up solving: - Report a better error on standard exceptions [check] - Report a better error for binaries that fail to load - Support Test Names with Spaces [check] As you can see, I only solved 2 of the 3 things I set out to solve! The last one is kind of a cop out, because I sort of just lucked into it. When I was messing around with the class attributes, I enhanced my framework to understand a special attribute, to be able to change the test name. Other than just getting it from the method name. So you could specify a test name with a space. Reporting a better error when binaries fail to load — this is really hard. What makes it hard, is that there isn’t (that I can find) a good API to report the missing dependency. This is something you need to hand roll. Now, there are tools that do it. Specifically Dependency Walker. But, my understanding is that I would need to roll my own dependency walking algorithm. This unfortunately will be a story for another day. I really hope you enjoyed reading this series. I had quite a bit of fun working on this project, and a lot of fun writing about it. “What we call the beginning is often the end. And to make an end is to make a beginning. The end is where we start from.” — T.S. Elliot Happy Coding! PL References: MSDN on Structured Exception Handling One thought on “The one where we reverse engineered Microsoft’s C++ Unit Test Framework (Part 3) – Exceptions” great series, entertaining and informative thanks man
https://unparalleledadventure.com/2019/02/05/the-one-where-we-reverse-engineered-microsofts-c-unit-test-framework-part-3-exceptions/
CC-MAIN-2021-43
refinedweb
2,967
65.32
10 Commandments of Object-Oriented Design Thou shalt not write duplicate code! Check out these rules to keep your code nice and clean in order to prevent unsightly errors. Join the DZone community and get the full member experience.Join For Free no, this isn’t the word of god. it isn’t the word of jon skeet/martin fowler/jeff atwood/joel spolsky (replace it with your favorite technologist) either. we were reviewing some code and started discussing why we cut corners and don’t follow common sense principles. even though everyone has their own nuggets of wisdom regarding how classes should be structured based on the functional context but there are still some fundamental principles which one could keep in mind while designing classes. i. follow the single responsibility principle every class should have one and only one axis of change. it is not only true for classes but methods as well. haven’t you seen those long-winded-all-encompassing gobbledygook classes or methods which when spread out on a piece of paper turn out to be half the length of the great wall of china? well, the idea is not to do that. the idea is that every class or a method has one reason to exist. if the class is called loan then it shouldn’t handle bank account related details. if the method is called getloandetails then it should be responsible for getting loan details only! ii. follow the open closed principle it enables you to think about how would your system adapt to the future changes. it states that a system should allow the new functionality to be added with minimal changes to the existing code. thus, the design should be open for extension, but closed for modification. in our case, the developer had done something like this: public class personalloan { public void terminate() { //execute termination related rules here and terminate a personal loan } } public class autoloan { public void terminate() { //execute termination related rules here and terminate a personal loan } } public class loanprocessor { public void processearlytermination(object loan) { if ( loan is personalloan ) { //personal loan processing } else if (loan is autoloan) { //auto loan processing } } } the problem with loanprocessor is that it would have to change the moment there is a new type of loan, for example, homeloan. the preferable to structure this would have been: public abstract class loan { public abstract void terminate(); } public class personalloan: loan { public override void terminate() { //execute termination related rules here and terminate a personal loan } } public class autoloan: loan { public override void terminate() { //execute termination related rules here and terminate a personal loan } } public class loanprocessor { public void processearlytermination(loan loan) { loan.terminate(); } } this way, the loanprocessor would be unaffected if a new type of loan was added. iii. try to use composition over inheritance if not followed properly, this could lead to brittle class hierarchies. the principle is really straightforward and one needs to ask — if i was to look at the child class, would i able to say “child is a type of parent?” or, would it sound more like “child is somewhat a type of parent?” always use inheritance for the first one, as it would enable to use the child wherever parent was expected. this would also enable you to honor yet another design principle called the liskov substitution principle . and use composition whenever you want to partially use the functionality of a class. iv. encapsulate data and behavior most of the developers only do data encapsulation and forget to encapsulate the code that varies based on the context. it’s not only important to hide the private data of your class, but create well-encapsulated methods that act on the private data. v. follow loose coupling among classes this goes hand-in-hand with encapsulating the right behavior. one could only create loosely coupled classes if the behavior was well encapsulated within classes. one could achieve loose coupling by relying on abstractions rather than implementations. vi. make your classes highly cohesive it shouldn’t be that the data and behavior are spread out among various classes. one should strive to make classes that don’t leak/break their implementation details to other classes. it means not allowing the classes to have code, which extends beyond its purpose of existence. of course, there are design paradigms like cqrs which would want you to segregate certain types of behavior in different classes but they are only used for distributed systems. vii. code to interfaces than implementations this promotes loose coupling and enables one to change the underlying implementations or introduce new ones without impacting the classes using them. viii. stay dry (don’t repeat yourself) yet another design principle that states not to repeat the same code at two different places. thus, a specific functionality or algorithm should be implemented at one place and one place only. it leads to maintenance issues if the implementation is duplicated. the reverse of this is called wet – write everything twice ix. principle of least knowledge i.e. law of demeter. this states that an object shouldn’t know the internal details of the objects it collaborates with. it is famously called — talk to friends and not friends of friends. a class should only be able to invoke public data members of the class it is collaborating with. it shouldn’t be allowed to access behavior or data for the classes that are composed by those data members. it leads to tight coupling if not followed properly, thus creating systems which are harder to change. x. follow the hollywood principle: don’t call us, we'll call you this enables to break the mold of conditional flow logic and allowing code to be executed based on events. this is either done via event callbacks or injecting the implementations of an interface. dependency injection , inversion of control , or observer design pattern are all good examples of this principle. this principle promotes loose coupling among classes and makes the implementation very maintainable. Published at DZone with permission of Martin Streve. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/ten-commandments-of-object-oriented-design
CC-MAIN-2021-31
refinedweb
1,022
52.8
Decomposing My .Net API (Part I) “I know what I have done, but I don’t know why I should do it!” If you ever have this feeling while trying to build a webapi using ASP.NET Core, read along and you may find your answer. Disclaimer: this is not a course on building a webapi, I only aim to answer questions like “Why should I use this in my code?” or “What is it inside my code?” What’s in the boilerplate? Make sure you are using .NET Core version 3, otherwise the convention may be different. Download .NET (Linux, macOS, and Windows) NET is free. There are no fees or licensing costs, including for commercial use. .NET is open-source and… dotnet.microsoft.com ASP.NET Core can generate over two dozens of templates, the one that I’m using is webapi. $ dotnet new webapi -n my-api .NET will auto-generate a template, and in our target directory, first off, obj is a folder you don’t need to worry about for this walk-through. Find yourself an editor, and open this folder with it. Out of the bag, there are several files, now let’s explain them one by one: Program.cs This is the main file, it’s official name is a Generic Host. Specifically for the webapi, the Main(string[] args) calls the function CreateHostBuilder(string[] args) to build the application main thread(Host). CreateHostBuilder(string[] args) may look weird because it uses a lambda expression which omits a few default settings, here is what it does, in full: There are several configurations in this function: - Line 9, 10 references to our appsettings.jsonand appsettings.Development.jsonfiles. - Line 13 add environmental variables, for example, we can setthe environment into Productionor Developmentin the command line. - Line 15–18 specifies that we can use the command line argument to pass in some settings. - Line 20–24 uses a web-specific builder to introduce ChainedConfigurationProviderwhich is the IConfiguration Configurationin Startup.cs Startup.cs This class contains a IConfiguration Configuration property. The constructor will pass in the default configuration in Program.cs while it calls webBuilder.UseStartup<Startup>() . Additionally, you can add configurations inside this class based on your own project development. ConfigureServices allows you to add services (reusable components) to your configuration, so you can use those functions across your application. Configure gives you the ability to add components to your application pipeline. By pipeline, it means data will be processed at each component then pass on to the next one, hence the order is necessary. appsettings.json JSON files in the directory are used to store key-value pairs, which contains configuration strings (for example, secret code to encrypt JWT). This file can be configured to cater to different environments. *.csproj This is a project file, it will be used by the Microsoft Build Engine to build your project. This file contains information needed for the MSBE, NuGet packet manager will put packet references inside this file. launchSettings.json This is a development environment only file. In this file, you can set the webserver you want to use, localhost connection strings, and other profiles to be used in a development setting. WeatherForecast related files They are sample files for the webapi. WeatherForecast.cs is called a model and WeatherForecastController.cs is called a controller. For this webapi, only models and controllers will be implemented, the view (data presentation) will be handled by a client application(be it a react/angular single page application). Design for this API happyren/CollectionApp Getting a full collection of things is satisfying, but it could be tedious in the progress. This platform aims to help… github.com Now into this API, it handles two parts of a broader sense of MVC architecture, the models and the controllers. In this implementation, these two parts are further split into four different concepts: model, repository, controller, data transmission object. - The database is where you store the data. - To use the database, you will need to map your models/entities to the database using a Data Context. (User model to the User table in DB) - At this stage, you can use data context to persist data into the database, however, code will be repetitive and complicate for certain operations. Repository pattern is therefore used to encapsulate operations on persistent data. - Models are the data objects you designed for your application. - Data Transfer Objects (DTOs) define how the data will be sent over the network. - Controllers decide what to send back to users when they make requests. Knowing what the design is, I’ll first show you the core folders and files for the design in this part. Then in the next part, I’ll stitch them together with various functionalities. Models folder Models are essentially responsible for forming your data, it defines what are the attributes relevant to the conceptual object you are modeling. CollectionGundam.cs This model is an entity, which has a physical meaning to be specific. This means it has to have a unique key to make it distinguishable. That’s where the public int Id { get; set; } comes into play. With the help of the Entity-Framework, this Id will be converted into a sequential id inside the database with it will be automatically incremented. The rest of the data fields are the attributes needed to describe a Gundam Model object, different attributes can be declared and defined for your specific model. Like.cs This is a data entity, but unlike the CollectionGundam, it represents a virtual relationship. A CollectionGundam can be liked by many User , meanwhile, a User can like many CollectionGundam . So in this many-to-many relationship, Like works as a lookup table. It doesn’t need a unique identifier, but rather, it can be uniquely identified by its Liker and Likee . This is why this Like doesn’t have an Id . Data folder The data folder contains repositories for accessing the database. They are a layer of abstraction between the web application and the database. They describe how data will be retrieved from and put into the database. DataContext.cs This is the main component to control the interaction between the application and the database. DbSet<Entity> corresponding to different tables(entities) in your database. There is a line of code that might be confusing: When you set up this DbContext, a database should be provided to the constructor, or as per official documentation, a DbContextOptions will be provided and configured externally. The configuration is done in the Startup.cs where the program is informed to use SQLite and read the connection string from appsettings.json . To set up a table inside the database, DbSet<TEntity> is instantiated with the model of your choice as the TEntity and the name of the table as the property name . CollectorRepository.cs and ICollectorRepository.cs Repositories are in charge of operations on corresponding tables in a data persistence layer. By declaring the operations inside an interface, we can implement data persistence using different technologies (be it a database, or XML). We first instantiate the DataContext as a readonly attribute for the repository, it will be the handler for our query to the database. For actions that do not retrieve data from the database, there’s no need for an async method. On the other hand, for those who do, you need to make them async so that they can wait for the data to be sent back. Specifically in this case, when a method is to retrieve the data for a specific user, it should be a Task which on completion, returns an object of User class. This is called the Task-based Asynchronous Pattern. Task<User>is a Task<TResult>class, aka a task with a return value of the type TResult. It executes on a separate thread other than the program main thread, and upon completion, returns an object of TResult. In this method, this.context.Users locates the Users table inside the database, then .FirstOrDefaultAsync(u => u.Id == id) will find the first user whose Id property has the same value as the id parameter we passed in. .Include(p => p.photos) joins the Users table and the UserPhotos table then includes photos that belong to this specific user. Of course, we have to await for this operation to fully transfer the data. Then we store the data inside a user variable and return it as an User object. DTOs folder Data Transfer Object is in charge of moving data between different layers. It takes whatever data(properties) you have, and map into the class you specified. There are various reasons for this design pattern. In this project, we want to: - Remove circular reference (User refer to Photo which then refers to User) - Hide particular properties that clients are not supposed to view (User has password data which should not be sent back to other users) DTOs are easy to set up as well, you only need to have the properties to be transferred (with getter and setter) inside that particular DTO. For example, when users are logging in, they usually type in their username and password. Then you will need a DTO which contains only username and password as properties. However, you will need a mapper to map a DTO object from (or to) a model object. Controllers Folder Controllers handle client requests and send back data correspondingly. As per MS Documentation, whenever you type in an URL inside your browser, it corresponds to a controller action. To further extend this idea, your interaction with the app which sends back request to the server will trigger controller actions. Be it a GET request to load a page, a POST request to submit a form, a DELETE request to remove a photo or comment. UsersController.cs This controller handles requests that access the endpoint */api/users . For every controller, you need to specify [Route("api/[controller]")] , [ApiController] , and public class {Name}Controller : ControllerBase . They indicate the current class is an API controller with the route of api/{Name}(lowercase) . The ICollectorRepository and ICollectionGundamRepository are two of the major data resource for this particular controller, therefore they need to be injected. IMapper maps a DTO object to a model object, and we will further discuss the implementation logic. As for a specific controller action, you will need an endpoint with an accepted access method assigned to it. [HttpGet("{id}") means that only GET method can trigger this action on endpoint api/users/{id} . It’s an async function, because upon completing the Task , this action can then return the expected object as an HTTP response. So far, we’ve discussed the essential parts of this webapi. In the next part, I’ll stitch them together with functionalities, and further explain how things are working in Startup.cs and what are those helper classes about?
https://medium.com/@kaixiang.dev/decomposing-my-net-api-part-i-92e30e804e0f?source=post_internal_links---------0----------------------------
CC-MAIN-2022-33
refinedweb
1,816
55.54
In the Box is Sean Campbell's article series on how to write code to get the most out of Windows. Current article list: - Setting Wallpaper The application allows you to browse to an image, view a preview, select the display style, and set the image as the Desktop background. - Poor Man's Power Monitor I wanted an application that made it really easy to know how much power you were using, and specifically where that power was going - Researching made easier with ResearchHelp I like productivity at my fingertips, so for this post, I'm going to walk through a tool that I've created to save time for online researching. This tool can be made to launch by simply using a shortcut key while you're in any application. - Building Network Utilities In this, the first In The Box article, Sean Campbell digs into the new System.Net.NetworkInformation namespace, and builds a simple utility that will look for devices on the network.
http://channel9.msdn.com/Forums/TechOff/75638-Discuss-the-Coding4Fun-In-the-Box-article-series/75638
CC-MAIN-2014-52
refinedweb
165
53.24
This post is a summary of the best python libraries for GraphQL. Python in recent years is starting to be on the list of top programming language. GraphQL is emerging but very promising query language and execution engine tied to any backend service. Python is one of the most popular languages used in data science, machine learning and AI systems. GraphQL was introduced by Facebook as an alternative to REST and it’s popular of flexibility on handling complex systems. Ariadne is a Python library for implementing GraphQL servers using schema-first approach. Ariadne is a Python library for implementing GraphQL servers. Features: pip install ariadne The following example creates an API defining Person type and single query field people returning a list of two persons. It also starts a local dev server with GraphQL Playground available on the address. Start by installing uvicorn, an ASGI server we will use to serve the API: Start by installing uvicorn, an ASGI server we will use to serve the API: pip install uvicorn Then create an example.py file for your example application: from ariadne import ObjectType, QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL # Define types using Schema Definition Language () # Wrapping string in gql function provides validation and better error traceback type_defs = gql(""" type Query { people: [Person!]! } type Person { firstName: String lastName: String age: Int fullName: String } """) # Map resolver functions to Query fields using QueryType query = QueryType() # Resolvers are simple python functions @query.field("people") def resolve_people(*_): return [ {"firstName": "John", "lastName": "Doe", "age": 21}, {"firstName": "Bob", "lastName": "Boberson", "age": 24}, ] # Map resolver functions to custom type fields using ObjectType person = ObjectType("Person") @person.field("fullName") def resolve_person_fullname(person, *_): return "%s %s" % (person["firstName"], person["lastName"]) # Create executable GraphQL schema schema = make_executable_schema(type_defs, [query, person]) # Create an ASGI app using the schema, running in debug mode app = GraphQL(schema, debug=True) Strawberry is a new GraphQL library for Python 3, inspired by dataclasses. An initial version of Strawberry has been released on GitHub. Strawberry was created by @patrick91 who is also an organizer of @pyconit. It was originally announced during Python Pizza Berlin. pip install strawberry-graphql Create a file called app.py with the following code: import strawberry @strawberry.type class User: name: str age: int @strawberry.type class Query: @strawberry.field def user(self, info) -> User: return User(name="Patrick", age=100) schema = strawberry.Schema(query=Query) This will create a GraphQL schema defining a User type and a single query field user that will return a hard-coded user. To run the debug server run the following command: strawberry run server app Open the debug server by clicking on the following link: This will open a GraphQL playground where you can test the API. Graphene is a Python library for building GraphQL schemas/types fast and easily. Graphene has multiple integrations with different frameworks: Also, Graphene is fully compatible with the GraphQL spec, working seamlessly with all GraphQL clients, such as Relay, Apollo and gql. For instaling graphene, just run this command in your shell pip install "graphene>=2.0"!
https://blog.graphqleditor.com/top-3-python-libraries-for-graphql/
CC-MAIN-2020-29
refinedweb
513
54.02
An abstract class implementing procedure to read STL file. More... #include <RWStl_Reader.hxx> An abstract class implementing procedure to read STL file. This class is not bound to particular data structure and can be used to read the file directly into arbitrary data model. To use it, create descendant class and implement methods addNode() and addTriangle(). Call method Read() to read the file. In the process of reading, the tool will call methods addNode() and addTriangle() to fill the mesh data structure. The nodes with equal coordinates are merged automatically on the fly. Default constructor. Callback function to be implemented in descendant. Should create new node with specified coordinates in the target model, and return its ID as integer. Callback function to be implemented in descendant. Should create new triangle built on specified nodes in the target model. Guess whether the stream is an Ascii STL file, by analysis of the first bytes (~200). If the stream does not support seekg() then the parameter isSeekgAvailable should be passed as 'false', in this case the function attempts to put back the read symbols to the stream which thus must support ungetc(). Returns true if the stream seems to contain Ascii STL. Return merge tolerance; M_PI/2 by default - all nodes are merged regardless angle between triangles. Return linear merge tolerance; 0.0 by default (only 3D points with exactly matching coordinates are merged). Reads data from STL file (either binary or Ascii). This function supports reading multi-domain STL files formed by concatenation of several "plain" files. The mesh nodes are not merged between domains. Unicode paths can be given in UTF-8 encoding. Format is recognized automatically by analysis of the file header. Returns true if success, false on error or user break. Reads data from the stream assumed to contain Ascii STL data. The stream can be opened either in binary or in Ascii mode. Reading stops at the position specified by theUntilPos, or end of file is reached, or when keyword "endsolid" is found. Empty lines are not supported and will read to reading failure. If theUntilPos is non-zero, reads not more than until that position. Returns true if success, false on error or user break. Reads STL data from binary stream. The stream must be opened in binary mode. Stops after reading the number of triangles recorded in the file header. Returns true if success, false on error or user break. Set merge angle in radians. Specify something like M_PI/4 (45 degrees) to avoid merge nodes between triangles at sharp corners. Set linear merge tolerance.
https://dev.opencascade.org/doc/refman/html/class_r_w_stl___reader.html
CC-MAIN-2022-27
refinedweb
430
67.96
I was in a code review earlier this week and someone pointed out the InterlockedOr, unlike the other InterlockedXxx operations, does not return the previous value. I found that hard to believe. I pulled up the MSDN docs and pointed this out Return Value InterlockedOr returns the original value stored in the variable pointed to by Destination. So, we set out to find out which one of us was right. It turns out that both of us are right, it just depends on how you call InterlockedOr! We created the following test application to see what was happening #include <windows.h> #include <stdio.h> extern “C” LONG _InterlockedOr ( IN OUT LONG volatile *Target, IN LONG Set ); #pragma intrinsic(_InterlockedOr) int _cdecl main(int argc, char *argv[]) { LONG old, cur = 0xF; old = _InterlockedOr(&cur, 0xF0); _InterlockedOr(&cur, 0xF0); return 0; } And then looked at the assembly that was generated > 16: old = _InterlockedOr(&cur, 0xF0); 0:000> u test!main+0x10 [d:\work\size\main.cpp @ 16]: 00e611d0 b9f0000000 mov ecx,0F0h 00e611d5 8d55f8 lea edx,[ebp-8] 00e611d8 8b02 mov eax,dword ptr [edx] 00e611da 8bf0 mov esi,eax 00e611dc 0bf1 or esi,ecx 00e611de f00fb132 lock cmpxchg dword ptr [edx],esi 00e611e2 75f6 jne test!main+0x1a (00e611da) 00e611e4 8945fc mov dword ptr [ebp-4],eax 0:000> p > 17: _InterlockedOr(&cur, 0xF0); 0:000> u test!main+0x27 [d:\work\size\main.cpp @ 17]: 00e611e7 b9f0000000 mov ecx,0F0h 00e611ec 8d55f8 lea edx,[ebp-8] 00e611ef f0090a lock or dword ptr [edx],ecx Completely different code is generated if capture the return value vs ignoring it! Wow, I didn’t expect the compiler to do that. When you capture the return value, the InterlockedOr intrinsic generates the standard pattern used to generate an Interlocked operation that is not supported by hardware (capture the old value, interlock compare and exchange for the new value, repeat if the old value from compare and exchange is not the captured old value). When you ignore the return value, a lock or (which does not set eax to the previous value) generated without a loop. If you compare the two implementations, the first implementation (the loop) can be a lot slower than the second both in terms of actually looping and in terms of prediction misses since there is a branch which could be mispredicted. If this API in your hot path, this might be very good information to know and change your usage of it to squeeze a little more cycles out of it. After testing this out, InterlockedAnd also exhibits the same behavior and, going out on a limb, I would assume the other Interlocked intrinsic also generate code the same way depending on if the return value is captured or not. They do! I often have to use GCC and I’m trying to make the code as compatible/portable between compilers as possible, so we’ve had to build our own header with the intrinsics implemented in gcc’s own atomic language (which is based of Intel’s official specs). Unfortunately there’s no way to make them morphing like this, so the slower loop path must always be implemented. This was actually the subject of a cl 13.x compiler bug: Checking the return value of these functions was broken. Seems to be fixed in 14.x, but a lot of people still build with 3790.1830 or previous. There’s also this one 😉 *subtle nudge to d* Did you notice that the assembly code was incorrect? The WDK 6001 compiler still generates wrong code. And the error matches erroneous InterlockedOr_Inline, InterlockedAnd_Inline, InterlockedXor_Inline functions. The loop should return _before_ mov eax,[edx], otherwise, if [edx] changes before cmpxchg (causing the branch), the loop will never end. Such mistakes (as in *_Inline functions in WINBASE.H) are easily caught by a code review, which obviously was not done for such an important function. Note that InterlockedAnd64_Inline function was obviously written by a more experienced programmer. It’s cleaner and it’s _correct_! Even though InterlockedAnd64_Inline is correct, the code generated by x64 compiler for _InterlockedAnd64 is incorrect (same error). alegr, when you get a chance, you should take a look at the documentation for cmpxchg, which states (from the AMD manual): "If the two values are equal the instruction copies the value in the second operand to the first operand and sets the ZF flag in the rFLAGS register to 1. Otherwise, it copies the value in the first operand to the AL, AX, EAX, or RAX register and clears the ZF flag to 0." In particular, consider how the second sentence in the preceding paragraph applies to the code in question.
https://blogs.msdn.microsoft.com/doronh/2006/11/10/the-case-of-amazingly-morphing-intrinsic-function/
CC-MAIN-2016-30
refinedweb
782
59.33
NAME PRANG::Graph::Choice - accept multiple discrete node types SYNOPSIS See PRANG::Graph::Meta::Element source and PRANG::Graph::Node for examples and information. DESCRIPTION This graph node specifies that the XML graph at this point may be one of a list of text nodes or elements, depending on the type of entries in the choices property. If there is only one type of node allowed then the element does not have one of these objects in their graph. ATTRIBUTES - ArrayRef[PRANG::Graph::Node] choices This property provides the next portion of the XML Graph. Depending on the type of entry, it will accept and emit nodes of a particular type. Entries must be one of PRANG::Graph::Element, or PRANG::Graph::Text. - HashRef[Str|Moose::Meta::TypeConstraint] type_map This map is used for emitting. It maps from the localname of the XML node to the type which that localname is appropriate for. This map also needs to include the XML namespace, that it doesn't is currently a bug. - Str name_attr Used when emitting; avoid type-based selection and instead retrieve the name of the XML node from this attribute. - attrName Used when emitting; specifies the method to call to retrieve the item to be output. SEE ALSO PRANG::Graph::Meta::Class, PRANG::Graph::Meta::Element, PRANG::Graph::Context, PRANG::Graph::Node Lower order PRANG::Graph::Node types:.
https://metacpan.org/pod/PRANG::Graph::Choice
CC-MAIN-2016-30
refinedweb
229
63.29
ANTS Memory Profiler - 7.4 The Class List - ANTS Memory Profiler Use the Class List to identify classes which you do not expect to be in memory, or classes with unexpectedly high memory usage. Use filters to restrict your investigation to objects with specific characteristics or specific parts of the application. The class list shows detail of memory usage per class. On the summary or class list, look for classes with unexpectedly high memory usage, or a large increase in size between snapshots. When you enable filters or use the find box, the values in the list only include objects that match the selected criteria. If you are checking where most memory is used, it can be useful to start by looking at Live Size or Live Instances. Click on the column heading to sort the column, and look for classes with an unexpectedly large size or number of instances. Right-click on a class and select Show Instance Categorizer to see where instances of the class are being referenced. If you are looking for a memory leak, it can be useful to begin by looking for unexpected differences between two snapshots in the Size Diff or Instance Diff columns. Click on the column heading to sort the column, and then look for classes where the memory usage or instance count has increased significantly. Use the Comparing snapshots filters to focus your analysis, depending on the snapshots you are comparing: - If you are looking for objects which exist in both the baseline and the current snapshot, select Only surviving objects; - If you are looking for objects which were created between the two snapshots, select Only new objects. After selecting an appropriate filter: - If the class that looks interesting is one you recognize, right-click and select Show Instance List to look for instances of the class. - If the class that looks interesting is not one you recognize, right-click and select Show Instance Categorizer to find out where instances of the class are being referenced. If your application has more than one process, select the process from which you want to view the classes by using the Process: dropdown box. The Process: option is not displayed if your application only has one process. A process followed by an exclamation mark (!) after its name was not running when the current snapshot was taken (either because it had already finished, or because it had not yet started). Namespace and Class Name To find a specific namespace or class, type part of the name in the find box. This can be useful, for example, if you are checking back on a memory leak you have fixed. In many cases, we do not recommend starting your investigation by looking for specific classes; instead, start by looking at the size or instances columns. We recommend this approach because a lot of the code being executed by your application is likely to be part of the .NET framework libraries or other third-party libraries, so you are likely to see leaks in classes which are not your own, even where your code is the cause of the leak. Live Size and Live Instances The Live Size column shows the total size of instances of the class in the current snapshot. The Live Instances column shows the total number of instances of the selected class in the current snapshot. The values do not include instances of classes referenced by the selected class. These values can be good starting points for finding out where most memory is being used by your application. To investigate why a class has a large size or high number of instances, do one of the following: - look at instances of the class on the instance list - use the instance categorizer to investigate whether another class is keeping instances of your class in memory unexpectedly. Size Diff and Instance Diff When you compare two snapshots, the Size Diff and Instance Diff column show the differences between the baseline snapshot and the current snapshot. An unexpected increase in the size of a class or number of instances may indicate a memory leak. For example, if you perform an action where you expect new objects to be cleaned up between the snapshots (such as opening and closing a dialog box), you would not expect the class to increase in size or the number of instances to increase. In some cases, an increase in size or number of instances may not indicate a leak: - For an application that includes a text editor, the size of the text buffer would be expected to increase as the user adds more text to a document. In this case, the Size Diff column for the text buffer class shows an increase in size, but this is not an indication of a memory leak. - For an application with a text editor backed by a DOM, the number of nodes of a DOM would be expected to increase. In this case, the Instance Diff column for the DOM classes shows an increase, but this is not an indication of a memory leak. Note that the Instance Diff column has a specific purpose when either of the following filters is enabled: - From the current snapshot, show only survivors in growing classes. - From the current snapshot, show only zombie objects. See Basic filters for more details.
http://www.red-gate.com/supportcenter/Content/ANTS_Memory_Profiler/help/7.4/amp_2_class
CC-MAIN-2013-20
refinedweb
891
56.29
PingBack from Where do get clr-namespace:MediaFlow ? Nevermind my last question. It builds fine but I get this XAML error I am trying to figure out: Property ‘ItemsSource’ does not support values of type ‘Customers’. When you change the ProjectionPlane ( p3 ) values ( RotationY, etc. ) in the animation, why doesn’t it update the slider values since they are set to TwoWay binding? Will this be fixed in SL3 RTW? Thanks. Good session. The Virtual Earth Silverlight Map Control CTP is designed to work with Silverlight 2.  However, The Virtual Earth Silverlight Map Control CTP is designed to work with Silverlight 2.  However, In early May, I gave a talk about the new features in Silverlight 3. As I’ve started to gather material
https://blogs.msdn.microsoft.com/jstegman/2009/03/22/perspective-3d-sample/
CC-MAIN-2016-30
refinedweb
124
67.76
XML::Easy::Tranform - XML processing with a clean interface The XML::Easy::Transform:: namespace exists to contain modules that perform transformations on XML documents, or parts thereof, in the form of XML::Easy::Element and XML::Easy::Content nodes. XML::Easy is a collection of modules relating to the processing of XML data. It includes functions to parse and serialise the standard textual form of XML. When XML data is not in text form, XML::Easy processes it in an abstract syntax-neutral form, as a collection of linked Perl objects. This in-program data format shields XML users from the infelicities of XML syntax. Modules under the XML::Easy::Transform:: namespace operate on XML data in this abstract structured form, not on textual XML. A transformation on XML data should normally be presented in the form of a function, which takes an XML::Easy::Element node as its main parameter, and returns an XML::Easy::Element node (or dies on error). The input node and output node each represent the root element of the XML document (or fragment thereof) being transformed. These nodes, of course, contain subordinate nodes, according to the structure of the XML data. A reference to the top node is all that is required to effectively pass the whole document. CPAN distributions under this namespace are: Manages XML Namespaces by hoisting all namespace declarations to the root of a document. Andrew Main (Zefram) <zefram@fysh.org> This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~zefram/XML-Easy-0.009/lib/XML/Easy/Transform.pod
CC-MAIN-2013-20
refinedweb
260
52.8
Advertisement This site is very good. But take care of the pro This site is very good. But take care of the programs and their output coming on the screen. In the above program to print date no code is written. So please rectify it as early as you can. Thank you. today i am reading this page.in the above program today i am reading this page.in the above program your output does not match with your coding part,so as soon as possible rectify it. thanks This site is very nice and good for biginner of ja This site is very nice and good for biginner of java. The program of servlet for displaying date is not correct because it shows HelloWorld output Now, you can get the correct example with the corr Now, you can get the correct example with the correct code and description. Thanks for pointing out the error. Chandan Kumar Verma Roseindia Member the o/p of the program is incorrect...the object p the o/p of the program is incorrect...the object pw prints "hello world" and not the date...there are no methods which invoke the date from the system I think u have put the wrong program.It is same as I think u have put the wrong program.It is same as previous "Hello World" program. validation in servlet i want the validation of time and time and date 2)string tokinezer hi This site is very good for freshers to know about java .. Regarding Response..... Now i am a software Trainee....Your website is very easy to learn for the beginners...It contains each and every steps that we follow ......It is very nice.... About Java/J2EE Tutorial Its very good for those who are willing to learn the Java Technology. All the Concepts and the examples are very easy to learn and Understand. Now, I am learning the advance Java concepts through our site. thanks for roseindia. Good Example This is a good example ... servlets this is amazing website and is very helpful for us to learn more n more. what about the .html file..?? this program is not running wen i am using it thru netbeans... what about the .html file..??? servlet I want disply only Date servlet prog prob i think ..url pattern must match with the class name....otherwise we have to use *.do.please rectify it,if it is so regarding output The output is not coming...some method is missing program error in the above program having some error in web.xml i.e <servlet-class>DateDisplay</servlet-class> ur wronglyu given the servlet class name instead of DateDisplay give DisplayingDate in the servlet-class value Wrong Name for class <servlet-class>DateDisplay</servlet-class> I think the name should be same public class DisplayingDate extends HttpServ
http://roseindia.net/tutorialhelp/allcomments/3124
CC-MAIN-2016-07
refinedweb
476
76.11
Anyone working with lists of data will encounter a need to combine them in a useful way. Often the best result is a dictionary consisting of keys and values. In this article, you’ll learn how to create a dictionary from two NumPy arrays. Problem Formulation: Given two NumPy arrays a and b. Create a dictionary that assigns key a[i] to value b[i] for all i. Example: Given two NumPy arrays a = np.array([1, 42, 0]) b = np.array(['Alice', 'Bob', 'Liz']) Create a new dictionary programmatically that assigns the elements in a to the elements in b, element-wise: {1: 'Alice', 42: 'Bob', 0: 'Liz'} After providing you some background for the input NumPy array, you’ll learn multiple methods to accomplish this. Background: NumPy for the Array NumPy is a Python library useful for working with arrays. NumPy stands for ‘Numerical Python’. Python users can use standard lists as arrays, but NumPy works faster because the array items are stored in contiguous memory. This makes it more efficient to, for example, iterate through the array rather than having to scramble across the memory space to find the next item. If we have Python and PIP already installed on our systems, then the installation of NumPy is easy: Creating a NumPy array is as simple as importing the NumPy library and calling the array() function. NumPy is often imported under the np alias: import numpy as np planet = np.array(['Mercury', 'Venus', 'Earth', 'Mars']) orbitalPeriod = np.array([88.0, 224.7, 365.2, 687.0]) Unlike Python’s standard lists, which can hold different data types in a single list, NumPy’s arrays should be homogeneous, all the same data type. Otherwise we lose the mathematical efficiency built into a NumPy array. Method 1: Zip Them Up Having created two arrays, we can then use Python’s zip() function to merge them into a dictionary. The zip() module is in Python’s built-in namespace. If we use dir() to view __builtins__ we find zip() at the end of the list: >>>dir(__builtins__) ['ArithmeticError', 'AssertionError'...,'vars', 'zip'] The zip() function makes an iterator that merges items from each of the iterable arrays, just like the interlocking teeth of a zipper on a pair of jeans. In fact, the zip() function was named for a physical zipper. d = {} for A, B in zip(planet, orbitalPeriod): d[A] = B print(d) # {'Mercury': 88.0, 'Venus': 224.7, 'Earth': 365.2, 'Mars': 687.0} When using the zip() function, we are guaranteed that the elements will stay in the given left-to-right order. No need to worry that the elements in the arrays will be mixed as they are combined into the dictionary. Otherwise the dictionary would be useless, as the keys would not align properly with their values. Method 2: Arrays of Unequal Lengths In some cases, our arrays may be of unequal lengths, meaning that one array has more elements than the other. If so, then using the zip() function to merge them will result in the dictionary matching the shortest array’s length. Here’s an example of the brightest stars in the Pleiades cluster with their apparent magnitudes: stars = np.array(['Alcyone', 'Atlas', 'Electra', 'Maia', 'Merope', 'Taygeta', 'Pleione']) magnitude = np.array([2.86, 3.62, 3.70, 3.86, 4.17, 4.29]) cluster = {} for A, B in zip(stars, magnitude): cluster[A] = B print(cluster) # {'Alcyone': 2.86, 'Atlas': 3.62, 'Electra': 3.7, 'Maia': 3.86, 'Merope': 4.17, 'Taygeta': 4.29} As we can see, the ‘ stars‘ array contained the Seven Sisters, the seven brightest stars in the Pleiades cluster. The ‘ magnitude‘ array, however, only listed the top six values for apparent magnitude. When the zip() function merged the two arrays, the seventh star was dropped entirely. Depending on our needs, this may be acceptable. But if not, then we can use the zip_longest() function from the itertools module instead of the zip() function. With this function, any missing values will be replaced with the fillvalue argument. We can insert any value we want, and the default value will be None. Let’s create the cluster dictionary again: from itertools import zip_longest cluster = {} for A, B in zip_longest(stars, magnitude, fillvalue='?'): cluster[A] = B print(cluster) # {'Alcyone': 2.86, 'Atlas': 3.62, 'Electra': 3.7, 'Maia': 3.86, 'Merope': 4.17, 'Taygeta': 4.29, 'Pleione': '?'} This time all Seven Sisters are listed, and the last unknown magnitude value is marked with a question mark, perhaps to be filled in later. By combining NumPy’s memory-efficient arrays with the zip() or zip_longest() functions’ ease of use as an iterator, we can quickly and simply create dictionaries from two arrays with a minimum of fuss. References - [1] NumPy: - [2] PIP: - [3] Planetary Orbital Periods: - [4] zip() - [4] builtins: - [6] The Pleiades Cluster: - [7] zip_longest(): - [8] StackOverflow:
https://blog.finxter.com/how-to-create-a-dictionary-from-two-numpy-arrays/
CC-MAIN-2022-21
refinedweb
814
66.33
I need to do the following program, but it need to have a do while loop, scanner for input, and a console program. Here are the instructions:. If someone could code this program by 5/9/10 it would be great. Thanks!! Sure... do { read( "" ); while ( comprehension < 100% ); If someone could code this program by 5/9/10 it would be great. Thanks!! When was this assignment given to you? How come you haven't posted your attempt? You lazy and want someone else to do it? :P I made your code but it has a few bugs included, so you HAVE to work a-little, in it however it will point you in the right direction. I know what the bugs are and how to fix them but I can't be writing your entire code for you - that would be against the forum rules. One of the bugs will take input for the names but it will return an error if the name contains a space - you can fix that, and I didn't include a way to format the output - you can do that.. :D Enjoy your assignment import java.util.*; public class Balance { public static void main(String [] args) { int numberA; int numberB = 0; String name; int money; Scanner in = new Scanner(System.in); System.out.println("How many users are you entering?"); numberA = in.nextInt(); String [] names = new String[numberA]; // To hold names int [] bank = new int[numberA]; // To hold balance do{ System.out.println("Enter name: "); name = in.next(); names[numberB] = name; System.out.println("Enter balance: "); money = in.nextInt(); bank[numberB] = money; numberB++; } while(numberB < numberA); getHighLow(bank, names); } public static void getHighLow(int [] myArray, String [] theNames ) { int high = myArray[0]; String rich = theNames[0]; int low = myArray[0]; String poor = theNames[0]; for(int i = 0; i < myArray.length; i++) { if(high <= myArray[i]) { high = myArray[i]; rich = theNames[i]; } else { low = myArray[i]; poor = theNames[i]; } } System.out.println("Highest balance belongs to "+rich+" with £"+high); System.out.println("\nLowest balance belongs to "+poor+" with "+low); }
https://www.daniweb.com/programming/software-development/threads/282175/do-while-loop-help
CC-MAIN-2016-50
refinedweb
345
74.08
Cython project management like npm in nodejs Project description Cython project management like npm in nodejs. This project is inspired by npm in nodejs. Installation You can easily install by: pip install cython-npm What problems does it solve ? When using cython, we face the problem of compile cython file. We can do it easily by: import pyximport; pyximport.install() But that it is not recommended to let pyximport build code on end user side as it hooks into their import system. The best way to cater for end users is to provide pre-built binary packages. So this project compiles .pyx file and provides pre-built binary packages for easy of use. Quickstart: Basic use to Complie file or folder from cython_npm.cythoncompile import export export('examplefile.pyx') export('./examplefolder') # then import them to use import examplefile from examplefolder import * You should do this code once time only. Create install file like package.json You can also compile many files or folders at once time. Create a file name install.py in the root of your project/package and write the code below: from cython_npm.cythoncompile import install Manymodules = [ # put your modules list here 'examplefile.pyx', './examplefolder' ] install(Manymodules) Run the file before start your project python install.py Or add first line import install in startup file of your project. Use install or export in parent folder will compile all .pyx file in subdirectories. ### Using require(‘path’) as nodejs You can also relative or fullpath import in python by require function. For example: from cython_npm.cythoncompile import require # import .pyx file. Will cause error if it is not compiled by export() yet. # Default value of recompile is True, only apply for .py file. To import .pyx, change recompile=False examplefile = require('../parentpackage', recompile=False) # import cython package from parent folder examplefile.somefunction() # it also support relative import .py file examplefile = require('../parentpackage') examplefile.somefunction() Using requirepyx(‘path’): requirepyx is simillar to require except: * Use for cython file (‘.pyx’) only * Equivalent to export(‘.pyx file’) and require(‘.pyx file’) Example: from cython_npm.cythoncompile import export export('examplefile') require('examplefile',recompile=False) # The code above is the same as: from cython_npm.cythoncompile import requirepyx requirepyx('examplefile') Using typecheck Another utils is typecheck support to raise error in typing module (from python 3.3): from cython_npm.typecheck import typecheck @type_check def checkstr(s: Any)->(None, str): return None, s x,y = checkstr('tuan') print(x,y) try: checkstr(120) except Exception as error: print(error) traceback.print_exc() # That will raise an error of TypeError checkstr(200) Example: Cython vs speed test battle This example compare the speed between cython vs python, Swift, Go and Code differences in doing a short calculation. Cython_npm is used in the test. This test is forked from ‘marcinkliks’, the original code and test is here: Swift vs Go vs Python battle. Note: We use Swift and Go test results as pattern and do not retest them. Go to see in test folder in github for more examples Testing condition: * Python version: Python 3.6.3 :: Anaconda, Inc. - About computer: MacBook Pro (13-inch, 2016, Two Thunderbolt 3 ports), 2 GHz Intel Core i5, 256GB SSD Test process and results as shown below: Recall the speed of Swift: 0m0.416s, Go: 0m0.592s and Pypy: 0m2.633s Test pure python code: sum = 0 is same/similar to original test time python test_python.py 9999010000 real 0m12.825s user 0m11.721s sys 0m1.061s Test cython code: Create run.py with code: from cython_npm.cythoncompile import export export('test_cython.pyx') # will do once time import test_cython Code in test_cython.pyx: cdef long sum = 0 cdef int i cdef int e: time python run.py time python run.py 9999010000 real 0m5.803s user 0m4.496s sys 0m1.211s Test cython code with list optimization and cache: create similar run.py. Code in test_cythoncache.pyx: from functools import lru_cache @lru_cache(maxsize=128) def dotest(): cdef long mysum = 0 cdef int i cdef int e for e in range(30): mysum = 0 x = [i for i in range(1000000)] y = [x[i] + x[i+1] for i in range(1000000-1)] i = 0 for i in range(0, 1000000, 100): mysum += y[i] print(mysum) dotest() Speed test result: time python run.py 9999010000 real 0m3.373s user 0m2.360s sys 0m1.001s Test cython code with cache and C array: create similar run.py. Code in test_cythoncache.pyx: from functools import lru_cache @lru_cache(maxsize=128) def dotest(): cdef long mysum = 0 cdef int i cdef int e cdef int x[1000000] cdef int y[1000000] for e in range(30): mysum = 0 for i in range(1000000): x[i] = i # y = [] for i in range(1000000 - 1): y[i] = (x[i] + x[i+1]) i = 0 for i in range(0, 1000000, 100): mysum += y[i] print(mysum) dotest() Speed test result: time python run.py 9999010000 real 0m0.085s user 0m0.067s sys 0m0.015s Conclusions - With a slight change, Cython make pure python code faster by 2X time. But it is very slow compare to Swift and Go - Appling some optimal technical, Cython make python nearly 4X time faster than the original code. It may be the acceptable result. Pypy result seems very attractive too. - Using C array, Cython make the code become very fast. It consumes only 0.085s to complete as 4X time faster than Swift, 6X time faster than Go. It maybe the fastest but it is unusable in real life. - After all, i wish cython and cython_npm could give you more usefull options in coding Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/cython-npm/
CC-MAIN-2021-39
refinedweb
961
69.38
2019-08-13 19:05:39 8 Comments I'm trying to write a program that reverses a name. I'm using gets() to read the string, so it doesn't put the \n in the string. #include <stdio.h> #include <string.h> void reverse_name(char *name) { const char *p = name; char initial; while (*p == ' ') // skip preceding white-spaces p++; initial = *p++; // store letter of first name while (*p != ' ') // skip until first white-space p++; // between first and last name while (*p == ' ') // skip additional white-spaces p++; // p now points to the first letter of the last name strcpy(name, p); // copy last name to the beginning strcat(name, ", "); strcat(name, &initial); strcat(name, "."); } For example, when inputting Immanuel Kant it should output Kant, I.. It prints garbage between the I and the . though. What's going wrong? Related Questions Sponsored Content 85 Answered Questions [SOLVED] How do I make the first letter of a string uppercase in JavaScript? - 2009-06-22 08:25:31 - Robert Wills - 1887435 View - 3569 Score - 85 Answer - Tags: javascript string letter capitalize 4 Answered Questions [SOLVED] C - [Error] invalid conversion from 'char' to 'const char*' [-fpermissive] 9 Answered Questions [SOLVED] Difference between using character pointers and character arrays 1 Answered Questions [SOLVED] Parsing a file in C (Lines) 8 Answered Questions 4 Answered Questions [SOLVED] Pick up upperCase letters from string and print them - 2014-01-21 16:27:20 - Henry Lynx - 504 View - 0 Score - 4 Answer - Tags: javascript string @ForceBru 2019-08-13 19:11:29 strcat(name, &initial)tries to treat the data at &initialas a C string, which is NULL-terminated. It will continue copying data from this address until it finds the null byte. But &initialis a pointer to a byte on the stack, and there's no guarantee that *(&initial + 1) == 0, so it continues copying whatever data it finds on the stack into the string. As pointed out in the comments, strcopying a part of a string into another part of the same string is undefined behavior. The memmovefunction is safer in this regard. However, you should probably just allocate a new memory region and build the resulting string there instead. @chqrlie 2019-08-13 19:49:13 This is one of the problems, copying a string on itself has undefined behavior too. @chqrlie 2019-08-13 19:23:35 There are multiple major problems in your code: while (*p != ' ') p++;makes a bold assumption that the string contains at least one space after the first word. Calling reverse_namewith the credentials of "Superman"or "Madonna", or just an empty string will cause undefined behavior. strcpy(name, p);violates a constaint on the arguments of strcpy: copying between overlapping strings has undefined behavior. strcat(name, &initial);passes the address of a single char, which is not a valid C string. You can append a single charwith strncat(name, &initial, 1). You just cannot simply perform the inversion in place as coded, and should be aware that the resulting string might be longer than the source string. Here is an corrected version: @Shuster 2019-08-13 19:29:20 Regarding your first point: I should have clarified that one is assumed to ener a first and last name, so input like "Superman"is ignored here. Thanks for pointing out though! @chqrlie 2019-08-13 19:45:58 @Shuster: defensive programming is a good idea, avoiding undefined behavior in unexpected situations. @Bwebb 2019-08-13 19:19:24 Since you can assume the initial is always 1 char, use this instead of the failing strcat.
https://tutel.me/c/programming/questions/57483931/reversing+a+name++printing+garbage+after+first+name+letter
CC-MAIN-2019-51
refinedweb
595
59.94
Hey I want to create a JAR library but not sure how to in MyEclipse. Im currently doing it manually using jar command but I cant seem to get it correctly The library code is: public class LibAdd { public static int addtwonumbers (int a,int b) { return a+b; } } From this, I generate the .JAR (using what command in case Im doing it wrong). Named (for example) LibAdd.jar Then in another project, in the build path, I include the LibAdd.jar and I want to do this: public class AnotherClass { public static void main(String[] args) { LibAdd l=new LibAdd(); //Can I do this,having no main??? int x=l.addtwonumbers(2,3); System.println.out(x); //OR System.println.out(l.addtwonumbers(8,5); } } Thanks for the help :)
https://www.daniweb.com/programming/software-development/threads/406377/how-do-i-create-a-jar-library
CC-MAIN-2021-04
refinedweb
130
57.47
. - Web root – this is where public files are held (wwwroot folder in web project). By default web root is located under content root. But there are also deployments where web root is located somewhere else. I have previously seen such deployments on Azure Web Apps. It’s possible that some ISP-s also use different directories in tree for application files and web root. Getting content and web root at code Paths to content root and web root are available through IHostingEnvironment in code like shown here. Notice how content root and wwwroot are located in totally different places in machine. Setting web root location To set location for web root we need hosting.json file in application root folder. Also we need some code to include the file – at least for Kestrel. My hosting.json is shown here. { "webRoot": "c:\\temp\\wwwroot\\" } It is loaded when program starts (Program.cs file). I made this file optional so my application doesn’t crash when hosting file is missing. public class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) .Build(); CreateWebHostBuilder(args).UseConfiguration(config) .UseKestrel() .Build() .Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } If there is no hosting file then default configuration is used and ASP.NET Core expects that web root is located under application content root. Wrapping up Although we don’t have Server.MapPath() call anymore in ASP.NET we have IHostingEnvironment that provides us with paths to application content root and web root. These are full paths to mentioned locations and not URL-s. We can use these paths to read files from both of locations if needed.
https://gunnarpeipman.com/aspnet-core-content-webroot-server-mappath/amp/
CC-MAIN-2022-40
refinedweb
284
60.01
Alesis Studio24 Here you can find all about Alesis Studio24 like manual and other informations. For example: review. Alesis Studio24 manual (user guide) is ready to download for free. On the bottom of page users can write a review. If you own a Alesis Studio24 please write about it to help other people. [ Report abuse or wrong photo | Share your Alesis Studio24 photo ] Manual Preview of first few manual pages (at low quality). Check before download. Click to enlarge. Alesis Studio24 User reviews and opinions No opinions have been provided. Be the first and add a new opinion/review. Documents CE DECLARATION OF CONFORMITY Manufacturers Name: Manufacturers Address: declares, that the product: Product Name: Model Type: conforms to the following Standards: EMC: EN 55022:1988 Class B; EN50082-1:1992; IEC 801-2:1984 2nd Edition, 4kV direct, 8kV air; IEC 801-3:1984 2; 3V/m 150MHz-1GHz, IEC 8014:1988 1st Edition 2; 1kV, 0.5kV (all tests were performed with fully-shielded cabling.) EN 60065 Sound Technology plc Letchworth Point, Letchworth, Hertfordshire, SGND, UNITED KINGDOM Phone: +44.1462.480000 Fax: +44.1462.480800 March, 1999 Studio 24 Analog Signal Processor Alesis Corporation 1633 26th Street Santa Monica, CA 90404 USA Safety: European Contact: Introduction CHAPTER 1 INTRODUCTION HOW TO USE THIS MANUAL Youve taken the leap and purchased an Alesis Studio 24 Recording Console with Inline Monitor. Congratulations. At Alesis, we design equipment thats used by everyone from first-time users to engineers with decades of experience. In either case, the Studio 24 packs a lot of power into a small package, and we wrote this manual so that no matter what your background is, you can get the most out of it. FOR BEGINNERS The first two chapters are designed to give you a background in console operation. If you read them carefully, the rest of the manual will be easier to understand, and youll be happier with your results. Mixers really arent as difficult as they seem to be, but theres a lot of things going on at one time. Chapter 1: Introduction describes the capabilities of the Studio 24 and explains the basic principles of mixing and recording. Chapter 2: Guided Tour provides a brief tour of the Studio 24, and shows you how the basic principles of all console operation apply to the particular features of the Studio 24. Chapter 3: Hooking It Up details installation and power hookups, back panel connections (inputs, outputs, and cables), and typical hook-up procedures. Chapter 4: Effects and Signal Processing contains information on how to connect external effects and how to use them properly. If you dont read any other chapter, read this oneeffects send and return is one of the most misunderstood aspects of mixing consoles. Chapter 5: Recording Applications covers the various uses for the Studio 24 in multitrack recording, with step-by-step instructions on setting up and mixing techniques. Chapter 6: Sound Reinforcement Applications covers the Studio 24s features when its connected to a PA system; but this chapter will also be useful for those doing live recording. Chapter 7: Description of Controls is a dictionary of each control for fast reference. Chapter 8: Troubleshooting. A guide to trouble-free operation, maintenance and service information. We have also included a block diagram, Gain Structure Chart and an Index. DIG.IN MIDI IN L R PRESET EDITED OUT EQ PCH L DLY M RVB R 1 L R EQ PCH L DLY M RVB R 2 EQ PCH L DLY M RVB R 3 EQ PCH L DLY M RVB R 4 EQ PCH L DLY M RVB R 5 EQ PCH L DLY M RVB R 6 EQ PCH L DLY M RVB R 7 EQ PCH L DLY M RVB R 8 PAGE 5 AUX Sends THE DIFFERENT MIXES AND WHAT THEYRE NEEDED FOR Now that you understand the different sources and different destinations used during the three stages of the multitrack recording process, lets look at each one individually, without the other components getting in the way. Please note that these illustrations show the controls in the order they are electronically, and omit controls that dont apply to the mix being explained. Here are the mixes that you will control during a typical multitrack recording session: MULTITRACK MIX This mix goes from the sources (microphones or line inputs) to the tracks of the multitrack recorder. It is controlled by the Channel Faders and sent via the two Group Master Faders to the Group Output jacks. (If you need to record more than two tracks at once, some signals will go to the multitrack directly from Channel Faders via the Direct Out jacks.) In the multitrack mix, the goal is to set the controls so that each track is recorded as loud as it can be without distorting the recorder. For example, a microphone is plugged into channel 1 MIC IN port, and its level is set by the TRIM control. The CHAN/MON REVERSE switch is left in the UP position. After passing through the INSERT jack on the top panel, signal may then pass through the 75 Hz filter (if its switch is down) and the EQ on its way to the Channel Fader and MUTE switch. At this point, signal is available to the DIRECT OUT jack (where it may be connected to the multitrack); in any case it then goes on to the channel PAN, the GRP and L/R assignment switches. The channel PAN affects what Group the mic will be sent to: panning hard left sends the signal to GRP 1, panning hard right goes to GRP 2, and pan settings between extreme left and right results in a mixture of both Groups. The mic is mixed with any other channel sources feeding the same group, via the Group Master faders to the selected track (in the illustration, Group and track 4). Please note a key concept: you can go from any channel input to any of the group, direct outs or main outputs. Inputs and tracks are independent of each other. You can plug a mic into channel 1, and record it on track 4 without repatching. MIC LINE TAPE IN IN IN Multitrack Recorder Mix (Groups, Directs and L/R) TRIM CHAN/MON REVERSE INSERT jack (to MON 1/2) HIGH MID FREQ LOW DIRECT OUT GROUP OUTPUTS MAIN L/R OUTS & INSERTS (to AUX sends) DIRECT OUT SOURCE Switch (from GRP 2 on Even Channels) GRP 1/2 (combined with signals from other channels) MONITOR (CONTROL ROOM) MIX This mix is what the engineer and/or performer hears in headphones or the control room speakers. During overdubbing, this mix is typically controlled by the Studio 24s MONITOR 1/2 section, and sometimes by the L/R mix. In the monitor mix, the goal is to set the controls so that the performers get 24 allows you to adjust the monitor and control room mix (change levels, pan position, or solo individual channels) without disturbing the signals being recorded to the multitrack. In the illustration, the microphone we recorded on track 4 comes back on TAPE IN #4. The CHAN/MON REVERSE switch is left at its up position. The purple LEVEL knob and the MONITOR PAN determine the mix going to the MONITOR 1/2 MASTER. At this point, the CONTROL ROOM SOURCE switch is set to MON 1/2, so the engineer can adjust the monitor 24,. Also, please note that the EQ, 75 HZ filter, and INSERT jack do not affect the MONITOR 1/2 mix. AUX SEND/RETURN SYSTEM AUX SENDS In the center of each channel module are the blue knobs that make up the Auxiliary Send section, which allows the signal to be routed to outboard signal processing equipment. There are two Aux knobs in each channel labeled 3 and 4 that set the level of signal sent out of the AUX SENDS jacks on the top panel. Since some people will use the Monitor section as an auxiliary send, theyre numbered 1 and 2. STEREO AUX RETURNS The Stereo Aux Returns, found near the upper right section of the top panel, are extra input channels designed for routing the signals back from signal processing equipment. Aux Returns can be thought of as very basic line input channels. The gray LEVEL knobs control how much effect will be added to the mix, either while tracking or mixing down. The purple MON 1/2 knobs control how much effect will be sent to the monitor section so you can hear it in the control room and headphone mix, independently of the amount going to the multitrack or stereo mix. If you are using a MIDI system with several keyboards, each with stereo signals, you can alternatively use the Stereo Aux Returns as additional line inputs. This is especially useful for keyboards that provide their own on-board signal processing, and therefore do not need to be routed to the other Aux Sends. CONTROL ROOM SYSTEM The SOLO switches in each channel, along with the Control Room switches and Headphone section, make up the Control Room system of the Studio 24. This is the engineers mix. It allows you to audition the different mixes that are going on at any given time and to hear individual inputs when needed, all without disturbing the other mixes that are going to the musicians, the PA system or recorder. It also controls the stereo meter display. Normally, the CONTROL ROOM OUT jacks are connected directly to the inputs of a stereo amplifier such as the Alesis RA-100, which power a set of near-field monitors such as the Alesis Monitor One or Point Seven reference monitors mounted within a few feet of the console. CONTROL ROOM SOURCE The Control Room can selectively monitor the Main outputs (L/R), MONITOR 1/2, the Aux mixes, the Group mixes, or an external mixdown tape deck. The lowest switch which is pressed will be the source; if no switches are down, the L/R mix will be heard. The Headphone jack outputs the same signal that the Control Room is hearing. Regardless of whats chosen as the control room source, if any of the 14 SOLO buttons are pressed anywhere on the console, the solo mix automatically becomes the control room source. Because there are so many solo buttons, we make it easy for you to find the one on the Channel thats taken over by turning on a green LED over the SOLO switch. (When SOLO is not in use, these green LEDs will flash in response to input level, but they wont turn on solid.) Theres also a master solo LED that shows you when the solo system is active. The solo system has its own MASTER control, which is used to adjust the level feeding the Control Room knob. The source of the solo is called SIP (for Solo-InPlace). This is the traditional stereo solo position that puts the soloed signal in the mix at the same volume and pan position as it is when the solo system is off. Note that the SOLO switches of the Studio 24 are nondestructive, meaning that they never affect any mix other than the Control Room mix. MASTER INPUTS AND OUTPUTS Top panel: at the upper right-hand corner of the top panel of the Studio 24 youll find most of the connectors that provide the outputs of the console: two 1/4 MAIN OUTs (plus two MAIN INSERT jacks), and two 1/4" GROUP OUT connectors (plus two GROUP INSERT jacks). See the next chapter Effects and Signal Processing for information about the AUX SENDS. Back panel: the CONTROL ROOM OUT jacks are to the right of the power connector on the back panel. Just to the right of these outputs are the 1/4 jacks for MONITOR 1/2 outputs. In addition to the balanced 1/4 MAIN OUT jacks on the front panel, there are two unbalanced RCA MAIN OUTs on the back panel. MAIN OUTPUTS The left and right MAIN OUTs are two balanced TRS 1/4" jacks which provide the primary stereo mix of the Studio 24. These are normally connected to the inputs of a mixdown tape machine or a PA system amplifier. The two MAIN OUTS connectors on the back panel function in the same way, including the INSERT capability of the front panel jacks, but at the lower level of -10dBV for connection to unbalanced equipment. 44) is required. The GROUP OUTPUTS are balanced 1/4" connectors which may be connected to the inputs of a multitrack tape machine. To send a mix of several channels to a single track, you may use a Group Output. (The DIRECT OUT jacks on the Studio 24s back panel normally send one source to one track. But you can route the Group Outputs to any Direct Out pairs using the DIRECT OUT SOURCE switches. See page 54 and 55 for details.) Other uses for Group Outputs: In certain applications, such as video postproduction, a pair of Group Outputs may be used to provide a different mix than the Main Outputs, such as a mix containing music and effects but minus the dialog. Group Outs may also be used as a feed to an effect device, a separate section of a PA system, or for a surround sound encoder. Using two groups for eight tracks: Alesis ADAT recorders have normalling input features, which allow you to record on any track without repatching, even when the mixer output is connected only to tracks 1 and 2. Theres more about this later in this manual, and in the ADAT manual as well. NEVER select tape as the source of the channel (by pushing the CHAN/MON REVERSE switch down) when the tape recorder is in input or record mode and the DIRECT OUT is connected to the track input. This will cause feedback, since the tape will be trying to record its own output. RECORDING MULTIPLE SOURCES TO ONE TRACK When more than one Channel is to be recorded onto the same track of a multitrack recorder, it is necessary to assign all desired Channels to a Group, and connect the Group Output to the input of the multitrack using the DIRECT OUT SOURCE feature of the Studio 24. If you connected the eight DIRECT OUT jacks to the track inputs of your recorder, you can assign several Channels, via the Groups, to any pair of DIRECT OUTs. Press the DIRECT OUT SOURCE switch to the GRP position on the Channel that corresponds to the track you want to record on. This routes all Channels assigned to a Group to the DIRECT OUT without repatching. Example: if you want to record Channels 1, 2 and 3 onto track 6 on the multitrack, 1. assign these Channels to GRP, 2. pan all three Channels hard right and 3. press the DIRECT OUT SOURCE switch above Channels 5 and 6 to the GRP position. The GRP 2 FADER now controls the overall level of the three Channels going to DIRECT OUT 6. To record two or more sources to a single track: With microphones or instruments connected to the desired input channels, set the input level correctly (see page 51, Setting Levels). Assign each of the Channels you wish to record onto the same track to GROUPS 1 and 2 by pressing the GRP button situated next to the Channel FADERs. If you want to record effects or other devices from a Stereo Aux Return, you may also press the GRP keys in the STEREO AUX RETURNS section. Use the PAN control on each of the assigned Channels to position the signals either fully to the left or fully to the right. If the panning is fully left, the Channel will be routed to Group 1. If the panning is fully right, the Channel will be routed to Group 2. The appropriate GROUP FADER will now control the level going to tape. Raise the GROUP FADER to its maximum position. To check the level of the Group on the Studio 24s meter, press the GRP 1/2 switch in the CONTROL ROOM section. Be sure that the Groups LINK TO L/R switch is in the Off position (up). Otherwise the signal will be assigned to the Main L/R Output directly, instead of monitoring whats coming back from the multitrack via the MONITOR 1/2 section. To monitor the track through the multitrack tape machine, place the tape machine track you are recording on into record or input mode, and raise the MON 1/2 control knob of the Channel the tracks output is connected to. Be sure the L/R buttons are in the Off position (up) for the Channels being recorded. Otherwise, this may cause the monitoring to be false if the signals can be heard from two sources: the Channels and MONITOR 1/2. Tip: Note that the overall level of Channels panned left is controlled by the GRP 1 FADER; the overall level of Channels panned right is controlled by the GRP 2 FADER. So if youre not getting signal from one or more Channels, check their PAN knobs. In this example, Channels 1, 2 and 3 must be panned hard right to be correctly routed to DIRECT OUT 6. If theyre panned left, they will be routed to DIRECT OUT 5. Also, when youre recording multiple sources to one track using this method, make sure that all channels are panned hard to the left or right as appropriate. This ensures that the PAN controls dont reduce the output level of the Channels by panning signal away from the GRP FADER. RECORDING MULTIPLE SOURCES TO TWO TRACKS (STEREO) Recording multiple sources onto two tape tracks is simple you just use the Groups. Pan hard left all channels going to Group 1, and pan hard right all channels going to Group 2. You can pan each channel to obtain the proper stereo positioning between left and right. To record multiple sources to two tracks in stereo: With microphones or instruments connected to the desired input channels, set the input level correctly (see page 51, Setting Levels). Assign each of the Channels (or Aux Returns remember that you can use the four STEREO AUX RETURNS jacks as extra instrument inputs) you wish to record onto the same track of tape to GROUPS 1 and 2 by pressing the GRP button situated next to the Channel FADER (or below the AUX RETURN LEVEL knob). Use the PAN control on each of the assigned Channels to position the signals as desired between the left (Group 1) and right (Group 2). The GROUP 1 and GROUP 2 FADERS will now control the levels going to tape. Raise them to the full up position (0). Be sure that the Groups LINK TO L/R buttons are in the Off position (up). Otherwise the signals will be assigned to the Main Output directly, instead of monitoring whats coming back from the multitrack on the Channel fader. If you have the eight DIRECT OUTS connected to your multitrack, try the following method: Press the DIRECT OUT SOURCE switch down (to the GRP position) on the Channels that correspond to the track numbers youre recording on. This routes the GRP outputs to the DIRECT OUTS (as well as the GRP OUTS). Example: to record Channels 1 - 4 onto tracks 7 and 8, press the DIRECT OUT SOURCE switch at the top of Channels 7 and 8: this routes all Channels that have their GRP switches down to DIRECT OUTS 7 and 8. This handy little feature allows you to record any Channel to any DIRECT OUT without repatching. When using this method, note that the overall level of Channels panned left is controlled by the GRP 1 FADER; the overall level of Channels panned right is controlled by the GRP 2 FADER. 7 To monitor the tracks through the multitrack tape machine, place the tape machine tracks you wish to record on into the record-ready or input mode, and raise the MON 1/2 LEVEL control knobs of the Channels the tracks outputs are connected to. Set the CONTROL ROOM SOURCE switch to MON 1/2 (all other CONTROL ROOM switches must be up). Set the Monitor PAN controls to hard left and right to hear the proper stereo image in the control room. If you dont perform this last step, the main PAN settings you make on the channels youre recording in step 3 will be incorrect in the final stereo image. Be sure the L/R buttons are in the Off position (up) for the Channels being recorded. Otherwise, this may cause the monitoring to be false if the signals can be heard from two sources: the Channels and the Tape Monitors. EQUALIZER SECTION 75 HZ SWITCH The graphic over this switch shows what this does: it cuts frequencies below 75 Hz at a rate of 18 dB per octave. This is called a high pass filter, but some people prefer to think of it as low cut filter. It is used to filter out undesirable subsonic frequencies which may be present in the signal (air conditioning rumble, mic stand noise, etc.). If you push this switch, you often wont hear any difference, because so few instruments (and no voices) actually have harmonics below 75 Hz, and many loudspeakers dont have good response below this point. As a rule of thumb, you dont want to press the 75 Hz switch on instruments such as kick drum, bass, or keyboards; but it can be very useful on voices (especially if youre boosting the 125 Hz region to get an effect using the LOW or MID controls). These are standard shelving treble and bass tone controls. The HIGH knob range is +/- 15 dB at a fixed frequency of 12 kHz. This means that frequencies above 12 kHz will be boosted or cut by the same amount , and frequency response between 1 kHz and 12 kHz will gradually rise or fall to the shelving point. The LOW knob range is +/- 15 dB at a fixed frequency of 80 Hz. This means that frequencies below 80 Hz will be boosted or cut by the same amount, and frequency response will gradually rise or fall from 80 Hz to about 1 kHz. MID EQ CONTROLS: For Channels 1 - 8, the Studio 24 features a semi-parametric midrange, which means that you can control some of the parameters or aspects of the midrange, besides just cutting and boosting a predetermined frequency range. Combined with the HIGH and LOW EQ controls, these make up a 3-band equalizer that can create the vast majority of tones you may need. The Mid controls consist of two knobs: FREQuency and MID gain control. Notice that the FREQ control is a lighter shade of green, to help you identify it. The FREQ knob changes the center frequency of the EQ. The range is sweepable between 120 Hz (bass) to 13 kHz (extremely high treble). The MID knob controls how much boost or cut is applied to the band chosen. At the center detent position, there is no effect (flat response). Turning to the right amplifies the band, to a maximum of 15 dB. Turning to the left cuts the band, to a maximum cut of -15 dB. To learn how the midrange EQ works, put some broadband material (like a CD) into a channel at a low level. Boost the mid level to its maximum, then sweep the FREQ control to hear the effect. You usually wont use such a dramatic EQ setting on a mix, but it will help you get acquainted with the center frequencies this affects. Midrange: maximum/minimum gain, centered frequency The SOLO button sends the Channels signal (and only that Channels signal, if no other SOLO buttons are pressed) directly to the Control Room section, cutting off any other signals to the Control Room. It allows the engineer to focus on one signal without disturbing any other mixes. When SOLO is pressed, the green -20 LED will light solid (even if no signal is present) and the master SOLO LED will light in the Master module section, to alert you that Solo is active. You can adjust the output level of the signal(s) being soloed by turning the SOLO knob in the Master module section. If youre listening to a soloed Channel in the Control Room, the CONTROL ROOM LEVEL knob will also affect the volume in the rooms speakers. Likewise, if youre listening to the solo in the headphones, the HEADPHONE LEVEL knob affects the solo volume. The meter will show the level of the soloed signal, unaffected by the master solo level knob, so you can easily compare the level of individual channels and set the TRIM control accurately. GROUP ASSIGN SWITCH: GRP The GRP switch assigns the output of the Channel the two Group output busses, usually for recording on a multitrack. The amount of signal sent to GRP 1 or GRP 2 is determined by the Channel PAN knob. Panning hard left puts all of the Channels signal to GRP 1; hard right puts all of the Channels signal to GRP 2. When the Channels PAN control is set to 12 oclock, both Groups receive the same amount of signal and will be heard from the center of the stereo image. Note that even when the Group switch is down, no signal will go from the Channel to an intended Group if the Channel PAN knob is turned to the wrong side. For example, if the GRP 2 fader is up but the Channel is panned hard left, no signal will go to GRP 2. Tip:Remember that the signals sent to GRP 1 and 2 with this switch can also appear at the Studio 24s DIRECT OUT jacks, if the DIRECT OUT SOURCE switch (see p. 76) is in the down position. L/R SWITCH The L/R switch sends the channels signal to the Master L/R FADER, depending on the setting of the Channel PAN knob. This switch is normally pressed for final mixdown, or if the L/R mix is being used for monitoring in the Control Room and Headphones. This linear 60 mm slide fader varies the level feeding the Channel PAN control and Assignment switches (L/R and GRP) and AUX 3/4. The fader is set for unity gain (level in = level out) when it is set at the 0 dB mark, 2/3 of the way up. When the fader is raised to its maximum, there is 10 dB of gain added to the signal. STEREO AUX RETURN SECTION (A AND B) This section is essentially a four-input addition to the channels, squeezed into the top of the master section. This section is where you determine how much signal will be heard from effect devices. MON 1/2 Turn these purple knobs in order to hear the Stereo Aux Returns in the Monitor 1/2 mix. This is a pre-fader stereo send typically used for performer monitors and headphone feeds. Signals from the left input will go to Monitor 1, and signals from the right input will go to Monitor 2. The MON 1/2 send is not affected by the LEVEL control beneath it. This switch is primarily used when submixing for PA applications, or possibly during a complicated recording mixdown. The LINK TO L/R switch functions essentially the same as the LINK TO L/R switch under the MONITOR 1/2 MASTER: if the switch is up, anything routed to a group only goes to the group output and the four DIRECT OUT SOURCE switches. When the switch is down, the group is sent to the L/R mix as well. For example, if you have six different drum mics that are in perfect balance with each other, but you need to bring the overall level of the drums down in the PA, turn the drum Channels L/R switches off, assign them to Group 1/2, and press Group 1/2s TO L/R switch. The Group 1/2 faders are now a submaster for the entire drum mix in the left/right stereo mix feeding the PA or mixdown deck. Sometimes you may need two separate subgroups, instead of a stereo pair. The MONO switch allows you to do this. When MONO is down, Group 1 will feed both left and right of the L/R mix, so, for example, it may be used as a vocal subgroup. (If there was no MONO switch and you did a subgroup, all the vocalists would wind up hard-panned to the left side of the mix only.) Group 2 will also appear in the center of the L/R mix. 2 MASTER FADERS The two Group Master FADERS adjust the total output level of all signals assigned to each Group. They get their signal from the GRP switches in the Channels and the Stereo Aux Returns. They send signal to the two Group output jacks, the GRP Control Room switches, the LINK TO L/R switches explained above, and to the DIRECT OUT SOURCE switches in Channels 1 - 8. Tip: The GROUP FADER of the Studio 24, like the L/R Master, is at unity gain (0 dB) when all the way up, not at 2/3 travel as with some other consoles. This allows you a greater range of control on fadeouts, and makes it easier to dial in the best gain structure, since the sweet spot of the fader is in a useful part of the taper. L/R MASTER FADER This is a stereo 60 mm fader with its unity 0 dB position at the top of its travel, like the group faders. Signal from the L/R output feeds the Control Room switch, and the top and back panels MAIN OUT jacks which are normally connected to a mixdown deck, or to a PA system. TOP PANEL INPUTS AND OUTPUTS MAIN OUTS Connect these jacks to your primary destination: the PA systems inputs, or the 2track mixdown recorder. Signal comes here from the L/R MASTER FADER, and passes through the Main Inserts. This output is a true, 3-wire balanced differential output with a maximum output level of +28 dBu. The MAIN OUTS are also duplicated on the back panel but are unbalanced RCA jacks at a level of -10 dBV instead of balanced 1/4 connectors. They receive the same signal as the top panel jacks, including any signal introduced by the MAIN INSERTS. Both sets of jacks may be used simultaneously. WARRANTY INFORMATION This product is warranted by Alesis to the original purchaser against defects in material and workmanship for a period of 1 year for parts and labor from the date of purchase. Complete terms of the Limited Warranty are stated on the Warranty Card packed with the product. Please retain a copy of your dated sales receipt for proof of warranty status should repairs be necessary. REFER ALL SERVICING TO ALESIS We believe that the Studio 24 is one of the most reliable mixing consoles that can be made using current technology, and should provide years of trouble-free use. However, should problems occur, DO NOT attempt to service the unit yourself. Service on this product should be performed only by qualified technicians. THERE ARE NO USER-SERVICEABLE PARTS INSIDE. OBTAINING REPAIR SERVICE Before contacting Alesis, check over all your connections, and make sure youve read the manual. Your Alesis dealer may be able to offer further assistance. Customers in the USA: If the problem persists, copy down the serial number of the Studio 24 and call Alesis USA at 1-800-5-ALESIS and request the technical support department. Talk the problem over with one of our technicians; if necessary, you will be given a return authorization (RA) number and instructions on how to return the unit to Alesis or the nearest authorized service center. All units must be shipped prepaid and COD shipments will not be accepted. You must indicate the RA number on the shipping label or the shipment will not be accepted. If you do not have the original packing, ship the Studio 24 in a sturdy carton or road case, with shock-absorbing materials such as foam or bubble-pack surrounding the unit. Shipping damage caused by inadequate packing is not covered by the Alesis warranty. Ship the unit with insurance via a carrier that provides a tracking system. Tape a note to the top of the unit describing the problem, include your name and a phone number where Alesis can contact you if necessary, as well as instructions on where you want the product returned. Alesis will pay for standard one-way shipping back to you on any repair covered under the terms of this warranty. Field repairs are not authorized during the warranty period, and repair attempts by unqualified personnel may invalidate the warranty. Customers outside the USA: Contact your local Alesis dealer for warranty assistance. Do not return products to the factory unless you have been given specific instructions to do so. Your warranty is valid only in the country of purchase. Internet address: Important information and advice is available on our web site: alesis.com E-mail may be addressed to: info@alesis.com Specifications SPECIFICATIONS All measurements taken with an Audio Precision System One. All noise measurements taken with trim at minimum and faders at unity gain with 22 Hz to 22 kHz bandwidth unless otherwise specified. Main In & Out measurements made on balanced +4 dBu connectors. (+4 dBu into a line input with faders at unity and the meter reading 0 will yield +4 dBu into a balanced load or -2 dBu into an unbalanced load. Unbalanced RCAs at -10dBV (.317 volts)) Subject to change without notice. FREQUENCY RESPONSE 10 Hz 75 kHz +0/-1 dB -3 dB Point: (any input to any output at nominal operating levels) >125 kHz CONNECTORS MIC IN jacks: Female XLR (Pin 1 ground, Pin 2 +, Pin 3 -) LINE IN jacks Female 1/4" 3-conductor phone (Tip = +, ring = -, sleeve = ground) TAPE IN, DIRECT OUT, 2 TRACK IN jacks: Female RCA INSERT jacks: Female 1/4" 3-conductor phone (Tip = send, ring = return, sleeve = ground) Inserting plug to first "click" allows prefader direct output without breaking normal signal flow MAIN OUT (top panel), CONTROL ROOM OUT, and AUX SEND jacks: Female 1/4" 3-conductor phone (Tip = +, ring = -, sleeve = ground) STEREO AUX RETURN jacks: Female 1/4" 2-conductor, unbalanced MAIN OUT (rear panel): Female RCA LEVELS MIC IN LINE IN TAPE IN MAIN 1/4 OUTPUT LEVELS (when meter is at 0 VU) MAIN RCA OUTPUT LEVELS MAXIMUM OUTPUT LEVEL HEADROOM -62 dBu to -12 dBu nominal, maximum level +11 dBu -42 dBu to +8 dBu nominal, maximum level +31 dBu (balanced) -10 dBV nominal, +13 dBV (+15.2dBu) maximum +4 dBu (1.24 volts) into a balanced load -2 dBu into an unbalanced load -10dBV (.316 volts) +21 dBu unbalanced, +27 dBu balanced (5 dB above "PK" segment of main meter) 23 dB above nominal output MAXIMUM GAIN CHANNEL PEAK LED ON: METER: INSERT/DIRECT OUT (tip) INSERT IN (ring) +76 dB, MIC IN to L/R outputs, balanced +70 dB unbalanced +72 dB MIC IN to MON 1/2 OUT +82 dB MIC IN to AUX 3-4 OUT +85 dB, MIC IN to MONITOR OUT, balanced. 6 dB below channel clipping Peak type -24 dB to PK (+18 dB over reference at L/R OUT, 5 dB before output clipping) Unity gain Maximum level +18 dBu IMPEDANCE MIC IN LINE IN TAPE IN OUTPUTS (MAIN, GROUP, DIRECT, AUX and MON): 50-150 ohm nominal source impedance (presents 3.8 k ohm load impedance) 50 to 2 k nominal (>22 k load impedance) 50 to 2 k nominal (>16 k load impedance) 150 unbalanced, 300 balanced NOISE PERFORMANCE (TYPICAL) Dynamic Range Signal-to-noise ratio MIC IN to INSERT OUT 111 dB (Mic/Line to Main L/R output) 88 dB (Mic/Line to Main L/R output) -129 dB Equivalent Input Noise at maximum gain, 150 source Mic output noise (minimum gain, 150 source, to INSERT) -91 dBu Mix Output Noise (faders at nominal, trims minimum, 150 source terminations): 16 channels assigned -83 dBu unbalanced, -77 dBu balanced 1 channel assigned -90 dBu unbalanced, -84 dBu balanced DISTORTION (THD+N) Measured with a 0 dBu signal into a MIC IN jack; TRIM set for +15 dBu output at INSERT jack: At INSERT jack: Better than 0.0010% At MAIN OUT (+21 dBu): Better than 0.0015% USA model: 120 VAC, 60 Hz 100 watts power consumption maximum Top Panel: Mic Inputs Balanced Line Inputs Channel Inserts Aux Sends Stereo Aux Returns Headphone Jack (1) Main and Group Inserts Group Outs L/R Main Outputs (balanced) Back Panel: Tape Inputs Direct Outputs Control Room and Monitor 1-2 Outputs 2-Track Inputs L/R Main Outputs (unbalanced) Dimensions: Studio 24 Console Weight: Studio 24 Console Total Shipping Weight: XLR (8) 1/4" TRS (16) 1/4" TRS (8) 1/4" TRS (2) 1/4" mono (4) 1/4" TRS 1/4" TRS (4) 1/4" TRS (2) 1/4" TRS (2) RCA/phono (8) RCA/phono (8) 1/4" TRS (4) RCA/phono (2) RCA/phono (2) (WxHxD) 15.38" x 16.65 x 4" (39 cm x 43 cm x 10 cm)see dimensional drawing 16 lbs. (7.3 kg) Approximately 21 lbs. (9.5 kg) DIMENSIONAL DRAWINGS: GAIN DIAGRAM dBu + 30 + 20 + -10 -20 -30 -40 -50 -60 -70 -62 dBu MIC input -42 dBu LINE input -10 dBV TAPE input -12 dBu MIC input + 8 dBu LINE input Max. line input + 32 dBu Max. internal level + 22 dBu + 10 db gain at max Max. balanced output + 28 dBu OUTPUTS Balanced + 4 dBu -2 dBu unbalanced 32, using all capital letters (Example: TRIM control, PAN knob, MIC IN jack, etc.). When something important appears in the manual, an icon (like the one on the left) will appear in the left margin. This symbol indicates that this information is vital when operating the Studio 32. For the experienced: a quick overview If you're already familiar with mixing consoles, here are some important points you need to know about the Alesis Studio 32 Recording Console. The Studio 32 follows commonly-accepted traditions for signal levels and routing. Channel Input Jacks: All inputs and outputs are balanced except the INSERT jacks and Stereo Aux Returns. All other 1/4 jacks are TRS 3-conductor types and may be used with +4 dBu balanced or -10 dBV unbalanced systems. The XLR and LINE IN jacks do not have a switch between them, and use the same TRIM control, so you can only use one of them at a time. The TAPE IN jacks are entirely independent, have no TRIM control, and can handle input levels up to +25 dBu. PEAK indicator headroom: The PEAK LED in each channel will light 5 to 6 dB before the onset of actual channel clipping. The same is true for the PK segment of the main meter (which corresponds to +18 dB over reference). PEAK is monitored both pre- and post-EQ. Monitor LINK TO L/R: Unlike most other monitors, the Studio 32's monitor busses are independent from the L/R mix, unless you LINK them to the L/R using the switch. Think of them as an AUX 1/2 send with independent input source selection from the channel source, which can be submixed into the L/R if desired. EQ: The 75 Hz high-pass filter switch is independent of the EQ and may be used even if the EQ IN switch is out. The midrange controls are fully parametric. The EQ section affects the channel path only, not the MONITOR 1/2 section. AUX: There are four post-fader Aux send busses, with two knobs from each channel. Both knobs in a channel are assigned to a pair of auxes by the same AUX ASSIGN switch: 3/4, or 5/6. The upper control can send from the Monitor or the Channel; the lower control is always from the channel. SOLO: Whether the SOLO keys function as SIP (stereo solo-in-place, also known as After-Fader-Listen or AFL) or PFL (Pre-Fader-Listen) is selected by a master solo status switch next to the Control Room section. The Stereo Aux Returns can only be soloed in SIP mode. FADERS and gain structure: The Group and L/R master faders are designed with a nominal "0" position at the top of their travel, not the 3/4 position. The channel faders have 10 dB of gain from the nominal position to the top of fader travel. Most other pots are marked with a nominal position (usually "2 o'clock"). The L/R, Group, and Direct outputs add an extra 6 dB of gain when used in balanced mode. Chapter 5 Description of Controls gives a knob-by-knob definition of each feature of the Studio 32, so if you know what the Q controls do, but you need more information on LINK TO L/R, this is where you can look it up. In any case, please remember after you get started that this manual contains information that will help you get the highest level of performance from your Studio 32. Even an expert may pick up some creative alternative techniques that aren't obvious at first glance. To find what you need quickly, refer to the index at the back of the manual, or the Table of Contents. About the Studio 32 The Studio 32 is an extremely flexible, 16-channel, 4-group plus L/R output, in-line monitor professional audio mixing console. The MONITOR 1/2 path of each channel has its own volume, pan, and access to the channels upper Aux send knob, so you can mix or monitor the tape input while the main channel path mixes a mic or line input. Each monitor control has its own source switch, so it may be used as a conventional pre-fader auxiliary send as well as a tape monitor section. The MONITOR 1/2 mix may be linked to the main stereo output, but also features its own 1/4 output jacks. This flexible design allows full mix control of 32 sources, plus 8 aux returns, for a total of 40 sources at mixdown. For this reason, the Studio 32 is perfectly suited for professional project studios with a large number of MIDI sequencer-controlled sources that are synchronized with 16 tracks of ADAT. It also makes an excellent console for live sound reinforcement use. Each channel features a high-quality 3-band equalizer with a fully parametric (not just sweep) midrange band. The midrange Q (bandwidth) can be set as narrow as 1/6th of an octave, or as wide as several octaves, for boosting or cutting any frequency range desired. An EQ IN/OUT switch permits the entire EQ circuit to be bypassed when desired, maintaining the minimum signal path. A switchable 75 Hz high-pass filter removes low frequency rumble and noise. The Studio 32 uses fully balanced +4 dBu inputs on 1/4" jacks for all LINE IN and TAPE IN connections. The Studio 32 may also be used with unbalanced -10 dBV level equipment. Each channel has its own balanced Direct Out, so that simultaneous 16-track recording is possible. All channels feature a high-quality, low-noise balanced microphone preamp with globally switchable 48-volt phantom power for condenser microphones. Each input channel features a green -20 dB signal present LED and a red PEAK LED to warn of input signals that are too high for the present trim or EQ setting. The MUTE and SOLO switches use these same LEDs to indicate when a channel is muted or soloed. Effects mixes are handled by four post-fader Aux send busses, with two controls in each channel that are assignable to either Aux 3-4 or Aux 5-6. The upper control, labeled Aux 3(5), features its own input source select switch that allows it to provide an effects send from either the channel fader or monitor level control. The lower control, Aux 4(6), is a post-fader send thats always sourced from the main channel fader. Four Stereo Aux Returns (labeled A, B, C, and D) are provided, each with its own assignment switches and MON 1/2 send control. Returns may be routed to the stereo mix, the groups, soloed to the control room, and added to the monitor mix, so that effects may be added to the final mix, printed to multitrack, monitored on headphones, or any combination desired. The Studio 32 provides insert points on each channel and the stereo main outputs, for use with compressors and graphic equalizers. Control room monitoring is made simpler by stereo-in-place Solo on each main channel, which is globally switchable to PFL (Pre-fader listen). Each Auxiliary mix and Group may be previewed in the control room while leaving the rest of the signal path undisturbed. Two built-in headphone jacks with a separate source select switch allow you to hear either the control room source, or the monitor mix. MIC IN LINE TAPE IN IN Multitrack Recorder Mix (Groups and L/R) (to MON 1/2 SOURCE) FADER SOURCE INSERT jack 75 HZ HIGH MID FREQ Q LOW EQ IN (Post-EQ to MON 1/2 SOURCE when MIC/LINE is selected at both) DIRECT OUT (to AUX sends) 1 GROUP OUTPUTS MAIN L/R OUTS & INSERTS GRP 1/2 (combined with signals from other channels) GRP 3/4 Monitor (Control Room) Mix This mix is what the engineer and/or performer hears in headphones or the control room speakers. During overdubbing, this mix is typically controlled by the Studio 32s MONITOR 1/2 section, and sometimes by the L/R mix. In the monitor mix, the goal is to set the controls so the performer gets 32 allows you to adjust the monitor and control room mix (change levels, pan position, or solo individual channels) without disturbing the signals being recorded to the multitrack. In the illustration, the microphone we recorded on track 4 comes back on TAPE IN #4. The MONITOR 1/2 source switch is set to the TAPE (up) position. The LEVEL pot (with the purple knob), and the MONITOR PAN determine the mix going to the MONITOR 1/2 MASTER. At this point, the CONTROL ROOM SOURCE switch is set to MON 1/2, so the engineer can adjust the monitor mix, and the HEADPHONES SOURCE switch is set to MON 1/2 as well, so that if the engineer hits any SOLO buttons, only the control room mix will be affected, not the headphone 32,. Post-EQ, Pre-Fader: The EQ, 75 HZ filter, and INSERT jack do not affect the MONITOR 1/2 mix unless both the FADER SOURCE and MONITOR SOURCE switches have selected MIC/LINE as the source. This feature allows you to hear what the engineer is doing to the EQ, or to an effect device in the INSERT jack, when youre using the MON 1/2 mix for headphones or a stage monitor mix. But the EQ and INSERT never affect the TAPE side of the MONITOR SOURCE switch, or if the MIC signal is going through MON 1/2 while TAPE is going through the CHANNEL FADER. (For clarity, the drawing on the next page doesnt show this detail; see the Block Diagram on page Error! Bookmark not defined. for the complete signal flow.) Starting at the source: input and TRIM Lets trace the signal flow from beginning to end. Note that the controls from top to bottom of each channel are not placed in the same order as they appear in the signal flow. To see the paths of the signal flow, refer to the block diagram on page Error! Bookmark not defined. Each input module has three possible sources (line, mic and tape in) and two paths (the main channel and the monitor). First, the signal arrives at either the line or mic input of a channel; you should not plug into both at once. If using the mic input with a condenser microphone, the rear-panel PHANTOM switch will be turned on to provide phantom power (after the mics have all been plugged in). Next we come to the gray TRIM knob, which is used to set the initial level of the signal. It is important to set this level properly, since high levels could lead to distortion and levels set too low will cause noise (see Setting Levels). Channel and Monitor source select switches: Each channel has its own FADER SOURCE SELECT switch, under the TRIM control, and MONITOR 1/2 SOURCE SELECT switch above the MONITOR 1/2 PAN control. These two switches are completely independent. If both switches are up, the TAPE INPUTS can be heard through the MONITOR 1/2 controls, while the MIC/LINE input appears at the main channel controls. This is the position normally used for tracking and overdubbing. If both switches are down, the tape returns are on the main channel while the MIC/LINE input appears at the monitor controls. This is the position normally used for mixdown (with the main channel assigned to L/R) or for bouncing tracks (with the main channel assigned to the appropriate Group or Groups). If the FADER SOURCE switch is up and the MONITOR SOURCE switch is down, MIC/LN is chosen for both. This is the position that would be used if MON 1/2 is going to be used for a pre-fader stage monitoring mix. The equalizer EQ section: The EQ section affects only the signal on the Channel fader, not the signal of the monitor section. An EQ IN switch allows you to hear the signal flat with no EQ at the touch of a button. Once the fader source has been chosen, and the EQ IN switch is down, signal will flow through the green knobs in the EQ section. The EQ has three bands: the Hi & Lo EQ, and the fully-parametric Mid EQ. The Hi & Lo EQ are shelving-type EQs, with 12 kHz and 80 Hz shelving points and an adjustable boost or cut of 15 dB. These act much like the bass and treble knobs found on most audio equipment: the 12 oclock position has no effect, and you turn to the right to get more of the frequencies and to the left to cut them. The Mid EQ has three knobs: one to set the amount of boost or cut, one to select the frequency you want to control (adjustable from 150 Hz to 15 kHz), and a Q or bandwidth control. The Q control adjusts how wide an area around the selected frequency should be cut or boosted, allowing you to be extremely specific about how you tailor your sound. To avoid low-end rumble and noise, turn on the 75 Hz high-pass filter, which removes frequencies below 75 Hz at a rate of 18 dB per octave. The 75 HZ switch has this effect even if the EQ IN switch is off. Direct Outputs The DIRECT OUT jack on each channel is a balanced 1/4" connector which provides a direct output of the post-fader channel signal. It is set for a unity-gain output, so it can drive either +4 dBu or -10 dBV devices depending on the setting of the TRIM control and the fader. If you want to record a single source to a track of tape, connect this to the inputs of your multitrack tape recorder, or for any other application where you need a direct output. (The other option is to connect the Group Out jacks to the recorder, as explained on page 31.) Insert The INSERT connector is a TRS 1/4" jack which consists of an insert send (the tip of the TRS plug) and an insert return (the ring of a TRS plug), and is used to insert an outboard effects device (such as a compressor, EQ, or chorus) directly into the signal path of only one channel: the channel it is connected to (as opposed to the Aux system, which combines many different channels into an effect). For details on this, see page Error! Bookmark not defined. Master Inputs and Outputs Along the top of the back panel above the master section of the Studio 32 youll find most of the connectors that provide the outputs of the console: two 1/4 MAIN OUT connectors (plus two MAIN INSERT jacks), and four 1/4" GROUP OUT connectors. The CONTROL ROOM OUT jacks are under the power connector. See the next chapter Effects and Signal Processing for information about the Auxiliary Outputs. Main Outputs The left and right MAIN OUT jacks are two balanced TRS 1/4" jacks which provide the primary stereo mix of the Studio 32. These are normally connected to the inputs of a mixdown tape machine or a PA system amplifier. Error! Bookmark not defined.) is required. Left Signal Right Signal Ground Tip Ring Sleeve Sleeve Chart of Connections The Studio 32 may be easily interfaced with most other professional recording and audio equipment. All inputs and outputs, with the exception of the microphone inputs, use 1/4" jacks, and may be used with balanced or unbalanced circuits. The microphone inputs are standard balanced XLR type jacks. Mic Inputs Line Inputs DIRECT OUT (Direct) Tape In Inserts Aux Sends Aux Returns Group Outs Main L/R Outs Main Inserts Control Room Outs 2 TRACK IN Headphone Connector XLR 1/4" TRS 1/4" Mono 1/4" TRS 1/4" TRS 1/4" Mono 1/4" Mono 1/4" Mono 1/4" TRS 1/4" TRS 1/4" TRS 1/4" Mono 1/4" TRS Balanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced Unbalanced or Balanced Unbalanced or Balanced Unbalanced Connecting to an Unbalanced -10 dBV Multitrack Recorder Interfacing the Studio 32 with a typical multitrack recorder using semiprofessional unbalanced phono or 1/4" phone jacks is a simple process. Alternatively, if you are using one or more ADATs, it is recommended that you use the balanced inputs and outputs using the ELCO-type connector on the ADAT (see next page). To interface with a typical unbalanced multitrack recorder: 1 Connect any microphones or instruments to be recorded into the MIC or LINE INPUTS of channels 1 through 16. Connect the four GROUP OUTs to the corresponding tape tracks by using either 1/4"-to-RCA cables or 1/4"-to-1/4" cables. Alternatively, you may decide to connect individual channel DIRECT OUT jacks to the track you want to record, but this will require you to repatch every time you want to record a different channel on that track of the recorder. Connect the tape machines outputs to the TAPE IN jacks of the same-numbered channels of the Studio 32. Whenever you want to hear the playback of the machine, track 1 will appear at the FADER SOURCE and MONITOR SOURCE switches of channel 1, track 2 will appear at channel 2, and so on. Connecting your recorder(s) at the -10 dBV unbalanced level can yield good results, provided that the cables between the multitrack and the Studio 32 are no more than 20 feet long. If cable runs must be longer than that, or if your studio has noise and grounding problems, we recommend a +4 dBu balanced hookup if possible (see next page). Connecting to a Professional +4 dBu Multitrack Recorder Professional recorders typically feature 3-pin XLR connectors on their inputs and outputs. ADATs feature a multipin ELCO connector that takes care of all the channels (8 inputs, 8 outputs) on a single connector. The nominal signal level of these units is +4 dBu (1.23 volts). In either case, connect these decks to the TAPE IN jacks, not the MIC IN XLR jacks. ADAT: The best method for connecting an ADAT is to purchase an ELCO-to-TRS multipair cable, available from many different cable manufacturers. This will connect from the ELCO-type connector on the ADAT on one end, fanning out to sixteen tip-ring-sleeve quarter-inch phone plugs (labeled INPUT 1, OUTPUT 1 and so on) on the other end. This method assures full-balanced outputs from the ADAT to the TAPE IN jacks. The connection from the Studio 32s GROUP or DIRECT OUT jacks to the ADATs inputs will also be balanced. The GROUP and DIRECT OUTS have plenty of headroom, with a maximum balanced output of +27 dBu before mixer distortion (although the ADATs own maximum is +19 dBu). Balanced cables between the recorder and the mixer can be very long, if necessary, without adding noise. XLRs: If you have a video or old analog deck with XLR inputs and outputs, you will need: An XLR female to 1/4" TRS cable for each output of the tape recorder; and, Sleeve (Ground) Tip (+) Pin 1 (Ground) Pin 3 (-) Pin 2 (+) Ring (-) An XLR male to 1/4"TRS cable for each send to the tape recorder. This arrangement will give you a balanced connection for recording and playback in most cases. However, some recorders with XLRs may not be truly balanced, with pin 2 or 3 (depending on vintage) tied to ground, which may cause a ground loop. Also, depending on the characteristics of the deck, metering levels may not match between the deck and the Studio 32. You may need to increase the Studio 32s fader level in order to get enough level on the multitracks meters. Some multitracks have high/low level input switches; follow the manufacturers instructions on setting these properly. Most complaints of noisy effects are due to send levels that are too low and return levels that are too high. You must structure the gain properly between the Studio 32 and the effect device. Selecting an Aux Send: First, you must decide which Auxiliary Sends to use. There are four post-fader sends from the Studio 32, labeled Aux 3 through Aux 6 because MON 1/2 is considered a special type of auxiliary send. To send a signal to the effect device from the monitor section, press the AUX SOURCE button down. This selects the post-monitor fader signal as the source of the AUX 3(5) knob directly below the switch. In a typical installation, Aux 3 is used for effect sends from the monitor. To send a signal to the effect device from the channel, use AUX 4 or AUX 6. The signal source for the lower AUX control always comes from the channel fader. In a typical installation, Aux 4 is used for effect sends from the channel. To send signal from the monitor and the channel to the same effect device(s), press the AUX SOURCE button down and press the TO 5/6 switch. Use AUX 5 and 6 for a combined effect send. To set the level going to the effects device: 3 Set the Aux Send(s) in the input module to about 2 oclock. Start the signal source(s); i.e., play the tape or instrument at typical levels. Raise the appropriate AUXILIARY MASTER to about 2 oclock. To check the output level, select AUX 3/4 or AUX 5/6 as the Control Room Source, and set the Aux Master to a setting that gives an average meter reading of 0 dB on the L/R meter. Raise the input control of the effects device until its meter or clip LED shows peak level, then lower the input control a bit. Consult the manual for the effect device for more information. Some effect devices have level setting switches on the back; these should be set so that a peak level can be reached with reasonable settings (neither too high nor too low) of the input control. To set the level coming FROM the effects device: In most cases, the output level of the effect device itself should be set relatively high, at nominal or maximum. Lower the output of the device only if the meter keeps the +10 LED on when the Stereo Aux Return is soloed, or if the effect levels are too loud even at low settings of the Stereo Aux Return LEVEL controls. To hear effects in the control room monitors: Its possible to put effects into the monitor or headphone mix without recording them to the multitrack. 1 Press the L/R switch of the Stereo Aux Return. Make sure the GRP 1/2 or GRP 3/4 switches are in the up position. Otherwise, the signal will be assigned to the group and effects may be sent to the multitrack recorder. Raise the Stereo Aux Returns LEVEL control until you hear the desired volume of effect return. Remember that you can SOLO the Aux Return to make adjustments to the sound, if desired, as long as the master solo select switch is in SIP (solo in place) mode (green solo master LED). You will be hearing the output of the effects device only, without any dry signal coming from the channel. To hear effects in the headphone/cue mix: Often while recording, musicians would like to hear some reverb or delay in their headphone mix. It is possible to meet this need without actually recording the effect. If youre using L/R as the cue feed, follow the steps for control room monitors above. If the headphone mixs source is MON 1/2: 1 Select MON 1/2 as the Control Room source so you can hear what the studio is hearing. Raise the MON 1/2 control (the purple knobs) of the Stereo Aux Return(s) until the desired balance is heard. To record effects onto the multitrack: In most cases, effects are added at mixdown instead of during tracking and overdubbing. However, you can record wet (with effects) in order to use the same device for some other effect at mixdown, or because the effect is essential to the part. To do this, you simply: 1 Assign the Stereo Aux Return to the Group that youre recording, by pressing the GRP switch. Returns A and B can be sent to Groups 1 and 2, and Returns C and D can be sent to Groups 3 and 4. (If this doesnt fit your needs, you will have to repatch.) To make sure youre hearing whats actually going to tape, make sure the L/R switch is up, and follow the procedure earlier in this section under Recording Multiple Sources. If the effect is stereo, it must be recorded onto two tracks. The left Aux Return input will go to the odd-numbered group (1 or 3) and the right Aux Return input will go to the even-numbered group (2 or 4). To record effects onto the mixdown deck: This procedure is the same as for hearing effects in the control room monitors described earlier: assign the STEREO AUX RETURNS to L/R and adjust the LEVEL controls. Connecting Signal Processors to Insert Jacks Inserts are used to connect signal processing devices directly into the signal path of a Channel. Normally, the device connected would be one that shapes the dynamics or tone of a signal (such as a compressor, gate, or EQ), rather than an effects device (such as a reverb). It is also possible to insert a stereo signal processor into the signal path of the MAIN L/R OUTS, using the MAIN INSERT jacks. This is desirable when either a group of instruments, or the entire mix, needs to be processed. All INSERT jacks on the Studio 32 are TRS jacks containing both an output (send) and an input (return). The tip of the plug is the Send and will be connected to the Input of the effects device or processor, and the ring of the plug is the Return and will be connected to the Output of the effects device or processor. A special Y-cable consisting of a TRS 1/4" plug on one end and two mono 1/4" plugs on the other end is required. See the illustration below. If a large amount of EQ is used, it may become necessary to decrease either the TRIM control, or the Channel FADER, or both. The EQ is capable of adding quite a bit of gain and is a frequent cause of overload distortion problems. The Studio 32 has been designed with plenty of headroom on the internal summing amplifiers (23 dB of headroom above a +4 dBu balanced output level). It is only possible to clip the mixer internally if several channels are at or near their maximum clipping point (with PEAK indicators flashing) and then sent at maximum gain to an output. You are in danger of this if: the meter is hitting the top of its range (PK) with the GROUP MASTER FADER set to nominal level, or the GROUP or MASTER FADER is set to -20 or lower, and the meter is reading 0 dB or above. Once again, it may be necessary to decrease either the TRIM control, the Channel FADERS, or both, of each of the Channels assigned to the Group. Maintain Proper System Levels As a good rule of thumb, try to run most volume level controls of other equipment receiving signal from the Studio 32 (amplifiers, effect devices) at 3/4 or 75% of full, as well. This will decrease the possibility of overload distortion and keep the amount of background noise to a minimum. How to Record a Single Source to One Track When recording a single source appearing on one Channel onto a single tape track, it is usually best to use the DIRECT OUT of the Channel. This provides the most direct connection between the Studio 32 Mixer and the multitrack. To record a single source to a single track: 1 With a microphone or instrument connected to the desired input channel, set the TRIM and fader level correctly (see page 45, Setting Levels). Make sure the channels FADER SOURCE switch is up. Connect the channels DIRECT OUT to the Input of the desired tape track (see page Error! Bookmark not defined., Connecting to a Multitrack Recorder). Place the track you want to record into the source or input mode (usually by arming the track for recording). At this point, you may see the channel meter of the recorder respond to the microphone or instrument. Adjust the fader for the proper recording level. To monitor (listen to) the signal through the multitrack tape machine, make sure the TAPE/ML switch of MONITOR 1/2 is up and raise the Monitor 1/2 LEVEL of the track being recorded. Note that this Monitor control may be in a different channel strip, if youre recording onto a different-numbered track. 5 To hear MONITOR 1/2 in the control room, raise the MONITOR 1/2 MASTER control, select MON 1/2 as the control room source (by making sure all other Control Room Select switches are up), and raise the control room level. To hear it in the headphones, you may select MON 1/2 directly as the headphone source. Patch these six outputs (Groups 1-4 and L/R) to the first six tracks of the recorder. 3 Patch the vocal and bass from their respective TAPE OUTs without assigning them to any of the main outputs: Voila, an 8-track digital recording that is easy to manage, and a happy audience and vocalist. The point of all these techniques is: dont limit yourself in how you use the different sections of the Studio 32. What works in one situation will require a different solution in another. Video Production and Post-Production The Studio 32 lends itself extremely well to post-production applications where a soundtrack is being developed for video or film. In most situations, a synchronization system is being used, which ties together all of the time-based equipment including one or more video tape recorders (VTRs), a multitrack tape recorder, and in many cases a computer running MIDI software. The software usually performs as a sequencer for adding virtual tracks (sequenced parts not recorded to tape), and recalling effects programs on MIDI-compatible outboard effects devices. Video deck outputs may be patched to either the LINE IN or TAPE IN jacks in most cases. To feed the output of the Studio 32 into a video deck, set the input of the video deck to line level or +4, and connect either the GROUP or MAIN L/R OUTPUTS to the video deck using appropriate adapter cables (usually 1/4 TRS to XLR/Male). Make sure the input level of the video recorder is not set to mic or -40 level. In live production, a typical setup would be to plug microphones into the Studio 32, with direct outputs feeding an ADAT. Using the techniques listed above (Using Monitor 1/2 to feed a cassette deck), make a reference stereo mix to record onto the VTRs audio tracks (or onto a single audio track if one must be used to record time code). Description of Controls CHAPTER 7: DESCRIPTION OF CONTROLS Channel Input Controls The TRIM knob adjusts the sensitivity of both the Mic and Line inputs. Proper setting of this control is essential for low-noise, distortion-free operation. In most cases, microphones require from 30 to 60 dB of preamplification, while line sources need much less or none at all. If the Channel PEAK LED lights when the FADER SOURCE switch is up,lower the TRIM control. Mic input gain: +10 dB (minimum) to +60 dB (maximum) Line input gain : -10 dB cut to +40 dB gain. MONITOR 1/2 LEVEL, MONITOR 1/2 PAN The purple LEVEL knobs control how much signal will be sent to the MONITOR 1/2 MASTER. The left/right balance of the MON 1/2 mix is set by the black PAN control directly above this knob. MONITOR 1/2 is a pre-fader, pre-mute stereo send typically used for control room monitors and headphone feeds. By turning the PAN fully left, the signal is routed only to MON 1. When turned fully right, the signal is routed only to MON 2. Its input can be derived from either the Channel or Monitor, as determined by the MONITOR SOURCE switch (see above). Its unitygain position is at full rotation. Channel Output Section The Channel PAN control sends the output of the channel in continuously variable degrees to either side of the stereo mix (if L/R switch is pressed -- see below), or to odd-even sides of the Group Assignment switches (pan left for Groups 1 and 3, pan right for Groups 2 and 4). The PAN control is a combination where to/how much control, in that it controls both the level and direction of a signal. The MUTE switch turns off the signal from the Channel Fader. It disconnects the signal from the L/R Main outputs, the Group outputs, the DIRECT OUT, and any Aux Sends. When pressed, the PEAK LED will light solid. The MUTE switch has no effect on the MONITOR 1/2 control. PEAK LED The red Channel PEAK LED will flash when the channels signal level (measured at several places in the channel) is within 5 dB of clipping or distortion. If it flashes, reduce the TRIM knob (or the EQ, or the gain of any device at the INSERT jack) until it stops flashing. The PEAK LED will come on solid when the MUTE key above it is pressed. -20 dB (Signal Present) LED The green -20 LED will light whenever a signal of -20 dB or higher is present anywhere in the channel circuit. This will help you determine what instruments are on what channels, and if the TRIM controls are set properly. The -20 LED has a second function as an indicator for the SOLO switch, described below. The SOLO button sends the channels signal (and only that Channels signal, if no other SOLO buttons are pressed) directly to the Control Room monitors, cutting off any other signals to the Control Room. It allows the engineer to focus on one signal without disturbing any other mixes. When SOLO is pressed, the green -20 LED will light solid (even if no signal is present). The soloed Channel also feeds the headphone outputs if the HEADPHONE SOURCE button in the master section is in the up or CR position (see page 73). The master SOLO LED will light in the Master module section, to alert you that Solo is active. You can adjust the output level of the signal(s) being soloed by turning the SOLO knob in the Master module section. The meter will show the level of the soloed signal, unnaffected by the master solo level knob, so you can easily compare the level of individual channels and, in PFL mode, set the TRIM control accurately. Auxiliary Outputs (including Mon 1/2) Auxiliary Outputs 3, 4, 5 and 6 are normally connected to the inputs of effect devices. The MON 1/2 jacks may be fed to a headphone amplifier in recording applications, or to a stage monitor system in PA applications. These jacks are 3conductor TRS with a forward-referenced ground to avoid ground loops. Channel Input/Output Jacks (16) Direct Out This jack provides the output of the channel, post-fader. Connect it to the input of a multitrack tape recorder if you need to record more than four tracks at a time, or if you only need one microphone per track. Unlike most DIRECT OUT jacks on other consoles, these are true +4 dBu balanced outputs, so you can easily repatch the sends to the tape recorder between the group and direct outs. In theory, the DIRECT OUT jacks provide a cleaner signal than that of the GROUP OUT jacks, but the difference is almost unmeasurable. You can be confident that if its more convenient for you, its perfectly OK to record from the Groups. Tape In Connect the outputs of your multitrack tape recorder to these jacks. It may be +4 dBu balanced (+26 dBu maximum level) or -10 dBV unbalanced. Actually, any typical line input (such as the output of a synthesizer or effect device) may be connected to these inputs, so you could use the Studio 32 as a 32-input line mixer, by running the tape inputs through the MONITOR 1/2 section, linked to the L/R Master. However, note that the TAPE IN jack does not pass through the TRIM control, so extremely low-level or high-level signals should be connected to the LINE IN jack instead. Insert jack This is a 3-conductor unbalanced send/receive jack for whatever is selected by the FADER SOURCE switch. The post-trim, pre-EQ, pre-fader signal appears at the tip connector, and the ring connector is an input to the Equalizer section of the channel. This is normally connected to an in-line effect processor such as a compressor or equalizer. See page Error! Bookmark not defined. for more information on how to use the insert jack. Line In jack This input jack may be used with balanced 1/4 TRS or unbalanced 1/4 sources. It connects to the Mic/Line side of the FADER SOURCE and MONITOR 1/2 SOURCE switches of the channel. Line signals pass through the TRIM control, which allows them to accept a wide range of input level (from +14 dBu nominal to -36 dBu nominal). When the TRIM is set to maximum, the LINE IN signal will be amplified 40 dB. When TRIM is at minimum, it will be attenuated (lowered) 10 dB. The LINE IN and MIC IN jacks of a single channel may not be used simultaneously. Mic In jack Headphone Dg130HA 1204FX TS320GSJ25M GR38N11CVF 836 XA MX-D301 Ducato LE52A656a1F Source 1600 60IRV Bass 2007 SU-WL100 SPF-83M Adat-HD24 BT100 20LS5RC Motorola D211 Pilot E522B GA-H55m-d2H HU80520 430 EX BIW125W WMR112A SL-3300 Challenge Cdx-gt200 MDX-C6500X Software DCR-TRV22K SU-A800D Review Switch DVD 592 GR-262SQA 4695MF FS518T LE40N87 DVD-VR320 VGP-WKB1 CQC3303N FAX-1460 FS-680 IS7-V Psm71 PX-61XM3A WMT-555C 3211 VTS Cyclecomputing C10 Dominoes F200 EXR VGN-NS31m S Printer DMR-EZ48V MZ-E33 Lexmark C510 2 Plus 10 GHZ Videostudio 10 Z1015 IS MA361 KD7-raid EMX62M HD6103 APC 500 19 01 HT902TB 14 0 DMC-FS20 Scanmaker V300 KEH-P3630R DP-300U DVD-R136 500CM PS-42S5S DCR-IP220E Lide 700F Digital Elph Kawasaki FA76 PD113 27AF44 PL42A410c2D 1172X KDC-MPV6022 AOC-100 53 SPB MX-42VM10 KM-6230 L75805 Aspire G600 Kapten CN405aprt54 FL632C 07530 Mkii 5730ZG UVW-1800P Motorola D811 Escort-1997 Triton 2000 RW7
http://www.ps2netdrivers.net/manual/alesis.studio24/
crawl-003
refinedweb
12,926
65.05
In this post I will go over a few things: - Implementing ISelectionFilter - which we will use while prompting user to select things via UI Before we even get to selection stuff let’s first make sure that we have our application and documents needed. We specified that to be the first thing to do in our pseudo code so let’s do that first:Now I will go over it line by line: - uiApp is our Revit application. This will give us project level access to Revit database. Next we want to prompt a user to select bunch of lines, so that we can measure their length. While user is selecting them we want to filter out any objects that are not Detail Lines. For that we can use something called ISelectionFilter like so: Here’s the line by line breakdown: - create a new public class that implements ISelectionFilter - . - define first method that will return a boolean true for elements that we want to allow. - . - define return statement. our rule is that if selected element Category Id value equals to that of BuiltInCategory.OST_Lines elements will be passed through. Basically we only allow Lines to pass through. - . - . - define second method for allowing references. - . - since we don’t want to pass references through we simply return false here. - . - . What this method will do, is that it will allow us to select only elements that are of category OST_Lines. That’s a pretty nifty little tool that is super helpful in our case. Let’s implement this filter in our code, and prompt a user to select something: Here’s a line by line breakdown: - create a new empty list of Elements that will be populated with elements selected by user. - this is just a shortcut so that I don’t have to type out a super long line of code later. - This defines our Selection class that will be used to prompt user to select things. - Now that we have our filter class defined let’s create an instance of it and assign it to “selFilter” variable. - This prompts user to “select lines” and when user is done will populate pickedRef list with selected elements. This is what our code should look like to this point*: *You should also notice that I added another using statement at line 10. This is just to make our code cleaner at line 42. If I didn’t add a using statement pointing directly at Selection class I would have to change line 42 to something like this: Selection.Selection sel = uiApp.ActiveUIDocument.Selection; That’s arguably much muddier hence the using statement. :-) Let’s Build this project now, and replace the dll file in Revit Addins folder. You don’t have to worry about the addin file, since that hasn’t changed. This is what we should be getting now in Revit: - This is area of my rectangle used to select things. - Only Detail Lines present within the selection rectangle were highlighted (selected). This means that our selection filter is working just fine. :-) Now that we have out selection filter implemented we can move on to rest of our code that will measure the length of all of the selected lines and return a value for you. First I want to iterate through my list of selected curves and return their length:Here’s the line by line breakdown. - each length is a double (a number) so we need a new list to store them in. - this starts a new foreach loop that will iterate through every selected detail line - . - since when lines were selected they were returned to us as Element objects we need to cast them to DetailLine class. We do that because we want to be able to access DetailLine properties of each of the Elements. - if somehow our cast failed it will return null. let’s check that we are not getting a null value here - . - now let’s add the Length of the line to our list - . - .. Now we should have a list that holds bunch of number values. Each value represents a length of the detail line. All we have to do now, is sum them all up and return that information to the user. Also, I mentioned before that I am interested in returning that info not only in imperial units of length but also in metric. This will require a few extra lines of code but it’s easy enough to cover here: Here’s the line by line breakdown: - here we build a string that will read out total length in ft. I also add a Math.Round method to round our results to two decimal places. - here we build a string that will read out total length in meters. Since all values returned by Revit are always in ft we have to add a * 0.3048 to convert from ft to m. - same as above but this time we convert to mm. - same as above but this time we convert to inch by multiplying by 12. - . - we create a new instance of String Builder. String Builder is an object that can be used to quickly concatenate bunch of strings into one continues string. - first we append “Total Length is: ” to string builder. - then we append a new line that has our total length in ft. - then we append a new line that has our total length in inches. - then we append a new line that has our total length in meters - finally we append a new line that has our total length in mm - . - last step of our code is to show the results to user. We can use a very simple TaskDialog object to do that. It will show a simple message window to the user that will contain our StringBuilder object converted to string. This should be it. Here’s all of our code for this example: Now if we Build this and again replace the DLL file with the latest one, this should be our result in Revit: This is it! If you stuck around with me, for this long, you were just able to build your first Revit plug-in. I am thinking about extending this into a series, and next time going over taking our External Command addin and showing you guys how to add it to a larger set of tools. I would like to show you how to create your own tab on Revit ribbon, add buttons and proper icons for your own tool-set branding. Since I already shared a small tool, called Legend Duplicator few weeks ago, it will be easy to take these two and put them together under our own tab in Revit. Final DLL and Addin files can be downloaded from here:CurveTotalLength (192 downloads) Thanks for following! Just finished the first three lessons on this, and after a little stumbling around, got my line length totals working! Thanks for taking the time to put this together. (Only real struggle was where we’d jump to a new section of code, trying to figure out where to pick up, but I think that’s with my lack of knowledge of C# structures. The ‘complete’ code at the bottom was my road map.) Glad you got it to work. Cheers!
http://archi-lab.net/building-revit-plug-ins-with-visual-studio-part-three/
CC-MAIN-2017-13
refinedweb
1,217
80.21
Asked by: IIS 6.0 ASP application bogs down despite free CPU & free memory Question - User-1653953264 posted OK, here is the configuration: Quad Core Xeon, 4GB RAM, 500GB sata running Win2K3 R2 / IIS 6.0. This server is also running a mail server and SQL Server 2000 is running as the backend for the ASP app. During a high traffic time I started to notice the browser requests were being serviced very slowly. I did some investigating and here is what I found: 3000+ concurrent users, well, 3000+ session were active, the server has a 20 min timeout. IIS had about 250MB of memory, SQL Server had about 1.7GB of memory. The CPU(s) never got over 50%. Yet with plenty of free memory and CPU cycles, the web requests were not being handled quickly. I did a recycle on IIS which booted all sessions but shouldn't affect SQL Server and suddenly the web requests started being handled quickly again, so this defiitely looks IIS related. I had upgraded from a P4 server which was pretty robust but would simply max out on CPU during these high traffic times, so now I have a more powerful server but seem to be getting limited elsewhere. I was unfamiliar with the Web Garden feature in IIS 6.0, read about it and it sounded great, so I made the mistake of adding some worker processes to my classic ASP app. Bad idea! User sessions started getting dropped because the processes don't share session data! I quickly went back to a single worker process. The app consists of a single index.asp file with many #include files which are conditionalized based on a page querystring variable, so I assume IIS sees this as one HUGE file. I figured that this may not be so bad because IIS could cache this one large file which is really the only page being accessed. I hope my assumption is true. Should I be using different ASP File cache option settings? Currenlty I have Cache limited APS files in memory set to 500 and Cache limited ASP files on disk set to the 2000. Number of script engines cahced is 250. These OK? This app uses it's own app pool and I have since adjusted my Request queue limit from 1000 to 8000 thinking that maybe this limit was bottlenecking this more powerful processor. I don't want to do too much recycling because with 3000 users, bumping them will simply cause a rush as they try to log back in. I figured that with the extra resources this server has, maybe if I find a way to spread these requests across a web garden that I'd make better use of resources. Since I can't use a web garden, I got the idea of creating subdomains for the same website www, www2, www3, etc. all pointing to the same app using the same SQL Server database. Now each would get it's own w3wp.exe process like a web garden. I'd simply round robin distribute my visitors across these subdomains. Two problems with this though, 1. I have a secure page which has to be on a specific subdomain and if I transfer users from another subdomain to the secure page, then their session will be lost. 2. A minor issue but my web logs will now be spread across 4 subdomains... unless there is a way to combine. Is this idea a good way to go? Sorry for the long post!!! Hopefully someone will have some insight and someone else will be helped by this information! Thanks...Tuesday, September 9, 2008 1:09 AM All replies - User844605415 posted What is the bitness of the OS? How about disk usage and network utilization during the high traffic time? Thanks, Mukhtar Desai IIS Performance TeamTuesday, September 9, 2008 2:21 AM - User-1653953264 posted OS is 32 bit but it's a quad core xeon and motherboard supports visibility of full 4GB of RAM. I checked disk utilization and didn't look like it would be limiting. Network bandwidth was very high but I my hosting provider provides good bandwidth and the server isn't throttled in anyway. Also, as I mentioned, when I restarted IIS, requests started happening quickly again, so it did seem related to the number of session or the number of requests overtime causing lack of resources for the worker process. Tuesday, September 9, 2008 4:09 AM - User989702501 posted Looks like hardware bottlenecks to me, can you do some performance analysis to look at ASP - request executing, in queue, etc. NLB is a good choice for you, say move out the SQL, then have 2 nodes NLB of IIS infront, with sticky session, no need to worry about the client sesion running around the two nodes, it will stick until the session end / expired.Tuesday, September 9, 2008 4:52 AM - User-823196590 posted What does the application do? Are you following good ASP coding practices (i.e. not putting db objects into session vars)? Any chance you could offload SQl to another box, at least for testing?Tuesday, September 9, 2008 8:26 AM - User-2064283741 posted First off don't use web gardens. 99.99% of the time there is no need for them. Really they are only good for a short term fix for certain coding issues. Is it just slow? How slow is 'slow'? The memory consumption of SQL looks high what is it doing there? Do a trace on your SQL server box and see if there is a bottleneck there. Run performance stats on the SQL server look out for locks, latches, etc. Compare this to your baseline stats for when the server was last know to be working well. What has changed? If you are getting trafic like 3000+ concurrent users then I would look at least tiering your setup - so have your SQL on another box. When it is slow can you perform an typical SQL query like in your app - compare the speed peak and off peak. But depending on your setup it could well be your mail server (although I would expect to see an increase in your CPU) I had to move mail of one of our budget mass hosters to another box as this was affecting the websites. Do you get any errors at all in your IIS logs in these busy times? It could be that you rare running out of TCP/IP connections. Maybe there are other factors like you mail, etc eating up all those TCP connections. I think Windows 2003 has 6000 (or is it 8,000) by default but that is total connections for all apps not just the obvious ones in IIS. If it is this you will see server busy type HTTP staus error messages. Also related to this do you have anything in the http sys error log? It could be asp as otehr have said look out for queues, etc there. Tuesday, September 9, 2008 9:39 AM - User-1653953264 posted What does the application do? Are you following good ASP coding practices (i.e. not putting db objects into session vars)? Any chance you could offload SQl to another box, at least for testing? Well, the application is a website... I call it an application because that's the way I think of it. I started coding it years ago and have hit most of the poor coding practice bumps and made corrections. No db objects in session vars, minimal use of session vars except to maintain a few user state variables consisting of integer values or short strings. I have clean-up code that runs at the end of every page to close DB connections and set record sets to nothing, etc. I can't easily move SQL to another box but what I can do and tried to do a bit of during the heavy traffic time was connect my dev machine to the SQL Server on the busy box using the IIS and the copy of the website on the dev box. I need to do some more testing during the next rush, but I don't believe I saw slow downs on the dev box which means I had a lightly loaded IIS paired with a heavily loaded SQL Server 2000 which seemed to be OK. I'm going to try this config during the next big rush. There is some pretty heavy disk activity going on. I have some pages with active content that updates periodically. To enhance performance, when and update occurs, I redraw the page and store the content to disk using a file system object. During the time inbetween updates, I just read from the disk file using a file system object and response.write instead of the other processing that would normally do to generate the page. Basically, I wrote a custom disk caching system for a couple of heavily hit pages on the site. These pages can be unique among groups of users, so I can have a several thousands of these pages being read from disk or being written during updates. This never was an issue on the old server. I have the ability to turn this feature off which would cause these pages to always be generated dynamically. This, in theory, should make the disk I/O go way down and the CPU usage go up, by how much, I don't know. With this upgraded hardware maybe the benefit of using the disk on the old system is now outweighed by the power of the processor in the new system meaning that now the Disk I/O is the bottleneck where on the old system, the CPU was. Hmmmm. This is very easy for me to test by switching a flag. I'll definitely try this.Tuesday, September 9, 2008 6:04 PM - User-1653953264 posted In reply to Rovastar: Hmmm... I read articles about resource contention which made using several worker processes sound appealing, but I can't use web gardens anyway since this is Classic ASP... I found out the hard way! It is just slow. Slow means several seconds, up to 10 seconds or more for a simple ASP page. I have one page where I show a flash "Processing" animation and then redirect to the actual page content. The page with the flash on it is very simple. I actually had a 10 second pause getting to that page rather than the actual page that had heavier processing. The SQL Server has tables, stored procedures, views. During these updates, some stored procedures are running, some using table variables which consume memory. I actually wasn't so surprised by the memory consumption of SQL Server as I was by IIS. IIS had well over 200MB. On the old server, I never saw it get over 150MB. Great suggestion about checking the SQL querys during these busy times. I didn't do it while it was happening because at the time, it really didn't seem like SQL was the bottle neck based on my test using the dev box running IIS and the same web site connecting to the busy box's SQL Server. Regardless, I'll give this a try. Regarding the Mail Server, I was concerned about it, but it really wasn't taking up much of the CPU cycles. I need to check the IIS logs, another good suggestion. I personally didn't see any Server Busy error pages but that doesn't mean other users didn't. How will I know if I've reached the TCP connection limit? The HTTP status error messages will appear in the system event log or in the IIS logs? Where do I adjust the connection limit? Is this a good idea? Did see anything else in the event logs. I'm looking through the IIS logs now. If I find anything I'll post. Thanks for the tips!Tuesday, September 9, 2008 6:27 PM - User-2064283741 posted Maybe it is not the database but worth checking. Nothing in the http error log? C:\WINDOWS\system32\LogFiles\HTTPERR That is processing http requests before getting to IIS log files. Here is a link where it explain about the TCP/IP connection limits in Windows 2003 See my post at the bottom - it is (5,000-1,024 nearly 4,000) maximum TCP connections on Windows 2003 And see here I cannot remember what http status/error message you get but look for anything not a success and investigate that (so any 4xx or 5xx errors in that time) When having a lot of concurrent connections. Also use perfmon to see how many concurrent connections you have and use the max counter value as well this will tell you the max amout you have had since last reboot. I always get a little concern when people have say 3,000+ connections on a single box there are a lot of others things to consider and more loops to jump through to get a smooth running system - hence why I (and others) recommend additional servers. ALthough WIndows/IIS can cope with more you have to tweak it some. I am not saying that this is your problem but you should look at this especially as normally websites increase in traffic/concurrent connections over time and the higher numbers means more potential problems if you are not used to those sort of environments. Ask yourself/your clients is it better to spend money now on new kit/infrastructure or risk have it fall over and then try and fix problems when you are really busy/successful. A downed website is not good for business.Wednesday, September 10, 2008 9:05 AM - User-1653953264 posted OK... I'm monitoring the busy traffic now. I have one browser with my site at the standard subdomain www, another browser at the subdomain www2 which should now get it's own IIS process, and a third browser which is opened to localhost with a copy of the website on it but connecting to the same, busy remote server. This should show whether a different IIS process is as slow as the busy process and whether or not the slowdowns are coming from IIS or SQL Server. I see slowness and so far, perfmon looks OK... I hope I'm tracking the right stats. I'll see how things going with these browser tests.Sunday, September 14, 2008 11:59 AM - User-1653953264 posted OK, I can say definitively that this problem seems to be with IIS. Both the localhost AND the www2 subdomain perform nicely while the www subdomain is very unresponsive to requests for the exact same page. I created another website in IIS for the www2 subdomain pointing to the exact same directory that the default www site points to and created it's own Application Pool. This way, I can test to see if it is IIS related only. Both of these are still pulling data from the same database and any disk I/O related issues will be shared since they are on the same box. So one IIS process is slow and the other is not which seems to point to IIS getting bogged down despite having plenty of resources. Any ideas? What can I check??Sunday, September 14, 2008 12:08 PM - User-1653953264 posted Clearly I'm not benefitting from the availability of the Quad Core Xeon and splitting up the processes helps in this case. But I'm not sure why this is an issue. Should the one pocess just use more of the resources? Here are some numbers: Busy w3wp.exe process - 227MB mem usage, 283MB peak mem usage. Perfmon numbers: ASP Server Pages - Requests Executing Avg 91, Max 98 duration 1:40, Requests Queued Avg 408, Max 508, Request Rejected 0, Request/sec Avg 28, Max 152, Sessions Current 2319, Max 2339 Memory - Pages/sec Avg 1.1, Max 41.966 Physical Disk Total - Avg Disk Queue Length Avg 104, Max 294 Processor Total - % Processor Time Total - Avg 11%, Max 66% SQL Server:Database - Active Transactions Avg 5, Max 9, Transactions/sec Avg 36, Max 170 SQL Server:General Stats - User Connections Avg 104, Max 107Sunday, September 14, 2008 12:45 PM - User-1653953264 posted dear god man... what a horrendous day.... I read an article about AspProcessorThreadMax in IIS 6.0. It menation about increasing the number of worker threads from the default of 25 to 50. This sounds like it could be related to what I'm seeing. The CPU usage is not maxing out, there is free RAM available, yet the server is very unresponsive. I have seen some times where the request queue was high and the requests excuting was low. Doesn't this mean that IIS simply can't catch up? Even the numbers above for Active Server Pages show that. I've bumped the AspProcessorThreadMax to 50 but my traffic has died down right now. This is horrible. Processing power to spare and I really don't know where things were getting choked. At least on my old server, it was clear that the CPU was the limiting factor. Any thoughts?Sunday, September 14, 2008 9:03 PM - User989702501 posted Well, asp queue is very high, while you are maxing on the asp executing, 25 x 4 = 100, and you getting 9X, so it is doing its job. Next, I would look at long running query, the one that stuck in the executing queue for so long and force the request queue to jam up. Take a look at the time taken field in the log file, use log parser to help.---Ch02Top10WebRequests.sql--- <?xml:namespace prefix = o<o:p></o:p>SELECT <o:p></o:p> TOP 10 <o:p></o:p> STRCAT(EXTRACT_PATH(cs-uri-stem),'/') AS RequestPath, <o:p></o:p> EXTRACT_FILENAME(cs-uri-stem) AS RequestedFile, <o:p></o:p> COUNT(*) AS Hits, <o:p></o:p> MAX(time-taken) AS MaxTime, <o:p></o:p> AVG(time-taken) AS AvgTime, <o:p></o:p> AVG(sc-bytes) AS AvgBytesSent <o:p></o:p>FROM %source% TO %destination% <o:p></o:p>GROUP BY cs-uri-stem <o:p></o:p>ORDER BY MaxTime, TotalHits DESC <o:p></o:p>---Ch02Top10WebRequests.sql--- <o:p></o:p> Damn... the IIS Insider archive screwed up, the Sep 2006 was missing. that was the last IIS insider column published. sigh. Run the above viaC:\LogParser\Samples>Logparser.exe file:Ch02Top10WebRequests.sql?source=”<//localhost/w3svc/1>”<o:p></o:p> +destination=”Top10WebRequests.txt” -o:NAT check if you have high process time request, look inside the scripts and do time-stamping or each function or data call, etc. next, you want wan to try iis debugdiag to see if it capture more valuable info to help you identify what's wrong.Monday, September 15, 2008 2:03 AM - User-1653953264 posted Hmmm... not really sure I followed all of that. Are you saying I need to figure out which page requests are running slowly causing the queue to back up? If so, I can try that. But again, it seems that on my system where I have quite a bit of spare memory and CPU cycles that things are getting choked off by some other limiting factor. That's why I raised the AspProcessorThreadMax from 25 to 50. I've also created www2, www3, and www4 each as their own website in IIS to spread users across 3 extra w3wp.exe processes, kind of like a web garden for ASP where they're session will be maintained for that process. I've implemented some code to round robin users who first hit to be sent to www, www2, www3, or www4 and stay there. I'll be able to turn this on and off at will. Thoughts??Monday, September 15, 2008 9:01 AM - User-931036931 posted Hey lkevinl, we are having somewhat the same issue, "IIS 6.0 ASP application bogs down despite free CPU & free memory" did changing AspProcessorThreadMax from 25 to 50 help ? did you manage to find a solution.. ThanksMonday, June 8, 2009 1:48 PM - User891286420 posted Hi All, we're also experiencing the same issue. Did either of you guys (lkevinl, or Dublin) get closer to solving the problem? Thanks in advance! Thursday, November 12, 2009 2:25 PM - User989702501 posted You might want to start a new thread and post your setup info, problem symptom etcSaturday, November 14, 2009 1:30 AM
https://social.msdn.microsoft.com/Forums/en-US/988272bf-db55-41f1-a9e9-89d8c10365b0/iis-60-asp-application-bogs-down-despite-free-cpu-amp-free-memory?forum=iis56classicasp
CC-MAIN-2021-49
refinedweb
3,452
71.34
Sep 14, 2014 04:21 AM|klbaiju|LINK Hi, I have developed an application in .net.it is working fine in local server.after uploading to online server and test. there is an error showing in web.config. following is. Member 610 Points Sep 14, 2014 04:25 AM|arindamnayak|LINK This is not error in web.config, your setting looks good. But the page you are browsing is getting error, so you need to check that page error first. Member 610 Points Sep 14, 2014 08:55 AM|arindamnayak|LINK Can you test the same web application in production/remote/deployed server. That you will help to resolve this problem. Note: After you change web.config to customerrormode = off, it is not still showing error message , if browsed deployed website ==> then, are you changing that in correct file. All-Star 23975 Points Sep 15, 2014 03:19 AM|Starain chen - MSFT|LINK Hi klbaiju, By default, there isn’t index.aspx file list in the Default Document. Set the startup page in your local application (In VS), it won’t affect the default page in the server. Please refer to this article to set the default document: # Default Document <defaultDocument> Best Regards Starain Chen All-Star 48920 Points Sep 16, 2014 09:12 AM|PatriceSc|LINK Hi, klbaijumy online application will work only if i removed klbaijuif i remove this some namespace will not work So it seems you go past a particular error but then bump into some other errors when doing that? What is the Framework you are supposed to use and make sure this version is available server side as well (.NET 4.5 should be able to run .NET 4.0 App, could it be that server side you don't even have 4.0 but an earlier Framework ??). Rather than a vague description such as "some namespace will not work", always state the actual error message (or the best English translation) so that we known what happens. It's easier to fix a problem when knowing exactly what is the problem. All-Star 23975 Points Sep 16, 2014 10:14 PM|Starain chen - MSFT|LINK Hi klbaiju, For this issue, please make sure the application pool’s .Net Framework version is v4.0, which is used for that website. Best Regards Starain Chen 7 replies Last post Sep 16, 2014 10:14 PM by Starain chen - MSFT
https://forums.asp.net/t/2008873.aspx?Error+showing+in+web+config+in+online+application
CC-MAIN-2021-25
refinedweb
403
73.58
PictureCard / React Displays a card with a picture and space for information and actions. To implement PictureCard component into your project you’ll need to add the import: import PictureCard from "@kiwicom/orbit-components/lib/PictureCard"; After adding import into your project you can use it simply like: <PictureCard image={{ original: "385x320", code: "dubai_ae", name: "Dubai Arab Emirates", placeholder: "385x320", }} Props Table below contains all types of the props available in PictureCard component. Image Table below contains all types of the props available for object in Image ImageCustom Table below contains all types of the props available for object in Image Functional specs You don’t have to pass entire src of the image. Just dubai_ae, paris_fretc. is enough. OnClickis also called on Enterand Spacekeypresses. For usage with server-side rendering (SSR), a placeholder can be emitted for it to work correctly. This is a React issue see more on this and. Lastly if you are using Next.js you can do this workaround with dynamic import set to SSR false. const PictureCard = dynamic({ loader: () => import('PictureCard'), loading: () => <Placeholder />, ssr: false, });
https://orbit.kiwi/components/picturecard/react/
CC-MAIN-2020-50
refinedweb
181
54.02
my question is: Write, compile, and run a C++ program to do the following: 1. Declare and initialize a character array named hurray as hurray[ ] = “Hooray for All of Us”. (Such initialization will ensure that the end-of-string escape sequence \0 is included as last entry in the array.) 2. Display the characters in the array using while loop and displaying one character at a time. Note: You need to declare a pointer variable named hurrayptr, initialize it appropriately, and then use (*hurrayptr++ != ‘\0’) 3. Count the number of elements in the array. Using the count to write a for loop to find the position of letter A in the array hurray. And here is the code: // Include Files #include <iostream> // used for cin, cout #include <curses.h> #include <cmath> #include <cstdlib> #include <cstring> using namespace std; int counter ( char* ); //Global Variables int main(void) { //Declaration Section char hurray[]="Hooray for all of us"; char *hurrayptr = hurray; int count=0, position; *hurrayptr--; // taking pointer back to one more position so that it should display characters properly in the loop. // NOTE: pointer is current at -1th position, next time in the loop, *hurrayptr++ will bring it to 0th position and it will then only //print the first character, otherwise it will skip the first character. count = counter ( *hurrayptr ); // sending the pointer to the function // counting total characters count-=1; // subtract one from returned count because function also counts the NULL '\0' character cout<<"\n\n Total characters: "<<count; // showing the positions of 'A' cout<<"\n\n\n"; // setting count to 0 again count=0; for( *hurrayptr = hurray; *hurrayptr!='\0'; *hurrayptr++) { if(*hurrayptr=='a' || *hurrayptr=='A') // Every time 'a' is encountered, the position (count) up to that will be printed cout<<endl<<"'A' is at position: "<<count; count++; } getch(); } // Count length of array function int counter( char *hptr ) { int count=0; //Specific conditions present in question while ( *hptr++ != '\0') { cout<<*hptr; count++; } return count; } but it is not running.. nd here is the result. can you plz tell me the error? my question is:
https://thenewboston.com/posts.php?user=78477&post=58556
CC-MAIN-2017-17
refinedweb
343
59.53
Funny differences between Mysql and Postgresql I hope someone can explain these funny differences between Mysql and Postgresql. (Yes, see update below.) Here’s an easy one… What is 11/5? select 11/5; What should a SQL engine answer? Anyone knows? I could check as I used to be a member of the “SQL” ISO committee, but I’m too lazy and the ISO specs are too large. Mysql gives me 2.20 whereas Postgresql gives me 2 (integer division). It seems to me like Postgresql is more in line with most programming language (when dividing integers, use integer division). It gets even weirder… how do you round 0.5? I was always taught that the answer is 1. select round(0.5); Mysql gives me 0 (which I feel is wrong) and Postgresql gives me 1 (which I feel is right). On both counts, Mysql gives me an unexpected answer. (The color scheme above for SQL statements shows I learned to program with Turbo Pascal.) Update: Scott gave me the answer regarding Mysql rounding rule. It will alternate rounding up with rounding down, so select round(1.5); gives you 2 under Mysql. The idea is that rounding should not, probabilistically speaking, favor “up” over “down”. Physicists know this principle well. Joseph Scott also gave me the answer, and in fact he gave me quite a detailed answer on his blog. I think Joseph’s answer is slightly wrong. I don’t think Mysql uses the standard C librairies because the following code: #include <cmath> #include <iostream> using namespace std; int main() { cout << round(0.5) << endl; cout << round(1.5) <<endl; } outputs 1 and 2 on my machine (not what Mysql gives me). MySQL likely to expect the kin… Trackback by Joseph Scott's Blog — 8/11/2004 @ 21:40 Regarding the rounding of 0.5, I was also taught that it should round to 1. But what about 1.5? I would guess that Daniel was taught that it rounds to 2; I was taught that it also rounds to 1. I learned this in lab courses in undergraduate physics. The general rule was (is) that if the digit to the immediate left of the positition being rounded is even, round up; otherwise round down. The rationale is that otherwise, on average, you will end up rounding up more often than down, skewing results slightly. Comment by Scott — 9/11/2004 @ 12:20 Hmm. Should have tried it BEFORE posting the last comment so as to avoid having to post another. It looks to me like MySQL follows a similar rounding rule, but with even/odd reversed: if the preceding digit is odd, round up; otherwise round down. So, for example, 1.5 and 2.5 both round to 2. Comment by Scott — 9/11/2004 @ 12:23 As to why MySQL rounds the way it does, that was directly from the MySQL docs. I didn’t really but it either, but it looks like that is their “official” explanation. Comment by Joseph Scott — 10/11/2004 @ 11:30
http://www.daniel-lemire.com/blog/archives/2004/11/08/funny-differences-between-mysql-and-postgresql/
crawl-002
refinedweb
513
84.37
libvmem man page libvmem -- volatile memory allocation library Synopsis #include <libvmem.h> cc ... -lvmem Memory pool management VMEM *vmem_create(const char *dir, size_t size); VMEM *vmem_create_in_region(void *addr, size_t size); void vmem_delete(VMEM *vmp); int vmem_check(VMEM *vmp); void vmem_stats_print(VMEM *vmp, const char *opts); Managing overall library behavior)); Error handling const char *vmem_errormsg(void); Description Non-Volatile Memory Library. These groups of interfaces are described in the following three sections. Managing Memory Pools To use libvmem, a memory pool is first created. This is most commonly done with the vmem_create() function described in this section. The other functions described in this section are for less common cases, where applications have special needs for creating pools or examining library state. Once created, a memory pool is represented by an opaque pool handle, of type VMEM*, which is passed to the functions for memory allocation described in the next section. VMEM *vmem_create(const char *dir, size_t size); The vmem_create() function creates a memory pool. The resulting pool is then used with functions like vmem_malloc() and vmem_free() to provide the familiar malloc-like programming model for the memory pool. vmem_create() creates the pool by allocating a temporary file in the given directory dir. The file is created in a fashion similar to tmpfile(3), so that the file name does not appear when the directory is listed and the space is automatically freed when the program terminates. size bytes are allocated and the resulting space is memory-mapped. The minimum size value allowed by the library is defined in <libvmem.h> as VMEM_MIN_POOL. Calling vmem_create() with a size smaller than that will return an error. The maximum allowed size is not limited by libvmem, but by the file system specified by the dir argument. The size passed in is the raw size of the memory pool and libvmem will use some of that space for its own metadata. vmem_create() returns an opaque memory pool handle or NULL if an error occurred (in which case errno is set appropriately). The opaque memory pool handle is then used with the other functions described in this man page that operate on a specific memory pool. This function can also be called with the dir argument pointing to a device DAX, and in that case the entire device will serve as a volatile pool. Device DAX is the device-centric analogue of Filesystem DAX. It allows memory ranges to be allocated and mapped without need of an intervening file system. For more information please see ndctl-create-namespace(1). VMEM *vmem_create_in_region(void *addr, size_t size); The vmem_create_in_region() is an alternate libvmem entry point for creating a memory pool. It is for the rare case where an application needs to create a memory pool from an already memory-mapped region. Instead of allocating space from a given file system, vmem_create_in_region() is given the memory region explicitly via the addr and size arguments. Any data in the region is lost by calling vmem_create_in_region(), which will immediately store its own data structures for managing the pool there. Like vmem_create() above, the minimum size allowed is defined as VMEM_MIN_POOL. The addr argument must be page aligned. vmem_create_in_region() returns an opaque memory pool handle or NULL if an error occurred (in which case errno is set appropriately). Undefined behavior occurs if addr does not point to the contiguous memory region in the virtual address space of the calling process, or if the size is larger than the actual size of the memory region pointed by addr. void vmem_delete(VMEM *vmp); The vmem_delete() function releases the memory pool vmp. If the memory pool was created using vmem_create_pool(), deleting it allows the space to be reclaimed. int vmem_check(VMEM *vmp); The vmem_check() function performs an extensive consistency check of all libvmem internal data structures in memory pool vmp. It returns 1 if the memory pool during the check is found to be consistent and 0 otherwise. Cases where the check couldn't be performed, are indicated by a return value of -1. Since an error return indicates memory pool corruption, applications should not continue to use a pool in this state. Additional details about errors found are logged when the log level is at least 1 (see Debugging and Error Handling below). During the consistency check performed by vmem_check(), other operations on the same memory pool are locked out. The checks are all read-only; vmem_check() never modifies the memory pool. This function is mostly useful for libvmem developers during testing/debugging. void vmem_stats_print(VMEM *vmp, const char *opts); The vmem_stats_print() function produces messages containing statistics about the given memory pool. The output is printed using libvmem's internal print_func function (see vmem_set_funcs() below). That means the output typically appears on stderr unless the caller supplies a replacement print_func or sets the environment variable VMEM_LOG_FILE to direct output elsewhere. The opts string can either be NULL or it can contain a list of options that change the stats printed. General information that never changes during execution can be omitted by specifying "g" as a character within the opts string. The characters . See jemalloc(3) for more detail (the description of the available opts above was taken from that man page). Memory Allocation This section describes the malloc-like API provided by libvmem. These functions provide the same semantics as their libc namesakes, but operate on the memory pools specified by their first arguments. void *vmem_malloc(VMEM *vmp, size_t size); The vmem_malloc() function provides the same semantics as malloc(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then vmem_malloc() returns either NULL, or a unique pointer value that can later be successfully passed to vmem_free(). If vmem_malloc() is unable to satisfy the allocation request, a NULL pointer is returned and errno is set appropriately. void vmem_free(VMEM *vmp, void *ptr); The vmem_free() function provides the same semantics as free(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It frees the memory space pointed to by ptr, which must have been returned by a previous call to vmem_malloc(), vmem_calloc() or vmem_realloc() for the same pool of memory. Undefined behavior occurs if frees do not correspond to allocated memory from the same memory pool. If ptr is NULL, no operation is performed. void *vmem_calloc(VMEM *vmp, size_t nmemb, size_t size); The vmem_calloc() function provides the same semantics as calloc(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then vmem_calloc() returns either NULL, or a unique pointer value that can later be successfully passed to vmem_free(). If vmem_calloc() is unable to satisfy the allocation request, a NULL pointer is returned and errno is set appropriately. void *vmem_realloc(VMEM *vmp, void *ptr, size_t size); The vmem_realloc() function provides the same semantics as realloc(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It vmem_malloc(vmp, size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to vmem_free(vmp, ptr). Unless ptr is NULL, it must have been returned by an earlier call to vmem_malloc(), vmem_calloc() or vmem_realloc(). If the area pointed to was moved, a vmem_free(vmp, ptr) is done. If vmem_realloc() is unable to satisfy the allocation request, a NULL pointer is returned and errno is set appropriately. void *vmem_aligned_alloc(VMEM *vmp, size_t alignment, size_t size); The vmem_aligned_alloc() function provides the same semantics as aligned_alloc(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It allocates size bytes from the memory pool and returns a pointer to the allocated memory. The memory address will be a multiple of alignment, which must be a power of two. If vmem_aligned_alloc() is unable to satisfy the allocation request, a NULL pointer is returned and errno is set appropriately. char *vmem_strdup(VMEM *vmp, const char *s); The vmem_strdup() function provides the same semantics as strdup(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with vmem_malloc(), on the given memory pool, and can be freed with vmem_free() on the same memory pool. If vmem_strdup() is unable to satisfy the allocation request, a NULL pointer is returned and errno is set appropriately. size_t vmem_malloc_usable_size(VMEM *vmp, void *ptr); The vmem_malloc_usable_size() function provides the same semantics as malloc_usable_size(3), but operates on the memory pool vmp instead of the process heap supplied by the system. It returns the number of usable bytes in the block of allocated memory pointed to by ptr, a pointer to a block of memory allocated by vmem_malloc() or a related function. If ptr is NULL, 0 is returned. Managing Library Behavior The library entry points described in this section are less commonly used than the previous section. These entry points expose library information or alter the default library behavior. const char *vmem_check_version( unsigned major_required, unsigned minor_required); vmem_check_version() is successful, the return value is NULL. Otherwise the return value is a static string describing the reason for failing the version check. The string returned by vmem_check_version() must not be modified or freed. void vmem_set_funcs( void *(*malloc_func)(size_t size), void (*free_func)(void *ptr), void *(*realloc_func)(void *ptr, size_t size), char *(*strdup_func)(const char *s), void (*print_func)(const char *s)); The vmem_set_funcs() function allows an application to override some interfaces used internally by libvmem. Passing in NULL for any of the handlers will cause the libvmem default function to be used. The library does not make heavy use of the system malloc functions, but it does allocate approximately 4-8 kilobytes for each memory pool in use. The only functions in the malloc family used by the library are represented by the first four arguments to vmem_set_funcs(). The print_func function is called by libvmem when the vmem_stats_print() entry point is used, or when additional tracing is enabled in the debug version of the library as described in the Debugging and Error Handling section below. The default print_func used by the library prints to the file specified by the VMEM_LOG_FILE environment variable, or to stderr if that variable is not set. Debugging and Error Handling Two versions of libvmem are typically available on a development system. The normal version, accessed when a program is linked using the -lvmem option, is optimized for performance. That version skips checks that impact performance and never logs any trace information or performs any run-time assertions. If an error is detected during the call to libvmem function, an application may retrieve an error message describing the reason of failure using the following function: const char *vmem_errormsg(void); The vmem_errormsg() function returns a pointer to a static buffer containing the last error message logged for current thread. The error message may include description of the corresponding error code (if errno was set), libvmem function indicated an error, or if errno was set. The application must not modify or free the error message string, but it may be modified by subsequent calls to other library functions. A second version of libvmem, VMEM_LOG_LEVEL, which can be set to the following values: 0 -). The same information may be retrieved using vmem_errormsg(). 2 - A trace of basic operations including allocations and deallocations is logged. 3 - This level enables a very verbose amount of function call tracing in the library. 4 - This level enables voluminous and fairly obscure tracing information that is likely only useful to the libvmem developers. The environment variable VMEM_LOG_FILE specifies a file name where all logging information should be written. If the last character in the name is "-", the PID of the current process will be appended to the file name when the log file is created. If VMEM_LOG_FILE is not set, output goes to stderr. All prints are done using the print_func function in libvmem (see vmem_set_funcs() above for details on how to override that function). Setting the environment variable VMEM_LOG_LEVEL has no effect on the non-debug version of libvmem. Example. Bugs Unlike the normal malloc(), malloc(3), posix_memalign(3), strdup(3), mmap(2), strerror(3), jemalloc(3), libpmem(3), ndctl-create-namespace(1) and <> Referenced By libpmem(3), libpmemblk(3), libpmemlog(3), libpmemobj(3), libvmmalloc(3), memkind_pmem(3).
https://www.mankier.com/3/libvmem
CC-MAIN-2017-13
refinedweb
2,123
51.99
HyperlinkHyperlink Cool URLs that don't change. Hyperlink provides a pure-Python implementation of immutable URLs. Based on RFC 3986 and 3987, the Hyperlink URL makes working with both URIs and IRIs easy. Hyperlink is tested against Python 2.7, 3.4, 3.5, 3.6, and PyPy. Full documentation is available on Read the Docs. InstallationInstallation Hyperlink is a pure-Python package and requires nothing but Python. The easiest way to install is with pip: pip install hyperlink Then, hyperlink away! from hyperlink import URL url = URL.from_text(u'') utm_source = url.get(u'utm_source') better_url = url.replace(scheme=u'https') user_url = better_url.click(u'..') See the full API docs on Read the Docs. More informationMore information Hyperlink would not have been possible without the help of Glyph Lefkowitz and many other community members, especially considering that it started as an extract from the Twisted networking library. Thanks to them, Hyperlink's URL has been production-grade for well over a decade. Still, should you encounter any issues, do file an issue, or submit a pull request.
https://libraries.io/pypi/hyperlink
CC-MAIN-2018-51
refinedweb
177
61.53
Network Security Tools/Modifying and Hacking Security Tools/Developing Dissectors and Plug-ins for the Ettercap Network Sniffer From WikiContent Ettercap is a network analyzer that is free and open source. Advanced features such as ARP poisoning, packet filtering, and OS fingerprinting, along with support for password dissectors and plug-ins make Ettercap a powerful tool and a favorite among many network administrators. Ettercap has been known to compile on various Unix and Linux flavors, and has been successfully ported to run on Microsoft Windows operating systems. This chapter introduces the concept of writing dissectors and plug-ins for Ettercap. Dissectors allow you to grab important information, such as usernames and passwords, that are transmitted over a network. For the purposes of understanding how to write a dissector, we will step through a dissector that captures and displays FTP usernames and passwords. Then, to demonstrate how to write an Ettercap plug-in, we will step through a plug-in that alerts the user when one host on the network attempts to establish a new TCP connection with another host. Installing and Using Ettercap The latest Ettercap source code is available from. Grab the latest tarball and compile Ettercap: [notroot]$ tar zxvf ettercap-NG-x.y.z.tar.gz [notroot]$ cd ettercap-NG-x.y.z [notroot]$ ./configure [notroot]$ make [root]# make install Warning Make sure you obtain and install an Ettercap version that is equal to or greater than 0.7.0. Ettercap APIs of versions older than 0.7.0 differ significantly, and are no longer supported. You can run Ettercap in console mode, curses mode, or GTK mode, the latter of which is shown in Figure 2-1. Run ettercap -h to discover the plethora of options and features Ettercap provides. See the ettercap manpage for more details on available options and features. Tip The Ettercap web site consists of a publicly available message board dedicated to providing support in case you experience problems. Access the message board by visiting. Writing an Ettercap Dissector A dissector captures protocol-specific information from the network. Most Ettercap dissectors are designed to capture usernames and passwords transmitted over the network in real time. Here is an example of how to run Ettercap in console mode to sniff passwords: [root]# ettercap --text --quiet ettercap NG-0.7.0 copyright 2001-2004 ALoR & NaGA Listening on en0... (Ethernet) eth0 -> 00:0B:25:30:11:B 192.168.1.1 255.255.255.0 Privileges dropped to UID 65534 GID 65534... 0 plugins 39 protocol dissectors 53 ports monitored 6312 mac vendor fingerprint 1633 tcp OS fingerprint 2183 known services Starting Unified sniffing... Text only Interface activated... Hit 'h' for inline help FTP : 10.0.0.1:21 -> USER: john PASS: try4ndgu355m3!! In the preceding example, the FTP dissector successfully sniffed the FTP password try4ndgu355m3!! of user john logged on to an FTP server running on host 10.0.0.1. In the following paragraphs, we will discuss the dissector responsible for capturing FTP usernames and passwords. First we will discuss the FTP authentication mechanism, followed by a detailed analysis of the FTP dissector source code. Overview of FTP Authentication This section discusses how FTP performs authentication. We need to understand this before we step through FTP dissector source code for Ettercap. FTP is a plain-text protocol, and it uses no encryption. FTP servers listen on TCP port 21 by default. To authenticate with an FTP server, the client establishes a connection to TCP port 21 and expects a banner that is preceded with 220: 220 Welcome to The banner string is irrelevant and can be changed by the FTP server administrator. By default, banner strings of some FTP servers provide the FTP server name and version number. With respect to the Ettercap dissector, we are concerned with only the 220 response code, which signifies that the FTP server is ready to serve further requests. To authenticate with the FTP server, a client sends the USER command followed by the user's username: USER john If the FTP server is ready to authenticate the user, it responds with a 331 response code: 331 Please specify the password. Next, the FTP client sends the PASS command followed by the user's password: PASS try4ndgu355m3!! If the supplied password is correct, the FTP server responds with a 230 response code: 230- Welcome to 230 Login successful. The outcome of a request to an FTP server depends mainly on the first digit of the three-digit response code. Table 2-1 lists FTP response codes and their meanings, based on the first digit of the code. Table 2-1. FTP response codes Because FTP is a plain-text protocol, you can use a telnet client to connect to the FTP server and test the authentication mechanism. Here is an example: [notroot]$ telnet 21 Trying 192.168.1.2... Connected to. Escape character is '^]'. 220 Welcome to. USER john 331 Please specify the password. PASS try4ndgu355m3!! 230- Welcome to 230 Login successful. Tip For more details on the FTP protocol, see RFC 959, available at. The FTP Password Dissector The FTP dissector's goal is to analyze FTP traffic on the network to obtain and display FTP usernames and passwords. The dissector, ec_, is located in the src/dissectors directory of the Ettercap source tree. The first few lines of the code use the include directive to include required header files for writing dissectors: #include <ec.h> #include <ec_decode.h> #include <ec_dissect.h> #include <ec_session.h> Prototypes for defined functions are declared next. We will discuss these functions in the next few paragraphs. FUNC_DECODER(dissector_ftp); void ftp_init(void); The ftp_init( ) function adds an entry into appropriate Ettercap data structures by invoking the dissect_add( ) function: void _ _init ftp_init(void) { dissect_add("ftp", APP_LAYER_TCP, 21, dissector_ftp); } Note that the _ _init macro is defined in ec.h as: #define _ _init _ _attribute_ _ ((constructor)) The _ _attribute_ _((constructor)) directive causes all functions to be invoked before main( ). Therefore, the ftp_init( ) function is automatically invoked when the ettercap executable is run. The dissect_add( ) function should be called by every dissector because it is used to add an entry into dissect_list, a structure used by Ettercap to manage enabled dissectors. The function prototype for dissect_add( ) is: void dissect_add(char *name, u_int8 level, u_int32 port, FUNC_DECODER_PTR(decoder)) Parameters accepted by dissect_add( ) are described in Table 2-2. Table 2-2. Parameters for dissect_add( ) Notice that the last parameter to dissect_add( ) is dissector_ftp. This designates the dissector_ftp( ) function as the entry point to the dissector code whenever traffic on TCP port 21 is captured. The FUNC_DECODER( ) macro is used to define dissector_ftp: FUNC_DECODER(dissector_ftp) The FUNC_DECODER macro is just a wrapper around dissector_ftp that defines it as a pointer. This is useful because, as we previously noted, dissector_ftp is passed to dissect_add( ), whose last parameter accepts only a pointer to a function. Because dissector_ftp( ) is invoked every time a packet on TCP port 21 is captured, DECLARE_DISP_PTR_END( ) is called to set ptr to point to the beginning of the data buffer, and end to point to the end of the buffer: DECLARE_DISP_PTR_END(ptr, end); Dissectors in Ettercap need to keep track of individual TCP connections. You initiate a TCP connection by sending a TCP packet with the SYN flag set, followed by a response TCP packet from the server that contains the SYN and ACK flags set. Therefore, the FTP dissector calls CREATE_SESSION_ON_SYN_ACK() , which creates a new session for the connection as soon as a packet with the SYN and ACK flags set is captured: CREATE_SESSION_ON_SYN_ACK("ftp", s, dissector_ftp); The first parameter to CREATE_SESSION_ON_SYN_ACK( ) indicates the name of the dissector, which in our case is ftp. The second parameter to CREATE_SESSION_SYN _ACK( ) is s, which is a pointer to the ec_session structure defined in ec_session.h. This structure holds individual session data, and is therefore used to keep track of individual TCP connections. The first TCP packet sent from the FTP server most likely contains the banner, including the 220 response code, and this is analyzed by calling the IF_FIRST_PACKET_FROM_SERVER() function. The IF_FIRST_PACKET_FROM_SERVER( ) macro expects the block to end with ENDIF_FIRST_PACKET_FROM_SERVER( ) : IF_FIRST_PACKET_FROM_SERVER("ftp", s, ident, dissector_ftp) { DEBUG_MSG("\tdissector_ftp BANNER"); if (!strncmp(ptr, "220", 3)) { PACKET->DISSECTOR.banner = strdup(ptr + 4); if ( (ptr = strchr(PACKET->DISSECTOR.banner, '\r')) != NULL ) *ptr = '\0'; } } ENDIF_FIRST_PACKET_FROM_SERVER(s, ident) The ident parameter is a void pointer, and is assigned to a new session identifier of type struct dissect_ident . As the name suggests, ident is used to identify sessions. PACKET is a global structure of type struct packet_object . It holds the actual network packet data. (See ec_packet.h for the definition of packet_object.) Using strncmp() , the FTP dissector code looks for the string 220 within the first three characters pointed to by ptr because 220 is sent by an FTP server upon connect, followed by the FTP server banner. PACKET->DISSECTOR.banner is then set to the banner of the FTP server, which is basically everything after the 220 string. Next, strchr() is used to point ptr to the end of the banner by searching for the \r character. The dissector makes sure to skip packets that contain no data. These packets are mainly ACK TCP packets that serve only as acknowledgments: if (PACKET->DATA.len == 0) return NULL; The FROM_SERVER macro is used to skip all subsequent packets from the server. After having obtained the 220 server string and banner, we do not care about any data coming from the FTP server. From there on, the dissector is concerned only with username and password data that is transmitted to the server: if (FROM_SERVER("ftp", PACKET)) return NULL; Whitespace in the beginning of packet data is skipped: while(*ptr == ' ' && ptr != end) ptr++; If ptr points to end, there is no more data to analyze, so the dissector returns: if (ptr == end) return NULL; The dissector uses strncasecmp() to look for the USER command sent by the FTP client to the server to capture the FTP username: if (!strncasecmp(ptr, "USER ", 5)) { DEBUG_MSG("\tDissector_FTP USER"); dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_ftp)); ptr += 5; SAFE_FREE(s->data); s->data = strdup(ptr); s->data_len = strlen(ptr); if ( (ptr = strchr(s->data,'\r')) != NULL ) *ptr = '\0'; session_put(s); return NULL; } The DEBUG_MSG( ) macro prints the given string to a designated debug file if Ettercap is compiled with the --enable-debug option. If Ettercap is unable to write to the debug file, the message is printed to stderr, which causes most Unix and Linux shells to output to the console by default. Note that the FTP dissector uses the session pointer(s) returned by CREATE_SESSION_SYN_ACK() to invoke IF_FIRST_PACKET_FROM_SERVER() , which requires a session pointer as its second parameter. However, the dissector creates a brand-new session in the preceding block when Ettercap is started after the FTP connection is established, in which case the banner and SYN+ACK packet would have already been sent and never been seen by the dissector. The dissector advances ptr by 5 to skip the USER command followed by whitespace, so now ptr points to the username sent by the FTP client. The SAFE_FREE( ) macro invokes free( ) to free data only if the data is not null. The session pointer's data and data_len items are set to the username string contained in ptr, and its length. Next, session_put( ) is invoked to store the session pointed to by s. This session is retrieved by the following if block, which attempts to capture the password sent by the FTP client. The strncasecmp() function compares the first five characters of ptr with the PASS string, which signifies that the FTP client has sent the user password to the server: if ( !strncasecmp(ptr, "PASS ", 5) ) { DEBUG_MSG("\tDissector_FTP PASS"); ptr += 5; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_ftp)); if (session_get_and_del(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) { SAFE_FREE(ident); return NULL; } if (s->data == NULL) { SAFE_FREE(ident); return NULL; } PACKET->DISSECTOR.user = strdup(s->data); PACKET->DISSECTOR.pass = strdup(ptr); if ( (ptr = strchr(PACKET->DISSECTOR.pass, '\r')) != NULL ) *ptr = '\0'; session_free(s); SAFE_FREE(ident); DISSECT_MSG("FTP : %s:%d -> USER: %s PASS: %s\n", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), PACKET->DISSECTOR.user, return NULL; } In the preceding code block, ptr is incremented by 5 to point to the password sent by the FTP client, which occurs after the string PASS. The dissect_create_ident( ) function is used to create a session identifier, ident, which is used to invoke session_get_and_del( ) . The session_get_and_del() function obtains the previous session into s, and deletes the session from memory because the dissector no longer needs the session after the current code block. If a previous session is not available, the dissector cannot proceed, and therefore returns after freeing ident. PACKET->DISSECTOR.user is set to the data stored in s->data, which contains the FTP username as set in the if (!strncasecmp(ptr, "USER ", 5)) block. If s->data is not set (null), the dissector returns because we cannot proceed without the FTP username being available. PACKET->DISSECTOR.pass is set to the password sent by the FTP server as pointed to by ptr. The strchr( ) function is used to parse until the end of the password by looking for \r. Next, s and ident are set free because the dissector no longer needs them. The DISSECT_MSG macro is used to display the FTP server IP address and the username and password sent by the FTP client to the FTP server. Once this is done, the dissector simply returns. Tip The source code for the FTP dissector is available in the src/dissectors/ec_ file in the Ettercap source tree. It is written by ALoR and NaGA, authors and maintainers of Ettercap. Writing an Ettercap Plug-in You can enable or disable Ettercap plug-ins on the fly, and therefore you can use them to extend Ettercap functionality on demand. Ettercap comes bundled with a variety of plug-ins that you can find in the plug-ins directory of the Ettercap source tree. The following sections show you how to write find_tcp_conn, a plug-in that detects the initiation of a new TCP connection on the network. The find_tcp_conn Plug-in To establish a TCP connection with a remote host, the source host sends a TCP packet with the SYN flag set to the remote host. If the remote host is listening on a particular port, it responds with a TCP packet with the SYN and ACK flags set. The source host then sends a TCP packet with the ACK bit set to formally establish the TCP connection. This sequence is known as the three-way TCP handshake . Therefore, to detect new TCP connections with other hosts, our plug-in has to analyze the network traffic for TCP packets that have the SYN flag set. The find_tcp_conn plug-in described in the following paragraphs analyzes TCP packets for the SYN flag, and if one is found, it alerts the Ettercap user that a host on the network is attempting to establish a new TCP connection with another host. The find_tcp_conn plug-in alerts the Ettercap user whenever a TCP packet with the SYN flag set is captured. Therefore, the plug-in alerts the Ettercap user even if the server host does not respond to the connection attempt. This plug-in can be useful for noticing when a SYN port-scan is being performed on a network. Warning The find_tcp_conn plug-in will not detect new TCP connections when the host running Ettercap is on a network switch because network switches attempt to segregate network traffic. Therefore, the find_tcp_conn plug-in will detect SYN packets from other hosts only when the host running Ettercap is on a network hub, or when Ettercap is instructed to perform ARP poisoning. Every Ettercap plug-in needs to include ec.h and ec_plugins.h. These files contain required global variables and plug-in APIs. The plug-in uses the packet_object structure defined in ec_packet.h along with various functions defined in ec_hook.h , so these header files need to be included as well: #include <ec.h> #include <ec_plugins.h> #include <ec_packet.h> #include <ec_hook.h> All Ettercap plug-ins should declare plugin_load() , which serves as the entry point of a plug-in. Following is its prototype: int plugin_load(void *); Following is the prototype of find_tcp_conn_init( ) , which is called when the plug-in is enabled, and find_tcp_conn_fini( ), which is called when the plug-in is disabled: static int find_tcp_conn_init(void *); static int find_tcp_conn_fini(void *); The plug-in invokes parse_tcp() when a TCP packet is received. Here is its prototype: static void parse_tcp(struct packet_object *po); The plugin_register( ) function in plugin_load() accepts a structure of type plugin_ops . Following is the definition of find_tcp_conn_ops , which is an instance of plugin_ops:, }; Most of the items defined by find_tcp_conn_ops are self-explanatory. Note that ettercap_version must be set to EC_VERSION. Ettercap uses this value to prevent a plug-in compiled for a different version of Ettercap from attempting to load. The init item declares the function that is called when the user enables the plug-in, and the fini item declares the function that is called when the user disables the plug-in. For example, in the Ettercap GTK frontend, you can enable or disable plug-ins by selecting "Manage the plugins" from the Plugins menu and double-clicking the plug-in names. Following is the definition of plugin_load( ) , which is called when the plug-in is loaded. Users can load a plug-in by pressing Ctrl-O from the GTK frontend and selecting the appropriate plug-in file. int plugin_load(void *handle) { return plugin_register(handle, &find_tcp_conn_ops); } Every plug-in must be assigned a unique handle, which the Ettercap engine generates when it invokes plugin_load( ). As a plug-in author, you simply need to pass handle to plugin_register( ) as its first parameter. The second parameter, find_tcp_conn_ops, is the structure we declared in the previous paragraphs. As we already have seen, this structure defines plug-in details as well as the init and fini items. Following is the definition of find_tcp_conn_init( ) , which is defined as our init function and is called when the Ettercap user enables the plug-in: static int find_tcp_conn_init(void *dummy) { USER_MSG("find_tcp_conn: plugin running...\n"); hook_add(HOOK_PACKET_TCP, &parse_tcp); return PLUGIN_RUNNING; } The USER_MSG( ) macro displays the given string to the Ettercap user. In the case of the GTK frontend, the string is displayed in the lower section of the GUI. In this case, the plug-in displays the string find_tcp_conn: plugin running... to let the user know the plug-in has been enabled. The hook_add() function takes in two parameters. Following is its prototype: void hook_add(int point, void (*func)(struct packet_object *po)) You use the point parameter to decide when the plug-in hook function is to be called. We pass HOOK_PACKET_TCP as the point parameter to hook_add( ) to indicate that we want parse_tcp( ) to be called every time Ettercap captures a TCP packet on the network. (For an explanation of other types of hooking points, see the doc/plugins text file in the Ettercap source tree.) The find_tcp_conn_init( ) function returns PLUGIN_RUNNING, which indicates to the Ettercap engine that the plug-in has initialized successfully. Here is a definition of find_tcp_conn_fini( ) , which is invoked when the Ettercap user disables the plug-in: static int find_tcp_conn_fini(void *dummy) { USER_MSG("find_tcp_conn: plugin terminated...\n"); hook_del(HOOK_PACKET_TCP, &parse_tcp); return PLUGIN_FINISHED; } The hook_del( ) function removes the parse_tcp( ) function as the hook function. After hook_del( ) returns, the Ettercap engine no longer invokes parse_tcp( ) when a TCP packet is received. The find_tcp_conn_fini( ) function returns PLUGIN_FINISHED to indicate to the Ettercap engine that the plug-in finished and can be deallocated. Following is the definition of the parse_tcp( ) function, which is called whenever Ettercap receives a TCP packet:)); } The if block inspects po, which contains the TCP packet captured by Ettercap. If the packet does not have the SYN flag set, L4.flags will not be equal to TH_SYN, and the function simply returns. The L4 structure signifies " Layer 4," also known as the Transport Layer of the OSI model where TCP operates. L3 signifies " Layer 3," also known as the Network Layer" where the IP operates. USER_MSG is invoked only if the previous if block did not return, in which case we can be certain that the captured TCP packet has the SYN flag set. Therefore, we call USER_MSG() to alert the user that an attempt to establish a new TCP connection was detected, as shown in Figure 2-2. The ip_addr_ntoa() function accepts an IP address of type ip_addr as the first parameter and returns a string representation when given a char pointer as its second parameter. Because po->L3.src and po->L3.dst contain the source and destination IP addresses of the packet and are of type ip_addr, the plug-in invokes ip_addr_ntoa( ) to convert them to strings to display them to the user via USER_MSG( ). The ntohs( ) function is passed po->L4.dst as the parameter, which contains the destination port. The ntohs( ) function converts a given value from network byte order to host byte order. This is useful in preserving portability because different CPUs use different byte orders. find_tcp_conn.c The easiest way to compile this plug-in is to make a new directory called find_tcp_conn in the plug-insdirectory in the Ettercap source tree. Then, copy over the Makefile from another plug-in called find_conn, and replace all occurrences of find_conn with find_tcp_conn. Run make, and you will end up with ec_find_tcp_conn.so in the .libs/ directory. To load this plug-in from the GTK frontend, press Ctrl-O and select this file. Press Ctrl-P to go to the plug-in management section, and double-click the "find_tcp_conn" entry to enable the plug-in. Here is the complete source code for find_tcp_conn.c for easy reference: #include <ec.h> /* required for global variables */ #include <ec_plugins.h> /* required for plugin ops */ #include <ec_packet.h> #include <ec_hook.h> /* prototypes */ int plugin_load(void *); static int find_tcp_conn_init(void *); static int find_tcp_conn_fini(void *); static void parse_tcp(struct packet_object *po); /* plugin operations */, }; /* this function is called on plugin load */ int plugin_load(void *handle) { return plugin_register(handle, &find_tcp_conn_ops); } static int find_tcp_conn_init(void *dummy) { USER_MSG("find_tcp_conn: plugin running...\n"); hook_add(HOOK_PACKET_TCP, &parse_tcp); return PLUGIN_RUNNING; } static int find_tcp_conn_fini(void *dummy) { USER_MSG("find_tcp_conn: plugin terminated...\n"); hook_del(HOOK_PACKET_TCP, &parse_tcp); return PLUGIN_FINISHED; } /* Parse the TCP request */)); } Tip See the doc/plugins text file within the Ettercap source tree for a listing and description of other useful plug-in-related function calls.
http://commons.oreilly.com/wiki/index.php?title=Network_Security_Tools/Modifying_and_Hacking_Security_Tools/Developing_Dissectors_and_Plug-ins_for_the_Ettercap_Network_Sniffer&oldid=9244
CC-MAIN-2014-15
refinedweb
3,751
53.81
Amazon CloudWatch metrics for Amazon EBS Amazon CloudWatch metrics are statistical data that you can use to view, analyze, and set alarms on the operational behavior of your volumes. Data is available automatically in 1-minute periods at no charge. When you get data from CloudWatch, you can include a Period request parameter to specify the granularity of the returned data. This is different than the period that we use when we collect the data (1-minute periods). We recommend that you specify a period in your request that is equal to or greater. Amazon EBS metrics Amazon Elastic Block Store (Amazon EBS) sends data points to CloudWatch for several metrics. All Amazon EBS volume types automatically send 1-minute metrics to CloudWatch, but only when the volume is attached to an instance. Metrics Volume metrics for volumes attached to all instance types The AWS/EBS namespace includes the following metrics for EBS volumes that are attached to all instance types. To get information about the available disk space from the operating system on an instance, see View free disk space. Some metrics have differences on instances that are built on the Nitro System. For a list of these instance types, see Instances built on the Nitro System. The AWS/EC2namespace includes additional Amazon EBS metrics for volumes that are attached to Nitro-based instances that are not bare metal instances. For more information about these metrics see, Amazon EBS metrics for Nitro-based instances. Volume metrics for volumes attached to Nitro-based instance types The AWS/EC2 namespace includes additional Amazon EBS metrics for volumes that are attached to Nitro-based instances that are not bare metal instances. For more information about these metrics see, Amazon EBS metrics for Nitro-based instances. Fast snapshot restore metrics AWS/EBS namespace includes the following metrics for fast snapshot restore. Dimensions for Amazon EBS metrics The supported dimension is the volume ID ( VolumeId). All available statistics are filtered by volume ID. For the volume metrics, the supported dimension is the volume ID ( VolumeId). All available statistics are filtered by volume ID. For the fast snapshot restore metrics, the supported dimensions are the snapshot ID ( SnapshotId) and the Availability Zone ( AvailabilityZone). Graphs in the Amazon EC2 console After you create a volume, you can view the volume's monitoring graphs in the Amazon EC2 console. Select a volume on the Volumes page in the console and choose Monitoring. The following table lists the graphs that are displayed. The column on the right describes how the raw data metrics from the CloudWatch API are used to produce each graph. The period for all the graphs is 5 minutes. For the average latency graphs and average size graphs, the average is calculated over the total number of operations (read or write, whichever is applicable to the graph) that completed during the period.
https://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/using_cloudwatch_ebs.html
CC-MAIN-2021-49
refinedweb
477
54.02
3v3 Power. It's easy to get started writing a digital HIGH or LOW to a GPIO pin, but you've got to remember a few things: Assuming you've installed WiringPi2-Python ( pip install wiringpi2 ) then try pasting the following into a .py file: import wiringpi2 as wiringpi HIGH = 1 LOW = 0 OUTPUT = 1 INPUT = 0 wiringpi.wiringPiSetup() wiringpi.pinMode(8,OUTPUT) wiringpi.digitalWrite(8,HIGH) Then run it with: sudo python myscript.py require 'wiringpi2' HIGH = 1 LOW = 0 OUTPUT = 1 INPUT = 0 io = WiringPi::GPIO.new io.pin_mode(9,OUTPUT) io.digital_write(9,HIGH) Connect to the MOSI pin of an ATmega328, Arduino Pin 11, for programming with AVRDude. Make sure your ATmega328 is powered by a 3.3v supply. If you're using 5v, make sure to use a logic-level converter. Connect to the MISO pin of an ATmega328, Arduino Pin 12, for programming with Gordon's modified AVRDude. Make sure your ATmega328 is powered by a 3.3v supply. If you're using 5v, make sure to use a logic-level converter. Connect to the SCK pin of an ATmega328, Arduino Pin 13,. The 5v0 power pins are connected directly to the Pi's power input and will capably provide the full current of your mains adaptor, less that used by the Pi itself. Don't be disuaded by what sounds like a measly low voltage. You can do a lot with this! I regularly use mine to power Arduinos and have even run a small Electroluminescent wire inverter right off the 5v pin! This pin is exactly the same as its 5v companion. Two is better than one, right? There's nothing much more to say about the 5v pin. The Revision 2.0 Raspberry Pi turns all the original "do-not-connect" pins into additional ground. Pay careful attention to where these are, because connecting any outputs or voltage supplies directly to ground will not to your Pi any favours! This pin doubles up as the UART transmit pin, TXD. UART is extremely useful if you want to get into Piduino ( a delightful blend of Arduino and Raspberry Pi ) territory. Hook the RXD up to the Arduino's TXD via a 3.3v <-> 5v logic level converter, and the TXD up to the Arduino's RXD. Personally I avoid using a logic level converter and run my breadboard Arduino on 3.3v. This pin doubles up as the UART recieve pin, RXD. Connect directly to the Reset (RST) pin of an ATmega 328. Pinout isn't meant to be printable, but it's a great quick-reference and a comprehensive starter guide to learning about your Raspberry Pi's GPIO pins. Now that the Raspberry Pi Model B Plus is here, I've updated Pinout with the 14 extra pins you'll find on your shiny new board. Note: While I've placed a gap to visually separate the additional 14 pins on the B+, you wont find this gap on the actual board! The 5v power pins, two of them, provide your project with any current your power adaptor can muster minus that which is used by the Pi itself. 5v power is great for regulating down to 3.3v, which you can then use to power an ATmega that's logic-level compatible with your Pi. If you need more than 5v, driving motors for example, you'll have to find your power elsewhere! At a measly 50mA max current, the 3.3v pin on the Raspberry Pi isn't terribly useful, but it's enough to light an LED or two. When powering a project from the Pi, the Ground pin completes your circuit. If you want to memorise this pinout, you should forget the ground pins spaced out around the GPIO header and focus just on the one below the 5v pins and pin 25. The 2 UART pins in WiringPi are: 15, 16 UART is a handy, straight forward way to interface an Arduino ( or bootloaded ATmega ) with your Pi. You must, however, be careful with logic-levels between the two devices: the Pi is 3.3v and the Arduino is 5v. Connect the two and you might conjure up some magic blue smoke. Personally I'm a fan of building out a Arduino Bootloaded ATmega 328 circuit on a breadboard with a voltage regulator to take the Pi's 5v line and convert it to 3.3v. The ATmega 328 seems to run quite happily at 3.3v using a 16Mhz crystal and you'll then have an Arduino clone with 3.3v logic.!') The 8 GPIO pins in WiringPi are: 0, 1, 2, 3, 4, 5, 6, 7 Known as the four-wire serial bus, SPI lets you daisy-chain multiple compatible devices off a single set of pins by assigning them different addresses. A simple example of an SPI peripheral is the MCP23S17 digital IO expander chip Note the S in place of the 0 found on the I2C version. Using it in WiringPi2 is a doddle: import wiringpi2 as wiringpi HIGH = 1 OUTPUT = 1 PIN_BASE = 65 SPI_ADDR = 0x20 wiringpi.wiringPiSetup() wiringpi.mcp23S17Setup(PIN_BASE,SPI_ADDR) # 16 pins including the starting pin mcp23S17pins = range(PIN_BASE,PIN_BASE+15) for pin in mcp23S17pins: wiringpi.pinMode(pin,OUTPUT) wiringpi.digitalWrite(pin,HIGH) You can also use the SPI port to "Bit-Bang" an ATmega 328, loading Arduino sketches onto it with Gordon's modified version of AVRDude. Hook up you Pi's SPI port to that of your ATmega, and power the ATmega from the 3.3v pin on the Pi. Make sure you're not running any SPI device drivers, and run "avrdude -p m328p -c gpio" to verify the connection. See the individual pins to learn how to connect up your ATmega. The Raspberry Pi's I2C pins are an extremely useful way to talk to many different types of external peripheral; from the MCP23017 digital IO expander, to a connected ATmega. You can verify the address of connected I2C peripherals with a simple one-liner: sudo apt-get install i2c-tools sudo i2cdetect -y 1 You can access i2c from Python using the smbus library: import smbus DEVICE_BUS = 1 DEVICE_ADDR = 0x15 bus = smbus.SMBus(DEVICE_BUS) bus.write_byte_data(DEVICE_ADDR, 0x00, 0x01) The inexpensive Raspberry Pi Ladder Kit is a great way to get started with GPIO tinkering. It connects 12 LEDs and 4 buttons directly to the GPIO pins, making it extremely easy to start programming. Using the pins on the left, you simply set 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9, the LEDs, to OUTPUT (1) and 10,11,12,14, the buttons, to INPUT (0) and start reading/writing. In practice, it's actually a little more complicated than this. The buttons all need their pull up/down switched to PUD_UP/UP (2), because pressing a button on the ladder board pulls that pin down to ground. The code below should get you started: import wiringpi2 as wiringpi INPUT = 0 OUTPUT = 1 LOW = 0 HIGH = 1 BUTTONS = [13,12,10,11] LEDS = [0,1,2,3,4,5,6,7,8,9] PUD_UP = 2 wiringpi.wiringPiSetup() for button in BUTTONS: wiringpi.pinMode(button,INPUT) wiringpi.pullUpDnControl(button,PUD_UP) for led in LEDS: wiringpi.pinMode(led,OUTPUT) while 1: for index,button in enumerate(BUTTONS): button_state = wiringpi.digitalRead(button) first_led = LEDS[index*2] second_led = LEDS[(index*2)+1] #print str(button) + ' ' + str(button_state) wiringpi.digitalWrite(first_led,1-button_state) wiringpi.digitalWrite(second_led,1-button_state) wiringpi.delay(20) The button locations and their corresponding pin numbers also don't correspond with those of the LEDs so we have to pair up the buttons accordingly for a basic example. Finally, never forget to call wiringpi.wiringPiSetup() or nothing much will happen! WiringPi is an attempt to bring Arduino-wiring-like simplicity to the Raspberry Pi. The goal is to have a single common platform and set of functions for accessing the Raspberry Pi GPIO across muliple. For more information about WiringPi you should visit the official WiringPi website. WiringPi uses its own pin numbering scheme, here you'll learn how WiringPi numbers your GPIO pins, what those pins do and how to do shiny things with them from within Python or Ruby. WiringPi, the Arduino-like GPIO library for the Pi, is available in C right from Gordon's git repository, Python, Ruby and even Perl and PHP to a lesser extent. Installing to Python couldn't be easier, just: sudo pip install wiringpi2 Note the 2 on the end? That's the all new, shinier WiringPi! The PiBorg LedBorg is an ultra-bright RGB LED board for the Raspberry Pi. It has its own driver, so you don't need to drive it manually. If you want a much, much wider range of colours, though, you can drive it manually using softPwm in WiringPi. The pin assignments for this are as follows: WiringPi pin 0: Red LED WiringPi pin 2: Green LED WiringPi pin 3: Blue LED This is easy using WiringPi in Python: import wiringpi2 as wiringpi wiringpi.wiringPiSetup() wiringpi.softPwmCreate(0,0,100) wiringpi.softPwmCreate(2,0,100) wiringpi.softPwmCreate(3,0,100) wiringpi.softPwmWrite(3,100) wiringpi.softPwmWrite(0,100) The Clockatoo buzzer is available on WiringPi pin 7, GPIO pin 4. The GeekRoo Clockatoo is a great little board combining a battery-backed up real-time clock, a 4 digit, 7 segment display and a buzzer into one package. GeekRoo's own instruction manual gets you started with the clock itself, but doesn't tell you how to use the buzzer. WiringPi's softTone does a great job of pulsing the buzzer at a variety of annoying ( or alerting ) speeds, try this for a simple alert tone: import wiringpi2 as wiringpi wiringpi.wiringPiSetup() wiringpi.softToneCreate(7) wiringpi.softToneWrite(7,1) The second parameter for softToneWrite is the frequency, drive it higher and the alarm sound will become steadily more irritating until you're sure to wake up!
http://pi.gadgetoid.com/pinout
CC-MAIN-2014-42
refinedweb
1,668
62.38
JDBC Training, Learn JDBC yourself Here are more tutorials you can learn: What... then you can retrieve it with the help of this example. Deleting... that help you in understand JDBC connection timeout. JDBC please fix the error please fix the error org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 14 in the jsp file...: { ///////////@@@@the above mentioneed is error and code is as follows need to fix errors please help need to fix errors please help it does have 2 errors what should i fix? import java.io.*; class InputName static InputStreamReader reader = new InputStreamReader(system.in); static BufferedReader input = new BufferedReader Please help me fix this code - MobileApplications Please help me fix this code Please help me in this area of code..., Confirm, Check2, Confirm2, delete; Alert error, errora, Alerta...) { } try { error = new Alert("", "One of the fiels is Empty Logic error? HELP PLEASE! :( Logic error? HELP PLEASE! :( Hello Guys! i have a huge problem. What I want to do is there is a retrieve jsp page. In the retrieve jsp page..." %> <jsp:useBean id="dataBean" class="sg.edu.nyp.DataBean" scope="session Java and JSP help Java and JSP help I have a website, on my website i have made a form...;title>JSP Form</title> <style> </style>... the exception if an Input/Output error occurs catch (IOException e) { e jsp error - JSP-Servlet jsp error HTTP Status 404 - /jsp... message /jsp/ description The requested resource (/jsp/) is not available..., The 404 or Not Found error message is an HTTP standard response code indicating Error page in JSP Error page in JSP In this section we will discuss about "Error page... an exception occurs that redirects programmer to error page. When you execute the JSP page a runtime error may occur inside the page or outside the page. JSP jsp error - JSP-Servlet jsp error Hello, my name is sreedhar. i wrote a jsp application... and showing the data base code and the connecction code. please help me to come.... -------------------------------------------- If you have any problem then send me source code and explain BSNL Broadband users - save yourself! giving you full access to the modems internals. What follows next is simple... So how should you secure yourself ? 1. Use RFC Bridged mode if it is sufficient...BSNL Broadband users - save yourself! Disclaimer : The information provided JSP error JSP error what is difference between global-exception and error-page in jsp. which condition they are use sql syntax error help sql syntax error help this query show syntax error .. i am unable...') where is the error ? Please send the error details and the datatype you are using for the given fields. error message - JSP-Servlet error message hi, friends after complete my servlet programe i... device, path, or file you may not have the appropriate permission to access". my sql+ is not working ,so what is the solution.plez any body give me the replay jsp-servelet,error http404 jsp-servelet,error http404 I am using mysql commandclient to connect with eclipse using jsp and servelet. I keep getting the error hhtp 404...) out.print("You are successfully registered..."); }catch What would you rate as your greatest weaknesses? What would you rate as your greatest weaknesses.... Be mindful of what you say. If you admit to a genuine weakness, you will be respected... of the question 1 when you start the interview. Once you know what is required jsp code error - JSP-Servlet jsp code error I have a jsp page named "tMastDepartment".which has... for this..plz help me I appreciate the correct code for this.. thank you Programming Error - JSP-Servlet me thank you sir. Hi Friend, We have modified your jsp file.Your...(""); } catch(SQLException se) { out.println("Database Error :"+se.getMessage()); } catch(Exception e) { out.println("General Error :"+e.getMessage Jsp Error - Development process ; Hi Friend, Please send your full code so that we can help you Thanks...Jsp Error Hi, While executing Add_Data.jsp , am getting following error. "Data type mismatch in criteria expression." "View_Data.jsp Programming Error - JSP-Servlet ??? And when i tried its giving me error than cannot find variable.In request.getParameter it wont work in next to next page so please help me how to do through session...?? Thank You Sir. Please do Reply me?? thankyou sir help me in solving this error help me in solving this error Hello, i have installed tomcat 6.0, i am getting following error while running application...,response); response.sendRedirect("/Simple/jsp/login.jsp"); }else can i print out the modulus sign so my output looks like 3 % 4 = 3. thank you! We have modified your code. The character you want to display in the printf method is actually invalid.Therefore error occurs. Anyways, check your code Please Help - JSP-Servlet . Thanks for your response.. You told me that its difficult to handle the problem.. Ok,Let me try my hands on it.. The help i need is can u please tell me... is sufficient.. Because this is very Urgent.. Thank you/Regards, R.Ragavendran..  Proogramming Error - JSP-Servlet : I want that ChequeNo , ChequeAmt ,BankName shoukd get validated but i tried its getting error sir can u please tell me how to do tht. Please Reply me sir Thank You Sir JSF error - JSP-Servlet $TreeNode Anyone could you please help me to solve the problem.... Thanks, githu Hi friend, Code to help in solving the problem Programming error - JSP-Servlet Programming error Actually there is an error in placeorder.jsp file... not get replaced. So please reply me Sir what to do and how to do?? And please reply me the answers of questions i asked you before and i have send you Programming error - JSP-Servlet : Designation: PhoneNo: Contact Details: Help...(8,contact); int x=ps.executeUpdate(); if(x>0) out.println("You have been Registered now you can place Order"); else response.sendRedirect("Registers.jsp would you please help me? would you please help me? Write a class Amount which stores sums of money given in pounds and pence. Your con- structor should take two ints... an error message to the screen and ignore the withdrawal Programming Error - JSP-Servlet what to do please reply me Sir??? Thank you Sir. Hi Friend Programming Error - JSP-Servlet ; PlaceOrder PlaceAd Welcome To Prayosha Ad Agency !! You can place Ad by coming... Agency has been accretited with an A grade star. So you are dealing Programming Error - JSP-Servlet ... Please?? Hi Friend, Do you want to create a combo box for states and cities?What is Main Category and Sub Category? Please clarify your question Error in reading Excel data using jsp ); } } %> </table> can anyone help me what is the solution for this. Do you have hello.xls in your c...Error in reading Excel data using jsp ERROR while executing bellow Error in loading jsp file - JSP-Servlet Error in loading jsp file I did as u have said. I copied iitem.jsp...:8080/webapps/examples/jsp/iitem.jsp In both cases,it is giving the following error.... What should I do now? Hi Friend, You have written wrong URL jsp help jsp help Hi i am doing my project in jsp.using netbeans 6 and mysql..... in what form should i load my project in CD and submit it. should i convert... with it. so that my project can run independently in any server. plz help me. am so file upload error - JSP-Servlet ://... error as following: javax.servlet.ServletException... ----------------------------------------------------------------------------- This error occured jsp error jsp error <p>hi, could please help whenever i run jsp file in my eclipse i got this error.my jsp file is</p> <%@ page language... encountered an internal error () that prevented it from fulfilling this request Web Search Applications ? Find What You Want Anytime, Anywhere. as many apps as you need to help you find what you need. Save yourself the effort...Web Search Applications – Find What You Want Anytime, Anywhere... that will fit with what you are looking for. This is where search engines came Difference between error and exception ???????? yourself or that might be thrown because of an obvious run-time error such as trying... such as 'out of memory'. Even if you caught an out of memory error, you wouldn't likely... condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can Help with javascript function - JSP-Servlet Help with javascript function I've got a button in a for loop.Each...; -------------------------------------------------------------------------- What... is that the function BookSeat() to change the value of the button being clicked to "You Error reporting in PHP while developing your applications. If your code reports the error correctly you can easily debug and fix your code. You can easily turn on the error reporting...Error reporting in PHP Hi, I am developing a complex application If you came on board with us, what changes would you make in the system? If you came on board with us, what changes would you make in the system.... You may be very bright, but no one can really understand what needs to be done... to have in-depth meetings with all of you to understand things here- like what jsp code compilation error - JSP-Servlet the following code.but it shows the following error.can you tell me where is the error and also what is the proper code for funds transfer. HTTP...jsp code compilation error hai, iam doing online banking project.i Null pointer exception error in Jsp - JSP-Servlet Null pointer exception error in Jsp Hi i write a login page. when i validate the login value then the nullpointer exception error is occured. my... then the following error is occured. HTTP Status 500 Null pointer exception error in Jsp - JSP-Servlet Tomcat/5.0.19 note i used netbean ide 3.6. Pleas help me how i finished this error.... thanks. Hi friend, Error in this lines of Code because you...Null pointer exception error in Jsp Expert:Majid Hi i write a login Fix Scrollbar position in a checkboxList after postback Fix Scrollbar position in a checkboxList after postback Hi, I have a CheckBoxList in which have lot of items and i set AutoPostBack="True".I am... true,that's why it is not working.Please help me java compilation error - JSP-Servlet of validations. Hi uma, I am sending you a link. This link will help you. Plz visit for more information. Java error class and the message to be appear what the error occurred. Let us understand a condition stack overflow error occurs when you call a recursive and there is no any... is you need to show the error message that occurred in your code. Here JSP Error - JSP-Servlet JSP Error When i am running my registration.jsp getting following error. HTTP Status 500... description The server encountered an internal error () that prevented it from fulfilling Don?t you think you are overqualified for this job? to the company. The position in question is exactly what you want to do and what... of study. 12. What options do you have in your career now? The interviewer... interest in the job, but avoid sounding desperate. Rather, you should position yourself Error - Struts inform what is the problem here. Friends I am stuch with this. Please help me. If you can please send me a small Struts application developed using eclips. My mail id: ksenthu83@gmail.com Please help me Friends!!!! Regards Required help about the concept of JSP page reloading Required help about the concept of JSP page reloading Hi, We have one application with Websphere portlet Factory generated JSP as front end... it is being observed when exception has occurred and error page is shown, if we refresh Need urgent help with C++ errors! don't know what to do. Please help!! #include<iostream.h> void main() { cout<<"Can somebody fix this?"; } the errors are listed as follows...Need urgent help with C++ errors! hi, i'm new to C++ programming JSP Error 500 In this section, you will learn how to generate error status 500 in jsp. You can see... JSP Error 500 JSP Error 500 is to generate error status 500 JSP error page - JSP-Servlet JSP error page Hi i have 1000 of JSP. but we coded it without adding.../DAO/bean layer and not in the JSP. let me know if you have any idea. Thanks... the exception occured in JSP. is there any short cut i can do? do not want to add this line JSP Tutorial JSP Tutorial In this section you will learn about the JSP. This section will help you in to understand What is JSP , What are the features of JSP ?, What... objects in JSP, JSP Scriptlets, JSP directives, Actions in JSP. What is JSP ? JSP Grid World project Run Error !! help please!! Grid World project Run Error !! help please!! i'm trying to make...); } } } } and Here is my error...: (it runs at first but when the bug hits a side, the error occurs and i exit the error but run does not work anymore JSP SQL Error JSP SQL Error Hi While trying to execute the below code i'm getting the following error "java.sql.SQLException: Io exception: Got minus one from a read call ". please help me out. <% try{ String Username jsp runtime error - JSP-Servlet jsp runtime error sir, when i am running ur prog... from this website.... i did the same as per guidelines...but i got error..!!!! org.apache.jasper.JasperException What is a stack overflow error? What is a stack overflow error? What is a stack overflow error Script error - JSP-Servlet running this it shows an error as "STACK OVERFLOW". Correct the code . The code...; ------------------------------------ If you have any problem then send me jsp code. Thanks java runtime error - JDBC java runtime error sir when i m running the jsp connectivity program it is giving the error as follows:' java.lang.NullPointerException at jsp...) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:151) please suggest me what may be the solution. thanking Error output - JSP-Servlet Error output Can anyone please assist me; The printed output should be: The product is 10. But instead of it I got; The product is undefined. Can anyone trace what went wrong of my code pls Xampp Error Apache shutdown unexpectedly - Solved Xampp Error Apache shutdown unexpectedly - Solved JSP Error Page JSP Error Page JSP Error Page is used to specify the custom... directive. The page errorPage.jsp shows the error generated in calling the JSP page Programming Error - JSP-Servlet integer.parseInt but its giving error. Please Reply me . Thank you. Hi Friend, We are providing you two different code.Fro first one Programming Error - JSP-Servlet ("mail.smtp.host", host); // To see what is going on behind the scene...(); } } }//End of class m geeting error in this can u please tell me whats the error nd how to solve Java servlet sql connectivity error - JSP-Servlet if you could help me out here. Thanks. hi, you must place What's wrong with my pagination code in JSP? What's wrong with my pagination code in JSP? Dear experts, I've...))"; But, none is working out. Hope you can tell me what's the query to use. Many... whatever lines that NetBean IDE has given me error signal. The resulted page code error - JSP-Servlet code error hii this program is not working becoz when the mouse is over the email link it must show the messsage "email tag 4 you " which... is error in this progrm. ss function describe() { window.status SQL error - JSP-Servlet to solve this. Help me. Hi friend its possible... Here is the solution...){ System.out.println("Error occured while updating!!!"); } con.close Programming Error - JSP-Servlet that image should get displayed. Then how to do this please reply me?? Thank you Sir...(""+filename Programming Error - JSP-Servlet statement in jsp i want to calculate the price of placing ad according to user... placeAd.jsp page. Please Reply me How to do this ??? Please Thank You Sir Programming Error - JSP-Servlet in jsp. when user types some thing in draft ad textarea then it should get... thank you. Hi Friend, Please send all the fields defined Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/81076
CC-MAIN-2016-18
refinedweb
2,743
77.53
I missed my blog so much! I took some vacation time to visit my family and then I was brave and lucky enough to have Lasik surgery. I've been willing to do that for a while and so far I love how the world looks without my glasses. I just got a printed proof of the new version of the Office Developer Poster that we will distribute during the next conferences. Updates to the poster include new namespaces, changes to Office Add-in technologies and VSTO, and final Office 2007 RTM brand names. We also added a link to the interactive version of the poster:. I keep finding the poster and the interactive roadmap as great learning tools to get started with Office development and as good collection of Office developer resources. Here is a quick peek of the latest version of the poster: If you are a poster fan like me, you can download your free copy now: Thanks to Rob Barker and the OBA team for providing this new poster. I am having a blast reading all namespaces and object names from a distance (without my glasses) J. PingBack from Erika Ehrli blog has this entry: Update: Office Developer Poster - Looks so much better now! The new
http://blogs.msdn.com/b/erikaehrli/archive/2007/08/13/update-office-developer-poster-looks-so-much-better-now.aspx
CC-MAIN-2013-48
refinedweb
210
75.74
Introduction Welcome to this installment of the .NET Nuts & Bolts column! When it comes to tips and tricks there are many items that can be considered. For this article we'll briefly recap the C# 4.0 language features, cover some tips, tricks, and reminders, and touch on a couple of useful tools. C# 4.0 Overview> Extension Methods Extension methods allow you to add new functionality on existing types. This ability even includes the ability to add new functionality to sealed classes. They are declared like static methods and called like instance methods. They are scoped by using clauses and are valid for interfaces and constructed types. The following code example demonstrates adding two methods to the decimal type from the .NET Framework. static class ExtensionSample { public static decimal Triple( this decimal d ) { return d*3; } public static decimal Half( this decimal d ) { return d / 2; } } decimal y = 14M; y = y.Triple().Half(); When building extension methods within your code base it is recommended to consider a separate namespace to allow them to be optional. It is also best you not be mean to others by applying to all objects by extending object. The following sample demonstrates what not to do as it alters the default behavior of all classes. Normally accessing a property or method on an object that is null a NullReferenceException would be generated. The extension method below would add a .IsNull() method that would alter that behavior, which then makes your code behave different from the default behavior expected from the .NET Framework. The following sample code demonstrates what not to do: namespace System { public static class MyExtensions { public static bool IsNull(this object o) { return o == null; } } } while (!myObject.IsNull()) { } Obsolete Code If you've been using the .NET Framework for a number of years chances are you've seen the Framework versions advance and seen instances where some of the .NET Framework classes such as prior Configuration classes have gone obsolete and you've received warnings from the compiler about it to make you aware. You may have wondered how to do that same thing with your own code. There is an Obsolete attribute that you can use to decorate your own classes and methods to indicate they are being phased out as well. If you're working independently of others, then chances are you won't need it. However, in working with a project team where you may have implemented a framework, helper classes or other conventions, it can be very helpful to use the Obsolete attribute to flag dead code that won't be used going forward. This allows them to be migrated over time rather than just deleting from your code. This is very handy as you refactor code to communicate through the compiler that a particular item is obsolete. By default the items are served up as warnings, but an optional flag can indicate if they should be treated as warnings. It is worthwhile to have that setting be a configuration value so that you can enable or disable it across the board. // Include message for compiler to present [Obsolete("This class is dead. It has been replaced by MyClass3.")] class MyClass1 { // ... } // Include message and generate a compiler error [Obsolete("This class is dead. It has been replaced by MyClass4. "), true] class MyClass2 { // ... } Garbage Collection If you are programming in .NET 3.5 or before you can force garbage collection through GC.Collect(), but it is heavily advised that you do not use it unless you really know what you are doing. It is very likely you'll outguess the garbage collection system and do more harm than good. With the release of the .NET Framework 4.0 there are new garbage collection options and ways to control the behavior, which does make it more feasible to trigger and control. (Note: this will likely be a future article). Using Keyword The using keyword has multiple uses. One lesser known is it can be used to provide automatic cleanup of disposable types. The compiler translates it in to try...finally behavior. I highly recommend using it whenever using IDataReader or the LINQ to Entity data context to retrieve data from the database. The following sample code demonstrates a simple implementation where a DataReader is wrapped in a using statement to ensure it is disposed when its use is out of scope. using (IDataReader reader = provider.ExecuteReader(dataCmd)) { // }
https://mobile.codeguru.com/csharp/article.php/c17299/C-Programming-Tips-and-Tricks.htm
CC-MAIN-2019-09
refinedweb
737
64.81
Posted in category machine learning with tags errors. Evaluation metrics are used to explain the performance of a model. Basically, we can compare the actual values and the predicted values to calculate the accuracy of our models. In this post, I try to understand the meaning and usage of some popular errors in the model evaluation. This article is not for you to learn, it’s for refrence only! What’s an error of the model? (regression metrics) The error of the model is the difference between the data points and the trend line generated by the algorithm. There are many ways to calculate this difference (regression metrics) - Mean Absolute Error (MAE) : $MAE = \frac{1}{n}\sum_{j=1}^n \vert y_j - \hat{y}_j \vert$. - Mean Squared Error (MSE) : $MSE = \frac{1}{n}\sum_{j=1}^n (y_j - \hat{y}_j)^2$ - Root Mean Squared Error (RMSR): $RMSR = \sqrt{\frac{1}{n}\sum_{j=1}^n (y_j - \hat{y}_j)^2}$ - Relative absolute Error (RAE): $RAE = \dfrac{\sum_{j=1}^n\vert y_j-\hat{y}_j\vert}{\sum_{j=1}^n\vert y_j-\bar{y}\vert}$ ($\bar{y}$ is the mean value of $y$) - Relative Squared Error (RSE): $RSE = \dfrac{\sum_{j=1}^n (y_j-\hat{y}_j)^2}{\sum_{j=1}^n (y_j-\bar{y}_j)^2}$ - R squared: $R^2 = 1 - RSE$. What’s their meaning? - MAE : It’s just the average error, the easiest one. All individual differences have the same role, there is no one being more weighted than the others. - MSE : It focuses on “larger” errors because of the squared term. The higher this value, the worse the model is. - MSE is more popular than MAE because in the MAE, all gears are equivalent while in MSE, the bigger gears will influence much on the final error. - RMSE : the most popular because it is interpretable in the same units as the response vector or $y$ units. - RAE : It’s normalized, i.e. it doesn’t depend much on the unit of $y$. - RSE : It’s used for calculating $R^2$. - $R^2$ : It represents how close the data values are, to the fitted regression line. The higher the R-squared, the better the model fits your data. The choice of metric, completely depends on - The type of model, - Your data type - Domain of knowledge. How about the metrics for classification models? Jaccard index (Jaccard similarity coefficient) : - $0 \le J \le 1$. - Higher is better : The common part is bigger, thus the numerator is bigger and the denominator is smaller. sklearn.metrics.jaccard_similarity_score F1-Score (F-score, F-measure) : - $0 \le F_1 \le 1$. - Higher is better : look at the formular of $F_1$ to see the reason. It needs both the precison and recall to be bigger. Other words, the False Negative is smaller (the wrong selected items are less) and the False Negative is smaller too (the wrong non-selected items are less). - Hard to remember TP, TN, FP, FN? What we choose (true/false), what the actual values (positive/negative = true/false). For example, “false positive” = “what we choose false are really false”, “false negative” = “what we choose false are actually true”. sklearn.metrics.f1_score - Log Loss : Logarithmic loss (also known as Log loss) measures the performance of a classifier where the predicted output is a probability value between 0 and 1. We can calculate the log loss for each row using the log loss equation, which measures how far each prediction is from the actual label. - $1 \ge LogLoss \ge 0$. - Smaller is better. sklearn.metrics.log_loss Accuracy score : using in scikit-learn sklearn.metrics.accuracy_score(y_test, y_pred) # accuracy_score = jaccard_similarity_score (binary & muticlass classification) The idea of K-fold cross validation? - We use CV to estimate how well a ML model would generalize to new data? It helps avoid overfitting and underfitting. - CV set and training set must use the same distribution! Why, check this. We choose different groups of CV set/training set to find the predictions, after that, we choose the best one. from sklearn.model_selection import KFold kf = KFold(n_splits=2) kf.get_n_splits(X) for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] Source of figures used in this post: k-fold, jaccard, f1-score.
https://dinhanhthi.com/accuracy-metrics-for-model-evaluation
CC-MAIN-2019-22
refinedweb
715
57.98
Any plans to have it installed? Thanks Any plans to have it installed? Thanks AFAIK we only have SQLite and MySQL. Soon we will also have PostgreSQL. What kinds of databases can I use? PythonAnywhere supports MySQL and SQLite. We're considering adding MongoDB and PostgreSQL in the future -- if you're interested in either (or something else entirely), let us know! To start using MySQL, you'll need to go to the MySQL tab on your dashboard, and set up a password. You'll also find the connection settings (host name, username) on that tab, as well as the ability to create new databases. MongoDB is a very popular request. Right behind Postgres. It does present some challenges in a multi user environment. It might be that we have to write our own user access layer from scratch. CouchDB is another alternative. I'm less interested in Postgresql, although I might be if coding stored procedures is included. In any case, either would open the door to users that get shut out by other services (many of whom say they will support something and then do not support that in an effective way). @dscapuano: Now is the time to make sure PA staff know what you want. Your statement about other services not supporting in an effective way has me writing this. Now is the time while PA is working out the implementation details. Tell them what is important to you. What you expect the feature to accomplish. They can't be sure to make it work as expected if they don't know what you are expecting. So, please provide details and I'm quite sure they will incorporate them if feasible. Anything not feasible will hopefully bring with it a suggested work around that will keep you in business. Most of these NoSQL solutions seem to share two things in common - they're quite different from SQL setups and they're quite different from each other. I'm guessing this means that there may be a larger incremental cost to supporting each one than there might be to setting up a random RDBMS, which are much more of a known quantity. Also NoSQL DB's seem to be tailored to application-specific needs much more closely. This isn't to say that there can't be a good generic setup, but I think it's worth being cautious. So, it's probably worth spending a decent amount of time picking the right initial candidate. I guess MongoDB may be a reasonable choice, based on my very limited experience, since it seems to be suited to the sorts of tasks one might have used a standard RDBMS for. Some of the others seem more tailored for massive data warehousing and log analysis, and I suspect that PA isn't really the right service for people who have those sorts of large-scale computing requirements - at least not right now. In the future, who knows! (^_^) In short, I think the current seeming approach of getting some solid traditional SQL options on the table is absolutely the right thing to do, but as a2j says it's also the time to canvas for opinion so that when the time does come, the best option is already clear. I could probably have saved everyone a lot of reading by writing "a2j: me 2" but I never did like AOL. Can we use PyMongo and just connect to an outside service like MongoLab? I'm trying but so far not working.... That should work for paying customers like you (thanks :-) Could you share the stack trace or other error you get? I'm back to basics here. I have a simple app working in Flask now and am going to see if I can get PyMongo working to connect to MongoLab. That would do the trick. Happy to pay for a service that works and is well supported. Just getting started here though! Great! Let us know how you get on, we're here to help. Just to confirm that the connection to MongoLab works as expected: from pymongo import MongoClient connection = MongoClient(MONGO_URL, MONGO_PORT) db = connection[MONGO_DB] db.authenticate(MONGO_USER, MONGO_PWD) Excellent, thanks for confirming! +1 on MongoDB support, although Mongolab looks good too! Bumped it up on our list. Just signed up to the free account to trial this service. Not even got my first web app running yet, but already blown away by this! My whole stack is here already (flask, wtforms, pymongo) without me having to do anything. If you could offer mongo instances too, that would be incredible. Will be signing up for a developer hosting account very soon. Big thank you to the poster that mentioned mongo lab - looks like a great service too. Cheers for the great work! Thanks, brightattic -- glad you like it! Please do let us know here in the forums -- or privately by the "Send feedback" link at the top of the page -- if you have any comments. Hi, To clarify, is access to MongoLab only for paid accounts? It's URL is on the whitelist for free accounts, but I'm getting ConnectionFailure: could not connect to xxxxxxxxxxxxx: [Errno 111] Connection refused when trying to connect from my app. Cheers. If the MongoLab connection is via http on port 80, then it should work for free accounts. Otherwise, it will only work for paid accounts. So I see the Mongolab connection code above. Do I also have to put an import pymongo in my wsgi file like I did for bottle? Will that do the trick? @glenn: Shouldn't that be port 80 or port 443? Well, there's a few bugs in some of the popular python HTTPS client libraries (see posts re tweepy, ad nauseam), which means that they don't always work well through the proxy... Got it...thx...☺? I'm a bit confused -- are you trying to connect from MongoLab to PythonAnywhere? We don't host MongoDB here, so that won't work. If you're trying to connect from PythonAnywhere to MongoLab then your connection settings will look something like mongodb://my-db-user:my-db-password@ds033217.mongolab.com:33217/my-database -- see this page on MongoLab's support pages. However, even then, you'll need a paid PythonAnywhere account for it to work. Free PythonAnywhere accounts only allow HTTP access out to a specific set of other websites. Paid ones have unlimited Internet access. Just to hiccup an old chestnut, where do you stand with adopting a nosql db such as MongoDB? We had a brief look at adding Mongo a few weeks ago. The result of our investigation is that our architecture doesn't support it at the moment. The architectural changes that are necessary are things that we want to do for many other reasons. They're quite big changes and so they could take a while to get done, but when they're done, providing Mongo and other NoSQL databases should be fairly simple. Sounds good! I have an account with Mongolabs, and going out to them should be ok for now. However, the sooner the better with Mongo on PA, because your service is the best in this business. Thanks, Dave Capuano Thanks Dave :-) There's an upvote on the to-do list on your behalf. +1 for MongoDB. I'm using the MongoLab solution for now. Thanks for letting us know about it! Thanks for letting us know! I've added your +1 to our to-do list. For those who want to have a NoSQL solution now you could look at this Release Announcement for PostgreSQL 9.2. Toward the bottom it references methods to use PG as a NoSQL solution...☺ But... is it Web Scale? Does anyone have a sample dataset/simple app we can try it out with? If not we could generate one if there is interest in order to verify prior to anyone developing a real world solution that may suffer from lackluster horsepower. ͡° ͜ʖ ͡° +1 for me regarding MongoDB! I'll get an even warmer/fuzzier feeling about PA if MongoDB is added. Thanks! I've added the upvote to our DB. It's getting pretty high up the list, though PostgreSQL is still ahead... Hi all, To those of you who have some experience with MongoDB: I have successfully connected my app to a MongoDB database on MongoLab and saving some data from an input form works like a charm. But somehow I totally do not understand how to load the data from the database. I do understand how to run queries like collection.find_one() etc but I just don'z understand to actually access the data inside the documents. Assuming I have a document quser = {"date": datetime.datetime.utcnow(), "age": age, "gender": gender_choice, "nation": nation, "industry": industry ] How on earth can I assign the string variable in the field "nation" for example to a Python variable "a" ?? Thanks for help OK, I totally missed the fact that the document is actually just a Python dictionary. So it works now by just saying: a = quser['nation'] or field_list = [] for field_name, value in quser.items(): field_list.append(value) +1 for MongoDB! I would upgrade my account to WebDev/Startup when MongoDB is supported! Loving pythonanywhere, great job! Thanks! Upvote for Mongo noted :-) +1 for Mongo for me, too. It's rapidly becoming my go-to data storage solution. Thanks, greg -- noted. Not sure if you guys already have me down as a +1 for MongoDB. If not, add me too :) We didn't. We do now. Haven't tried MongoDB yet but I've heard great praises about it. +1 for me. Also I'm interested in using it for Flask. Thanks. Cool. I've added you to the list. for me also MongoDb would be a real plus to PythonAnywhere. I have a commercial project in mind that WILL run Mongodb. I would be glad to host it on Pythonanywhere. For yet, it still has to be developped (only at idea stage), so I still have some time before the need to host it. +1 for Mongodb OK, thanks! I've added the +1 to our tracker. With a paying account you can access external Mongo databases, by the way, so if you're happy with using multiple providers for your infrastructure (us for hosting and, say, MongoHQ for the database) then you can start right away! +1 from me for mongodb Thanks for letting us know! How much would you pay for a MongoDB service? $20 per month? plus some extra charges per GB of storage over some base amount, a bit like our custom plans? +1 from me for MongoDB Thanks! I've added another upvote to the ticket. +1 for mongodb +1 for mongodb FWIW, I have had good luck with teaching using PythonAnywhere and the free database offering from MongoLabs. You need to be aware that when you connect to it you're already at a database, and you can't get a list of databases. So the usual 'show dbs' thing doesn't work and just tells you you're not authorized. I found this initially kind of a distraction, since I assumed the issue was because my password was wrong, but they just want you to go ahead and connect to your (only) database and past that it works fine. I suggested to them that they make that obvious somewhere, because it means you can't really move smoothly past the "show dbs" part of just about every mongo tutorial there is, and perhaps they have done so. In any case, past that it works great. The only other caveat is that it requires access that isn't on the PA whitelist, so my students who wanted to use it were encouraged to get paid accounts, but the PA staff was helpful about temporarily whitelisting the addresses in question when necessary, and were my class to have had no other alternative for MongoDB I would have followed up on that further. Bottom line, though, is that PA + MongoLabs looks like a pretty good option. Hope this helps! This is the code I use to access the MongoLab database: import pymongo client = pymongo.MongoClient("mongodb://<xxx>:<xxx.xxx.xxx>@ds<port>.mongolab.com:<port>/<databasename>") db = client.<databasename> print db.collection_names() ...where the bracketed values you will get when you sign up at MongoLabs. The code prints this: [u'system.indexes', u'system.users', u'stuff', u'objectlabs-system', u'objectlabs-system.admin.collections'] And then you can go on from there... I'd also would like to see MongoDB on PA, as I'm stuck and can't get my website working with the PA's free account. PA service is great, but unfortunately lack of local support for MongoDB is a dealbreaker for me as I require mongoDB and my website to run on the same system. I'll shop around for something else, but I may come back if support for MongoDB is added at some point. I like the PA service though. @kenk have you looked at Good rates and a free account, I us it for the odd job where I need to use mongo @graingerkid -- great suggestion. When we add MongoDB then we're probably going to do it by partnering with MongoLab or MongoHQ. For best performance, start your instance with them in the Amazon Web Services us-east-1 region, or the best approximation thereto. Thanks for suggestion. I have seen MongoLab and I'll try to evaluate the option too. In my case MongoDB is very central to the project and, on paper, it would be beneficial to have it close to webserver. But in practice it may not be big factor. I'll try and report back on this topic. I think MongoLabs' pricing is the same wherever you start the instance, so (unless I'm wrong on that) I'd definitely recommend us-east-1. BTW I don't think MongoDB connections from inside PythonAnywhere will work from a free account, so you'd need a paying account to access MongoLabs from here. If you'd like us to temporarily enable outgoing connections to them from your account so that you can try before you buy, just let us know over the "Send feedback" link at the top right -- drop in a link to this forum thread so that the person dealing with it knows why you're asking for it. Another +1 for MongoDB support :D I recently upgraded to paid PA account. A quick test using MongoLabs worked a charm. But hey, if I'm paying here, let's get it all localised right here. Thumbs up for you guys. Cool. I've bumped the ticket for you. Just a thought, would it be within the realms of possibility to include a Mongo shell in the 'others' category on the Consoles tab? That could be used to connect directly to a MongoLab hosted instance. You can do that yourself with a custom console. Just put the command that you'd use to connect to mongolab in the command field and it will start with that every time you click it. @glenn, wouldn't we need the mongo program installed in order to do that? The command to connect to a MongoLab-hosted instance would be: mongo ds12345.mongolab.com:12345/[database_name] -u [dbuser] -p [dbpassword] Ah, looks like we don't have the mongodb client installed. Will fix that. In the meantime, you can use a python library like pymongo. Or you can also download the client manually: cd wget tar -xvf mongodb-linux-x86_64-3.0.4.tgz ln -s ~/mongodb-linux-x86_64-3.0.4/bin/mongo ~/.local/bin/mongo mongo Great, thanks. I can confirm that downloading the client as above works and allows me to connect into my MongoLab-hosted instance. I didn't create the link though, as for some reason I don't have a bin directory in my ~/.local/. So instead my custom console just uses the full path to the mongo binary. that'll work too! will add a ticket to include the mongo client as part of our standard image... Hi Guys pythonanywhere newbie here, Ive been using pymongo package locally up until now, importing MongoClient and setting up a client with client=MongoClient() Im getting an connection refused error message. pymongo.errors.ConnectionFailure: [Errno 111] Connection refused Anyone Any Tips? What mongodb server are you trying to connect to? @glenn this is it, Ive been using localhost up until now...I'm looking into MongoLab here now after reviewing earlier comments. I assumed I could create a db locally here. I don't know where you got that idea. We don't support mongodb servers at all at the moment. So you're getting connection refused because there is nothing to talk to there. @glenn thanks for the info. Much appreciated :) @glenn I am using the hacker account and I cannot connect to a mongo db at MongoLab. The problem is that the MongoLab is on MongoDB version 3.0.x and on pythonanywhere you use pymongo 2.7.1 which has authentication problems with MongoDB 3.0.x. I am running locally with pymongo 3.2.1 and it works perfectly, but when I upload the same code to pythonanywhere it fails because of an auth error. Is there any way to update the pymongo plugin to a newer version. Please let me know because this issue is critical for me. Hi Martin, if you upgrade pymongo, does it help? Either by using a virtualenv or with the --user flag for pip? @harry I updated with the --user flag and it works now. Thanks a lot Thanks for confirming! Can I check if the mongo was installed for use as a custom console? I'm using python code and pymongo but some admin would be some much easier in a console directly (I am using mlabs). Maybe I just need some step by step help, thanks in advance! (Post above "will add a ticket to include the mongo client as part of our standard image...", July 2015 I think refers) P.S. I love PA I'm afraid we haven't got round to that no... Maybe you can download it and just run it from inside your home folder somehow though? If it needs compiling, we have gcc and so on... I have also asked for the mongo client, pretty recently. Since Harry proposed this first, I'll go ahead and mention it: it turns out that if you go find the mongo*tar.gz at their download site for Ubuntu 14 LTS and you unzip/unpack it, you get some binaries. One of them is mongo, but there are also things like mongodump and mongoimport/mongoexport, etc. The download site is here: You'll want to use wget to grab this: If you take these binaries and put them into ./local/bin, you're done. :-) (As long as .local/bin is in your path, and perhaps you might have to restart bash...) The mongo client connects to MLabs perfectly, and it functions as expected. Sometimes you have to read the docs very carefully to get the command line right, but in general it works quite well. Best wishes, -greg Hi, I have a free pythonanywhere account, does this mean I wont be able to access a remote MongoLab? Thank you. We have whitelisted mongolab in particular, and you will be able to access it over http/https. If you want to access anything else/over any other protocol you may need to upgrade. FYI, and I'm sure you're aware of this, Mongolab has changed its url to "mlab.com" and the remainder of their URLs now derive from that. -greg Yup, *.mlab.com is on the whitelist too. Totally understood. But I do have students using it at the $5 level, and we've had great success with it. Thanks for the clarification. Hello Admins, Based on the thread, I wanting to confirm the cause behind what I am seeing. I am using pymongo/pymodm to interface with the mongolab instance (pymodm as the ORM). I am getting the error: pymongo.errors.ServerSelectionTimeoutError: ds139288.mlab.com:39288: [Errno 111] Connection refused I am presuming, since I am free user, even though *.mlab.com is on the whitelist for free users, the fact that it tries to connect to port 39288 (and NOT 80), is why the connection is refused. Please do confirm/suggest alternatives. Thanks. -S. Yup. The non-http port is why it is blocked for free accounts. I tried what systix did and I have a student account. I am also using pymodm to interface with mlab. I get the the same [Errno 111] Connection refused. Any ideas how to fix this? You account has unrestricted internet access, so it should work. Have you tried it in a console that you started since your upgrade? Here's a help page about MongoDB on PythonAnywhere that hopefully will be useful for anyone with questions about this in the future. Any suggestions for extra stuff we should put on there much appreciated!
https://www.pythonanywhere.com/forums/topic/254/
CC-MAIN-2018-43
refinedweb
3,554
74.49
Root Mean Squared Error Overview One of the more standard measures of model accuracy when predicting numeric values is the Root Mean Squared Error. Basically, for every predicted value, you: - Find the difference between your prediction and the actual result - Square each value - Add each value together - Take the square root of that - Divide by the number of observations This allows us to get an absolute-value measure of how far off from correct each prediction was, over or under. Additionally we take the root (as opposed to just MSE), in order to express the error in interpretable units. Fitting a Model from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression # dummy dataset X, y = make_regression() X.shape, y.shape ((100, 100), (100,)) We want to build a simple Linear Regression model with our dummy data. But as we’ve discussed in other notebooks, we first need to split our data up into training and test sets, so let’s do that. from sklearn.model_selection import train_test_split train_X, test_X, train_y, test_y = train_test_split(X, y) [arr.shape for arr in train_test_split(X, y)] [(75, 100), (25, 100), (75,), (25,)] Now we can fit our model with our training data model = LinearRegression() model.fit(train_X, train_y) LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) And use that model to make a prediction on our test data model.predict(test_X) array([ 157.19999884, 182.84477034, 198.61054437, 168.05031037, 102.80607835, -161.14849689, -45.37499645, 77.02471828, 174.79940023, 70.73630468, 96.67254953, -22.69534224, -251.23474593, 191.22108821, -302.14564522, -149.39232913, 167.25523265, 212.15791823, 251.71364073, -90.09065502, -16.90454986, -21.64715521, 94.58179599, -292.43390204, 131.28127778]) Scoring Accuracy If we want to see how close we were, we compare against test_y and follow the same steps above. import numpy as np predictions = model.predict(test_X) error = predictions - test_y mse = np.sum(error * error) / len(error) rmse = np.sqrt(mse) rmse 59.635789214540765 Or we just use the sklearn implementation from sklearn.metrics import mean_squared_error mse = mean_squared_error(test_y, predictions) rmse = np.sqrt(mse) rmse 59.635789214540765
https://napsterinblue.github.io/notes/machine_learning/validation/rmse/
CC-MAIN-2021-04
refinedweb
349
65.12
Just my two cents on R side. On 1/28/21 10:00 PM, Nicholas Chammas wrote: > On Thu, Jan 28, 2021 at 3:40 PM Sean Owen <srowen@gmail.com > <mailto:srowen@gmail.com>> wrote: > > It isn't that regexp_extract_all (for example) is useless outside > SQL, just, where do you draw the line? Supporting 10s of random > SQL functions across 3 other languages has a cost, which has to be > weighed against benefit, which we can never measure well except > anecdotally: one or two people say "I want this" in a sea of > hundreds of thousands of users. > > > +1 to this, but I will add that Jira and Stack Overflow activity can > sometimes give good signals about API gaps that are frustrating users. > If there is an SO question with 30K views about how to do something > that should have been easier, then that's an important signal about > the API. > > For this specific case, I think there is a fine argument > that regexp_extract_all should be added simply for consistency > with regexp_extract. I can also see the argument > that regexp_extract was a step too far, but, what's public is now > a public API. > > > I think in this case a few references to where/how people are having > to work around missing a direct function for regexp_extract_all could > help guide the decision. But that itself means we are making these > decisions on a case-by-case basis. > > From a user perspective, it's definitely conceptually simpler to have > SQL functions be consistent and available across all APIs. > > Perhaps if we had a way to lower the maintenance burden of keeping > functions in sync across SQL/Scala/Python/R, it would be easier for > everyone to agree to just have all the functions be included across > the board all the time. Python aligns quite well with Scala so that might be fine, but R is a bit tricky thing. Especially lack of proper namespaces makes it rather risky to have packages that export hundreds of functions. sparkly handles this neatly with NSE, but I don't think we're going to go this way. > > Would, for example, some sort of automatic testing mechanism for SQL > functions help here? Something that uses a common function testing > specification to automatically test SQL, Scala, Python, and R > functions, without requiring maintainers to write tests for each > language's version of the functions. Would that address the > maintenance burden? With R we don't really test most of the functions beyond the simple "callability". One the complex ones, that require some non-trivial transformations of arguments, are fully tested. -- Best regards, Maciej Szymkiewicz Web: Keybase: Gigs: PGP: A30CEF0C31A501EC
https://mail-archives.us.apache.org/mod_mbox/spark-dev/202101.mbox/%3C79f01918-4354-0962-8cdd-e448707cb179@gmail.com%3E
CC-MAIN-2021-25
refinedweb
444
59.64
#include <stdlib.h> #include "core/net.h" #include "drivers/pcap/pcap_driver.h" #include "debug.h" #include <pcap.h> Go to the source code of this file. PCAP driver. pcap_driver.c. Definition at line 30 of file pcap_driver.c. Disable interrupts. Definition at line 342 of file pcap_driver.c. Enable interrupts. Definition at line 331 of file pcap_driver.c. PCAP event handler. Definition at line 353 of file pcap_driver.c. PCAP driver initialization. Definition at line 107 of file pcap_driver.c. Send a packet. Definition at line 387 of file pcap_driver.c. PCAP receive task. Definition at line 445 of file pcap_driver.c. PCAP timer handler. This routine is periodically called by the TCP/IP stack to handle periodic operations such as polling the link state Definition at line 320 of file pcap_driver.c. Configure MAC address filtering. Definition at line 433 of file pcap_driver.c. PCAP driver. Definition at line 80 of file pcap_driver.c.
https://oryx-embedded.com/doc/pcap__driver_8c.html
CC-MAIN-2018-51
refinedweb
155
64.98
If you are old enough to remember programming in the pre 1990s, you’ll likely have used the keyword “goto” in your code at some point and the longer you have been programming, the more you will have used it. If you came to programming after that, you’ll (hopefully) have been told from day one not to use it. You may even use a a language that doesn’t support it. The “goto” statement took a long time to die, but it has gone from being a fundamental programming concept to a programming pariah used by only the most misguided of developers (and possibly a few folk working on extreme edge-case applications.) This highlights the fact that software engineering/ craftsmanship is an evolving field, where what constitutes best practice can change over time. Other previously considered best practices have suffered a similar fate to the goto keyword, and I’ll cover some of those later. Others though seem to either resist challenge, or just never get properly challenged. I wish to address one of those here: the “private” keyword. Why do folk use private? There are two aspects of OO that at first glance seem to encourage it: encapsulation and inheritance: Encapsulation “Data hiding”, or encapsulation is key to OO. If I have a list class, I allow other classes to interact with the list, but I hide the list’s implementation away. Any developer using my List class should not need to worry about how the list is stored, instead I should provide a set of List-related methods, eg Split, AddToHead for manipulating it. Inheritance As “Uncle Bob” puts it: “The Open-Closed Principle … says that objects should be open for extension but closed for modification. In other words, you should be able to change what a module does without changing the module”. This principle was regarded as best practice in the early days of OO. The combined requirements of data hiding and preventing modification through inheritance inevitably gave rise to the private keyword for hiding member variables (fields) away. The thinking being that fields themselves should be private and that public methods should be provided for accessing those fields. Many younger developers may not aware of this, but this “open for extension but closed for modification” mantra led to some pretty daft ideas. One such was that if I had some arbitrary code: when it was noticed that Div(n, 0) results in an a divide by zero error, method Div would not be fixed as that would be modification of the API and so could impact existing code. Instead one would extend, eg: In the early 90s, I actually tried to argue for the adoption of this practice in the company I worked for at the time. With hindsight I am very pleased that I was voted down by my more pragmatic colleagues. These days, with the great ideas of unit tests and refactoring gaining in popularity, the mantra of “open for extension but closed for modification” has gone from a mere dubious idea to a downright debunked one. Modifying through refactoring is now positively encouraged. There is another twist in the tale of why “private” is so popular and that is due to properties (getters and setters if you prefer, though to my mind these should refer only to the weird accesor methods that Java has instead of proper properties). Because one can wrap a private field in a public read/ write property, there seems to have developed a consensus that one should do so always without exception. This is a bad state of affairs as it results in ridiculous stuff like: Why do I claim this is a ridiculous class? Two reasons. First, there is only pseudo encapsulation occurring with the class, as the the two properties fully expose the underlying data. They serve no purpose whatsoever other than to add complexity to the class (thus increasing the chances of bugs) whilst fulfilling some grossly misguided belief that best practice is being followed. The other is that it is a classic attempt at writing a value object (VO) by someone who doesn’t know what a VO is. A key feature of a VO is that it should be immutable: its a value, not a reference. Shame on you if you didn’t spot that! 😉 Before we go any further, let me make one thing clear: the well thought out use of public properties and hidden fields is good practice as it hides the implementation. What I’m suggesting is that blindly using them in a simple full-mutable record-style (or tuple-style if you prefer) class is bad practice. We can rewrite the above class to make it a proper VO: You may notice that I’ve not only made the class a true VO, I’ve switched the fields from private to protected. This brings us to the main topic: why using protected rather than private for fields should be regarded as good practice and the use of the private keyword should be avoided at all costs. As previously mentioned, one reason people use private rather than protected stems from the outdated idea of “extend, do not modify”, but there is more to it than that. There is also a belief that developers somehow need protecting from side effects within the base class when extending it and from needing to know about the base class’ inner workings. Many such folk seem to view public and protected as somehow equivalent. They are not. Protected respects encapsulation; public doesn’t. Finally, people just use private because that is what other folk, and many automatic tools, do. Regarding the second point, I personally find this attitude both patronising and symptomatic of a lazy attitude to writing classes. Its patronising in that the base class’ developer doesn’t trust me. It’s lazy because documenting a class properly for the benefit of anyone wanting to extend it takes effort. It’s much easier to just mark everything private and hide it away. This attitude is especially annoying when used in frameworks or libraries for which the source is available. I can see those useful fields and support methods sitting there tempting me, but I can’t access them. I’m sure I’m not the only one who has had to resort to cutting and pasting the code for a set of private members out of a base class into a sub class in order to modify some subtle aspect of the base class’ behaviour simply because the original developer used the private keyword. If they’d used protected, then the issue would never have arisen. If you have ever done more than simple work with the Flex SDK, then you’ll likely know exactly what I mean. Even when the source isn’t available, debuggers taunt the developer with details of private members beyond our reach. This, coupled with the over-zealous use of the private keyword, has even spawned an entire micro-industry in hacks to the Flash event classes to work around its perceived shortcomings. I found an article by the previously mentioned software engineer, “Uncle Bob”, which argues the opposite of this article. It is worth addressing the points he raises in order to explain why those points are misguided in my view, which should reinforce why I’m so anti the “private” keyword. “How do you protect a module from the forces that would try to modify it?” As previously discussed, inheritance is all about modification (what’s the override keyword for, if not for providing alternate behaviour for a method for example?) If you want to protect a class from modification, make it immutable and final. If you don’t make it immutable and final, accept that someone developing a sub class is doing so because they want to modify your class’ behaviour! So please make it simple for them to do so. “If a variable is not private, then it is open to be used in a way that the module that owns that variable does not intend … For example, given a variable v used by a module m, such that v should never be negative. If you make v … protected someone could set it to a negative number breaking the code in m…” Write your class. Document how it works. Document that v should not be negative and explain why. Then step away and leave sub class developers to make up their own minds. If I chose to make v negative, then I have to deal with the consequences. Don’t treat me as a child and try to prevent me doing so. If course if v is to be accessible outside of m‘s inheritance tree, put a public property in place to prevent outside agencies making it negative. Again: public and protected are not equivalent. Protected respects encapsulation; public doesn’t. “Privacy does not preclude extensibility. You can create public or protected accessor methods that: 1) provide extenders access to certain variables, and 2) ensure that the extenders don’t use the variable in an unintended way.” Let’s rewrite that to reflect modern software development techniques and what ought to be best practice. Encapsulation does not preclude access to an object’s protected values. You can create public properties that provide external functionality access to those values whilst ensuring that the external functionality cannot modify those values in an unintended way. Conclusion To wrap up, here is a list of what I’d regard as best practice with regard to what’s been discussed here: - Avoid using the “private” keyword. If possible, never use it. Pretend it doesn’t exist. - Follow some sensible rules of encapsulation: - Is the class as simple record/ tuple-style class (a DTO) with no methods for causing side effects to the fields? If so, make the fields public. - If not, does the field contain data that needs to be exposed to external functionality? If yes then make it protected and wrap it in a public property only if changing its value has side effects, it needs validating or it is a read-only value. If it doesn’t need validating, has no side effects and doesn’t need to be read-only, leave it public. - If the field should not be exposed to external functionality then make it protected. - Properly document your class so that developers can easily extend it and can understand the consequences of modifying the base class’ behaviour. Remember, unless you unlucky enough to be using Java or another archaic language with no proper property support, you can always refactor your class to replace a public field with a protected one with a public accessor property if requirements change. Refactoring is the key: do not design your class with future expectations in mind. Design it to meet only your current requirements and write unit tests to test that functionality. Then in future you can refactor to meet new requirements (which probably won’t be what you were expecting) confident in the knowledge that your unit tests will pick up any breakdown in existing functionality. If enough developers adopted these modern development best practices, we just might be able to consign the private keyword to software engineering history, which is where it belongs. UPDATE: I have written a new – shorter! – article that demonstrates the unit-testing benefits of using protected rather than private. See ‘Real world use-case of “use protected, not private”‘ 62 thoughts on “Why the “private” keyword is the modern day “goto”” 6. thanks for re-iterating my point, but why? again on point 3. to make something extensible does not mean to make all variables accessible to the extending class by using protected this is “sometimes” the only way to do so in an intelligible manner but by no means is or should this be the only way to design something with extension in mind. The last few years I have also come to the conclusion that private survives little use… and is more cumbersome… fields might as well be protected and offer the possibility of more flexibility in derived classes. David, Excellent article! Just one comment: everything you said about ‘private’ shouldn’t also stand for ‘final’? I mean: if you are really really absolutely positively sure that your class should be ‘final’, why not just document it as this and let the developers ‘deal with the consequences’ if they wish to inherit from it? I think two worlds are clashing here: the library developers and the library users. The first want ‘private’ to have freedom to modify their classes without breaking user’s code; the other want freedom to modify the library without touching the library itself. I feel the first is the less reason. Modifications are extensions in most cases, and often you can put the modification into a derived class, where you are free to define new private members. After I was forced to use ‘#define private protected’ a couple of times, I adopted two simple policies: 1. I put data members into ‘protected’ instead of ‘private’ if I have no good reason to do otherwise. I use ‘private’ only if I am absolutely sure the connected functionality *must* be handled in this class. The typical guidelines say that data members are best in ‘private’; I do not think so. 2. never put functions in private. If a function in ‘protected’ is using private members, it is going to be ‘semantically private’ anyway (meaning you cannot put the same code in a derived class), but I let people who are deriving from my class to replace the function or use it if they want. It is their mess. When I saw this post title, I said to myself, ‘Hey, this man is throwing the one rock to make the avalanche!’. And the avalanche is keep rollin’ until now. Long time ago, when there are no AS3, I believe that any inaccessible part of a class should be labeled as a private member. And after I dive into big projects using AS3 I keep swearing library creators as I had to made a turn around to solve some of possibly simple problems. Sometimes it’s just because I can’t name my new method with the built in method that inaccessible. Sometimes I just need to made a little change to the existing ones. All in all, +1 for modifiable private methods, keep the private still in private, but let me modify it if I really need to do. In other words : Use protected for useful methods! (That pretty the same, but I hope you understand what I meant to say) Hey there David, I’d like to ask you a question, if you don’t mind. In one of your comments, you mentioned “modern managed languages” in opposition to C++. Now, I’ve been getting the impression that you’re not too fond of Java (which I would regard as at least more recent than C++), either, so could you give some examples what languages you’re thinking of or which ones you’d recommend? Note that I have very little experience with programming, so I don’t really know what the more subtle benefits/detriments of C++ or Java are. @Socob, There is no simple answer to your question. What do you want to do with the language? Which platforms do you want to target? Which languages do you enjoy using? Is speed or maintainability more important to you? Do any patterns particularly appeal to you? Do you like to develop using the command line or do you prefer to stay within an IDE? I was afraid something like that would be the answer. Generally, for my purposes, I’m not unhappy with what I’m using right now, which is Delphi – of course, if you have some kind of opinion on that, I’d be glad to hear about it. However, I was intrigued when you talked about said unnamed “modern” languages, because it sounded like you had something specific in mind. Additionally, at least to my knowledge, there haven’t really been any ground-breaking newcomers to the group of programming languages since Java (the only more recent thing worth mentioning that I can think of is C#, which I know nothing about), so I was surprised when you complained about Java’s age/lack of modernity. Another thing is that with Delphi, sometimes I feel like things are more complicated to do than, say, in PHP. Now, PHP probably isn’t the best example for a “good” language, but its arrays with string indices (array[“a”]) is something that springs to my mind. It’s not the only example, but more like a general feeling I have. So, really, I don’t know exactly what I’m looking for. I just have this feeling that there’s something I don’t know about and that I’m missing out on. I’m sorry that you’ve had to put up with my ramblings, but if you can make some sense of it, I’d appreciate it if you could comment on it. Don’t use “private”, don’t use protected either. Document props and methods as private. Don’t type props. Let everything be objects, only document variables as what their interfaces are. And namespaces – who needs them if You can just put info in docs… Sorry for sarcasm, but I just found it as the shortest way to describe my opinion about this idea. What You encourage, David, I think we call a philosophy of liberal programming, where user is not hampered in any way, he’s free and can do what he wants with the libraries. I agree with that. Sometimes, however, a developer doesn’t want to let users use his library beyond his own functionality. Sometimes users want the same – mainly because when there are no private properties, then everything is private – I don’t know which parts I shouldn’t change on my own, so for future compatibility I don’t change anything. Similarly, if I’ll read in an instruction of an electric kettle that I can do whatever I want with it, then I’ll be scared to touch it with wet hands, as opposed to an instruction that clearly state what’s dangerous. only document classes* as what their interfaces are. @Broady, You offer a reductio ad absurdum fallacy as your argument and thus it is unfortunately a non-argument regardless of whether you are being sarcastic or not. If a developer doesn’t want a user to use his library beyond his own functionality, then the correct thing to do is to mark the classes as final or sealed. If a class is not marked that way, the developer is implicitly allowing the user to extend and override the built-in functionality. In this case, avoiding private and using protected instead encourages the developer to document how the class works from the perspective of a user wishing to extend and override the built-in functionality. In the nine months since I wrote this article I have been examining both my own and other people’s code with regard to the use of the private keyword. What has struck me the most is that it is harder as a library developer to use protected as one must document better. Private is the lazy developer’s tool of choice…
http://www.davidarno.org/2010/07/22/why-the-private-keyword-is-the-modern-day-goto/
CC-MAIN-2016-40
refinedweb
3,253
59.53
Dj continue using the regular username format, you can do that too. It's the best of both worlds! To make sure propoer credit is given, this code is modified from a django group posting from Vasily Sulatskov. To use this file, save it in your project as something like: email-auth.py Then, add the following lines to your settings.py file: AUTHENTICATION_BACKENDS = ( 'yourproject.email-auth.EmailBackend', ) You can see a full implementation here - Author: - chris - Posted: - March 2, 2007 - Language: - Python - authentication - Score: - 47 (after 49 ratings) Does it works admin app? In my case not :) # This is certainly a useful snippet, but it seems a little over complicated. What's wrong with just: ...and then just adding it in front of Django's ModelBackend? # The admin login view displays a message "Your email address is not your username" if you attempt to login with an email address and password that do not match (e.g. mistyped the password). # adurdin: Alter your template registration/login.html to reflect the change in authentication method. chris: Just thought I'd let you know, I'm using this and it seems to work very well Thanks # The problem is, the email field in User model is not unique, so you have to do 2 things: monkeypatch your database by addinng necessary constraint to the email field and generate some-kind-of-unique username. Unfortunately, the field is only allowed to keep 30 characters, so you cann't just use munged email or md5 hash for username... # More problems with this. Users of our applications keep reporting me various places in django's own admin where "weird" usernames are shown. Sometimes it's really hard to customize admin templates to display something other than default __str__provided by Django. I'm thinking on dynamic replacing __str__in django.contrib.auth.models.User, maybe using signals? # The key to having this work with user object functions like 'has_perm()' and the admin interface is that you have to add both the new and default backends to your settings file: 'AUTHENTICATION_BACKENDS = ( 'yourproject.email-auth.EmailBackend', "django.contrib.auth.backends.ModelBackend", ) ' # One other thing - the max_length for username in contrib.auth.forms.login is 30. It should be increased to the length of the email field, 75 characters by default. # Sorry if this is a dumb question, but what would be the correct way to do that? # Rich: Probably two ways. Firstly, you can manually alter the database yourself after running syncdb. In fact, you could hook a callback onto the post_syncdb signal to do it automatically every time. Secondly, you could simply edit the django source which is installed to change the field width. Find and edit the User class in django/contrib/auth/models.py. # lars: I misread this the first time too. cogat is saying the the FORM field is limited to 30 chars. nothing to do with the db. the database still stores a username (whatever you want, random, truncated version of email etc.) but the EmailBackend checks against the EMAIL in the db. the db does not have to be altered thus. # Also see this blog post which does a similar thing, but looks for a separate "email" argument to the "authenticate" method. # In Django 1.0 (since beta2) replace from django.core.validators import email_re with from django.forms.fields import email_re Frank, web development Manchester # How can we make it so there is no username field at all? We have 20,000 Users and they all use their emails currently. (making a switch to django) # This is good, but there is a problem - the authentication form limits usernames to 30 characters - emails longer than that are rejected by the charfield clean method. To properly allow for the (legitimate) case of emails longer than 30 characters the authentication views need to be overridden. # A solution for the problem is suggested here: Basically you can monkey patch the form with: AuthenticationForm.base_fields['username'].max_length = 75 #
http://www.djangosnippets.org/snippets/74/
crawl-002
refinedweb
662
66.44
Getting the Mouse Position (Windows, Windows Phone) On Windows, you can use Mouse.GetState at any time to get the mouse position and the state of the mouse buttons. On Windows Phone, you can also get the primary touch location by using GetState, but only when MouseState.LeftButton is in the Pressed state. The locations in MouseState.X and MouseState.Y will then correspond to the primary touch location on the screen. When LeftButton is in the Released state, X and Y are invalid. To retrieve the current mouse position on Windows Call Mouse.GetState to get the MouseState object. Read MouseState.X and MouseState.Y to get the mouse position, in pixels, relative to the upper-left corner of the game window. To retrieve the primary touch location on Windows Phone Call Mouse.GetState to get the MouseState object. If LeftButton is in the Pressed state, read MouseState.X and MouseState.Y to get the screen coordinates of the primary touch location. Example The following code demonstrates this procedure: MouseState ms = Mouse.GetState(); if (gameIsPaused) { if(pausedImageOnScreen && (ms.LeftButton == ButtonState.Pressed)) { gameIsPaused = false; } base.Update(gameTime); return; } // on Windows, the current state of the mouse cursor can be obtained at any time. #if WINDOWS curMousePos.X = ms.X; curMousePos.Y = ms.Y; #endif // if the mouse button is held down (or the touchscreen is pressed for phone), drop // a piece of food at the location given. if (canDrop && ms.LeftButton == ButtonState.Pressed) { foodLocations.Add(new Vector2(ms.X, ms.Y)); canDrop = false; } else if (ms.LeftButton == ButtonState.Released) { // wait until the button is released before allowing the player to drop another // piece of food. canDrop = true; }
http://msdn.microsoft.com/en-ie/library/bb197572(en-us).aspx
crawl-003
refinedweb
277
61.83
Line fronts Using the pygmt.Figure.plot method you can draw a so-called front which allows to plot specific symbols distributed along a line or curve. Typical use cases are weather fronts, fault lines, subduction zones, and more. A front can be drawn by passing f[±]gap[/size] to the style parameter where gap defines the distance gap between the symbols and size the symbol size. If gap is negative, it is interpreted to mean the number of symbols along the front instead. If gap has a leading + then we use the value exactly as given [Default will start and end each line with a symbol, hence the gap is adjusted to fit]. If size is missing it is set to 30% of the gap, except when gap is negative and size is thus required. Append +l or +r to plot symbols on the left or right side of the front [Default is centered]. Append +type to specify which symbol to plot: box, circle, fault (default), slip, or triangle. Slip means left-lateral or right-lateral strike-slip arrows (centered is not an option). The +s modifier optionally accepts the angle used to draw the vector (default is 20). Alternatively, use +S which draws arcuate arrow heads. Append +ooffset to offset the first symbol from the beginning of the front by that amount (default is 0). The chosen symbol is drawn with the same pen as set for the line (i.e., via the pen parameter). To use an alternate pen, append +ppen. To skip the outline, just use +p with no argument. To make the main front line invisible, add +i. Out: <IPython.core.display.Image object> import numpy as np import pygmt # Generate a two-point line for plotting x = np.array([1, 4]) y = np.array([20, 20]) fig = pygmt.Figure() fig.basemap(region=[0, 10, 0, 20], projection="X15c/15c", frame='+t"Line Fronts"') # Plot the line using different front styles for frontstyle in [ # line with "faults" front style, same as +f (default) "f1c/0.25c", # line with box front style "f1c/0.25c+b", # line with circle front style "f1c/0.25c+c", # line with triangle front style "f1c/0.3c+t", # line with left-lateral ("+l") slip ("+s") front style, angle is set to 45 # and offset to 2.25 cm "f5c/1c+l+s45+o2.25c", # line with "faults" front style, symbols are plotted on the left side of # the front "f1c/0.4c+l", # line with box front style, symbols are plotted on the left side of the # front "f1c/0.3c+l+b", # line with circle front style, symbols are plotted on the right side of # the front "f1c/0.4c+r+c", # line with triangle front style, symbols are plotted on the left side of # the front "f1c/0.3c+l+t", # line with triangle front style, symbols are plotted on the right side of # the front, use other pen for the outline of the symbol "f1c/0.4c+r+t+p1.5p,dodgerblue", # line with triangle front style, symbols are plotted on the right side of # the front and offset is set to 0.3 cm, skip the outline "f0.5c/0.3c+r+t+o0.3c+p", # line with triangle front style, symbols are plotted on the right side of # the front and offset is set to 0.3 cm, skip the outline and make the main # front line invisible "f0.5c/0.3c+r+t+o0.3c+p+i", ]: y -= 1 # move the current line down fig.plot(x=x, y=y, pen="1.25p", style=frontstyle, color="red3") fig.text( x=x[-1], y=y[-1], text=frontstyle, font="Courier-Bold", justify="ML", offset="0.75c/0c", ) fig.show() Total running time of the script: ( 0 minutes 3.965 seconds) Gallery generated by Sphinx-Gallery
https://www.pygmt.org/v0.5.0/gallery/lines/linefronts.html
CC-MAIN-2022-27
refinedweb
640
75.5
I agree on some of the points, but disagree on two points. Point 1. Python structures have development and execution speed. I agree. Python can get even better than a list of dictionaries, using a structure which is either a LIst or a diCTionary at each level (a "lict"). Just recursively get the children. Notice notice whether the attributes are unique to decide whether to make a list or a dictionary. Point 2. Objects are more obvious than python dictionaries. I disagree. The one thing in mathematics one needs to learn in order to do topology, category theory, abstract algebra, homology, cohomology, braids, and K-Theory is: the arrow. An arrow from A to B means that "for each a in set A, there is exactly one b in set B." >From this all more advanced mathematical concepts form. The two most important of these mathematical concepts which are based on the arrow diagram are: - the SQL dependency model - the Python dictionary model In my opinion, the consecutive python dictionary references: database["table_name"]["row_key"]["column_name"] is easier to work with than: database.get_cell(database.get_table("table_name"), "row_key", database.get_column("table_name", "column_name")) And very similar abbreviations can be used for efficiency in both cases. table=database["table_name"] row=table["row_key"] cell=row["column_name"] vs. table=database.get_table("table_name") column_id=table.get_column("column_name") row=table.get_row("row_key") cell=row.get_column(column_id) Point 3. A "standard" object model might be better. I disagree. For example, in Java, the new JDOM model makes it one level less deep to access the nodes in an XML document. Since Java came up with a new "standard" model that is easier to work with and also faster at runtime, than DOM, it follows that current standards are not perfect. JDOM is just one step better than DOM. There are many steps better to be gotten. The same in Python. We are nowhere near a good object model, nor does RDF, SVG, or any of the other complex applications based on XML come close to the level of the model we will shortly be needing. We should always be looking to improve our data models, and an object model is just one aspect of our data model. Even objects themselves should be reevaluated and thrown away when something better is discovered. For example, bottom-up object-oriented design replaced top-down design just about everywhere except at the requirements level where the objects come together to actually solve a problem. That happened because we need to test software to make it work, but people don't like to test, and bottom-up requires less testing. Therefore, the replacement for object-oriented design will be something that requires even less testing than objects. Of course, the answer is arrows. The replacement for objects will be dataflow diagrams with their constraints expresses as mathematical dependencies between sets (that is, arrow diagrams). UML use cases, dataflow diagrams, hierarchy diagrams, finite state machines, and Sequence Diagrams are just the beginning. Someday someone will modify UML and Object Oriented Design by: - adding "arrow-dependencies" strong enough to express geometric and semantical constraints - changing the finite state machines to colored Petri nets - combining the sequence diagrams with timing charts - adding sprite graphics to SVG - adding XLINK, XSQL, etc., to browsers - standardizing the javascript on browsers - permitting browser to print multi-page diagrams - enhancing activities to include the whole 2D hierarchy of processes-activities-tasks and requirements-activities-outputs, annotating them with the tools used - adding a default web rendering of data as relational 2D tables like spreadsheets with a SQL query in each cell, with mouse adjustable-width cells, floating headers, and updating just like a spreadsheet only over the web (any other rendering would require a few minutes of rendering programming) after which objects will be obsolete. This could happen as early as 5 years from now. Paul wrote: > Before the XML heavyweights get in on this, I would make the following points:> > * A lists and dictionaries approach certainly has its merits: > speed (at least according to the PyRXP people), familiarity, > interoperability with other Python stuff. > > * Once you start to look into more advanced features, it would > seem to me that the lists and dictionaries model approaches > such a level of complexity that a "proper" object model would > be better. That is because you would need to find more > efficient ways (in terms of expression) of requesting an > attribute with a given namespace, for example, than examining > raw dictionaries. Certainly, it appears to me that... > > attr = element.getAttributeNS(some_namespace, some_name) > > ...is more obvious than... > > attr = element[some_namespace][some_name] > > ...especially if it's hidden in lots of heavy XML processing > code. > > * You could write your own object model. Frederik Lundh's > ElementTree is like this. I'm not 100% convinced that it's > beneficial to drop a standard object model that is widely > understood for another which is more Pythonic, although this > is a tradeoff that might be appropriate for some situations.
https://mail.python.org/pipermail/python-list/2003-January/209599.html
CC-MAIN-2017-30
refinedweb
828
52.19
Make -- A Tutorial Adam de Boor Berkeley Softworks 2150 Shattuck Ave, Penthouse Berkeley, CA 94704 adam@bsw.uu.net ...!uunet!bsw!adam 1. Introduction This is a historic document describing PMake, the antecessor of BSD and MirOS make, NetBSD(TM) nmake and some others. Please keep this in mind while reading the following docu- mentation. In case of doubt please consider the manual page for your make executable. Make is a program for creating other programs, or anything else you can think of for it to do. The basic idea behind Make is that, for any given system, be it a program or a document or whatever, there will be some files that depend on the state of other files (on when they were last modi- fied). Make takes these dependencies, which you must specify, and uses them to build whatever it is you want it to build. OpenBSD's Make is based upon PMake, a parallel make origi- nally developed for the distributed operating system called Sprite. PMake departs from usual Make practices in several ways. A large number of those quirks are not relevant in a modern POSIX world, and hence development of OpenBSD's make has aimed at removing unwanted differences. Useful features of OpenBSD's Make which are not POSIX compliant will be flagged with a little sign in the left margin, like this: Also note that this tutorial was originally written for PMake, and hence may not be totally accurate. This tutorial is divided into three main sections _________________________. April 9, 2016 PSD:12-2 Make -- A Tutorial corresponding to basic, intermediate and advanced Make usage. If you already know Make well, you will only need to skim chapter 2. Things in chapter 3 make life much easier, while those in chapter 4 are strictly for those who know what they are doing. Chapter 5 has definitions for the jar- gon I use and chapter 6 contains possible solutions to the problems presented throughout the tutorial. 2. The Basics of Make Make, Make will look for Makefile and makefile (in that order) in the current directory if you don't tell it otherwise. To specify a different makefile, use the -f flag (e.g. ``make -f program.mk''). A makefile has four different types of lines in it: + File dependency specifications + Creation commands + Variable assignments + Comments, include statements and conditional direc- tives Any line may be continued over multiple lines by ending it with a backslash. The backslash, following newline and any initial whitespace on the following line are compressed into a single space before the input line is examined by Make. 2.1. Dependency Lines depen- dencies deter- mined by the ``operator'' that separates them. Three types of operators exist: one specifies that the datedness of a target is determined by the state of its sources, while April 9, 2016 Make -- A Tutorial PSD:12-3 fol- lows: : If a colon is used, a target on the line is considered to be ``out-of-date'' (and in need of creation) if + any of the sources has been modified more recently than the target,: + any of the sources has been modified more recently than the target, or + the target doesn't exist, or + the target has no sources. If the target is out-of-date according to these rules, it will be re-created. This operator also does some- thing else to the targets, but I'll go into that in the next section (``Shell Commands''). Enough words, now for an example. Take that C program I men- tioned earlier. Say there are three C files (a.c, b.c and c.c) each of which includes the file defs.h. The dependen- cies link- ing together .c files -- it must be made from .o files. Likewise, if you change defs.h, it isn't the .c files that need to be re-created, it. E.g. a.o depends on both defs.h and a.c. April 9, 2016 PSD:12-4 Make -- A Tutorial The order of the dependency lines in the makefile is impor- tant: the first target on the first dependency line in the makefile will be the one that gets made if you don't say otherwise. That: {} These enclose a comma-separated list of options and cause the pattern to be expanded once for each element of the list. Each expansion contains a different ele- ment. Make con- tained in the list. E.g. [A-Za-z] will match all letters, while [0123456789] will match all numbers. 2.2. Shell Commands ``Isn't that nice,'' you say to yourself, ``but how are files actually `re-created,' as he likes to spell it?'' The re-creation is accomplished by commands you place in the makefile. These commands are passed to the MirBSD Korn shell (better known as ``/bin/mksh'') to be executed and are expected to do what's necessary to update the target file (Make set of one or more of these shell commands. The creation script for a target should immediately follow the dependency line for that tar- get. set of shell commands. This set April 9, 2016 Make -- A Tutorial PSD:12-5 of shell commands will only be executed if the target on the associated dependency line is out-of-date with respect to the sources on that line, according to the rules I gave ear- lier. I'll give you a good example of this later on. To expand on the earlier makefile, you might add commands as follows: program : a.o b.o c.o depen- dency Make to do different things. In most cases, shell commands are printed before they're actually executed. This is to keep you informed of what's going on. If an `@' appears, however, this echoing is suppressed. In the case of an echo command, say ``echo Link- ing index,'' it would be rather silly to see echo Linking index Linking index so Make, Make will consider an error to have occurred if one of the shells it invokes returns a non-zero status. When it detects an error, Make's usual action is to abort whatever it's doing and exit with a non- zero status itself (any other targets that were being April 9, 2016 PSD:12-6 Make -- A Tutorial created will continue being made, but nothing new will be started. Make will exit after the last job finishes). This behavior can be altered, however, by placing a `-' at the front of a command (``-mv index index.old''), certain command-line arguments, or doing other things, to be detailed later. In such a case, the non-zero status is sim- ply ignored and Make keeps chugging along. In Make -j mode, a set of shell commands attached to a tar- get is fed to a shell as a single script. This is experi- mental behavior from PMake's period which hasn't been fixed yet. Make has a -B flag (it stands for backwards-compatible) that forces each command to be given to a separate shell. Unfor- tunately, it also inhibits -j. termi- nal. If you can't do this for some reason, your only other alternative is to use Make in its fullest compatibility mode. See Compatibility in chapter 4. 2.3. Variables Make has the ability to save text in variables to be recalled later at your convenience. Variables in Make April 9, 2016 Make -- A Tutorial PSD:12-7 Any whitespace before value is stripped off. When appending,- lines (other than the final one) are replaced by spaces before the assignment is made. This is typically used to find the current directory via a line like: CWD != pwd Note: this command will be invoked each time the Makefile is parsed, regardless of whether or not the result will actu- ally be used for making targets. If the end result is only needed for shell commands, it is much cheaper to use VARIABLE = `shell-command` The value of a variable may be retrieved by enclosing the variable name in parentheses or curly braces and prefixing the whole thing with a dollar sign. For example, to set the variable CFLAGS to the string ``-I/usr/local/include -O,'' you would place a line CFLAGS = -I/usr/local/include -O in the makefile and use the word $(CFLAGS) wherever you would like the string -I/usr/local/include -O to appear. This is called variable expansion. To keep Make from substituting for a variable it knows, pre- cede the dollar sign with another dollar sign. (e.g. to pass ${HOME} to the shell, use $${HOME}). This causes Make, in effect, to expand the $ macro, which expands to a single $. There are two different times at which variable expansion occurs: When parsing a dependency line, the expansion occurs immediately upon reading the line. If any variable used on a dependency line is undefined, Make will print a message and exit. Variables in shell commands are expanded when the com- mand is executed. Variables used inside another variable are expanded whenever the outer variable is expanded (the expan- sion of an inner variable has no effect on the outer vari- able. I.e. if the outer variable is used on a dependency line and in a shell command, and the inner variable changes value between when the dependency line is read and the shell command is executed, two different values will be substi- tuted for the outer variable). Variables come in four flavors, though they are all expanded the same and all look about the same. They are (in order of expanding scope): April 9, 2016 PSD:12-8 Make -- A Tutorial + Local variables. + Command-line variables. + Global variables. + Environment variables. The classification of variables doesn't matter much, except that the classes are searched from the top (local) to the bottom (environment) when looking up a variable. The first one found wins. 2.3.1. Local Variables Each target can have as many as seven local variables. These are variables that are only ``visible'' within that target's shell commands and contain such things as the target's name, all of its sources (from all its dependency lines), those sources that were out-of-date, etc. POSIX defines short names for these variables, which should be used for porta- bility. OpenBSD's Make has longer synonyms, which will be used in the rest of this tutorial for clarity. Four local variables are defined for all targets. They are: .TARGET The name of the target (POSIX: @). .OODATE The list of the sources for the target that were considered out-of-date. The order in the list is not guaranteed to be the same as the order in which the dependencies were given. (POSIX: ?) .ALLSRC The list of all sources for this target in the order in which they were given. (shorter: >, not POSIX). .PREFIX The target without its suffix and without any leading path. E.g. for the target ../../lib/compat/fsRead.c, this variable would contain fsRead (POSIX: *) . Three other local variables are set only for certain targets under special circumstances. These are the ``.IMPSRC,'' ``.ARCHIVE,'' and ``.MEMBER'' variables. When they are set and how they are used is described later. Four of these variables may be used in sources as well as in shell commands. These are ``.TARGET'', ``.PREFIX'', ``.ARCHIVE'' and ``.MEMBER''. The variables in the sources are expanded once for each target on the dependency line, providing what is known as a ``dynamic source,'' allowing you to specify several dependency lines at once. For exam- ple, $(OBJS) : $(.PREFIX).c will create a dependency between each object file and its corresponding C source file. April 9, 2016 Make -- A Tutorial PSD:12-9 2.3.2. Command-line Variables Command-line variables are set when Make is first invoked by giving a variable assignment as one of the arguments. For example, make "CFLAGS = -I/usr/local/include -O" in a sane way, (you don't want to know). := and ?= will work if the only variables used are in the environment. != is sort of pointless to use from the command line, since the same effect can no doubt be accomplished using the shell's own command substitution mechanisms (backquotes and all that). 2.3.3. Global Variables Global variables are those set or appended-to in the makefile. There are two classes of global variables: those you set and those Make sets. As I said before, the ones you set can have any name you want them to have, except they may not contain a colon or an exclamation point. The variables Make sets (almost) always begin with a period and always contain upper-case letters, only. The variables are as fol- lows: MAKE The name by which Make was invoked is stored in this variable. .MAKEFLAGS All the relevant flags with which Make was invoked. This does not include such things as -f.. 2.3.4. Environment Variables Environment variables are passed by the shell that invoked Make and are given by Make to each shell it invokes. They are expanded like any other variable, but they cannot be altered in any way. Using all these variables, you can compress the sample April 9, 2016 PSD:12-10 Make -- A Tutorial makefile even more: OBJS = a.o b.o c.o program : $(OBJS) cc $(.ALLSRC) -o $(.TARGET) $(OBJS) : defs.h a.o : a.c cc -c a.c b.o : b.c cc -c b.c c.o : c.c cc -c c.c 2.4. Comments Comments in a makefile start with a `#'. Make will compress the two into a single `#'. 2.5. Parallelism PMake was specifically designed to re-create several targets at once, when possible, when using the -j flag $$). The other problem comes from improperly-specified dependen- cies that worked in sequential mode. While I don't want to go into depth on how Make works (look in chapter 4 if you're interested), I will warn you that files in two different ``levels'' of the dependency tree may be examined in a dif- ferent order in parallel mode than in sequential mode. For example, given the makefile a : b c b : d Make may examine the targets in the order c, d, b, a. If the makefile's author expected Make to abort before making c if an error occurred while making b, or if b needed to exist April 9, 2016 Make -- A Tutorial PSD:12-11 before c was made, s/he will be sorely disappointed. The dependencies are incomplete, since in both these cases, c would depend on b. So watch out. Another problem you may face is that, while Make is set up to handle the output from multiple jobs in a graceful fashion, the same is not so for input. It has no way to regulate input to different jobs, so if you use the redirec- tion from /dev/tty I mentioned earlier, you must be careful not to run two of the jobs at once. 2.6. Writing and Debugging a Makefile Now you know most of what's in a makefile, what do you do next? There are two choices: (1) use one of the uncommonly- available makefile generators or (2) write your own makefile (I leave out the third choice of ignoring Make and doing everything by hand as being beyond the bounds of common sense). When faced with the writing of a makefile, it is usually best to start from first principles: just what are you try- ing've got three source files, in C, that make up the program: main.c, parse.c, and output.c. Harking back to my pithy advice about dependency lines, you write the first line of the file: expr : main.o parse.o output.o because you remember expr is made from .o files, not .c files. Similarly for the .o files you produce the lines:) April 9, 2016 PSD:12-12 Make -- A Tutorial): 1) The string ``main.o parse.o output.o'' is repeated twice, necessitating two changes when you add postfix (you were planning on that, weren. 2) There is no way to alter the way compilations are per- formed: April 9, 2016 Make -- A Tutorial PSD:12-13ol- lary: Variables are your friends. Once you've written the makefile comes the sometimes- difficult task of making sure the darn thing works. Your most helpful tool to make sure the makefile is at least syn- tactically correct is the -n flag, which allows you to see if Make will choke on the makefile. The second thing the -n flag lets you do is see what Make would do without it actu- ally doing it, thus you can make sure the right commands would be executed were you to give Make its head. When you find your makefile isn't behaving as you hoped, the first question that comes to mind (after ``What time is it, anyway?'') is ``Why not?'' In answering this, one flag will serve you well: ``-d m.'' This causes Make to tell you as it examines each target in the makefile and indicate why it is deciding whatever it is deciding. You can then use the information printed for other targets to see where you went wrong. Something to be especially careful about is circular depen- dencies. E.g. a : b b : c d d : a In this case, because of the way Make works, c is the only thing Make will examine, because d and a will effectively fall off the edge of the universe, making it impossible to examine b (or them, for that matter). Make will tell you (if run in its normal mode) all the targets involved in any cycle it looked at (i.e. if you have two cycles in the graph (naughty, naughty), but only try to make a target in one of them, Make will only tell you about that one. You'll have to try to make the other to find the second cycle). When run as Make, it will only print the first target in the cycle. 2.7. Invoking Make Make comes with a wide variety of flags to choose from. They may appear in any order, interspersed with command-line variable assignments and targets to create. Some of these flags are as follows: -d what This causes Make to spew out debugging information that may prove useful to you. If you can't figure out why Make is doing what it's doing, you might try using this April 9, 2016 PSD:12-14 Make -- A Tutorial flag. The what parameter is a string of single charac- ters that tell Make what aspects you are interested in. Most of what I describe. makefile Specify a makefile to read different from the standard makefiles (Makefile or makefile). If makefile is ``-'', Make uses the standard input. This is useful for making quick and dirty makefiles... -i If you give this flag, Make will ignore non-zero status returned by any of its shells. It's like placing a `-' before all the commands in the makefile. -k This is similar to -i in that it allows Make to con- tinue when it sees an error, but unlike -i, where Make''... -m directory Tells Make another place to search for included makefiles via the <...> style. Several -m options can be given to form a search path. If this construct is used the default system makefile search path is com- pletely overridden. To be explained in chapter 3, sec- tion 3.2. -n This flag tells Make not to execute the commands needed to update the out-of-date targets in the makefile. Rather, Make will simply print the commands it would April 9, 2016 Make -- A Tutorial PSD:12-15 have executed and exit. This is particularly useful for checking the correctness of a makefile. If Make doesn't do what you expect it to, it's a good chance the makefile is wrong. -q If you give Make this flag, it will not try to re- create anything. It will just see if anything is out- of-date and exit non-zero if so. -r When Make starts up, it reads a default makefile that tells it what sort of system it's on and gives it some idea of what to do if you don't tell it anything. I'll tell you about it in chapter 3. If you give this flag, Make won't read the default makefile. -s This causes Make to not print commands before they're executed. It is the equivalent of putting an `@' before every command in the makefile. -t Rather than try to re-create a target, Make will simply ``touch'' it so as to make it appear up-to-date. If the target didn't exist before, it will when Make finishes, but if the target did exist, it will appear to have been updated. -B Forces OpenBSD Make to be as POSIX-compatible as possi- ble. This includes: + Executing one shell per shell command + Using sequential mode. -D variable Allows you to define a variable to have ``1'' as its value. The variable is a global variable, not a command-line variable. This is useful mostly for people who are used to the C compiler arguments and those using conditionals, which I'll get into in section 4.3 -I directory Tells Make another place to search for included makefiles. Yet another thing to be explained in chapter 3 (section 3.2, to be precise). -P When creating targets in parallel, several shells are executing at once, each wanting to write its own two cent's-worth to the screen. This output must be cap- tured by Make in some way in order to prevent the screen from being filled with garbage even more indeci- pherable than you usually see. Make has two ways of doing this, one of which provides for much cleaner out- put and a clear separation between the output of dif- ferent jobs, the other of which provides a more immedi- ate response so one can tell what is really happening. The former is done by notifying you when the creation of a target starts, capturing the output and transfer- ring it to the screen all at once when the job fin- ishes. The latter is done by catching the output of the shell (and its children) and buffering it until an entire line is received, then printing that line pre- ceded by an indication of which job produced the out- put. Since I prefer this second method, it is the one used by default. The first method will be used if you give the -P flag to Make. April 9, 2016 PSD:12-16 Make -- A Tutorial Flags without arguments may follow a single `-'. E.g. make -f server.mk -DDEBUG -I/chip2/X/server/include -n will cause Make to read server.mk as the input makefile, define the variable DEBUG as a global variable and look for included makefiles in the directory /chip2/X/server/include. 2.8. Summary A makefile is made of four types of lines: + Dependency lines + Creation commands + Variable assignments + Comments, include statements and conditional direc- tives `-', Makeition- ally assigned-to using the `=' operator, appended-to using the `+=' operator, conditionally (if the variable is unde- fined) Make doesn't know about them. There are seven local vari- ables: .TARGET, .ALLSRC, .OODATE, .PREFIX, .IMPSRC, .ARCHIVE, and .MEMBER. Four of them (.TARGET, .PREFIX, .ARCHIVE, and .MEMBER) may be used to specify ``dynamic sources.'' Variables are good. Know them. Love them. Live them. Debugging of makefiles is best accomplished using the -n, and -d m flags. 2.9. Exercises TBA 3. Short-cuts and Other Nice Things Based on what I've told you so far, you may have gotten the impression that Make is just a way of storing away commands and making sure you don't forget to compile something. Good. That's just what it is. However, the ways I've described April 9, 2016 Make -- A Tutorial PSD:12-17 have been inelegant, at best, and painful, at worst. This chapter contains things that make the writing of makefiles easier and the makefiles themselves shorter and easier to modify (and, occasionally, simpler). In this chapter, I assume you are somewhat more familiar with Unix than I did in chapter 2, just so you're on your toes. So without further ado... 3.1. Transformation Rules As you know, a file's name consists of two parts: a base name, which gives some hint as to the contents of the file, and a suffix, which usually indicates the format of the file. Over the years, as UNIX- has developed, naming conven- tions, with regard to suffixes, have also developed that have become almost as incontrovertible as Law. E.g. a file ending in .c is assumed to contain C source code; one with a .o suffix is assumed to be a compiled object file that may be linked into any program; a file with a .ms suffix is usu- ally a text file to be processed by Troff with the -ms macro package, and so on. One of the best aspects of Make comes from its understanding of how the suffix of a file pertains to its contents and Make's ability to do things with a file based solely on its suffix. This ability comes from some- thing Make by placing them as sources on a dependency line whose target is the special target .SUFFIXES. E.g. .SUFFIXES : .o .c .c.o : $(CC) $(CFLAGS) -c $(.IMPSRC) The creation script attached to the target is used to transform. There are several things to note about the transformation rule given above: 1) The .IMPSRC variable. This variable is set to the ``implied source'' (the file from which the target _________________________ - UNIX is a registered trademark of AT&T Bell Labora- tories in the USA and other countries. April 9, 2016 PSD:12-18 Make -- A Tutorial is being created; the one with the first suffix), which, in this case, is the .c file. 2) The CFLAGS variable. Almost all of the transforma- tion Make would take care of the rest. To give you a quick example, the makefile in 2.3.4 could be changed to this: OBJS = a.o b.o c.o program : $(OBJS) $(CC) -o $(.TARGET) $(.ALLSRC) $(OBJS) : defs.h The transformation rule I gave above takes the place of the 6 lines[1] ``make'' will do the right thing, it's much more informative to type ``make -d s''. This will show _________________________ [1] This is also somewhat cleaner, I think, than the dynamic source solution presented in 2.6 April 9, 2016 Make -- A Tutorial PSD:12-19 you what Make is up to as it processes the files. In this case, Make Make automati- cally redefined as the suffixes they involve are re- entered.) Another way to affect the search order is to make the depen- dency explicit. In the above example, a.out depends on a.o and b.o. Since a transformation exists from .o to .out, Make uses that, as indicated by the ``using existing source a.o'' message. The search for a transformation starts from the suffix of April 9, 2016 PSD:12-20 Make -- A Tutorial the target and continues through all the defined transforma- t ``make : Make starts with the target jive.out, fig- ures't find it, so it looks for jive.l and, lo and behold, there it is. At this point, it has defined a transformation path as follows: .l -> .c -> .o -> .out and applies the transformation rules accordingly. For complete- ness, and to give you a better idea of what Make actually did with this three-step transformation, this is what Make printed for the rest of the process: April 9, 2016 Make -- A Tutorial PSD:12-21 Suff_FindDeps (jive.o) Make do with targets that have no known suffix? Make simply pretends it actually has an empty suffix and searches for transformations accord- ingly. Those special transformation rules involve just one source suffix, like this: .o : cc -o $(.TARGET) $(.IMPSRC) 3.2. Including Other Makefiles Just as for programs, it is often useful to extract certain parts of a makefile into another file and just include it in other makefiles somehow. Many compilers allow you say some- thing like #include "defs.h" to include the contents of defs.h in the source file. Make allows you to do the same thing for makefiles, with the added ability to use variables in the filenames. An include directive in a makefile looks either like this: .include <file> or this .include "file" The difference between the two is where Make searches for the file: the first way, Make will look for the file only in the system makefile directory (or directories) The system makefile directory search path can be overridden via the -m April 9, 2016 PSD:12-22 Make -- A Tutorial option. For files in double-quotes, the search is more com- plex: 1) The directory of the makefile that's including the file. 2) The current directory (the one in which you invoked Make). 3) The directories given by you using -I flags, in the order in which you gave them. 4) Directories given by .PATH dependency lines (see chapter 4). 5) The system makefile directory. in that order. You are free to use Make variables in the filename--Make will expand them before searching for the file. You must specify the searching method with either angle brackets or double-quotes outside of a variable expansion. I.e. the fol- lowing SYSTEM = <command.mk> #include $(SYSTEM) won't work. 3.3. Saving Commands't be run more than once in the same directory at the same time (each one creates a file called __.SYMDEF into which it stuffs information for the linker to use. Two of them run- ning. Make allows you to do this by inserting an ellipsis (``...'') as a command between commands to be run at once and those to be run later. So for the ranlib case above, you might do this: lib1.a : $(LIB1OBJS) rm -f $(.TARGET) ar cr $(.TARGET) $(.ALLSRC) ... ranlib $(.TARGET) lib2.a : $(LIB2OBJS) rm -f $(.TARGET) ar cr $(.TARGET) $(.ALLSRC) ... ranlib $(.TARGET) April 9, 2016 Make -- A Tutorial PSD:12-23 This would save both ranlib $(.TARGET) commands until the end, when they would run one after the other (using the correct value for the .TARGET variable, of course). Commands saved in this manner are only executed if Make manages to re-create everything without an error. 3.4. Target Attributes Make allows you to give attributes to targets by means of special sources. Like everything else Make uses, these sources begin with a period and are made up of all upper- case letters. There are various reasons for using them, and I will try to give examples for most of them. Others you'll have to find uses for yourself. Think of it as ``an exercise for the reader.'' By placing one (or more) of these as a source on a dependency line, you are ``marking the target(s) with that attribute.'' That's just the way I phrase it, so you know. Any attributes given as sources for a transformation rule are applied to the target of the transformation rule when the rule is applied. .DONTCARE If a target is marked with this attribute and Make can't figure out how to create it, it will ignore this fact and assume the file isn't really needed or actually exists and Make just can't find it. This may prove wrong, but the error will be noted later on, not when Make tries to create the target so marked. This attribute also prevents Make. Say also that you have to load other files from another system before you can compile your files): April 9, 2016 PSD:12-24 Make -- A Tutorial vari- ables of targets that depend on them (nor are they touched if Make crea- tion pro- gram with cc) must be performed on a machine with the same architecture. Not all export sys- tems will support this attribute. .IGNORE Giving a target the .IGNORE attribute causes Make to ignore errors from any of the target's commands, as if they all had `-' before them. prog1 : $(PROG1OBJS) prog2 MAKEINSTALL prog2 : $(PROG2OBJS) .INVISIBLE MAKEINSTALL April 9, 2016 Make -- A Tutorial PSD:12-25 where MAKEINSTALL is some complex .USE rule (see below) that depends on the .ALLSRC variable con- taining every- thing else to be done so. Specifically it forces the target's shell script to be executed only if one or more of the sources was out-of-date. In addition, the target's name, in both its .TARGET variable and all the local variables of any tar- get that I mentioned ear- lier,, Make Make. This forces Make to execute the script associated with the target (if it's out-of-date) even if you gave the -n or -t flag. By doing this, you can start at the top of a system and type make -n and have it descend the directory tree (if your April 9, 2016 PSD:12-26 Make -- A Tutorial makefiles are set up correctly), printing what it would have executed if you hadn't included the -n flag. .NOEXPORT If possible, Make will attempt to export the creation of all targets to another machine (this depends on how Make was configured). Sometimes, the creation is so simple, it is pointless to send it to another machine. If you give the tar- get the .NOEXPORT attribute, it will be run locally, even if you've given Make the -L 0 flag. .NOTMAIN Normally, if you do not specify a target to make in any other way, Make will take the first tar- get on the first dependency line of a makefile as the target to create. That target is known as the ``Main Target'' and is labeled as such if you print the dependencies out using the -p flag. Giving a target this attribute tells Make that the target is definitely not the Main Tar- get. This allows you to place targets in an included makefile and have Make create something else by default. .PRECIOUS When Make is interrupted (you type control-C at the keyboard), it will attempt to clean up after itself by removing any half-made targets. If a target has the .PRECIOUS attribute, however, Make will leave it alone. An additional side effect of the `::' operator is to mark the tar- gets as .PRECIOUS. .SILENT Marking a target with this attribute keeps its commands from being printed when they're exe- cuted, just as if they had an `@' in front of them. .USE By giving a target this attribute, you turn it into Make's equivalent of a macro. When the tar- get (as I call them) will use the sources of the target to which it is applied (as stored in the .ALLSRC variable for the tar- get) as its ``arguments,'' if you will. For example, you probably noticed that the commands for creating lib1.a and lib2.a in the example in section 3.3 were exactly the same. You can use the .USE attribute to eliminate the repetition, like so: April 9, 2016 Make -- A Tutorial PSD:12-27 target's local variables. There is no limit to the number of times I could use the MAKELIB rule. If there were more libraries, I could continue with ``lib3.a : $(LIB3OBJS) MAKELIB'' and so on and so forth. 3.5. Special Targets As there were in Make, so there are certain targets that have special meaning to Make. When you use one on a depen- dency line, it is the only target that may appear on the left-hand-side of the Make can't figure out any other way to create. It's only ``sort of'' a .USE rule because only the shell script attached to the .DEFAULT target is used. The .IMPSRC vari- able Make can hang commands you put off to the end. Thus the script for this tar- get will be executed before any of the commands you save with the ``...''. .EXPORT The sources for this target are passed to the exportation system compiled into Make. Some sys- tems will use these sources to configure them- selves. You should ask your system administrator April 9, 2016 PSD:12-28 Make -- A Tutorial about this. .IGNORE This target marks each of its sources with the .IGNORE attribute. If you don't give it any sources, then it is like giving the -i flag when you invoke Make -- errors are ignored for all com- mands. .INCLUDES The sources for this target are taken to be suf- fixes Make will place ``-I/usr/local/X/lib/bitmaps'' in the .INCLUDES variable and you can then say cc $(.INCLUDES) -c xprogram.c (Note: the .INCLUDES variable is not actually filled in until the entire makefile has been read.) .INTERRUPTWhen Make is interrupted, it will execute the com- mands Make may not have been compiled to do this if the linker on your system doesn't accept the -L flag, though the .LIBS vari- able will always be defined once the makefile has been read. .MAIN If you didn't give a target (or targets) to create when you invoked Make, it will take the sources of this target as the targets to create. .MAKEFLAGSThis target provides a way for you to always specify flags for Make when the makefile is used. The flags are just as they would be typed to the shell (except you can't use shell variables unless they're in the environment), though the -f and -r flags have no effect. .NULL This allows you to specify what suffix Make should pretend a file has if, in fact, it has no known suffix. Only one suffix may be so designated. The last source on the dependency line is the suffix April 9, 2016 Make -- A Tutorial PSD:12-29 that is used (you should, however, only give one suffix...). .PATH If you give sources for this target, Make will take them as directories in which to search for files it cannot find in the current directory. If you give no sources, it will clear out any direc- tories added to the search path before. Since the effects of this all get very complex, I'll leave it til chapter four to give you a complete expla- nation. .PATHsuffixThis does a similar thing to .PATH, but it does it only for files with the given suffix. The suf- fixThis target applies the .MAKE attribute to all its sources. It does nothing if you don't give it any sources. .SHELL Make Make the -s flag and no commands will be echoed. .SUFFIXES This is used to give new file suffixes for Make to handle. Each source is a suffix Make should recog- nize. If you give a .SUFFIXES dependency line with no sources, Make will forget about all the suf- fixes it knew (this also nukes the null suffix). For those targets that need to have suffixes defined, this is how you do it. In addition to these targets, a line of the form attribute : sources applies the attribute to all the targets listed as sources. 3.6. Modifying Variable Expansion Variables need not always be expanded verbatim. Make defines several modifiers that may be applied to a variable's value before it is expanded. You apply a modifier by placing it after the variable name with a colon between the two, like so: ${VARIABLE:modifier} April 9, 2016 PSD:12-30 Make -- A Tutorial charac- ters: don expan- sion regular- expression/wildcard characters have any special meaning save ^ and $. In the replacement string, the & character is replaced by the search-string unless it is preceded by a backslash. You are April 9, 2016 Make -- A Tutorial PSD:12-31 allowed to use any character except colon or exc- lamation point to separate the two strings. This so-called delimiter character may be placed in either string by preceding it with a backslash. T Replaces each word in the variable expansion by its last component (its ``tail''). For example, given OBJS = ../lib/a.o b /usr/lib/libm.a TAILS = $(OBJS:T) (``exten- sion''). So ``$(OBJS:E)'' would give you ``.o .a.'' R This replaces each word by everything but the suf- fix (the ``root'' of the word). ``$(OBJS:R)'' expands to `` ../lib/a b /usr/lib/libm.'' In addition, the System V style of substitution is also sup- ported. This looks like: $(VARIABLE:search-string=replacement) It must be the last modifier in the chain. The search is anchored at the end of each word, so only suffixes or whole words may be replaced. 3.7. More on Debugging 3.8. More Exercises (3.1)You've got a set programs, each of which is created from its own assembly-language source file (suffix .asm). Each program can be assembled into two versions, one with error-checking code assembled in and one without. You could assemble them into files with dif- ferent- checking versions have ec tacked onto their prefix)? (3.2)Assume, for a moment or two, you want to perform a sort of ``indirection'' by placing the name of a variable into another one, then you want to get the value of the first by expanding the second somehow. Unfortunately, Make doesn't allow constructs like April 9, 2016 PSD:12-32 Make -- A Tutorial $($(FOO)) What do you do? Hint: no further variable expansion is performed after modifiers are applied, thus if you cause a $ to occur in the expansion, that's what will be in the result. 4. Make for Gods This chapter is devoted to those facilities in Make, I assume a greater familiarity with UNIX or Sprite than I did in the previous two chapters. 4.1. Search Paths Make supports the dispersal of files into multiple direc- tories Make: .PATH.h : /sprite/lib/include /sprite/att/lib/include would tell Make to look in the directories /sprite/lib/include and /sprite/att/lib/include for any files whose suffix is .h. The current directory is always consulted first to see if a file exists. Only if it cannot be found there are the direc- tories in the specific search path, followed by those in the general search path, consulted. A search path is also used when expanding wildcard charac- ters. If the pattern has a recognizable suffix on it, the path for that suffix will be used for the expansion. Other- wise the default search path is employed. When a file is found in some directory other than the current one, all local variables that would have contained the target's name (.ALLSRC, and .IMPSRC) will instead con- tain the path to the file, as found by Make. Thus if you have a file ../lib/mumble.c and a makefile April 9, 2016 Make -- A Tutorial PSD:12-33 .PATH.c : ../lib mumble : mumble.c $(CC) -o $(.TARGET) $(.ALLSRC) the command executed to create mumble would be ``cc -o mum- ble ../lib/mumble.c.'' (As an aside, the command in this case isn't strictly necessary, since it will be found using transformation rules if it isn't given. This is because .out is the null suffix by default and a transformation exists from .c to .out. Just thought I'd throw that in.) If a file exists in two directories on the same search path, the file in the first directory on the path will be the one Make uses. So if you have a large system spread over many directories, it would behoove you to follow a naming conven- tion that avoids such conflicts. Something you should know about the way search paths are implemented is that each directory is read, and its contents cached, exactly once -- when it is first encountered -- so any changes to the directories while Make is running will not be noted when searching for implicit sources, nor will they be found when Make attempts to discover when the file was last modified, unless the file was created in the current directory. While people have suggested that Make should read the directories each time, my experience sug- gests that the caching seldom causes problems. In addition, not caching the directories slows things down enormously because of Make's attempts to apply transformation rules through non-existent files -- the number of extra file- system searches is truly staggering, especially if many files without suffixes are used and the null suffix isn't changed from .out. 4.2. Archives and Libraries UNIX's one copy in the archive and one copy out by itself. The problem with libraries is you usually think of them as -lm rather than /usr/lib/libm.a and the linker thinks they're out-of-date if you so much as look at them. Make solves the problem with archives by allowing you to tell it to examine the files in the archives (so you can remove the individual files without having to regenerate them later). To handle the problem with libraries, Make. April 9, 2016 PSD:12-34 Make -- A Tutorial doesn: .o.a : ... rm -f $(.TARGET:T) OBJS = obj1.o obj2.o obj3.o libprog.a : libprog.a($(OBJS)) ar cru $(.TARGET) $(.OODATE) ranlib $(.TARGET) This will cause the three object files to be compiled (if the corresponding source files were modified after the object file or, if that doesn: April 9, 2016 Make -- A Tutorial PSD:12-35 # # 4.3. On the Condition... Like the C compiler before it, Make allows you to configure the makefile, based on the current environment, using condi- tional statements. A conditional looks like this: April 9, 2016 PSD:12-36 Make -- A Tutorial #if boolean expression lines #elif another boolean expression more lines #else still more lines #endif com- parisons as well. && represents logical AND; || is logical OR and ! is logical NOT. The arithmetic and string opera- tors: com- mand line). defined The syntax is defined(variable) and is true if variable is defined. Certain variables are defined in the system makefile that identify the system on which Make is being run. exists The syntax is exists(file) and is true if the file can be found on the global search path (i.e. that defined by .PATH targets, not by .PATHsuffix tar- gets). unde- fined). This can be used to see if a variable con- tains a given word, for example: April 9, 2016 Make -- A Tutorial PSD:12-37 #if !empty(var:Mword) The arithmetic and string operators may only be used to test the value of a variable. The lefthand side must contain the variable expansion, while the righthand side contains either a string, enclosed in double-quotes, or a number. The stan- dard pro- gram, make -D DEBUG) will also cause the debug version to be made. #if defined(DEBUG) || make(debug) CFLAGS += -g #else CFLAGS += -O #endif April 9, 2016 PSD:12-38 Make -- A Tutorial annoy- ance ``make draft print'' since you would use the same formatter for each target. As I said, this all gets somewhat complicated. 4.4. A Shell is a Shell is a Shell In normal operation, the Bourne Shell (better known as ``sh'') is used to execute the commands to re-create tar- gets. Make also allows you to specify a different shell for it to use when executing these commands. There are several things Make must know about the shell you wish to use. These things are specified as the sources for the .SHELL target by keyword, as follows: path=path Make needs to know where the shell actually resides, so it can execute it. If you specify this and nothing else, Make will use the last component of the path and look in its table of the shells it knows and use the specification it finds, if any. Use this if you just want to use a different version of the Bourne or C Shell (yes, Make knows how to use the C Shell too). name=name This is the name by which the shell is to be known. It is a single word and, if no other keywords are speci- fied (other than path), it is the name by which Make attempts to find a specification for it (as mentioned above). You can use this if you would just rather use the C Shell than the Bourne Shell (``.SHELL: name=csh'' will do it). quiet=echo-off command As mentioned before, Make command The command Make should give to turn echoing back on April 9, 2016 Make -- A Tutorial PSD:12-39 again. filter=printed echo-off command Many shells will echo the echo-off command when it is given. This keyword tells Make in what format the shell actually prints the echo-off command. Wherever Make, Make wants to start the shell running with echoing on. To do this, it passes this flag to the shell as one of its arguments. If either this or the next flag begins with a `-', the flags will be passed to the shell as separate argu- ments. Otherwise, the two will be concatenated (if they are used at the same time, of course). errFlag=flag to turn error checking on Likewise, unless a target is marked .IGNORE, Make. ignore=command to turn error checking off This is the command Make uses to turn error checking off. It has another use if the shell doesn't do error- control, but I'll tell you about that...now. hasErrCtl=yes or no This takes a value that is either yes or no. Now you might think that the existence of the check and ignore keywords would be enough to tell Make if the shell can do error-control, but you'd be wrong. If hasErrCtl is yes, Make uses the check and ignore commands in a straight-forward manner. If this is no, however, their use is rather different. In this case, the check com- mand is used as a template, in which the string %s is replaced by the command that's about to be executed, to produce a command for the shell that will echo the com- mand to be executed. The ignore command is also used as a template, again with %s replaced by the command to be executed, to produce a command that will execute the command to be executed and ignore any error it returns. When these strings are used as templates, you must pro- vide newline(s) (``\n'') in the appropriate place(s). The strings that follow these keywords may be enclosed in April 9, 2016 PSD:12-40 Make -- A Tutorial single or double quotes (the quotes will be stripped off) and may contain the usual C backslash-characters (\n is new- line, \r is return, \b is backspace, \' escapes a single- quote inside single-quotes, \" escapes a double-quote inside double-quotes). Now for an example. This is actually the contents of the <shx.mk> system makefile, and causes Make: # # This is a shell specification to have the bourne shell echo # the commands just before executing them, rather than when it reads # them. Useful if you want to see how variables are being expanded, etc. # .SHELL : path=/bin/mksh \ quiet="set -" \ echo="set -x" \ filter="+ set - " \ echoFlag=x \ errFlag=e \ hasErrCtl=yes \ check="set -e" \ ignore="set +e" It tells Make the following: + The shell is located in the file /bin/mksh. It need not tell Make that the name of the shell is mksh as Make Make usually uses)). Make will remove all occurrences of this string from the output, so you don't notice extra commands you didn com- mands to do so are set +e and set -e, respectively. This will cause Make to execute the two commands echo "+ cmd" sh -c 'cmd || true' April 9, 2016 Make -- A Tutorial PSD:12-41's the last command it executed). 4.5. Compatibility There are three (well, 3 1/2) levels of backwards- compatibility built into Make. Most makefiles will need none at all. Some may need a little bit of work to operate correctly when run in parallel. Each level encompasses the previous levels (e.g. -B (one shell per command) implies -V) The three levels are described in the following three sec- tions. 4.5.1. DEFCON 3 -- Variable Expansion As noted before, Make's where they would have been set if you used Make, anyway) or always give the -V flag (this can be done with the .MAKEFLAGS target, if you want). 4.5.2. DEFCON 2 -- The Number of the Beast Then there are the makefiles that expect certain commands, such as changing to a different directory, to not affect other commands in a target's creation script. You can solve this is either by going back to executing one shell per com- mand (which is what the -B flag forces Make to do), which slows the process down a good bit and requires you to use semicolons and escaped newlines for shell constructs, or by changing the makefile to execute the offending command(s) in a subshell (by placing the line inside parentheses), like so: install :: .MAKE (cd src; $(.MAKE) install) (cd lib; $(.MAKE) install) (cd man; $(.MAKE) install) This will always execute the three makes (even if the -n flag was given) because of the combination of the ``::'' operator and the .MAKE attribute. Each command will change April 9, 2016 PSD:12-42 Make -- A Tutorial to the proper directory to perform the install, leaving the main shell in the directory in which it started. 4.5.3. DEFCON 1 -- Imitation is the Not the Highest Form of Flattery The final category of makefile is the one where every com- mand requires input, the dependencies are incompletely specified, or you simply cannot create more than one target at a time, as mentioned earlier. In addition, you may not have the time or desire to upgrade the makefile to run smoothly with Make. If you are the conservative sort, this is the compatibility mode for you. It is entered by giving Make the -B flag. direc- tories doesn't work across command lines, etc. + If no special characters exist in a command line, Make will break the command into words itself and execute the command directly, without executing a shell first. The characters that cause Make to execute a shell are: #, =, |, ^, (, ), {, }, ;, &, <, >, *, ?, [, ], :, $, `, and \. You should notice that these are all the characters that are given special meaning by the shell (except ' and , which Make deals with all by its lonesome). 4.6. The Way Things Work When Make reads the makefile, it parses sources and targets into nodes in a graph. The graph is directed only in the sense that Make knows which way is up. Each node contains not only links to all its parents and children (the nodes that depend on it and those on which it depends, respec- tively), but also a count of the number of its children that have already been processed. The most important thing to know about how Make uses this graph is that the traversal is breadth-first and occurs in two passes. After Make impli- cit- mented (since the .USE node has been processed). You will April 9, 2016 Make -- A Tutorial PSD:12-43 note that this allows a .USE node to have children that are .USE nodes and the rules will be applied in sequence. If the node has no children, it is placed at the end of another queue to be examined in the second pass. This process con- tinues until the first queue is empty. At this point, all the leaves of the graph are in the exami- nation queue. Make removes the node at the head of the queue and sees if it is out-of-date. If it is, it is passed to a function that will execute the commands for the node asyn- chron Make traverses the graph back up to the nodes the user instructed it to create. When the examination queue is empty and no shells are running to create a target, Make is finished. Once all targets have been processed, Make executes the com- mands attached to the .END target, either explicitly or through the use of an ellipsis in a shell script. If there were no errors during the entire process but there are still some targets unmade (Make keeps a running count of how many targets are left to be made), there is a cycle in the graph. Make does a depth-first traversal of the graph to find all the targets that weren't made and prints them out one by one. 5. Answers to Exercises (3.1)This is something of a trick question, for which I apo- logize. The trick comes from the UNIX definition of a suffix, which Make doesn't necessarily share. You will have noticed that all the suffixes used in this tutorial (and in UNIX in general) begin with a period (.ms, .c, etc.). Now, Make's idea of a suffix is more like English's: it's the characters at the end of a word. With this in mind, one possible solution to this problem goes as follows: .SUFFIXES : ec.exe .exe ec.obj .obj .asm ec.objec.exe .obj.exe : link -o $(.TARGET) $(.IMPSRC) .asmec.obj : asm -o $(.TARGET) -DDO_ERROR_CHECKING $(.IMPSRC) .asm.obj : asm -o $(.TARGET) $(.IMPSRC) (3.2)The trick to this one lies in the ``:='' variable- assignment operator and the ``:S'' variable-expansion modifier. Basically what you want is to take the pointer variable, so to speak, and transform it into an invocation of the variable at which it points. You might try something like April 9, 2016 PSD:12-44 Make -- A Tutorial $(PTR:S/^/\$(/:S/$/)) which places ``$('' at the front of the variable name and ``)'' at the end, thus transforming ``VAR,'' for example, into ``$(VAR),'' which is just what we want. Unfortunately (as you know if you've tried it), since, as it says in the hint, Make does no further substitu- tion on the result of a modified expansion, that's all you get. The solution is to make use of ``:='' to place that string into yet another variable, then invoke the other variable directly: *PTR := $(PTR:S/^/\$(/:S/$/)/) You can then use ``$(*PTR)'' to your heart's content. 6. Glossary of Jargon attribute: A property given to a target that causes Make to treat it differently. command script: The lines immediately following a dependency line that specify commands to execute to create each of the targets on the dependency line. Each line in the command script must begin with a tab. command-line variable: A variable defined in an argument when Make Make. creation script: Commands used to create a target. See ``command script.'' dependency: The relationship between a source and a target. This comes in three flavors, as indicated by the opera- tor. dynamic source: This refers to a source that has a local variable invocation in it. It allows a single depen- dency line to specify a different source for each tar- get on the line. global variable: Any variable defined in a makefile. Takes precedence over variables defined in the environment, but not over command-line or local variables. input graph: What Make constructs from a makefile. Consists of nodes made of the targets in the makefile, and the links between them (the dependencies). The links are directed (from source to target) and there may not be any cycles (loops) in the graph. April 9, 2016 Make -- A Tutorial PSD:12-45 local variable: A variable defined by Make depen- dency line) and specifies the relationship between the two. There are three: `:', `::', and `!'. search path: A list of directories in which a file should be sought. Make Make to do special things when it's encountered. suffix: The tail end of a file name. Usually begins with a period, .c or .ms, e.g. target: A word to the left of the operator on a dependency line. More generally, any file that Make might create. A file may be (and often is) both a target and a source (what it is depends on how Make is looking at it at the time -- sort of like the wave/particle duality of light, you know). transformation rule: A special construct in a makefile that specifies how to create a file of one type from a file of another, as indicated by their suffixes. variable expansion: The process of substituting the value of a variable for a reference to it. Expansion may be altered by means of modifiers. variable: A place in which to store text that may be retrieved later. Also used to define the local environ- ment. Conditionals exist that test whether a variable is defined or not. April 9, 2016 PSD:12-46 Make -- A Tutorial Table of Contents 1. Introduction .................................... 1 2. The Basics of Make .............................. 2 2.1. Dependency Lines ................................ 2 2.2. Shell Commands .................................. 4 2.3. Variables ....................................... 6 2.3.1.Local Variables ................................. 8 2.3.2.Command-line Variables .......................... 9 2.3.3.Global Variables ................................ 9 2.3.4.Environment Variables ........................... 9 2.4. Comments ........................................ 10 2.5. Parallelism ..................................... 10 2.6. Writing and Debugging a Makefile ................ 11 2.7. Invoking Make ................................... 13 2.8. Summary ......................................... 16 2.9. Exercises ....................................... 16 3. Short-cuts and Other Nice Things ................ 16 3.1. Transformation Rules ............................ 17 3.2. Including Other Makefiles ....................... 21 3.3. Saving Commands ................................. 22 3.4. Target Attributes ............................... 23 3.5. Special Targets ................................. 27 3.6. Modifying Variable Expansion .................... 29 3.7. More on Debugging ............................... 31 3.8. More Exercises .................................. 31 4. Make for Gods ................................... 32 4.1. Search Paths .................................... 32 4.2. Archives and Libraries .......................... 33 4.3. On the Condition... ............................. 35 4.4. A Shell is a Shell is a Shell ................... 38 4.5. Compatibility ................................... 41 4.5.1.DEFCON 3 -- Variable Expansion .................. 41 4.5.2.DEFCON 2 -- The Number of the Beast ............. 41 4.5.3.DEFCON 1 -- Imitation is the Not the Highest Form of Flattery ...................................... 42 4.6. The Way Things Work ............................. 42 5. Answers to Exercises ............................ 43 6. Glossary of Jargon .............................. 44 April 9,.
https://www.mirbsd.org/htman/sparc/manPSD/12.make.htm
CC-MAIN-2016-18
refinedweb
10,445
71.75
can someone pllllllllllllllllz help me with this!!!!!!!! my problem is i have to write a c++ program that inputa a character and an integer. The out put should be a diamond composed of the character and extencing the widht specified byt he integer. for example, if the integer is 11 and the character is an asterisk (*), the diamond would look like this: if the input integer is an even number, it should be increased to the next odd number.if the input integer is an even number, it should be increased to the next odd number.Code:* *** ***** ******* ********* *********** ********* ******* ***** *** * i have tried this out..but i think my logic is wrong...pliz help me on this [b]Code Tags added by Kermi3[/code][b]Code Tags added by Kermi3[/code]Code:# include <iostream> using namespace std; int main() { int n, r, oddInt; char c; // Get int and char cout << "Enter number of rows: "<< flush; cin >> n; cout << "Enter a character: "<< flush; cin >> c; // determine whether n is odd or even if (n > 1 && n < 23) { oddInt = 3; while ( oddInt <= 23) { oddInt = oddInt + 1; } } else if ( n < 1 && n > 23) { cout << "Illegal integer"<< endl; } // draw triangle // r = row // s = space r= 1; while ( r <= n) { c = 1; while (c <= r ) { cout << c; c++; } r++; cout << endl; } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/36160-someone-pliz-help.html
CC-MAIN-2013-48
refinedweb
215
62.41
0 hello, all! I am an absolute rookie in the world of C++ language, and not a good one either... I have an assignment to create a random number guessing game, and I am struggling with it. I have most of it done, but we have to generate the number of tries when the user wins, the number of games played, won,and the percentage of games won. unfortunately, when I play more than once, the tries add up, and I do not know how to count them out of the loop. The percentage does not seem to be working either. here is what I have so far: #include<iostream> #include<cstdlib> #include<ctime> using namespace std; const int EXIT_VALUE = -1, MIN_NUMBER = 1, MAX_NUMBER = 100, MAX_GAMES = 256; int main() { int guess; char answer='y'; int lostCount = 0; int totalGames = 0; int tries = 0; int winGames = 0; double averageWin = 0.0; { do { srand(time(NULL)); int randomNumber = MIN_NUMBER + rand() % (MAX_NUMBER - MIN_NUMBER + 1); cout<<"Im thinking of a number between 1-100. Take a guess: "; cin>>guess; tries++; while(guess!=randomNumber) { if(guess == EXIT_VALUE) { cout << "Too bad... The number was:" << " " << randomNumber << endl; lostCount++; cout << "would you like to play again?" << endl; cin >> answer; if (answer == 'Y' || answer == 'y') cout << "please enter a number between 0 and 100:" << endl; cin >> guess; } if(guess>randomNumber) { cout<<"Too high,Guess again: "; cin>>guess; ++tries; } else if(guess<randomNumber) { cout<<"Too low,Guess again: "; cin>>guess; ++tries; } } if(guess=randomNumber) { cout<<"Congratulations!! You found the number!"; cout << "it took you" << " " << tries << " " << "tries to find the number!" << endl; winGames++; } cout << "Would you like to play again? y/n "; cin >> answer; } while (answer =='y' || answer =='Y'); totalGames = winGames + lostCount; averageWin = winGames / 100; if (answer == 'n' || answer == 'N') cout << "Thank you for playing! you have played" << " " << totalGames << " " << "games,"<< endl; cout << " won" << " " << winGames << " " << "games, and the average of your winning games is"; cout << " " << averageWin << " " << "%" << endl; } system ("pause"); return 0; }
https://www.daniweb.com/programming/software-development/threads/396969/number-guessing-game
CC-MAIN-2016-44
refinedweb
319
71.04
Gleam has reached v0.5! It’s quite a bit larger than any of the previous releases, so let’s take a look. Labelled arguments When functions take several arguments it can be difficult for the user to remember what the arguments are, and what order they are expected in. To help with this Gleam supports labelled arguments, where function arguments are given an external label in addition to their internal name. Take this function that replaces sections of a string: pub fn replace(string, pattern, replacement) { // ... } It can be given labels like so. pub fn replace(in string, each pattern, with replacement) { // The variables `string`, `pattern`, and `replacement` are in scope here } These labels can then be used when calling the function. replace(in: "A,B,C", each: ",", with: " ") // Labelled arguments can be given in any order replace(each: ",", with: " ", in: "A,B,C") // Arguments can still be given in a positional fashion replace("A,B,C", ",", " ") The use of argument labels can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent. One neat thing is that unlike proplist arguments in Erlang or Elixir, Gleam’s labelled arguments are resolved entirely at compile time and have no performance or memory cost at runtime. A more familiar syntax One bit of common feedback was that the syntax for enums, case expressions, and blocks felt a little strange or not in keeping with the wider language. In response to this we have adopted a syntax closer to that found in C-influenced languages such as ECMAScript. case x { 1 -> "It's one" 2 -> "It's two" // Braces can be used for multiple statements _ -> { let number = int.to_string(x) string.concat(["I'm not sure what ", number, " is"]) } } pub enum Cardinal { North East South West } Multi-subject case Often it is useful to pattern match on multiple values at the same time. Previously in Gleam the solution was to wrap the values in a struct and pattern match on all values at once. case Pair(x, y) { Pair(1, 1) -> "both are 1" Pair(1, _) -> "x is 1" Pair(_, 1) -> "y is 1" Pair(_, _) -> "neither are 1" } To remove some boilerplate here Gleam’s case expression now supports pattern matching on multiple values. case x, y { 1, 1 -> "both are 1" 1, _ -> "x is 1" _, 1 -> "y is 1" _, _ -> "neither are 1" } Theoretically a case expression can match on up to 16,777,215 values. If you need to match on more values than this please let me know because wow, I wanna know what your code is doing. Record compatibility Gleam’s structs are Erlang tuples at runtime. This is great for performance and memory usage but makes constructing them from Erlang or Elixir less straightforward than if they were maps. To resolve this Gleam’s structs now at runtime have a tag atom in their first position, making them compatible with Erlang records. An Erlang record definition header file is generated for each struct which can be imported into an Erlang project or used from Elixir using the Record module. // src/cat.gleam pub struct Cat { name: String is_cute: Bool } pub fn main() { Cat(name: "Nubi", is_cute: True) } %%% src/program.erl -module(program). -export([main/0]). %% Import the Cat record definition -import("gen/src/cat_Cat.hrl"). %% Use the Cat record main() -> #cat{name = <<"Nubi">>, is_cute = true}. # lib/program.ex defmodule Program do # Import the Cat record definition require Record Record.defrecord(:cat, Record.extract(:cat, from: "gen/src/cat_Cat.hrl")) # Use the Cat record def main do cat(name: "Nubi", is_cute: true) end end Anonymous structs One drawback to structs now being Erlang record compatible is that they can no longer be used to interop with Erlang tuples that do not have a tag atom in the first position. Anonymous structs map 1 to 1 onto Erlang tuples can are useful for any situation where interop with Erlang tuples is required. fn main() { struct(10, "hello") // Type is struct(Int, String) struct(1, 4.2, [0]) // Type is struct(Int, Float, List(Int)) } Anonymous structs don’t need to be declared up front but also don’t have names for their fields, so for clarity prefer named structs for when you have more than 2 or 3 fields. Unqualified imports Tired of typing module names repeatedly for imported types and values? Well now you don’t have to. import animal/cat.{Cat, stroke} pub fn main() { let kitty = Cat(name: "Nubi", is_cute: True) stroke(kitty) } Project creation The terminal command gleam new now accepts a --template flag to generate different styles of project. An OTP application template has been added alongside the existing OTP library template. gleam new my_fantastic_application --template app In addition all projects generated by gleam new come with the required configuration for CI on GitHub Actions. Push the project to GitHub and your code will be automatically compiled and your tests run on every code update. To enable this we’ve created two new GitHub Actions for setting up Erlang and Gleam in your GitHub workflow. The rest As per usual, in addition to these features there’s been a number of other improvements to the quality of the error messages, the generated code, and a smattering of bug fixes. 😊. Code Mesh 2019 Last month I got to speak about Gleam at my favourite conference Code Mesh! A recording of the talk can found on their YouTube channel: Thanks Lastly, a huge thank you to the contributors to and sponsors of Gleam since last release! - Christian Wesselhoeft - Guilherme Pasqualino - John Palgut - Jonny Arnold - ontofractal - Stefan Hagen - Štefan Ľupták If you would like to help make strongly typed programming on the Erlang virtual machine a production-ready reality please consider sponsoring Gleam via the GitHub Sponsors program. Thank you! 💜
https://gleam.run/news/gleam-v0.5-released/
CC-MAIN-2022-33
refinedweb
986
57.4
view raw I wrote a piece of code, it was marked by an auto machine-bot. We are not allowed to question this bot, its "100% correct". I got 90%. Professor wont go over it, and we are "meant to" pay a higher year student to help us if we have troubles, because this is a basic level course. Here is the code: def something(placeholder): """ append intengers """ siba = list() try: for items in placeholder: if int(items): siba.append(int(items)) except ValueError: pass return siba placeholder = ["123", "+142", "-39", "GRTG356", "x", "12-3", "123+"] print(something(placeholder)) Your error handling will currently return the list if a value inside can't be converted to a int. it should instead go to the next item. def something(placeholder): """ append intengers """ siba = list() for items in placeholder: try: siba.append(int(items)) except ValueError: pass return siba If I supply your original code with ["123", "+142", "-39", "GRTG356", "x", '1', "12-3", "123+", '572'] it would return ["123", "+142", "-39"] when it should instead return [123, 142, -39, 1, 572]
https://codedump.io/share/3ClhERANJqJO/1/need-help-understanding-section-of-code
CC-MAIN-2017-22
refinedweb
180
69.82
epc 0.0.5 EPC (RPC stack for Emacs Lisp) implementation in Python Links: - Documentation (at Read the Docs) - Repository (at GitHub) - Issue tracker (at GitHub) - PyPI - Travis CI Other resources: - kiwanami/emacs-epc (Client and server implementation in Emacs Lisp and Perl.) - tkf/emacs-jedi (Python completion for Emacs using EPC server.) What is this? EPC is an RPC stack for Emacs Lisp and Python-EPC is its server side and client side implementation in Python. Using Python-EPC, you can easily call Emacs Lisp functions from Python and Python functions from Emacs. For example, you can use Python GUI module to build widgets for Emacs (see examples/gtk/server.py for example). Python-EPC is tested against Python 2.6, 2.7 and 3.2. Install To install Python-EPC and its dependency sexpdata, run the following command.: pip install epc Usage Save the following code as my-server.py. (You can find functionally the same code in examples/echo/server.py): from epc.server import EPCServer server = EPCServer(('localhost', 0)) @server.register_function def echo(*a): return a server.print_port() server.serve_forever() And then run the following code from Emacs. This is a stripped version of examples/echo/client.el included in Python-EPC repository.: (require 'epc) (defvar my-epc (epc:start-epc "python" '("my-server.py"))) (deferred:$ (epc:call-deferred my-epc 'echo '(10)) (deferred:nextc it (lambda (x) (message "Return : %S" x)))) (message "Return : %S" (epc:call-sync my-epc 'echo '(10 40))) If you have carton installed, you can run the above sample by simply typing the following commands: make elpa # install EPC in a separated environment make run-sample # run examples/echo/client.el For example of bidirectional communication and integration with GTK, see examples/gtk/server.py. You can run this example by: make elpa make run-gtk-sample # run examples/gtk/client.el License Python-EPC is licensed under GPL v3. See COPYING for details. - Downloads (All Versions): - 3 downloads in the last day - 381 downloads in the last week - 1958 downloads in the last month -
https://pypi.python.org/pypi/epc
CC-MAIN-2015-35
refinedweb
344
59.8
OS module is a python module that allows you to interact with the operating systems. It uses various functions to interact with the operating system. Using it you can automatically tell the python interpreter to know which operating system you are running the code. But while using this module function sometimes you get AttributeError. The AttributeError: module ‘os’ has no attribute ‘uname’ is one of them. In this entire tutorial, you will learn how to solve the issue of module ‘os’ has no attribute ‘uname’ easily. The root cause of the module ‘os’ has no attribute ‘uname’ Error The root cause of this attributeError is that you must be using the uname() function wrongly. The import part of the os module is right but the way of using the uname() is wrong. If you will use os.uname() on your Windows OS then you will get the error. import os print(os.uname()) Output Solution of the module ‘os’ has no attribute ‘uname’ The solution of the module ‘os’ has no attribute ‘uname’ is very simple. You have to properly use the uname() method. If your operating system is Unix then its okay to use os.uname(). But in case you are using the Windows operating system then import platform instead of import os. In addition call platform.uname() instead of os.uname(). You will not get the error when you will run the below lines of code. import platform print(platform.uname()) Output Conclusion OS module is very useful if you want to know the system information. But there are some functions that lead to attributerror as that function may not support the current Operating system. If you are getting the ‘os’ has no attribute ‘uname’ error then the above method will solve your error. I hope you have liked this tutorial. If you have any queries then you can contact us for help. You can also give suggestions on this tutorial. Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://gmailemail-login.email/module-os-has-no-attribute-uname-solved/
CC-MAIN-2022-33
refinedweb
341
66.94
Calculates the projection of a complex number on the Riemann sphere #include <complex.h> double complex cproj ( double complex z ); float complex cprojf ( float complex z ); long double complex cprojl ( long double complex z ); The Riemann sphere is a surface that represents the entire complex plane and one point for infinity. The cproj( ) function yields the representation of a complex number on the Riemann sphere. The value of cproj(z) is equal to z, except in cases where the real or complex part of z is infinite. In all such cases, the real part of the result is infinity, and the imaginary part is zero with the sign of the imaginary part of the argument z. double complex z = -INFINITY - 2.7 * I; double complex c = cproj(z); printf("%.2f %+.2f * I is projected to %.2f %+.2f * I.\n", creal(z), cimag(z), creal(c), cimag(c)); This code produces the following output: -inf -2.70 * I is projected to inf -0.00 * I. cabs( ), cimag( ), creal( ), carg( ), conj( )
http://books.gigatux.nl/mirror/cinanutshell/0596006977/cinanut-CHP-17-41.html
CC-MAIN-2018-43
refinedweb
169
65.42
csFontCache Class Reference [Common Plugin Classes] A cache for font glyphs. More... #include <csplugincommon/canvas/fontcache.h> Detailed Description A cache for font glyphs. It is intended as a baseclass, which a canvas extends to store glyphs in a canvas-dependent way. It provides facilities to quickly locate data associated with a specific glyph of a specific font, as well as means to manage glyphs if only a limited space to store them is present. Definition at line 53 of file fontcache.h. Member Typedef Documentation Array of a number of glyphs. This is the "first" dimension of the glyphs array, and consists of a variable number of "planes". If a plane doesn't contain a glyph, it doesn't take up memory. Definition at line 139 of file fontcache.h. Member Function Documentation Add a glyph to the cache. Set up stuff to cache glyphs of this font. Store glyph-specific information. Store glyph-specific information, but omit some safety checks. Find an LRU entry for a specific cache data. Find an LRU entry for a specific font/glyph pair. Request cached data for a glyph of a known font. Request whether a font is known already. Get cached data for the least used glyph. Cache canvas-dependent information for a specific font/glyph pair. Reimplemented in csGLFontCache. Request cached data for a glyph of a known font. Uncache canvas-dependent information. Reimplemented in csGLFontCache. Delete empty PlaneGlyphs from known fonts. Remove a glyph from the cache. @@ Does not update PlaneGlyphs! Remove a glyph from the cache. Fill the basic cache data. Uncache this font. Uncache cached glyph data. Draw a string. Reimplemented in csGLFontCache. Member Data Documentation the current clipping rect Definition at line 152 of file fontcache.h. First entry in LRU list. Definition at line 89 of file fontcache.h. Array of known fonts. Definition at line 157 of file fontcache.h. Allocator for LRU list entries. Definition at line 94 of file fontcache.h. Last entry in LRU list. Definition at line 91 of file fontcache.h. The documentation for this class was generated from the following file: - csplugincommon/canvas/fontcache.h Generated for Crystal Space 2.0 by doxygen 1.6.1
http://www.crystalspace3d.org/docs/online/api-2.0/classcsFontCache.html
CC-MAIN-2014-35
refinedweb
368
63.56
Postinit bind Anyone know why the following code generates the following error - or a better way to do an attribute bind on instanciation? public class RectangleX extends Rectangle { postinit { anchorX = bind getWidth()/2; anchorY = bind getHeight()/2; }; } Error: Sorry, I was trying to understand an expression but I got confused when I saw "bind" which is a keyword. Your solution is the right one. Be aware, that "let" (which was renamed to "def" in a later release) does not have the exact same meaning like final var. If you do the following, "a" cannot be reassigned, but it can change its value: [code] def a = bind b; [/code] Hi, use the let keyword. [code] public class RectangleX extends Rectangle { postinit { let anchorX = bind getWidth()/2; let anchorY = bind getHeight()/2; }; } [/code] That didn't work, though it seemed promising. Looking at the docs, it sounds like the "let" keyword might mean something like "final var", meaning once it's declared, you can't reassign it. I found success with this: override attribute anchorX = bind getWidth()/2;
https://www.java.net/node/684385
CC-MAIN-2015-18
refinedweb
176
67.08
A Gentle Re-Introduction to QuickTime for Java Pages: 1, 2 Let's assume that you really do need QuickTime for Java — you need to deliver as an application, you're writing a cool transcoding servlet, or whatever. Where should you begin? First, check the system on your desk. Is it a Mac or a Windows box? Good. Sorry, no QuickTime on other operating systems, and thus no QTJ — and that includes CodeWeavers' CrossOver for Linux, which supports only the QuickTime browser plug-in, not QT in applications. Next, you need to install QuickTime, which is available from Apple's site, if you don't already have it. I will assume from this point on that everyone is using QuickTime 6, which you need for some of the more interesting topics we'll be covering, such as MPEG-4. By the way, you don't need to purchase QuickTime Pro for QTJ development, though unlocking the editing and exporting features of Apple's player does make it easier to create test media for your development needs. Mac OS X users can expect Java 1.3.1, QuickTime, and QuickTime for Java to be installed with the operating system. Windows users don't necessarily have any of these. Start at java.sun.com to get Java, then go get QuickTime from the link above. QuickTime for Java is not part of the "Recommended" QuickTime install, so you need to do a "Custom" install and specifically select QuickTime for Java. Figure 1. Custom install of QuickTime on Windows It's important to install Java first, since the QTJ installer needs to find Java installations on your system and install its QTJava.zip and QTJava.dll files where Java can find them. There are QuickTime for Java SDKs available for download on Apple's site, but they are not strictly required for development, as all you really need to compile is the QTJava.zip file that is placed in your $JAVA_HOME/lib/ext directory. The SDK contains the javadocs and about 50 demo applications. While both are available on the web, it's well worth your time to get the SDK to have local copies. Source Code Download the source code for the simple player example. It's not quite HelloWorld, but a basic player is pretty much the first thing to create with a media API. Here's a simple player that asks the user to locate a QuickTime-playable file on the filesystem, opens the movie in a new frame, and plays it: HelloWorld package com.mac.invalidname.simpleqtplayer; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.File; import quicktime.*; import quicktime.app.*; import quicktime.app.players.*; import quicktime.app.display.*; import quicktime.io.*; import quicktime.std.*; import quicktime.std.movies.*; public class SimpleQTPlayer extends Frame { Movie movie; public SimpleQTPlayer (String title) { super (title); try { QTSession.open(); FileDialog fd = new FileDialog (this, "Select source movie", FileDialog.LOAD); fd.show(); if (fd.getFile() == null) return; // get movie from file File f = new File (fd.getDirectory(), fd.getFile()); OpenMovieFile omFile = OpenMovieFile.asRead (new QTFile (f)); movie = Movie.fromFile (omFile); // get a Drawable for Movie, put in QTCanvas MoviePlayer player = new MoviePlayer (movie); QTCanvas canvas = new QTCanvas(); canvas.setClient (player, true); add (canvas); // windows-like close-to-quit addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent e) { QTSession.close(); System.exit(0); } }); } catch (Exception e) { e.printStackTrace(); } } public static void main (String[] args) { SimpleQTPlayer frame = new SimpleQTPlayer ("Simple QTJ Player"); frame.pack(); frame.setVisible(true); try { frame.movie.start(); } catch (Exception e) { e.printStackTrace(); } } } Here's what the output looks like — in my case, a home movie running in a simple AWT Frame: Figure 2. Simple QTJ Player Try it with different kinds of media that QuickTime supports, such as .mov and .avi videos, still images in various formats, and .mp3 and .wav audio files. (You'll get a zero-size window if you play an audio-only file.) This simple app should play most, if not all, of the supported media types. Before we fight with the compiler — which will be a hassle the first time you do it — let's examine what the code does. The essential QuickTime stuff is in the constructor: QTSession.open() Movie.fromFile Movie OpenMovieFile MoviePlayer QTCanvas setClient() Frame WindowListener main() start() There are some peculiarities here: the number of imports is probably surprising for such a small application, and you might wonder if there aren't some unnecessary extra steps here. In particular, why do we hand the Movie to this MoviePlayer object? Why is it then sent to the QTPlayer, not in a constructor, but in the curiously named setClient method? QTPlayer setClient Don't worry, all will be covered in due course. Let's look at compiling first. The QTJava.zip file that contains the QTJ classes is put in your Java extensions directory by the installer. Strangely, it only gets picked up for running applications and applets, not for compiling. When you compile, you must explicitly put the file in your CLASSPATH. On the command line, use a javac or jikes argument like -classpath /System/Library/Java/Extensions/QTJava.zip (that's the Mac OS X path; the Windows path will depend on where you installed the JDK). In an IDE, it's usually a matter of dragging and dropping QTJava.zip into your current project: CLASSPATH javac jikes -classpath /System/Library/Java/Extensions/QTJava.zip Figure 3. Dragging QTJava.zip into Project Builder project on Mac OS X It will be pretty easy to tell if you don't have the CLASSPATH correct, as all of those imports will fail, looking something like this: SimpleQTJPlayer.java:5: package quicktime does not exist SimpleQTJPlayer.java:6: package quicktime.app does not exist SimpleQTJPlayer.java:7: package quicktime.app.players does not exist SimpleQTJPlayer.java:8: package quicktime.app.display does not exist Obviously, this is enough of a hassle that if you are not using an IDE, you may want to set up a Makefile or an Ant build.xml file to save you from ongoing CLASSPATH misery. The example code for these articles will continue to provide Ant files to build the code, and you're welcome to use them for your own QTJ development. Makefile There's one additional compile-time hassle: in making huge changes to how Java works in Mac OS X, Apple's 1.4.1 implementation is not currently compatible with QuickTime for Java. The problem comes from Apple's move to using Cocoa for their AWT/Swing implementation in 1.4.1, instead of Carbon, which they used for 1.3.1 and QTJ. I wrote about this in an O'Reilly weblog last month, and the problem has not been resolved as of this writing. The workaround on Mac OS X is to use Java 1.3.1 explicitly, which will reportedly still be in the next major release of Mac OS X. In fact, since 1.4.1 is currently an optional download, it's safer to code to 1.3.1 anyway. Unfortunately, 1.4.1 becomes the default when installed, so it's a hassle. When working from the command line, you can specifically point to the 1.3.1 javac and java by using the path: java /System/Library/Frameworks/JavaVM.Framework/Versions/1.3.1/Commands I've included this path in the sample code's my.ant.properties.mac file, which you need to rename to my.ant.properties to get picked up by ant. If you're using an IDE, there's probably a way to set your compiler and interpreter version to 1.3 in the GUI — in Project Builder, it's under "Java Compiler Settings" in the Target Settings: ant Figure 4. Setting Project Builder to use Java 1.3.1 for QTJ on Mac By the way, people have been asking me if I think the 1.4.1 problem means that QTJ is doomed and if they should go looking for another media API. For what it's worth, I prefer to just wait and see what happens — Apple hasn't officially dropped or deprecated QuickTime for Java. In the past, they've been pretty clear about when a technology is toast. Furthermore, Amazon still has a listing for a new edition of a QTJ book, written by Apple insiders, due in September. The situation is unclear — maybe we'll get more information at WWDC. In the meantime, while I'd prefer not having to work around the 1.4.1 situation, it's not time to panic. Not yet, anyway. URL It's important to think of a Movie not just in terms of what you can call on it, but also what it represents. In QuickTime, a Movie represents an organization of different kinds of time-based data, but it does not represent the data itself. In the QuickTime way of thinking, Movies have Tracks that refer to Media, which represent the low-level data like media samples (for example, audio samples or video frames). Track Media This division allows you to go as deeply into the details as you need. Suppose you have a Movie that's made up of successive video tracks of different sizes. (You'll be able to create such a thing by the end of part 2.) If you want to know the size it will take up on screen, perhaps to create a rectangle big enough to accommodate all of the tracks, then you could call Movie.getBox(). But if you need to know the size of just one of those tracks, you could iterate over the Track objects, find the one you want, and call its getSize(). Movie.getBox() getSize() Another key concept of Movies is that they have a time scale, an integer that represents the time-keeping system within the movie. This value defaults to 600, meaning the movie has 600 time units per second. Values returned by methods like getDuration() and getTime() use this time scale, so a 30-second movie with a time scale of 600 returns 18000 for getDuration(). More interesting, though, is the fact that the various Media inside this Movie can and will have totally different time scales — uncompressed CD-quality audio might have a time scale of 44100, since it's 44.1 kHz — but the Movie isolates you from such details, so you don't have to worry about it, unless you want to iterate over the Media objects and investigate them specifically. 600 getDuration() getTime() 18000 The Movie object wraps a structure and many functions from the native QuickTime API. Other classes in QTJ are unique to the Java version. The QTCanvas is an AWT component that offers a bridge from the QuickTime world to the Java display. To use a QTCanvas, call the setClient() method to hook it up to a class implementing the Drawable interface. Drawable is another QTJ-only creation, which indicates the ability of certain QTJ classes to provide pixels and sizing information to a QTCanvas. MoviePlayer is used for the simplest playback needs — other special-purpose Drawables exist for playing movies with a controller (QTPlayer), showing output from a capture device (SGDrawer), rendering effects (QTEffectPresenter), and for stream-broadcasting (PresentationDrawer). Drawable SGDrawer QTEffectPresenter PresentationDrawer Notice that I described the QTCanvas as an AWT component. SimpleQTPlayer is written entirely in AWT, not Swing. That's because the QTCanvas is a native component, allowing QuickTime to use hardware-accelerated rendering of your movie. The disadvantage, of course, is the difficulty of mixing AWT and Swing components. Because heavyweight AWT components will appear on top of any Swing components, a QTCanvas will appear above Swing JMenus, blasting through JTabbedPanes, and generally making a nuisance of itself, if you're not careful. SimpleQTPlayer JMenu JTabbedPane If you must use Swing for a QTJ app, there are two options. First, you can use the JQTCanvas, a lightweight Swing component introduced in QuickTime 6 that behaves like other JComponents in honoring Swing z-axis ordering. Unfortunately, its performance is generally poor; the movie must be re-imaged in software to get it into Swing's graphic space so that it can be painted. The second alternative is to carefully design your Swing layout to accomodate the heavyweight QTCanvas, not using overlapping components. The most common problem people experience with this is JMenus disappearing under the QTCanvas. You can get around this by calling setLightweightPopupEnabled (false) on your JMenus. JQTCanvas JComponent setLightweightPopupEnabled (false) Now we've got a basic player, but of course, that's what we got from the QuickTime plug-in when we started. In Part 2, we'll delve into what makes QuickTime unique by getting into the editing API, allowing us to write a basic video editor with just a handful of code..
http://www.onlamp.com/pub/a/onjava/2003/05/14/qtj_reintro.html?page=2
CC-MAIN-2015-35
refinedweb
2,143
64.61
Hi, any objections to commit the following? It removes the code which almost exactly in emacs.c now. The ChangeLog entry is carefully constructed so interested people can easy find Gerd's note about putting it in #if 0 in ChangeLog.8: 1999-11-22 Gerd Moellmann <address@hidden> * emacs.c (gdb_valbits, gdb_gctypebits, gdb_emacs_intbits) (gdb_data_seg_bits): New variables. * lisp.h (enum gdb_lisp_params): Put in #if 0, since it doesn't work on systems not allowing enumerators > INT_MAX, and it won't work if EMACS_INT is long long. Now we have this information twice in the sources. Of course everything will stay in CVS... 2001-10-26 Pavel Janík <address@hidden> * lisp.h (gdb_lisp_params): Remove code in #if 0 which is now in emacs.c. --- lisp.h.~1.390.~ Thu Oct 25 07:30:49 2001 +++ lisp.h Fri Oct 26 19:22:29 2001 @@ -162,26 +162,6 @@ #define GCTYPEBITS 3 #endif -#if 0 /* This doesn't work on some systems that don't allow enumerators - > INT_MAX, and it won't work for long long EMACS_INT. These - values are now found in emacs.c as EMACS_INT variables. */ - -/* -}; - -#endif /* 0 */ - #ifndef NO_UNION_TYPE #ifndef WORDS_BIG_ENDIAN -- Pavel Janík I would expect that this error is caused by the summer temperatures. -- Carsten Gross
https://lists.gnu.org/archive/html/emacs-devel/2001-10/msg00314.html
CC-MAIN-2020-40
refinedweb
208
67.86
From our sponsor: Reach inboxes when it matters most. Instantly deliver transactional emails to your customers. Nowadays, it’s really hard to navigate the web and not run into some wonderful website that has some stunning effects that seem like black magic. Well, many times that “black magic” is in fact WebGL, sometimes mixed with a bit of GLSL. You can find some really nice examples in this Awwwards roundup, but there are many more out there. Recently, I stumbled upon the Waka Waka website, one of the latest works of Ben Mingo and Aristide Benoist, and the first thing I noticed was the hover effect on the images. It was obvious that it’s WebGL, but my question was: “How did Aristide do that?” Since I love to deconstruct WebGL stuff, I tried to replicate it, and in the end I’ve made it. In this tutorial I’ll explain how to create an effect really similar to the one in the Waka Waka website using Microsoft’s BabylonJS library and some GLSL. This is what we’ll do. The setup The first thing we have to do is create our scene; it will be very basic and will contain only a plane to which we’ll apply a custom ShaderMaterial. I won’t cover how to setup a scene in BabylonJS, for that you can check its comprehensive documentation. Here’s the code that you can copy and paste: import { Engine } from "@babylonjs/core/Engines/engine"; import { Scene } from "@babylonjs/core/scene"; import { Vector3 } from "@babylonjs/core/Maths/math"; import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera"; import { ShaderMaterial } from "@babylonjs/core/Materials/shaderMaterial"; import { Effect } from "@babylonjs/core/Materials/effect"; import { PlaneBuilder } from "@babylonjs/core/Meshes/Builders/planeBuilder"; class App { constructor() { this.canvas = null; this.engine = null; this.scene = null; } init() { this.setup(); this.addListeners(); } setup() { this.canvas = document.querySelector("#app"); this.engine = new Engine(this.canvas, true, null, true); this.scene = new Scene(this.engine); // Adding the vertex and fragment shaders to the Babylon's ShaderStore Effect.ShadersStore["customVertexShader"] = require("./shader/vertex.glsl"); Effect.ShadersStore[ "customFragmentShader" ] = require("./shader/fragment.glsl"); // Creating the shader material using the `custom` shaders we added to the ShaderStore const planeMaterial = new ShaderMaterial("PlaneMaterial", this.scene, { vertex: "custom", fragment: "custom", attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"] }); planeMaterial.backFaceCulling = false; // Creating a basic plane and adding the shader material to it const plane = new PlaneBuilder.CreatePlane( "Plane", { width: 1, height: 9 / 16 }, this.scene ); plane.scaling = new Vector3(7, 7, 1); plane.material = planeMaterial; // Camera const camera = new ArcRotateCamera( "Camera", -Math.PI / 2, Math.PI / 2, 10, Vector3.Zero(), this.scene ); this.engine.runRenderLoop(() => this.scene.render()); } addListeners() { window.addEventListener("resize", () => this.engine.resize()); } } const app = new App(); app.init(); As you can see, it’s not that different from other WebGL libraries like Three.js: it sets up a scene, a camera, and it starts the render loop (otherwise you wouldn’t see anything). The material of the plane is a ShaderMaterial for which we’ll have to create its respective shader files. // /src/shader/vertex.glsl precision highp float; // Attributes attribute vec3 position; attribute vec3 normal; attribute vec2 uv; // Uniforms uniform mat4 worldViewProjection; // Varyings varying vec2 vUV; void main(void) { gl_Position = worldViewProjection * vec4(position, 1.0); vUV = uv; } // /src/shader/fragment.glsl precision highp float; // Varyings varying vec2 vUV; void main() { vec3 color = vec3(vUV.x, vUV.y, 0.0); gl_FragColor = vec4(color, 1.0); } You can forget about the vertex shader since for the purpose of this tutorial we’ll work only on the fragment shader. Here you can see it live: Good, we’ve already written 80% of the JavaScript code we need for the purpose of this tutorial. The logic GLSL is cool, it allows you to create stunning effects that would be impossible to do with HTML, CSS and JS alone. It’s a completely different world, and if you’ve always done “web” stuff you’ll get confused at the beginning, because when working with GLSL you have to think in a completely different way to achieve any effect. The logic behind the effect we want to achieve is pretty simple: we have two overlapping images, and the image that overlaps the other one has a mask applied to it. Simple, but it doesn’t work like SVG masks for instance. Adjusting the fragment shader Before going any further we need to tweak the fragment shader a little bit. As for now, it looks like this: // /src/shader/fragment.glsl precision highp float; // Varyings varying vec2 vUV; void main() { vec3 color = vec3(vUV.x, vUV.y, 0.0); gl_FragColor = vec4(color, 1.0); } Here, we’re telling the shader to assign each pixel a color whose channels are determined by the value of the x coordinate for the Red channel and the y coordinate for the Green channel. But we need to have the origin at the center of the plane, not the bottom-left corner. In order to do so we have to refactor the declaration of uv this way: // /src/shader/fragment.glsl precision highp float; // Varyings varying vec2 vUV; void main() { vec2 uv = vUV - 0.5; vec3 color = vec3(uv.x, uv.y, 0.0); gl_FragColor = vec4(color, 1.0); } This simple change will result into the following: This is becase we moved the origin from the bottom left corner to the center of the plane, so uv‘s values go from -0.5 to 0.5. Since you cannot assign negative values to RGB channels, the Red and Green channels fallback to 0.0 on the whole bottom left area. Creating the mask First, let’s change the color of the plane to complete black: // /src/shader/fragment.glsl precision highp float; // Varyings varying vec2 vUV; void main() { vec2 uv = vUV - 0.5; vec3 color = vec3(0.0); gl_FragColor = vec4(color, 1.0); } Now let’s add a rectangle that we will use as the mask for the foreground image. Add this code outside the main() function: vec3 Rectangle(in vec2 size, in vec2 st, in vec2 p, in vec3 c) { float top = step(1. - (p.y + size.y), 1. - st.y); float right = step(1. - (p.x + size.x), 1. - st.x); float bottom = step(p.y, st.y); float left = step(p.x, st.x); return top * right * bottom * left * c; } (How to create shapes is beyond of the scope of this tutorial. For that, I suggest you to read this chapter of “The Book of Shaders”) The Rectangle() function does exactly what its name says: it creates a rectangle based on the parameters we pass to it. Then, we redeclare the color using that Rectangle() function: vec2 maskSize = vec2(0.3, 0.3); // Note that we're subtracting HALF of the width and height to position the rectangle at the center of the scene vec2 maskPosition = vec2(-0.15, -0.15); vec3 maskColor = vec3(1.0); color = Rectangle(maskSize, uv, maskPosition, maskColor); Awesome! We now have our black plane with a beautiful white rectangle at the center. But, wait! That’s not supposed to be a rectangle; we set its size to be 0.3 on both the width and the height! That’s because of the ratio of our plane, but it can be easily fixed in two simple steps. First, add this snippet to the JS file: this.scene.registerBeforeRender(() => { plane.material.setFloat("uPlaneRatio", plane.scaling.x / plane.scaling.y); }); And then, edit the shader by adding this line at the top of the file: uniform float uPlaneRatio; …and this line too, right below the line that sets the uv variable uv.x *= uPlaneRatio; Short explanation In the JS file, we’re sending a uPlaneRatio uniform (one of the GLSL data type) to the fragment shader, whose value is the ratio between the plane width and height. We made the fragment shader wait for that uniform by declaring it at the top of the file, then the shader uses it to adjust the uv.x value. Here you can see the final result: a black plane with a white square at the center; nothing too fancy (yet), but it works! Adding the foreground image Displaying an image in GLSL is pretty simple. First, edit the JS code and add the following lines: // Import the `Texture` module from BabylonJS at the top of the file import { Texture } from '@babylonjs/core/Materials/Textures/texture' // Add this After initializing both the plane mesh and its material const frontTexture = new Texture('src/images/lantern.jpg') plane.material.setTexture("u_frontTexture", frontTexture) This way, we’re passing the foreground image to the fragment shader as a Texture element. Now, add the following lines to the fragment shader: // Put this at the beginninng of the file, outside of the `main()` function uniform sampler2D u_frontTexture; // Put this at the bottom of the `main()` function, right above `gl_FragColor = ...` vec3 frontImage = texture2D(u_frontTexture, uv * 0.5 + 0.5).rgb; A bit of explaining: We told BabylonJS to pass the texture to the shader as a sampler2D with the setTexture() method, and then, we made the shader know that we will pass that sampler2D whose name is u_frontTexture. Finally, we created a new variable of type vec3 named frontImage that contains the RGB values of our texture. By default, a texture2D is a vec4 variable (it contains the r, g, b and a values), but we don’t need the alpha channel so we declare frontImage as a vec3 variable and explicitly get only the .rgb channels. Please also note that we’ve modified the UVs of the texture by first multiplying it by 0.5 and then adding 0.5 to it. This is because at the beginning of the main() function I’ve remapped the coordinate system to -0.5 -> 0.5, and also because of the fact that we had to adjust the value of uv.x. If you now add this to the GLSL code… color = frontImage; …you will see our image, rendered by a GLSL shader: Masking Always keep in mind that, for shaders, everything is a number (yes, even images), and that 0.0 means completely hidden while 1.0 stands for fully visible. We can now use the mask we’ve just created to hide the parts of our image where the value of the mask equals 0.0. With that in mind, it’s pretty easy to apply our mask. The only thing we have to do is multiply the color variable by the value of the mask: // The mask should be a separate variable, not set as the `color` value vec3 mask = Rectangle(maskSize, uv, maskPosition, maskColor); // Some super magic trick color = frontImage * mask; Et voilà, we now have a fully functioning mask effect: Let’s enhance it a bit by making the mask follow a circular path. In order to do that we must go back to our JS file and add a couple of lines of code. // Add this to the class constructor this.time = 0 // This goes inside the `registerBeforeRender` callback this.time++; plane.material.setFloat("u_time", this.time); In the fragment shader, first declare the new uniform at the top of the file: uniform float u_time; Then, edit the declaration of maskPosition like this: vec2 maskPosition = vec2( cos(u_time * 0.05) * 0.2 - 0.15, sin(u_time * 0.05) * 0.2 - 0.15 ); u_time is simply one of the uniforms that we pass to our shader from the WebGL program. The only difference with the u_frontTexture uniform is that we increase its value on each render loop and pass its new value to the shader, so that it updates the mask’s position. Here’s a live preview of the mask going in a circle: Adding the background image In order to add the background image we’ll do the exact opposite of what we did for the foreground image. Let’s go one step at a time. First, in the JS class, pass the shader the background image in the same way we did for the foreground image: const backTexture = new Texture("src/images/lantern-bw.jpg"); plane.material.setTexture("u_backTexture", backTexture); Then, tell the fragment shader that we’re passing it that u_backTexture and initialize another vec3 variable: // This goes at the top of the file uniform sampler2D backTexture; // Add this after `vec3 frontImage = ...` vec3 backgroundImage = texture2D(iChannel1, uv * 0.5 + 0.5).rgb; When you do a quick test by replacing color = frontImage * mask; with color = backImage * mask; you’ll see the background image. But for this one, we have to invert the mask to make it behave the opposite way. Inverting a number is really easy, the formula is: invertedNumber = 1 - <number> So, let’s apply the inverted mask to the background image: backImage *= (1.0 - mask); Here, we’re applying the same mask we added to the foreground image, but since we inverted it, the effect is the opposite. Putting it all together At this point, we can refactor the declaration of the two images by directly applying their masks. vec3 frontImage = texture2D(u_frontTexture, uv * 0.5 + 0.5).rgb * mask; vec3 backImage = texture2D(u_backTexture, uv * 0.5 + 0.5).rgb * (1.0 - mask); We can now display both images by adding backImage to frontImage: color = backImage + frontImage; That’s it, here’s a live example of the desired effect: Distorting the mask Cool uh? But it’s not over yet! Let’s tweak it a bit by distorting the mask. To do so, we first have to create a new vec2 variable: vec2 maskUV = vec2( uv.x + sin(u_time * 0.03) * sin(uv.y * 5.0) * 0.15, uv.y + cos(u_time * 0.03) * cos(uv.x * 10.0) * 0.15 ); Then, replace uv with maskUV in the mask declaration vec3 mask = Rectangle(maskSize, maskUV, maskPosition, maskColor); In maskUV, we’re using some math to add uv values based on the u_time uniform and the current uv. Try tweaking those values by yourself to see different effects. Distorting the foreground image Let’s now distort the foreground image the same way we did for the mask, but with slightly different values. Create a new vec2 variable to store the foreground image uvs: vec2 frontImageUV = vec2( (uv.x + sin(u_time * 0.04) * sin(uv.y * 10.) * 0.03), (uv.y + sin(u_time * 0.03) * cos(uv.x * 15.) * 0.05) ); Then, use that frontImageUV instead of the default uv when declaring frontImage: vec3 frontImage = texture2D(u_frontTexture, frontImageUV * 0.5 + 0.5).rgb * mask; Voilà! Now both the mask and the image have a distortion effect applied. Again, try tweaking those numbers to see how the effect changes. 10 – Adding mouse control What we’ve made so far is really cool, but we could make it even cooler by adding some mouse control like making it fade in/out when the mouse hovers/leaves the plane and making the mask follow the cursor. Adding fade effects In order to detect the mouseover/mouseleave events on a mesh and execute some code when those events occur we have to use BabylonJS’s actions. Let’s start by importing some new modules: import { ActionManager } from "@babylonjs/core/Actions/actionManager"; import { ExecuteCodeAction } from "@babylonjs/core/Actions/directActions"; import "@babylonjs/core/Culling/ray"; Then add this code after the creation of the plane: this.plane.actionManager = new ActionManager(this.scene); this.plane.actionManager.registerAction( new ExecuteCodeAction(ActionManager.OnPointerOverTrigger, () => this.onPlaneHover() ) ); this.plane.actionManager.registerAction( new ExecuteCodeAction(ActionManager.OnPointerOutTrigger, () => this.onPlaneLeave() ) ); Here we’re telling the plane’s ActionManager to listen for the PointerOver and PointerOut events and execute the onPlaneHover() and onPlaneLeave() methods, which we’ll add right now: onPlaneHover() { console.log('hover') } onPlaneLeave() { console.log('leave') } Some notes about the code above Please note that I’ve used this.plane instead of just plane; that’s because we’ll have to access it from within the mousemove event’s callback later, so I’ve refactored the code a bit. ActionManager allows us to listen to certain events on a target, in this case the plane. ExecuteCodeAction is a BabylonJS action that we’ll use to execute some arbitrary code. ActionManager.OnPointerOverTrigger and ActionManager.OnPointerOutTrigger are the two events that we’re listening to on the plane. They behave exactly like the mouseenter and mouseleave events for DOM elements. To detect hover events in WebGL, we need to “cast a ray” from the position of the mouse to the mesh we’re checking; if that ray, at some point, intersects with the mesh, it means that the mouse is hovering it. This is why we’re importing the @babylonjs/core/Culling/ray module; BabylonJS will take care of the rest. Now, if you test it by hovering and leaving the mesh, you’ll see that it logs hover and leave. Now, let’s add the fade effect. For this, I’ll use the GSAP library, which is the de-facto library for complex and high-performant animations. First, install it: yarn add gsap Then, import it in our class import gsap from 'gsap and add this line to the constructor this.maskVisibility = { value: 0 }; Finally, add this line to the registerBeforeRender()‘s callback function this.plane.material.setFloat( "u_maskVisibility", this.maskVisibility.value); This way, we’re sending the shader the current value property of this.maskVisibility as a new uniform called u_maskVisibility. Refactor the fragment shader this way: // Add this at the top of the file, like any other uniforms uniform float u_maskVisibility; // When declaring `maskColor`, replace `1.0` with the `u_maskVisibility` uniform vec3 maskColor = vec3(u_maskVisibility); If you now check the result, you’ll see that the foreground image is not visible anymore; what happened? Do you remember when I wrote that “for shaders, everything is a number”? That’s the reason! The u_maskVisibility uniform equals 0.0, which means that the mask is invisible. We can fix it in few lines of code. Open the JS code and refactor the onPlaneHover() and onPlaneLeave() methods this way: onPlaneHover() { gsap.to(this.maskVisibility, { duration: 0.5, value: 1 }); } onPlaneLeave() { gsap.to(this.maskVisibility, { duration: 0.5, value: 0 }); } Now, when you hover or leave the plane, you’ll see that the mask fades in and out! (And yes, BabylonJS has it’s own animation engine, but I’m way more confident with GSAP, that’s why I opted for it.) Make the mask follow the mouse cursor First, add this line to the constructor this.maskPosition = { x: 0, y: 0 }; and this to the addListeners() method: window.addEventListener("mousemove", () => { const pickResult = this.scene.pick( this.scene.pointerX, this.scene.pointerY ); if (pickResult.hit) { const x = pickResult.pickedPoint.x / this.plane.scaling.x; const y = pickResult.pickedPoint.y / this.plane.scaling.y; this.maskPosition = { x, y }; } }); What the code above does is pretty simple: on every mousemove event it casts a ray with this.scene.pick() and updates the values of this.maskPosition if the ray is intersecting something. (Since we have only a single mesh we can avoid checking what mesh is being hit by the ray.) Again, on every render loop, we send the mask position to the shader, but this time as a vec2. First, import the Vector2 module together with Vector3 import { Vector2, Vector3 } from "@babylonjs/core/Maths/math"; Add this in the runRenderLoop callback function this.plane.material.setVector2( "u_maskPosition", new Vector2(this.maskPosition.x, this.maskPosition.y) ); Add the u_maskPosition uniform at the top of the fragment shader uniform vec2 u_maskPosition; Finally, refactor the maskPosition variable this way vec3 maskPosition = vec2( u_maskPosition.x * uPlaneRatio - 0.15, u_maskPosition.y - 0.15 ); Side note; I’ve adjusted the x using the uPlaneRatio value because at the beginning of the main() function I did the same with the shader’s uvs And here you can see the result of your hard work: Conclusion As you can see, doing these kind of things doesn’t involve too much code (~150 lines of JavaScript and ~50 lines of GLSL, including comments and empty lines); the hard part with WebGL is the fact that it’s complex by nature, and it’s a very vast subject, so vast that many times I don’t even know what to search on Google when I get stuck. Also, you have to study a lot, way more than with “standard” website development. But in the end, it’s really fun to work with. In this tutorial, I tried to explain the whole process (and the reasoning behind everything) step by step, just like I want someone to explain it to me; if you’ve reached this point of this tutorial, it means that I’ve reached my goal. In any case, thanks! Credits The lantern image is by Vladimir Fetodov
https://tympanus.net/codrops/2019/11/26/creating-a-distorted-mask-effect-on-an-image-with-babylon-js-and-glsl/
CC-MAIN-2020-29
refinedweb
3,460
55.74
> First of all, we need a means to identify resources, both local ones and > remote ones. > The (ssh-like) URI idea seems to be good enough for it. > > cat anne@computer_one:/dev/microphone > anne@computer_two:/dev/speakers > > Ok... it's very naive, I admit; but it's just an example. plan 9 can already do this import computer_one /dev /n/dev1 import computer_two /dev /n/dev2 cat /n/dev1/microphone>/n/dev2/speakers > > What else do we need? > 1) A common interface to devices and files (like Plan 9) it seems you already know 9p can do this. > The common protocol... well Plan 9 uses 9P, which is very nice, but I have > a different approach. > > I'd encapsulate messages into SOAP (XML) envelopes. > > This has one big advantage and one big disadvantage. > Advantage: it has no endianness problems, because it's just text in some > encoding. > Disadvantage: it is horrendously inefficient. i see no advantage as 9p does not have an endian problem. > However it has also got other nice aspects: > - it's easy to create new messages: the whole infrastructure is there, you > just have to generate some XML. > - [I believe] it is a simple concept to understand > - [I believe] it is simple to debug (messages are easily interpretable) 9p has these properties. > Then, the operating system analyzes the message, and it decided whether > it's a local or a remote operation. > If it's a local one, it just carries it out and it sends an XML message > back to the user process, and the C library will just decode it and return > a value to the user in the standard way. > Basically... the user doesn't know what's going on under the C API, it's > transparent (as much as possible). > > If it isn't a local operation, the kernel acts as a proxy and forwards the > request to the target host, which in turn will realize it's a proxy > operation and it will return values back to the caller. this sounds like a vague discription of a process' mount table. > > The key concept is: > what you can do locally you can also do remotely. > > ...by virtue of making it the *single* way to access the kernel. > So you can't say: "this is going to be implemented for the local interface > only... we'll take care of the remote one afterwards", no way. perhaps some of the papers here () would be helpful. i'd start with _the organization of networks in plan 9_. - erik
http://fixunix.com/plan9/46950-rpc-esque-system-calls.html
CC-MAIN-2015-14
refinedweb
421
64.61
To extend the functionality of you web application relative to your requirements you are supposed to use existing yii core libraries or use external libraries. There are some steps to ensure security, uniqueness, modularity, performance and to avoid rework in future. These questions are important because they impact on how seriously you need to take issues such as coding standards, updates, security, support and documentation. Even if you’re just writing a extension for your own use or for the use of your colleagues, you need to think hard about how you’re going to go about it so that you don’t make a rod for your own back. Simple things like consistent spacing, indenting, informative variable naming and succinct comments are a good place to start. If you code to a standard your code will be easier to understand, edit , debug and extends for others in programming world. You can start from scratch or modifying existing one, by modification you can simply extend its functionality what you want. Here we are assuming from scratch !. Before the development classify your extension and try to avoid dependencies on external scripts because its difficult to keep your extension according to external scripts modifications even on other extensions as well for both developer and you, because sometime developer changes extension folder or project file structure. 1) Name extension folder in lower case , dash separate two words,etc like myext, my-ext, myExt,myext-v1.0 etc. 2) Copy all sources/files to folder like js, css, images, supporting libs,classes,namespaces etc. 3) Some comments on top of each or at least one file for extension description, author,contact info, version, package and copyrights license etc. /** * MyCurrentClassName class file. * This is description of MyCurrentClassName for developer to use it further ! * @author Fazal Burhan <Skype: fburhan810> * @link * @copyright Copyright © Fazal Burhan 2014- * @license New BSD License */ 4) For Access all the dependent files, use Yii standards Classes like - Register your script - Current extension folder : $dir = dirname(FILE) . DIRECTORY_SEPARATOR . 'sources/files'; - CAssetManager :to avoid naming conflict , available as Yii::app()-assetManager read more 5) Initialize & check all the variables/attribute before use. 6) To access yii core libraries or other classes you can use import() in our extension Yii::import(‘zyx.abc.MyClasss’); // class Yii::import('application.components.* '); // for entire package 7) Use your extensions : if your extension is in protected/extensions the you can access it by $this->widget('ext.myext.MyExt'); You can pass parameters like $this->widget('ext.myext.MyExt', ‘property’=>’value’, ‘Options’=>array('property1'=>'value1', 'property2'=>'value2' ), ); Where ext is alias used for extensions in protected if want to define your own , you can use Yii::setPathOfAlias('myAliase',DIRECTORY_SEPARATOR . 'vendor'); in config Then $this->widget('myAliase.myext.MyExt'); Example /** * MyCurrentClassName class file. * This is description of MyCurrentClassName for developer to use it further ! * PHP Version 5.1 * @package Widget * @author Fazal Burhan <Skype: fburhan810> * @copyright Copyright © Fazal Burhan 2014- * @license MIT * @link */ class MyExt extends CWidget { /** * @var string the hello . */ public $hello = 'Hello World'; public $cssFile; // it better to have private attribute for security then you have to define getter and setter methods // initialized all the variable and scripts used public function init() { // get & publish assets $path = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.myext.source', -1, false)); $this->cssFile = $path . '/myext.css'; // load css // register scripts $cs = Yii::app()->clientScript; $cs->registerCssFile($this->cssFile); // register css } /** * Run this widget. * renders the needed HTML code. */ public function run() { echo $hello; } } <?php $this->widget('ext.myext.MyExt'); //using param $this->widget('ext.myext.MyExt', array( 'hello' => 'Hello world ! i am Here', )); Security and Performance are basic objectives of yii. There are some interesting topics on it go through according to your requirements if it has high values to you !. Internationalization doesn’t have to be a big deal but is essential if you want to reach the widest audience possible. Turn on debug The Yii debugger will find errors in your code that while they may not crash you extension should still be corrected to make sure that you’re doing things correctly. So, turn on YII_DEBUG set true in index.php in root directory. Study the Yii Core library Yii often has functions that will solve a programming task in one function/class that you may have written many lines of code to achieve. Check out to make sure you’re not writing more code than you need to. Get some peer review Getting others to look at your code is a strong form of quality control. Other users will find faults that you haven’t noticed in your own testing. Don’t be afraid to post your code: everyone makes mistakes. Don’t use deprecated functions! Use a good Yii discussion forum If you have a problem, ask others. There are plenty of forums for Yii solutions Take some pride in your work! It’s easy to release a Yii with a rider that you take no responsibility for the effects of your code. Now, that’s a necessary given: you can’t be responsible for how your extension will be used. But you can take a professional pride in how you go about your work. Always do your best. Your reputation will be the better for it. Total 2 comments Posting your code on github and asking for a review on the yii IRC channel is a good way to get others to look at your code. It also worth mentioning that if you use a good IDE (like PhpStorm) you get valuable help with formatting the code properly, detecting code weaknesses and injecting standard documentation blocks. Please login to leave your comment.
http://www.yiiframework.com/wiki/611/extension-development-beginner/
CC-MAIN-2017-47
refinedweb
945
55.54
Graphic Thinking for Architects & Designers TH RD E ITION Graph·c Thinking for Architects & Designers PAUL ASEAU JOHN WILEY & SONS, INC. New Yor k Chich ester Weinheim Brisb ane Singapor e Toron to Thi s book is printed on acid-free paper. il' e 2001 by John Wil ey & Sons . All rights re served . Publish ed simultaneou sly in Canada . Int erior D esign: Da vid Levy No part of thi s p ublication may be reprod uce d, stored in a retrieval syst em or transmitted in any form or by an y me ans, electronic, m echanical , photocopying, recording, scanning or otherwise, excep t as permitted under Sections 107 or 108 of the 1976 United Stat es Copyright Act, without either the prior w ritten pe rm ission of th e Publisher, or authorization through payment of th e appropriate p er -cop y fe e to the MA 0192 3, 1978) 750-8400, fax 1978) 750-4744. Requests to the Publi sh er for p er m iss io n sho u ld be add ressed to the Permissions Department , John Wiley & Sons, Inc ., 605 Third Avenue, New York , NY 10158-0012, (212) 850-6011 , fax (212) 850-6008, E-Mail: PERMREQ@WILEYCOM. This publication is design ed to provide accurate and author itative information in re gard to th e subject matter covered. It is sold with th e under standing th at th e publish er is no t engaged in rendering professional se rvices . If professional advice or othe r expe rt ass istance is required , th e services of a compe te nt professional per son sh ould be sou ght. Librar y of Congress Cataloging-in-Publication Data: Lase au , Paul, 1937 Graphi c think in g for ar chitects & d esi gners I Paul Laseau .-3rd. ed. p. em . Includes bibliographical ref er en ces and ind ex. ISBN 0-471-3529 2-6 (pap er) 1. Architectural dr awing . 2. Com m u nication in ar chi tectural design . 3. Architecture-Sketch-book s. I. Ti tle. 4. Graphic arts. NA2705 .L38 2000 720 '.28 '4-dc21 Pr inted in th e United Stat es of America . 10 98 7 99- 08680; 9 • Contents vi 8 Discovery 141 Preface to the Third Edition vii 9 Verification 163 Preface to the First Edit ion viii Foreword Acknowled gments 1 Int roduction ix 1 BASICSKILLS CO MMUNICATION 10 Process 179 11 Individual Design 189 12 Team Design 203 2 Drawi ng 17 13 Public Design 217 3 Conventions 39 14 Conclusion 231 4 Abst raction 55 Notes 237 5 Expression 67 Bibliography 239 Illustration Credits 242 Index 244 APPLIED SKILLS 6 Analysis 7 Exploration 81 115 v • Foreword au l Las eau p roposes tw o re late d ideas: th e first is th at of "graphic th inking"; th e second is gra p hic thin king as a de vice for com m uni cati on bet w een the de signe r and the designed for. Th e follow ing brief remarks are addressed to the relati onship betw een the two ideas. P d irect th e ac tions of others and wh o co m m un ica te their de cision s to th ose w ho wo rk thro ugh dr aw ings ma de by d raft sm en . Design ing, as a separate task , has co me in to being . Th e professional designer, th e profession al draftsman, and the as sem bly lin e occ ur simultan eously as related phen omena . Histor ica lly, buildi ng d es ign was not so ind iffer eh t to human w ell-being that "com m un ication with the peopl e" becam e an issue until th e ac t of draw in g wa s divided into tw o sp ec ialized activities. The first wa s design drawi ng, in w hic h th e design er exp res sed h is or h er ideas. Th e seco nd was d raft in g used to in struct the builder. This all occ urred some tim e ago, bu t the m om en tum of the ch ange fr om craftsm an ship to draftsm an sh ip , broug h t abou t by the pe culiar form of in d ustrialization we have ch osen to adopt , persists. It now exte nd s to the division of labor in th e design er 's office. Th e build ing of gr eat bu ildings is no longer the cre ation of m aster cr aftsmen led by a m as ter builder but of archite ctural offi ces organized along the lines of in dus tri al production . The task of th e ar ch itec t has been divided and subdivided in to an as sembly line of designer, con str u ct ion m anager, in ter ior desi gner, decora tor , struc tural, elec tri cal, and m ech anical engi neers, an d d raft sm en . Design dec isions onc e made by th e designer on the drawing board ar e now made by th e p rogram m er on comput er p rintou ts. De sign d rawing began as and remains a m eans of gen era tin g ideas, for ta ppi ng in itial con cepts to be sorted out and developed , or simply as an enjoyable ac tivi ty. Dra ftin g is an eigh t-h our ta sk p er forme d dai ly, fill ing shee ts of paper w ith precise lines d ic tated by ot hers. Long ago, when the w ork of individual craftsme n beca m e larger and m ore com plex, wh en a cathedr al rather than a chair w as to be designed , dimension s had to be esta blis he d so th at th e work of a single cra ftsm an co u ld be coo rd ina te d with th e w ork of m any. Drawing w as introdu ced as a cr eativ e device for plan n ing wo rk. • Cr aft sm en ha ve a lways u sed drawings to hel p th em visua lize the ir ideas as th ey made adj ustments in th e continu ous p ro cess of fitt in g parts tog eth er. Dr awing under these cond itions is in sep arabl e fr om the w ork itself. Som e historian s say th at th e w orking draw in gs for the gr eat church es of the tw elfth and thirteenth centuries w er e d rawn on boards that w er e later nai led int o the const ruct ion . But drawing also has other purposes. Th e d ivisi on of labor in cr eases product iv ity. Art ifacts requ iri ng several wee ks of wo rk by a sing le sk illed cra ftsman are d ivid ed in to sm all er st and ardi zed w ork tasks. Pr oduc tion is increa sed as skill is elimina te d. The cr aftsm an' s expression of m at eria l, design sen se , and sket ches are bani sh ed fr om the wo rkplace . Drawings an d specificatio ns pre de te rm ine a ll fac et s of t he w ork. Design decision s are give n to a new class of wo rk m en who do not w ork w ith the mat er ial but in st ead vi There are those of us w ho believe that indu strial ization cou ld have been ach ieved w ith out dest roy ing the crafts m an 's skill, love, and respect for material and the joy of building. We find it even less desirable tha t the jo y of creativity a nd grap hic thi nking that acco mpanies th at ac tivity should leave th e design er 's offi ce for the m em ory ban k of a comp uter. The built world and artifacts around us are ev i den ce of the alm os t fat al erro r of basing design on the mindl ess w ork of the ass embly line . To devel op pro gr amming and operat ion al resea rc h based on m ind less design would be to con tin ue a dis astrous hist oric continu um . Graphic th in king is of course necessa ry to help rej uven ate a mo ri bund design sy stem. But com muni ca tion "w ith th e pe ople " is n ot enough . Cr ea tiv ity itself m ust be share d , and sha red wi th everyone from do w el kn ock er to "Liebe r Meis ter." The nee d fo r grap hic thinking is grea t, bu t it is greater on th e w or kben ch es of the as sem bly lin es at Riv er Rouge th an on the desks of the chi ef designers of Skid m ore, Ow ings & Merrill. - F ORREST W ILSON, 1980 Preface to the Third Edition w enty years have passed since th e fir st pu bli ca tion of th is book . Th e events of the inter ve n ing ye ars have served to re in force m y in itial assu mp ti on s and th e poin ts made by For rest Wilson in th e Forew or d . T The ac celerated developmen ts in persona l com p u ters and th eir app lica tion to arch itectural des ign a nd co nstru cti on ha ve rai sed m or e for cefully t h e question of th e role of ind ivid ual thought a nd creativ ity wi th in p roce sse s tha t a re incr easingly com p lex and special ized . W ill in d iv id ua ls exp erie nce m or e opportunities for expression and co ntri buti on or w ill t heir con tributions be devalued because of th e speed and p recision of comp uter- dr iven processes? Alt ho ug h th e In tern et /web ha s d ra ma tically increased ind ividu al access, tw o major philosop hical camps still guide comp uter deve lopmen t and app lica ti ons. O ne cam p se es th e co m p ut er as a w ay to exten d and im prove tradi tional bus in ess or ganizat ion , w ith it s se gm enta tion of tas ks and relia nc e on spe cialists. The other ca m p see s th e comp uter as a w ay to re vo lution ize busin ess by br oade nin g the sc op e . and impact of th e in d ividual to th e benef it of bot h the • ind ividual and the org anization . O ne vie w is of ind i vid ual s supporting inform ation ; th e ot he r is of info r mation supporting in d ivid uals. A pr emi se of the first edition of this book was that in d ividu al , creative th inking has a vital role in a pres , ent and fu tur e society th at m ust cop e w ith complex, interr elat ed p robl e m s. Add ressing such problems d ep en ds up on a com p reh ensive u nde rs ta nd ing of th eir nature ra ther th an shoehorn ing them in to con venien t, si m p listic, th eoretica l mod els . And visua l com muni cati on pr ovi des a n im por tan t tool for describing and under standi ng co m plexity. Inc reased com pre hensive, ra ther tha n spe cialized , kno w ledge in the possession of ind ividu als shou ld benefit both the orga nization and the indi vidual. In thei r book, In Search of Excellence, I Peters and Wate rman illus trated th at the effec tiveness of organizations depends up on an understa nd ing of val ues, aspira tion s, an d m ean ings th at is share d by all me m bers. We are als o be com ing m ore aware that the m ental and ph ys ica l health of in d ividual s is a valid as well as pra ctical conc er n of orga ni zations . vii Preface to the First Edition n the fall of 1976, while participating in a discus sion group on design communication at the U niversity of W isconsin-Milwaukee, I had the occ asion to mention my book Graphic Problem Solving. Essentially, that book was an attempt at con vincing architects to apply their freehand concept gath ering skills to nontraditional problems dealing more with the processes than the products of archi tecture. During the discussion , Fuller Moore stated that the graphi c skills I had assumed to be part of arch itectural training were being neglected in the schools and that a more basic book on drawing in support of thinking was needed. Soon after, I had th e chance to talk to several architects about the sketches th ey use to d evelop designs in con trast to the "fin ished drawings th ey use in p resen tations." Most cre ative architects had de veloped impressive freehand sketching sk ills and felt comfortable sketching while thinking . Some architects d r ew observations or design ideas in sm all sketchbooks they carried with them at all times. Both the architects and th e educa tors I interviewed expressed concern over the appar en t la ck of freehand graphic skills in pe op le now entering the profession. I As I began to collect materials for this book , 1 wondered about the re levance of sketching in archi tecture. Could sketching be better applied to design ing as p racticed tod ay ? The answer to this qu estion depends on an exami nation of the present challenges to architectur al design : 1 . To be more respon sive to needs, a problem-solv ing process. 2. To be m ore scientific, more reliable, or pr'> dict able. The response to these challenges was su ggest ed by Heinz Von Foerster: ...the language of arch itecture is conn otative lan guage because its in tent is to initiate interpretation . v iii • The crea tive architectural space begets crea tivity, new insights, new cho ices. It is a ca talyst for cogni tion . This suggests an ethical imperative that applies not only to architects but also to anyone who acts on that imperative. A ct always so as to: inc rease, enlarge, enhance the number of choices. I Relating these ideas to the challenges en um erated earl ier, I see two correspo nding imperatives: 1. Ar chitects sh ou ld solve p roblem s wi th peopl e in st ea d of for them by helping them under stand their ne eds and the choices of designs th at me et those ne eds. This is d one by bringing th ose who use the build ings int o the process of de sig ning those bu ild ing s. 2. Archi tect s m us t better u n ders tand sc ience and how mu ch it has in common with architec tur e. Jacob Bronowski pointed out th at the crea tive sci entist is more in teres ted in exploring and exp and ing id eas th an in es tablishing fixed "truths." The unique qu al ity of human beings lies in th e increase rather than the decrease of diversity. Within this context , sketches can contribu te to de sign, first by facilitat ing the exploration and d iver sity of ea ch designer's th in kin g. Second, sket che s can help open up the desi gn process by developing com m unicat ion with people instead of presentin g con clu sions to people. Th e not ion of graphic think ing gr ew out of the recognition that sketchi ng or drawing can and should support the de signe r 's thinking. I re ali ze that som e readers w oul d be more comfo rtable w ith a bo ok about either thi nkin g or drawi ng , but I felt it was cri t ical to deal w ith th eir inte raction . Pu lling th em apart se emed to be like tr ying to u nde rs tan d ho w a fish swims by studying th e fish and the water sepa rately. I hope you will be able to bear w ith the rough spots in this book and find som e th in gs that wi ll help in your work. AcknowLedgments h is book is ded icat ed to th ose ar chitects who gen erou sly took time to discuss their use of drawing s in de sign d uring m y or iginal an d su bs eq uent rese arch . Man y of th em als o pro vided sketches to illustrate th e text. Th eir ded ication to creativity in arch itecture, enthusiasm for dr aw ing, and co m me nts abou t their de sign p rocesses were a gre at he lp and inspirat ion for my work. Among the se architec ts, I am especiall y indeb ted to David Stieg litz, T hom as Bee by, Mor se Pay ne , Thomas La rso n, Mich ae l Ge b har t, Rom a ldo G iurgola , Jam es Tice , Nor m a n Crow e, Harry Egin k , Kir by Lock ard , and Steven and Cathi H ouse. T Recognition is due th e following p eop le for the ir p articu la rly important contribution s to this eff ort: Full er Moore for first su ggesting the id ea. Robert McKim for his ins ights to visual th in king and his en cou rage m ent. Jim An ders on for vital co mments on graph ic co mmu nication. • Karl Brown for comments and other val uab le ass is tan ce . Mi ch ele Laseau for technical ass istanc e. Jack Wyman , Ken Car penter, Juan Bonta , Ch arles Sappen field , and oth er pr ese nt and past col lea gues at the College of Architecture and Planning, Ball State University for com me n ts an d moral support. A special thanks to Forrest Wilson for his enth usi astic sup por t at th e humbling ou tset of thi s effort. Fin all y, th anks must be given to my wife, Peggy, and children , Mich ele , Kevi n, an d Made lein e, for their grea t patience and sa cri fices whi le I struggled with revision s. Pr eviou sly p ublished draw in gs w ere pho tographed by Jerry Hoffm an and Stev en Talley. ix .~~ "'_ .:; . \ - : -- , .1 )I ~ . .• \ H .. · ~ ' ' i _ .. q ,. . -~ ,r , .... . 10, c , \ -: \. .... .;.. • • 1 Introduction rap hic thin king is a te rm I ha ve ad opted to describe thin kin g assisted by ske tch ing. In ar chitecture , t his type of thin king is usually associate d w ith the concep tua l design stages of a projec t in wh ich th inkin g and s ke tch ing w ork closel y toge th er as st im ula n ts for develop ing ideas. In terest in th is form of th inki ng is prom ot ed by a reexam ination of the histor y of ar ch itectura l des ign , th e impact of visu al com mun ication in society, and new concepts of th e role of design and design ers. G The re is actua lly a ve ry strong tradit ion of grap hic th in king in archi tecture. Looking th ro ugh rep ro du c tions of th e not ebo oks of Leon ardo da Vinci, w e are str u ck by th e d yn am ic t hin kin g t hey re flect . It is im possible to rea lly u nd erst and or app rec ia te da Vin ci's thin king apa rt fro m his d rawi ngs because the graphic images and th e thinking are one, a unity. A close r look at the se ske tches reve als certain featur es tha t are instr uc tive for anyone intereste d in grap hic th in king. 1. There are m any d ifferent ideas on one page-his attention is constantly sh ifting from one su bje ct to another. 2 . The way da Vin ci looks a t prob lems is di ve rse both in m ethod and in scale- there are oft en per spect ives, sections, p lans, de ta ils, an d panoram ic view s on the sam e page. 3 . T he thin king is exp lor a to ry, op en-end ed - the sket ches are loose and fr agm ented w h ile sho w ing how th ey were der iv ed . Ma ny alt erna tiv es for extend ing th e id eas ar e sugges te d . The sp ecta tor is invited to parti cipate. Wh at a m arvelous exa mple! Here is a mi nd in fer m ent, using draw ings as a m eans of discover y rath er than as a w ay to imp ress other peop le. Alt ho ug h it is oft en d iff icult to fi nd reco rds of develop m en tal sketch es in hist or ica l documen ts , t her e is eno ug h sur v ivin g evide nce to in d ica te th a t th e use of sk etches for th in king w as com m on to ar ch itects thr oughout history. Depe nd ing on th e d ic tat es of th e bui ld ing trades or customs, the dr aw ing conven tions varied from plan to sec tion to ele vat ion . For alm ost tw o centuries, th e Ecole des Beaux Art s in Paris used the plan esquisse as th e found ation for its Figure 1-2 By Edwin Lutyens. Castle Drago and British Pavilion 1911 Exposition, Rome. ;,~ j' ~ .t .oli\ ~ ,. ' 0 '· L , . .-l I ', . Figure 1-3 By Edwin Lutyens. Castle Drago and British Pavilion 1911 Exposition, Rome. tr ain in g m e th od . W it h th e establis hme n t of la rge arch itec tura l fir ms in the U ni ted States, th ree dimension al scale models gradua lly rep laced d raw ing for the purposes of design deve lopment. Th e use of de sign ing sk etc h e s furt h er decl ined w ith th e ad vent of professio na l m ode l makers an d profes siona l rende rer s. 1 f .......-. . ~ '. ' ..L ! --...._---' "T'" , . i \ ) ~ I I -~ / - ,- ' ~ _. ..r ~.r ' ~-~ "I .""';' ' ., j ' - U . i'J.' ., : '\ ~_ . ' '" . ' ,., ,; . t.~! 1.-'\ 11' "; / ./ . '. >.... _ ...... .., ". , [ " r r "> • \ ~ ~ -I:':" - ,- . .. : ' \ -- <, t,.. ..- .. , ~~ --~~ ~. -; ( " 1 \ _.. . . . ~i WI' ;p, , Ii ) ,~\ ej JIJ:i I' I ' /J. 'f l -t ~~~ ~7 - .s ~ " , ~-T"~ '" ~. -" ,/),. ,)I" V:' -.-~ ~.• ' ~~ . ~ [I),. ; •.- - -r "' ., - . ~'-_ i.o--r---:::> . ' C-7~ t" '~ .~ ,. 6r>o" 1 \ ; . . < ~ I ~~.!l-:"" ~- . -~ . .. - Figure 1-4 By Alvar Aalto. Th er e ha s, of cours e., been an int ense in te rest in ar ch itec ts ' drawings re kindled by exhibits lik e the Beaux-Arts and 200 Years of Am erican Architectural Dr aw ings. But th e emphasis is mo stl y on com m uni cation of the final fixed product , and these pres enta tion drawin gs tell us p ractica lly nothing about the w ay in w h ich the b uildin gs were designed. The think in g sketches ar e necess ary to understand the step -by -step proc es s. Yet ev en when the thinking sketch es ar e avai la ble , as in the do cuments of the work of LeCorbusier, they ar e usually overlooked in favo r of th e renderin gs or photos of the finished w ork. We ar e ju st beginnin g to appreciate th e impor tance LeCorb usier pl aced on sketches. As Geoffrey Broad bent no te s, "All the internal harmony of the work is in th e drawin gs.. .. It is incredible that artists today shoul d be in di ffer en t (even ho stile) to th is prime m over, this' sca ffolding' of th e project. "l 2 Intr oduction ~. \fJ!lJiK~-:'1. I . Tt1~~""'~ . \ ," Figure 1-5 By Th omas Larson. The Grandberg Residence. • -c.· ·~ -- .- ILJI \. ~~~~ Figure 1-6 By Tho mas Beeby. House of Virgil. Among mod ern arc hitects, Alvar Aalto has left us proba bly one of th e best models of th e gra p h ic think in g tradition. His sket ch es are rapid and divers e; they def tly pr obe th e s ubject. Hand, eye , a nd mi nd are int en sely concentra ted . The sketc hes record th e level of develop men t , profi ciency, an d clari ty of Aalto ' s ide as. There are m any other architect s w hose work we can turn to , particul arly here in the United States, whe re w e are exp eriencing a resurgen ce of ske tching. Their draw ing s ar e inventive, diverse, and p rov oca tive. Whethe r they are m akin g notes in a sketchbook or turning over con ce pt s in th e design studio , th ese cre ative design ers are looking for som et hing specia l over and above solving the design pro bl em , like the gourmet w ho is lookin g fo r somethin g more than food . T hey e njoy the eure k a experience , and they enjoy th e sea rch as w ell. Th is book is really a bo ut find ing th ings, about se ein g new ideas, about di scov ery, and abo ut sharing ideas a nd d iscove ries . Figure 1-7 By Norman Jaffe. Int rodu ction 3 Figure 1-8 Battl e of Cety I with the Chet a. Figu re 1-9 Greek geometry Figure 1-10 ExpLoration map. VISUAL COMMUNICATION THROUGH TIME Through out his tory, vi sion has h ad an important imp act on th inki ng. Starting with th e cav em an , dr aw ings we re a way of "freez ing" ideas and even ts out side of hi m and cr eati ng a history. In m any ways, the "second wo rld " man cr ea ted through his images w as critical to the evo lution of thinking. Man was able to separate th e he re an d now fr om what could be imag ine d, the fu ture. Through im ages, the world of the spirit , the ideal world of mythology, and compelling ut op ias be came immedia te an d real. Th e ideals of an entire cult ure could be contained in one pi cture; the unsp eakable could be shared with others. Fro m earli es t tim es, thi s vi su al expression of thinking ha s be en commu na l. O n ce a concept , such as the notion of m an be ing able to fly, wa s converte d to an im age, it w as free to be rein ter preted again and again by others un til the airplane was inven ted. Ma n used signs and sym bols lon g before w ritten la ng uages w ere ado p ted. Early w ritte n langua ges, 4 Int rodu ction Figure 1-11 Constellation of sta rs such as Egyptian hieroglyphics, were hi ghly sp ecial ized set s of symbols derived fr om p ict ures. Th e devel opmen t of geometry, combining mat hemati cs w ith diagram s, m ade it pos sible to think of str ucture and othe r abstractions of reality. This led"to the const r uc tion of objects or buildings of monumental scal e fr om desi gn s. In addit ion to tr ying to make se n se of hi s immediat e surroundin gs, man used d rawings to reach outnto the unknown. Ma ps rec ons tituted from notes and sketches of ex p lore rs spar ked the im aginati on and s ti m ula te d new d iscoveries about our w orld and th e un ivers e. In spite of the asc endance of writt en language, vis ual co m m u nication con tin ue s to be an essenti al part of the wa y w e think. This is re ve aled in th ese phrases that liberally sp rinkle our everyday conversa tion : "I see what you m ean ; take anothe r look at the situation ; put this all in pe rspective." Alt h ough research opinion varies , it seems gen erally acc ep ted that 70 to 80 p ercent of what w e learn I S thro ugh sigh t. ;:jight seems to be the m ost rapid an d compre- Ir= m II ~~~ Figure 1-12 Figure 1-13 Figure 1-14 Figure 1-15 Figure 1-16 Figure 1-17 he nsiv e of ou r se nse s fo r rec eIv m g in formation. T hr oug h cen turies of condi tion ing, w e rely on vision for a n ea rly wa rn ing of dange r. Not only h av e w e co m e to dep end on s ight as a pri m a ry m ea n s of understandi ng th e w orl d , bu t we ha ve al so lea rn ed to tran sla te in fo rm ati on pi c ked up b y th e senses in to visual clu es so tha t , in ma ny w ays, sigh t is actu all y us ed as a substi tu te for the oth er senses. There is a m ple evidence that vi sual comm u n ica tion is becomi ng an eve n m ore powerfu l force in our lives. Th e m os t ob vi ous exa m p le is te le v is ion , thr ough wh ich we ca n exp lore th e sk ies, the oc ea ns, a n d th e societ ie s of our sh ri n k in g p lan e t. We re ly heavily on grap hics to ex p lain a n d p er suad e . Cartoons have becom e a very sophisticated m ean s of distilling an d reflecti ng our c ultur e. Bu t th e most sig n ifica nt re volutio n is the sh ift of visual com m u n ica tio n from th e realm of specialis ts to that of th e gen eral p u bli c. In st an t ly d eveloping film a nd v id eo recorders are just th e beg in n ing of th e visual tools that w ill becom e as com m on as the PC an d the calc u lator. The poten tia l of visu a l com m u n ica tion w ill be tested as we be gin th e tw ent y-first ce n tury. Two over riding features are the de luge of inf orma tion th a t w e must absorb and th e increasingly in te rac tive na ture of th e problems we m us t solve . As Edward Hami lto n p u t it , "Up ...to the prese nt age we h av e ab sor b ed inf ormation in a one -th ing-at-a-time , an a bs tract, lin - ear, fragm ented bu t sequential way... . Now, the term pattern ...w ill ap p ly in creasin gly in un dersta nd ing th e w orld of total -en v ir on m en ta l stim ul i in to which we are mo v ing.'? We se ek patte rn s, no t on ly to screen for sign ifica n ce of in for ma tio n , b u t also to illus tr a te p rocesses or stru ctures by w h ich our world ope ra tes. Th e em ergin g tech n ology for collecting, storing, and d isp layi ng d ifferen t m od els of reality h old s excit ing p rom ise. Co mpu ter-co ns truc te d sa tellite m aps, video ga mes, com p ut er gr aphics, and th e mi n iaturiza tion of com p u ting and re cording eq u ipmen t will open up a n ew e ra in v isual com m un ication . Th e full use of this new capab ility w ill be directly rel ated to the d evelop ment of our ow n vis ual think in g. "Com p u te rs ca n no t see or drea m , nor can they cr ea te : comp u ters are la n guage -bo u n d . Sim ilarly; thinkers w h o ca nnot escape the st ruc ture of la n guage , w ho are u naw a re tha t th in k ing ca n occur in ways havin g littl e to do w ith la nguage, a re often ut i lizing on ly a sma ll part of their bra in tha t is indeed like a comp ut er." Th is observation by Robert McK im p oints out the critic al issue of man-machi ne in ter ac tion . T he n ew equ ip m e n t is of no va lue in itself; it is on ly as good as our im agina tion can make it. If we are to rea lize the potential of visual technology , we must lea rn to th in k visua lly. Visua l Comm unication Thro ugh Time 5 Figure 1-18 Conceptual sketches. VISUALTHINKING The study of visual thin king has developed in maj or pa rt fr om the st udy of cr ea tivity wi thin the field of p sycho logy. Th e w ork of Rudolp h Arn h eim in th e psychology of art has been particularly signi fica nt . In his book , Visual Think ing, he laid a basic fram ew ork fo r r esearch by dis solv ing the artificial barrier bet w een th in king an d the ac tion of the se nses. "By cogn itive , I mean all m enta l op erations invo lve d in re ce ivin g, sto ri n g, an d processing of in for m ation: se n sory p erce ption , m em ory, th in king , learn in g.'" T his w as a n ew w ay of und erstand ing p er cep tion , namely, an int egration of mi nd and sen ses ; th e focu s of th e study of creativity sh ifts fr om the mi nd or th e senses to the in terac tion of bo th. Vis ual th in kin g is th erefore a form of th inking that uses the products of vision -seeing, im agining, an d drawi ng. Wi thi n th e context of de sign ing, th e focu s of this book is on th e third p rod uct of vision, d raw ings or ske tches. When th in k ing becom es ex ternalized in th e form of a sketched im age , it can be sa id to have become grap hic. There ar e stro ng indications that thin kin g in any fie ld is greatly enha nced by th e us e of more than on e sense, as in doing w hile seeing. Although this book 's foc u s is on arch itectu ra l design, it is my hope tha t other readers w ill find the exp lanation s and exa mples usef ul. T he long history of a rc hitec tura l design has p rod uced a grea t w ealt h of graphic tech niqu es and imagery in response to hi gh ly complex, com prehen sive, quantita tive-qual itative prob lems. Tod ay, arc hi te ct ura l desi gn attem pts to deal w ith our total man -made environ m ent , a prob lem that is p ers onal and pressing for everyone . The graphic thinking tools used by archi tec ts to solve p rob lem s of intera ction, conflict, efficie ncy, and aesthetic s in build ings have now become im portant to all part s of society w ith its own in cr easingly complex problem s. 6 Introduction I f ~.- ;// . r . f ,;:;:, Ii,,"· /"'''":k '~ 'f '< , ,, L, . -. /k,:~, ~'h!".. J..{J. .. .._. , J ./ '. ;;." f '" ~- ~ . c \ '-"0 t'n~"," "lY.<r:;;c :11< ' ' . ( _ \ ;' ' - I -...... " . .' l' oIO" j ) .100;: r~.r ~~'~ ~f. iF_~. i'J . ". .,•, 1/, . i. . , 'if'; ' '.,, -- - -' l. .:J., ~ .. '\'I ..< '1 . rt' ,.:,.... ( "... i . .~ .-.. . , -,' ''''';-- . ~ :' l· -~«>~'~;1i.~::i··: ·;' ::::c,," ...; .- G ._ . . I \ J oIl.: '\ { ! \; '; Jt,~~I' y .] '- ." ., -I. ,, ~ , . ' " ": ~. !'t .i \I t\ ,,·. . ~•. f :'l'...".f' \' c..~t". ~. t~ ! 1 Figure 1-19 Conceptual sketches. J ~ ~ Figure 1-20 Conceptual sketches using digital media. Visual Thinking I~ \ Figure 1-21 Graphic thin king process. GRAPHIC THINKING AS A COMMUNICATION PROCESS The proc ess of graphic th inking ca n be seen as a con versa tion wi th ourse lves in w hich we comm unicate w ith sketches. Th e com mun ication p ro cess involves th e sketched image on th e paper, th e eye, the brain, an d the hand. How can this ap parently closed ne t w ork gen erate ideas th at ar e not already in the br ai n? Part of the answer lies in th e def inition of an ide a . Th e so-called new id eas are really a new way of look ing at and com bi ning old ide as. All ide as can be said to be co n n ected; the t h in king p rocess re shuffles ideas, focu ses on pa rts, and re com bines th em . In th e d iagra m of th e graph ic-th in ki ng p rocess , all four pa rts-eye, brain , hand , a nd ske tch - ha ve the capa bility to add, subtract, or mo dify the information tha t is being passed th rou gh th e com m unica tion loop . The eye, assisted by pe rc ep tion, can select a foca l p oint and screen ou t oth er in form at ion . We can re ad ily accep t th at the brain ca n add in formation . Bu t th e oth er two parts, han d and sketch , are also important to th e p roce ss. A differ en ce oft en exists betw een w hat we in tend to draw and w ha t act uall y is draw n . Draw ing ability, m aterials, and our m ood ca n all be sources of change. And yes , even the image on pa p er is su bjec t to change. Differences in ligh t in tensity and angle, the size and d istance of th e image from the eye, reflect ivity of pap er, an d transp are n cy of m edia all op en up new possibilities. The potential of graphic thinking lies in the con tin uou s cycling of inform ati on- laden im ages from pa pe r to eye to brain to hand and back to the pap er. Th eoreticall y, t he m ore often the informa tio n is pas sed aroun d the loop , th e m ore oppor tun ities for change. In th e sequen ce of im ages opp osite, for exam ple, I started with a sketc h of car toon-l ike bu bble s to 8 Introduction rep re sent spaces in a hou se tha t is ye t to be designed. Dep end ing on my exp erience, int er est s, and what I am tr yin g to do , I w ill see ce rt ain th ings in the sketch an d ign or e oth ers . T he resulting perce pt u al im age seg r ega tes sp ec ial-u se sp aces, th e livi n g roo m an d kitchen , fr om several other mo re pr iva te or support spaces. Next, I form a m ental im age to further organ ize th e spaces and give th em or ien ta tion bas ed on what I already kn ow about th e site or a south ern exp osur e for th e living room and ki tchen. Wh en this m en ta l im age is tr a nsferred to pap er once mo re , it goe s th rough yet another ch ange in which the special sp aces begi n to ta ke on distinctive forms. T his is, of cours e, an overs im p lification of th e proce ss. Grap hic thi nkin g, like visu al com mu ni catio n w ith th e rea l world, is a con ti n uous process. In for m ation is sim ultan eously dar ting a ll over th e ne tw ork. W hen graphic th inkin g is mo st active , it is similar to wa tching a fantastic array of firew orks and loo king for the one yo u rea lly enjoy. Not on ly is it pro d uctive, it is fun . In Arnh eim 's w ords, "Far from b ei n g a passive mech an is m of regis trati on li ke the p ho togr ap hi c cam era , our vis ua l appa ra tu s co pes w ith th e in coming im ages in ac tive str uggle;" Visu al thin kin g an d visual per ception cannot be se parated from ot her types of th inking or percept ion . Ver bal thinking, for example, adds mo re to the idea of a ki tchen or livin g roo m w ith su ch q ua lifiers as brigh t, ope n , or co m fort able . Obvio u sly, grap h ic thin king is n ot all yo u need to k now in or der to solve p ro ble m s or thi n k crea tivel y, bu t it ca n be a ba sic tool. Grap hic thinking ca n op en up chan nels of com m uni ca tion w ith ou rse lve s and th ose p eople w ith w hom we work. The sketches generated are im po r tan t because they sh ow ho w we are th inking about a problem, not ju st w ha t we th ink abo ut it. I Figure 1-23 Dialogue. Grap h ic th in king takes advantage of the po w er of v isual percep tion by making vis ual images exte rn al a nd exp licit. By p u tti ng th em on paper, we give vis ua l images objectivity outs id e our brain , an existen ce of th ei r ow n over tim e. As Ro b er t M cKim p oi n ts out , gra phic th in king, as externalized th inkin g: has several advantages over internalized thought. First, direct sensory involvement wi th materials pro vides sen sory nourishment-litera lly 'food for thought.' Second, thin k ing by manipulating an actual structure permits serendipity-the hap py accident, the unexpected discovery . Third, thinking in the direct context of sight, touch, an d mo tion engenders a sense of im mediacy, actuality, and action. Finally, the ex terna lized thoug ht structure provides an object for critical contemplation as well as a visible form tha t can be shared with a colleague." To the person w ho m ust reg u larly se ek n ew solu tion s to problems, who must th ink creatively, the se q ua lities of im med ia cy, stimu la tio n, acci de n t , a nd con templa tion are very importa nt. To th ese q ualities I would add one more sp ecia l att r ib ute of graph ic th in k in g, sim u lta neity. Ske tc hes a llow u s to see 'a grea t amoun t of informa tion at the same time, expos ing re lationsh ips and descr ibing a wid e range of su b tleties. Ske tch es a re direct an d represen ta tive. According to Arn he irn, "Th e power of visual la nguage lies in its sp ont aneou s ev idence, its almost ch ild like simpli ci ty.. .. Da r kn ess means d a r kn es s, thin gs tha t be long togeth er are shown toget h er, and what is great an d h igh app ear s in large size and in a high loca tion. "7 Figure 1-22 Evolution of images. Gra phic Thinking As a Com m unication Process 9 , '\ ','-1 .\ } ' -Y I .!'--, ~ ~ :;..~ ~ ~ .,. ,. i\ J~ Figure 1-24 By David Stiegletz. Development sketches on back of a placemat, Siegler Residence. Figure 1-25 Front of placemat , Hotel Mercur, Copenhagen. 10 In troduction EFFECTIVE COMMUNICATION A st a nd ard story th at m any archit ects del ight in tell in g de scribes h ow the m ost ba sic co nc ept fo r a multim illion -doll ar project was first scribbled on the ba ck of a restauran t na p kin . I have wo nd er ed w hy both th e telle r and th e listener alw ays se em to derive a m use me nt from s uc h a sto ry. Perhaps the story restores confidence in the strength of the ind ividual de signe r, or m ay be it is the incongruity that de cision s on suc h im por ta nt matters ar e being made in suc h a re laxed , cas ua l m ann er. Viewing th is story in the con text of gr aphic thinking, it is not at all sur prising th at in spired , inven tiv e thi n kin g sho ul d ta ke place at a resta ura nt tabl e. Not on ly are th e eyes, m inds, and han ds of at leas t tw o person s interacting with th e im ages on th e napk in , but als o they ar e further stim ulated by con versat ion . Besi des , these pe rso ns a re separa ted fr om th eir day-to-day wo rk prob lems ; th ey are rel axing in a pleasant at m osphere, and with th e co nsu mptio n of good food , th eir level of anxiety is significan tly recfuced. They ar e op en , ready, prepared for d iscovery ; ind eed , it would be surprising onl y if the most cr eative ideas w ere n ot born in this setting. To be effective commun ica tors, arc hitec ts m ust: 1. Un d ers ta nd the bas ic elem e nt s of co mmun ica tion-th e com m unicator, th e receiver or aud ience , the m ed ium , and the context-e-and their ro le in effect iven ess. 2. Develop a gra p hic language fr om w h ich to dr aw the m ost effective sketch es for specifi c com m uni cati on tasks. 1 . Never take for gra nte d th e process of comm un ica tion and be w illing to tak e the time to examin e their effe ctiveness. Basic co m m unica tion th eo ry stresses th e com m u nication loop betw een the com munica to r or sender and the receiver in order to att ain maximum effec tiveness. Response fr om th e audienc e is essential to a speaker wh o wants to get his m es sa ge across. The inform ation com ing from the receiver is as im porta nt as what th e sender, th e archit ect , transmits. And so we m ust p ay very clo se atte n tio n to th ose p ers ons with whom we h op e to comm un ica te . The bes t app ro ac h is to try to p la ce one se lf in th eir shoes . What ar e th ey expecting? Wha t are th eir co nce rns? Equ ally important , w e sho uld be awa re of our m ot i vations and conce rns. Do w e h ave an unconscious or hi dden agenda? S ~N 17E:e. ~e lv£R ArGhrtt.e..t c /il'nt A ~ d l e Y\c.e Ol'$ I ~"'(.Y' CONl E-XT ObJe-d'lV e?1 Lo CCtt IOl'\, flo'V lI'DI)/Io' t n0 11Ml / Clrcuyy,.<;{o.I1 C1'S Figure 1-26 The st ruct ure of comm unications. As furth er chap ters r ev iew th e m any w ay s gr aphi c thin ki ng is us ed in the practice of arch itec ture, it is critical to remember that individ uals ca nnot really be cut off from the ir environm ent or th eir soci et y. The grap hic thinking of on e person thrives in the presence of goo d com pa ny and a su pportive atmos phere. See k both enthusias tically. Altho ugh th e m edium with w hich this book dea ls is principally fre ehand sketches, th e basic me thods are ap pli cable to many graphic m ed ia. But each specific m ed ium has so m e u niq ue characte ris tics th at have sp ecia l effec ts on co m m un ication. Expe rim enta tion wi th differ ent media is th e fast est route to using them eff ect ively. Although there are books on th e us e of th ese m ed ia, th ere is no su bstitute for practi ce, becau se w e all have different n eeds and abiliti es. The context for com m u n icatio n includes su ch th ings as location , time, duration , weather, and type of space, w ha t took place be fore the com mu nic ation, w hat will ta ke place after. We may be able to con trol some of the se context variables, but we ca nnot afford to igno re th em . E ffective Com m unica tion 11 I t 0:.;::,.() i: ~o Q ,.:;. ~ ~ st- > ..'. ~ 1.'1 1 .. j ;~ jii!11 o o o Figure 1-27 Gym, St. Mary's College, C. F. Murphy Associates, architects . Figure 1-28 Wall sectio n, Headquarters Building, Smith, Hinchman & Grylls Associates, Inc. THE ROLE OF GRAPHICTHINKING IN ARCHITECTURE their p ur pose is to exp lain to other pe opl e the prod u ct s of o ur th in kin g, the co n cl us io n s. Tra in in g in ar ch itectu ral sch ool s h as been primarily gear ed tow ar d the at ta in ment of finished presen tation skills, whil e in architectural offi ces, th e emphasis has been on turning out working drawings that clearly pr es ent the necessary di rectives for the contractors. To realize the pot ential of gra phic th in king in ar chi tecture, w e m ust unders tand to day 's prevailing atti tu de s on th e design process and the use of d raw ings in that pro cess. In th e ea rly 1960s, A. S. Levens w as ab le to write w ith conf id ence tha t: One source of confusion in thi nkin g ab out design is the tendency to identify design wi th one of its lan guages, drawing. T his fallacy is sim ilar to th e confu sion w hich would result if musical composition were to be identi fied w ith the w riting of not es on a sta ff of five lines. Design, lik e m usical composition, is done essentially in the m ind an d the making of drawings or wri ting of no tes is a recording process. 8 Today, w e hav e broade r conc ep ts of h ow an d wher e design takes place, bu t drawings are st ill nor ma lly th ought of as sim ply representations of ideas; 12 Introduction In response to Levens' ana logy, graphic th in king treats drawings more like a piano than a score sheet. Like com position, desig n is poss ib le witho ut an instrum en t to provid e feedback, bu t for m ost des ign ers this is not very produ ct ive. Design thi nking and design comm u nica ti on sh ould be interactive; t his implies n ew roles for graph ics. As w e anticipate th e p oten tial of comp uters and other evol vi ng comm uni cation te ch nol ogies , the con cept of feedbac k wi ll be key to effective use of media . • I NDlVl DUAL IEAM Figure 1-29 ORGANIZATION OF THE BOOK bu ild ing could get designing started. Distortion of an eleva tion might re veal a new approach to de tailing. Rever sal of a process diagram m ight suggest a mo d ifi ca tio n of the bu ilding program. The first m ajor sec tion of th e book is devo ted to the basic grap hic th inking ski lls of repre sen tation and con ception . Th e section incl udes four chapters dealing with drawi ng, the use of conventions, abstraction, and expression . My aim is to pro mo te an awareness of the rich variety of graph ic tools availab le for adding pro ductivi ty and enjoy me n t to th in king activities. Th e third section of the book considers grap hic th inking as communi cat ion in three des ign cont exts: individual, tea m, and public . The em p hasis is on better communication so that ideas can be sha red. Th e se cond sec tio n of th e boo k addresses the applicat ion of grap hic thin ki ng to de sign processes. Its four chapters discuss analysis, ex plora tion, discov ery, and verificat ion . Although there are some obvious applicat ions of thes e use s to a n u m ber of design pr ocess m odels, I have purposely avo ided promoting a spec ific design process. O ne of the problems wi th design p roce ss models is th eir accept ance in too sim plistic a way; types of th ink ing or behavior are cate gor ized, and the int ermeshi ng of processe s and ide as is ignored . Instead of cat egories, we ne ed flex ibility. Ma nip u lat ion of gra p hic images, for examp le, might be used at ma ny stages of de signi ng . I still wo uld not attemp t to guess w here it wo uld be ha ndy for a spe cific p roj ect . Man ip ulati on of the ste reotyp es for a Th is boo k is a coll ection of im age s, id eas, and de vices that I hop e a re he lp fu l a nd enjoyable. The approach is eclectic ra ther than dis cr imi nating, inclu sive no t excl usive, expectan t n ot co n clu sive. T he intent is not simpl y to describ e examples bu t to con vey th e excitem en t of grap hic th ink in g and even m ake it contagi ou s. We all have sp ecial , uni qu e ca p acities for th inkin g, w hich , if un locked , co u ld make grea t contributions to th e solu tion of problems we face. Arn heim emphas izes tha t "Every gre a t art ist gives bi rth to a ne w un iverse, in w hi ch the fam iliar things look th e w ay th ey have n ever before looked to anyone. " 9 Th is book is writ ten in anticipati on of a tim e when many of us w ill be ab le to give birth to our own uni verses. O rganiza tion of the B ook 13 BASIC SKILLS • 2 Drawing hiS chapte r's focus is on th e ba sic represen ta tion skills help ful to graphic thinking m eth ods as prese n te d in th e rem ainde r of thi s book . De ve loping freeha nd draw ing skills is n eces sary to th e att a in m en t of graphic thinking an d per ceptual skills. Some might say, "I really admir e good draw ings and those designers wh o have a qui ck hand , but 1 hav e accepted th e fact tha t 1 w ill never be th at good ." Bun k! It ju st is not SO l Anyone can learn to d raw we ll. If you don 't believe m e, ta ke th e time to tal k to people w ho draw very wel l. You w ill find that their fir st drawi ngs w ere ten tative . Th ey probably took every oppo rtunity to draw. With tim e and hard w ork , th ey gr ad ua lly im p roved and n ever regretted th e eff ort th ey made. T The re are tw o impo rtant co ndi ti on s to keep in m ind wh en trying to develop any skill : 1 . Skill comes w ith re petition. 2. The surest w ay to p rac ti ce an y s kill is to enjo y w hat you ar e doing. Because of th e he av y em phas is on ra tionalization in formal ed uca tio n, many people mis tak enly th ink that th ey can master a ski ll, suc h as drawing, sim ply by understanding concepts. Con cepts ar e helpful. but pr actice is esse ntia l. The orchestra conduc tor Artie Shaw on ce explai ned w hy he refu sed all requ ests by parents to audition the ir childr en. He felt that th e wo rst thing you can do to a talented child is to tell him he has talent. Th e greats in the m us ic bu siness, rega rdless of na tu ral talent, became successful through hard work an d a com m it m ent to their cr aft. They believed in themselv es but knew the y would have to stru ggle to prove th emselves to ot hers. The focus of energy, sense of comp etition , and year s of hard work are essential to becom ing a fine m usicran . The kn owled ge t ha t d raw ing a nd t hin king are im p ort a n t to ar chitecture is not sufficien t. Nat ura l draw in g talent is no t enoug h . To sus ta in th e n eces sary lifeti m e effort of learn ing and p erfecting gra p hic th in kin g, w e nee d to find p leasure in drawing an d think in g. We must be challen ged to do it be tter than those arc hitec ts w e ad m ire do. Morse Payne of Th e Arch itec ts Collaborat ive once noted th e infl uence of Ralp h Raps in on many talented designers: "To w at ch Ralph kn ock out one of his beaut ifu l per sp ectives in fifte en min utes w as tru ly ins piring. It set a goal for us that was very challenging." 1 For tunately, t here is still a lot of respect wit hin th e architec tura l profession for high-quali ty d raw ing. Th e person who ca n expres s hims elf b ot h graphicall y a nd verba lly on an impromptu basis is highly ' valued . W hen hiri ng, off ices oft en loo k for a bi li ty to commun icate ove r ability to be origina l. They know that your ability to develop ideas w ith th em is muc h m or e important in the long run than the idea tha t yo u in itially bri ng to them. It is possi ble to be a n architec t w ithout having w ell-developed grap hic thi nking skills. A barber or a bartender ca n surely cut hair or serve d rinks withou t being able to carry on a conversation . But th e job is a lot ea sier if you enjoy tal king w ith people, an d you will prob ably do more business. 1 believe that grap hic thinking can m ak e design m or e enjoyable and more eff ective. Four types of basic ski lls sup po rt grap hic th in k ing: observa tion , pe rc ep tion , d iscr im ina tion, and imagin ation . Although these are considered to be pr i marily th in king sk ills , in this ch apter 1 have tr ied to show how gr aph ic mean s may be used to pro mo te th ese sk ills an d att ain a funda m ental inte gra tion of gra p hics a nd th in ki ng . The se q uen ce in w h ich the skills are add ressed reflects my ass umption th at each thi nking skill sup ports those th a t foll ow. 17 • 2 Drawing his cha p ter' s focus is on the basic represe nta tion skills helpful to gra p h ic th in king m etho ds as p rese n ted in th e rema inder of th is bo ok . Develop ing free hand d raw ing skills is ne ces sary to th e atta inmen t of graphi c think ing and p er cep tual skills. Some m igh t say, "I really adm ire goo d d ra w ings a nd th ose desi gn er s wh o have a qui ck han d, bu t I have acce pt ed the fact th at I wi ll ne ver be th at good ." Bu n k! It jus t is not so! Anyone can learn to d raw well . If you don 't believe m e, take the time to ta lk to pe op le w ho dr aw very w ell. You w ill find that th eir first draw ings w ere ten ta tive . They p roba bly took every oppo rtu ni ty to draw. W ith time and hard wo r k, th ey gradually imp roved and never re grette d the effort th ey mad e. T T h er e a re tw o im por tan t con dition s to keep in mi nd when trying to develop any sk ill: 1. Skill co mes w it h rep etition . 2. Th e surest w ay to prac tice any s kil . is to en joy what you are d oi ng. Beca use of th e heavy em p has is on rationa lizati on in form al edu cati on, m any peop le mi staken ly think th at th ey ca n ma ster a skill , such as draw ing, simply by understandi ng co nc ep ts. Concepts are helpful, but practice is esse ntial. The orchestra conductor Artie Shaw on ce explained why he refused all requests by parents to au dit ion th eir child ren. He felt that th e wo rst thing you can do to a talented child is to tell him he has talent. Th e grea ts in the m usic bu siness, regardless of na tural talent , became successful th ro ugh hard work and a com m it m en t to their craft. They believed in themselves but knew the y would have to struggle to prove th em selves to oth ers. Th e focus of en ergy, se nse of competiti on, an d years of hard work are essential to becom ing a fine musician. Th e know ledge th at d raw ing and t hi nk ing are imp or ta n t to a rchi tect ure is not sufficien t. Nat ura l d rawing talen t is not enou gh . To susta in the neces sary lifeti m e effort of learning and perfectin g grap hic th inking, w e n eed to find p leasure in draw ing and thin ki ng . We must be ch all enged to do it bett er than those arch itects w e admire do . Morse Payne of The Architects Colla bo rat ive once noted the in fluence of Ralph Rapsin on m any tal en ted designers: "To w atch Ralp h knoc k out one of his bea u tiful perspec tives in fifteen minutes w as tr uly inspiring . It set a goal for us that was ver y ch allenging.": For tu nate ly, th ere is st ill a lot of resp ect w ithin th e architectura l profession for high-q ua lity d raw ing. T he pe rso n who ca n ex press h ims elf both gra ph ically and verba lly on an im p ro mp tu basis is hig hly · valued . W hen hir ing, off ice s oft en loo k for abi lity to com m u n ica te ove r ab ility to be original. The y know that your a bility to develop ideas w ith th em is mu ch m ore im por tan t in th e long run th an th e idea that you initially b ring to th em . It is possible to be a n arc hitect w itho u t hav ing we ll-developed graphic th inkin g sk ills. A barber or a bartender can su rely cut hair or serve drin ks wi tho ut being a ble to car ry on a conversation . Bu t th e job is a lot eas ier if you enjoy talking wit h people, and you w ill pr ob ably do more b usines s. I be lieve that grap hic thin kin g can ma ke d esign m ore en joya ble and mo re effe ct ive . Four ty pes of basic s kills support graphic th ink ing: obs ervation, p ercep tion , d iscrim ina tio n , and im agin ation. Alt hough th ese are considered to be p ri marily th inking skills, in this chap ter I have tried to sho w how grap h ic me ans may be used to promote th ese sk ills and attain a fund amental int egrat ion of graphics a nd th inki ng. T he se q uence in whic h the sk ills a re addressed reflec ts my ass u mption tha t each thi n king skill supports th ose that follow . 17 , 1.11~~ \;:J,,~~ ' t \? I ~ ~:;~~ ', " i4"-~ tl ) ;Y J f" " ~If":/ ' ,e ~ II ' ~ ':) :,. ;f1 \-.L.~ "~~~ ~~ ~ L:f,~s ~ .~ -r =: c ' <, .@J / ~' THE SKETCH NOTEBOOK Frederick Perls hel d that, "People who look at thin gs withou t see ing th em w ill exp er ience the same defi cien cy when call ing up me ntal pi ctures, while those who .. .loo k at thi ngs sq ua rel y and wi th recognition w ill have an eq u ally .a ler t in ternal ey e. " 2 Visual im agery is cr itica l to the creati ve design er ; he must rely on a very rich collection of visual memori es . The rich ne ss of these memories depen ds on a w ell-deve l oped and act ive visu al perception . The sk etch note boo k is an excellen t way of coll ecting visua l im ages and sha rpe n ing percep tio n , for it promotes see ing rather th an just lookin g. Arc hitects who have gotte n int o th e sketch not ebook ha bi t q u ick ly discover its us efu lne ss. All I can say is to try it; you'll like it. A sketch notebook should be sm all and portable, able to fit in to a pocket so it can be carr ied an ywhere. It sh ou ld ha ve a d u ra ble bind ing and cove rs so it w on 't com e ap art. Car ry it w ith you at all times and leave it next to your be d at nigh t (some of the best id eas com e to pe op le ju st b efo r e going to sleep or ri ght up on aw ak ening). As the nam e implies, it is a book for notes as w ell as for sketches and for remind ers, r ecipes, or anythi n g else you can think about. Com bin ing ver ba l an d grap hi c not es h elps unite verbal and visual thin king. D rawing V :>\" t ,,~ , / '0 -:\: ' ,) , ",,--- ~1:t ;> Figure 2-3 By Lawrence Halprin. r'~.::. c'; / h'? _ r rN N ( ~ 1k~}Ir~ ~/".u .1 """, ' &C 6 - ,(,"',) ~~~ P'1-~ ~ · ~'i· l ,I 1: Figure 2-4 By Karl Brown. 18 , -, - ' ,. ' n'l';' _ ~G Figure 2-2 By Lisa Ko lber. .E(f " Figure 2-5 By Karl Mang . Fig ure 2-6 By Ronald Margolis. Old Mai n Building, Wayne University. : -_.- -----.-__.-y / Figure 2-7 By Patrick D. Nall. Th e Sketch N otebook 19 Figure 2-8 Spanish Steps, Rome. OBSE RVATION The thousands of students who pass through archi tectu ral schoo ls are us ua lly to ld th at they shou ld learn to sk et ch fr eeha nd and , to a cer tain degr ee, how . Rarely are they told w hat they sh ou ld ske tch or w hy. Draw ing cu bes and othe r still-life exercises ar e an att em p t to teach ske tching d ivorced from th in k ing. Mo st st uden ts fin d it bori ng, and it drive s some away from sketchi ng for the rest of th ei r lives. I pre fer to sta rt students with th e sket ching of exis tin g buildi ngs beca use : 1. The y ar e drawing subjects in wh ich th ey have a basic in terest and are re ady to dis cuss. 2. T he eye an d m in d as well as the hand ar e involved ; percep tion becomes fine-tuned , and we begin to sor t out our vis ual experiences. 3. On e of th e best ways to learn about archi tectural design is to look close ly at existin g buildi ngs and spaces. 20 D rawing The clearest way to dem on str ate the valu e of fr ee hand sketchi ng for develop in g grap hic thinking skills is to compa re sketchi ng wi th ph otogra phy. Although a cam era is oft en a us eful or expedient too l, it lac ks many of the attributes of ske tche s. SKetches have the ab ility to rev eal our perc ept ion , th erefore giving more im po rtan ce to certain pa rts, wh ereas a photo shows everything wi th equal em phas is. In the sketch of the Spanish Steps in Rom e , the focu s is on the ch urc h , ell ipse, and step s as orga n izin g elem en ts for th e e ntire ext erior space. Th e sign ifican t im pact of the flowers in th e p hoto ha s been elim ina ted in the sketch . The abstra ction can be pushed furt her until there is on ly a pa ttern of light and dark, or we ca n fo cus on ly on certain det a ils, suc h as lamp posts or window s. This on e scen e alo ne is a d ict ion ary of urban design . But you do not have to wa it until you get to Rome to get s tarted ; th ere ar e lesso ns a ll around us. Becom e a prospec tor of ar chitect ural design ; build your ow n collec tion of good ideas whil e you learn to sket ch . It is a lot of fun. Figure 2-9 Spanish . Steps r Rorne. Figure 2-10 Wrn ' dow Det ail. Figure 2-9a Spanish Steps, R_orne. : Fig ure 2-11 Street lamp detai l. Observation 21 I(YM~ ?trl-{4 lJY~ {! IJ Figure 2-12a House drawing structure. Figure 2-12b Tones. BUILDING A SKETCH corr ect p rop or tion s it makes n o d iffere nce w hat is draw n from t he n on; th e sketch w ill alw ays look w rong. So take your time; look ca refully at th e sub ject ; continually compar e your sketch wi th w hat you see. Now add the ton es. The se re presen t the sp ace defini ng elemen ts of ligh t, shadow, and color. Again , look carefully at the subject. Where are th e lightest ton es; where are th e da rkest? The sket ch is becoming m ore re a listic. Th e d etail s are ad ded las t . At thi s poin t everyth ing is in its place, a nd you can really concen trat e on th e details one at a tim e. It is no lon ger ove rw helming; you can re lax and enjoy it. In his book D rawing Bu ildings, Richard Dow ner pre sen ted the most effecti ve app roach to fr eeh an d sketc hing I have ever com e across . "Th e fi rst an d m ost importan t th ing ab ou t dra w ing buildi ngs is to realize that what you intend to draw should inter est you as a su bject .'? Nex t , it is im por tan t to select a va ntage point th at be st descri bes your subject. Now you ar e r eady to bu ild the sketch by a three-ste p process of sketching basic structure, tones, an d th en det ails. The basic st ructure sketch is most important. If the p arts ar e not show n in their proper p lace and A Fi gure 2-13a Bowl drawing structure. 22 D rawing Figure 2-13b Tones. Figure 2-13c Finished bowl drawing. Figure 2-12c Text ure and color. Figure 2-12d Finished house drawing . Building a Sk etch 23 IZJ D L7k1 \ 1 Figure 2-17 Structure Sketch Figure 2-14 Fig ure 2-15 Fi gure 2-16 24 Dra wing T he most im port an t part of a sketch , the basic lin e draw ing, is also the mo st d ifficult skill to m as te r. It re quires a lot of practice, but I have a few suggestions th at sho uld help : 1. To help sha rp en th e se ns e of propo rtion need ed for ske tching , practi ce dr aw ing squares and th en rec tangles that are tw o or th ree times longer on one side th an on th e other. Now try to find squares in a scene yo u are ske tchi ng . (At th e beginn in g, th is co uld be don e w ith tracing pap er over a photograp h.) 2. Use a cross or a fra m e to get th e parts of th e sk etch in th eir prop er p lace, or maybe a p romi ne nt fea tur e of the scene or subjec t can act as an organizer for the ot her parts of the sketch . 3. ·Alth ough pen cil ca n certai n ly be us ed for sk etchi ng, I pref er fe lt -tip or in k pens b eca use the lines they prod uc e are simple and clear. If a line is in th e wrong place, it is qu ite ev ide n t. Because the lin e can not be eras ed , it m ust be redr aw n to get it right. This proc ess of rep et ition and checking against t he subjec t develops ski ll. Drawings th at are so light they ca n be ign ored or erased den y the design er the feed back essen tia l to his im pro vem ent. 4. To gai n mor e co nt r ol ov er line m a king, try so me sim ple exercises sim ilar to our "id le m om ent " doodl es . Th e sp irals, like tho se above , are d rawn fr om the ou ts id e toward the cen te r, both clockw ise and co unte rclockw ise . Try to m ake them as fas t as p ossib le without let tin g the lines touc h each ot her ; tr y to get th e lines close to each othe r. Stra ight hatch in g can be done in several directi ons , always striv ing for consistency. Fi gure 2- 18 Figure 2-1 9 Figure 2- 20 Tones Tones can be represen ted with differe nt den sities of hatching or com binations of cross-ha tching . The lines s ho u ld be p arallel and have eq ual spa ces between them . Always re m em ber that th e ma in purpose of the cross- ha tching is to ob tai n different levels of gray or dar kne ss . Use straight strokes as if you were pa inting the sur faces w ith a brush . Errati c or irreg ular lin es d raw att ention to th em and di stract th e e ye fr om m ore im po rtant thing s. There is no st r ict r ule for ap ply ing tones on a sket ch, bu t I ha ve some prefer enc es tha t se em to work well. Horizontal ha tch ing is used on horizontal surfaces, di ago na l hatch ing on vertical surfaces . Wh en two ve rti cal surfaces meet, the h at ching on on e is at a slig htly di ff eren t an gle from the hatching on the other surfac e. App ly tones in a three-step process: 1 . Indicate any texture that appears in th e surface, such as the vertical boards on a barn . 2. If th e textur e in d ication does not prov ide the level of darkness of th e subject , add the necessary addi tional hatching over th e entire surface. 3 . No w app ly m ore ha tch in g w here any s had ow s fall. To show gradat ions of sha dow, add a su cces sio n of hatches at different angl es. The refinement of ton es in a d raw ing is ach ieved by loo king carefully at th e su bjec t a nd by ge tt in g m or e control over t he consistency of the lines. Severa l alt ern ative techniqu es for ske tc hing in tones are illustr ated throughout th is bo ok . The one show n at t he ri ght ab ove is a ra pid me thod usin g ra n dom strokes. De sign ers usua lly de ve lop tech niq ues w ith w hi ch they feel m ost com for table. Bu ilding a Sketch 25 = == -ififf ~I ~I r ~ ')!! .~~ ../ ~u[1fj 0000 L..J l--J L.....-..> '--.J 1= ~ ~ ·,.j71iii~~~~;) ~11i/W WJ&il. ~ Figure 2-21 Fi gure 2-22 Details Detai ls a re ofte n the most in terestin g or compe lling as pe ct of buildings. T he window is an exce lle n t exam p le. T her e, the de ta ils ca n be th e result of a tr an siti on be tw een tw o m a ter ial s-brick and glass- or b etween two b u ild ing elements-wall and op e ning. The w ood w indow frame , brick arch , key stone, and w indowsi ll ma ke t hese transi tio ns po ss ib le , an d each of th ese de tai ls tells us more abou t th e b ui lding . O n a regular basis, I have students sk etch window s, doors, or other bu ild ing elemen ts so they ga in an unde rstand ing a nd appre ciat ion of the con tribution of detai ls to th e q uali ti es and func tions of the bui lding . Details tell us so m e thi ng of need s a nd ma ter ia ls as w ell as our in ge n uit y in re lating th em . Th e ske tc h of the me ta l grating around th e b ase of t h e tree exp la ins bot h the need s of the tr ee and the use of th e su rfa ce under the tree where people w alk . Figure 2-23 26 In m ost arc h it ectural sce nes, th ere a re d et a ils close to us a n d othe rs fa rth er away. We can see m or e of th e close det ail and sho u ld sho w in th e ske tc h suc h things as sc re w s or fas te ne rs or fin e joints a n d tex tur es. As d etai ls recede in th e sk et ch , few er a n d few er of the pi eces ar e sho w n , unt il on ly th e ou tline is v isib le. Drawing Figure 2-25 MO lltgomery, Alabama. Combining Observations Fi gure 2-24 Sail Francisco. Ca lifornia. Wit h practice , struc ture , ton es, a nd d etai ls ca n be effective ly combined to ca p ture th e com p le te se nse of a subject. Old er houses of d ifferent sty les ar e suit ab le su bj ects for practicin g a nd developing ob ser va tion sk ills. T he y a re usua lly readi ly access ib le and p ro v ide a varie ty o f v is u a l effect s th a t ca n sus ta in yo ur in te rest. Try vis iting favorit e houses at d iffer ent tim es of d ay in orde r to v iew the impact of di ffer ent light ing co n d itions. Walk arou n d , approa ch , a nd re tr ea t fr om th e su bj ect to captur e a va r ie ty o f appearances . Building a Sketch 27 TRACING Trac ing ex isting graph ic mat erial is anoth er w ay to bu ild sketching skills. Ma king an overlay of you r ow n drawing s w ith tr acing paper is an ob vious but und er used dev ice. Rath er th an overwork a d raw ing th at is h ead ed in t he w rong directi on, make an ov er lay sh owing th e ele men ts that need to be corrected and then, in anothe r overlay, ma ke a w hol e new ske tc h incorpor ating th e ch an ges. You w ill learn more from yo ur mi stak es, and th e fina l sketc h w ill be better an d fresher. Tracing can also be do ne by lay ing a tran s pare n t s hee t with a grid ov er a draw ing or p ho to, draw ing a larger gr id, and th en transferring the draw in g square by sq uar e. A thi rd tec hniq ue uses a slide projector a nd a sm a ll m irr or to p roject images of a conveni ent size for tracing on your d rawi ng ta ble. The large sketc h on page 3 1 w as don e in this w ay. IJ o 01 1'0 0 Figure 2-26a Orig inal sketc h. n o No m att er th e rea son you th ou gh t copy ing w as im pr op er or illega l, forget it. Ma st er dr af tsm en su ch a s Leon ardo da Vinc i cop ied oth er p eo pl e's wo r k w hen th ey were learn ing to d raw. No tracing is ever th e sa m e a s th e or igina l. You w ill pi ck out some details and simplify other parts. Tracing forces you to look closel y at th e or igina l sketc h or photo an d better un der stand the su bject. DOD Figure 2-26b Overlay sketch. ) MWJrt4~~11-¥ Figure 2-26c Final sketch. M \t?RD1<... IA~LE ~ -611~ ~?etf~ I~ I'1j kt-~td.-l - up ~~~: ~J"'T r "Z061'V-. ~w; ) ""'T' i ii i i " 'm [e-V\ :7L '' ~ lIdu,y flat~ 9 1 A.('~ j. li\ol 4~~~lA-!PtUltw$ ~kj?ru . ~~LWt>r- ~ \ '>\< J :tl~ -n-ttwl~ l?l1X _f!. ~-tvu4d crr 11 11 1 ><1 wood. ~4: ( ~( d0 ~ ~ th '\1\ l?oMt{ 'f~~) Ml~D1< 130)( Fi gure 2-27 Projection table and projection box. 28 Dra wing Fi gure 2-28a Original sketch. Figure 2-28b Enlargement of sketch. Figure 2-29 Tracing after Ray Evans. Figure 2-30 Tracing after Ray Evans. Tracing 29 ~ Fig ure 2-31 Sketc h of Athens, Ohio. (a) Figu re 2-32 Sketch of Athens, Ohio. Figure 2-33 Sketch of At hens, Oh io. 30 Drawing Figure 2-34 a (opposite), b (above) Plan, section, and perspective of garden-court restaurant, Salzburg, Austria. PERCEPTION Many a rchitects have b ecome m et hodica l abo ut sketch and note taki ng. Gordon Cullen , the British illus trator and urban d es ign consult an t, had a m ajo r influe nce on the use of ana lyti ca l sket ches. His book Townscape' is a wond erful collec tion of visua l percep t ions of th e urba n e n v iro n me n t. Th e sketc he s a re clear and com p rehe nsive , im p ress ive ev ide nce of w ha t can be dis covered wi th gra p hic thinking. Using pl ans , sect io ns , and perspectives, th e sketches go beyond th e obvio us to uncover n ew percep tio ns . Tones ar e used to iden tify m ajor orga ni zers of sp ace. (In the book , many of th ese tones are achieved m ec hani cally, b u t th ey are easily rendered in sket ches by hatch ing wi th grease pe nci l or large felt tip markers.] The verba l ca tego ri zation of urban ph e nom ena th rough shor t titles helps to fix the visual p ercep t ions in our memori es; verbal and gra phic communications are working together. And these are not complica ted sketches; th ey ar e w ithin th e poten tial of most designe rs , as show n in the ske tc hes oppo site, w hich apply Cullen 's techn iq ues to th e ana lysis of a small midweste rn town . As Joh n Gund elfinger puts it : A sk etchbook should be a personal diary of what interests you and not a collection of finished draw ings compiled to impress with weight and numb er. ..a finished on-the-spot drawin g...shouldn't be the rea son you go out, for the objective is drawing and not the drawing. I often learn more from drawings that don't work out, studying the unsuccessful attempts tc see where and why I went off ..can learn more than from a drawing where everything fell into place . The draw ings that succeed do so in some measure because of the failures I've learned from preceding it, and so certain pitfalls were unconsciously ignored while drawing. S Perception 31 rt~ ;~t~~ Figure 2-35 Waterfront, Mobile, Alabama. 11 , I ~ k ~ ~ /~~ c h~ k-.tk ~~ Ea ch subject ma y re veal new w ays of seei ng if we remain op en to its specia l ch aracteris tics. It m ay be th e red undancy of form s or a pattern of shadows; it may be an aw are ness of the sp ecial set of elemen ts an d circu ms tances th at p ro du ces a p articularly in ter estin g visual experience. A sketch of the interior of a cathedra l can uncover th e exciting p lay of scale and m at er ials. Th e ac t of dr aw ing can d rama tically heigh ten your visu al sensitivity. I ~.JIIiF Figure 2-36 Salzburg, Austria. ~? Figure 2-37 Mobile, Alabama. 32 Drawing ~. · ---~I c.,K . . , . - -- _ .., M.A.~1-€ =._~~~'S. Figure 2-38 By Todd Calson. West minster Cat hedral. Figure 2-39 Ohio Universit y Quad, Athens, Ohio. Percep tion 33 Figure 2-40 Cartoon style sketch, after Rowland Wilson. Fi gure 2-42 Afte r Saul Steinberg. o oL ::=I:>::J ()~ Figure 2-41 After Saul Steinberg. Figure 2-43 After Saul Steinberg. DISCRIMINATION Cartoons ar e a n im portan t source of sk et ch ing id eas. My favo r ite sourc es are T he N ew Yor k er a nd Pu nch m aga zin es, but th e re a re many oth e r sou rces. Cartooni st s co nvey a co nv inc ing sense of reality w ith an in c red ib le economy of m ean s. Simp le con tou r lin es suggest d et ail inform ati on w h ile con cen tra ting on ove ra ll shape s. Michael Folke s desc ribes some of the d iscip line of cartoon drawings : .. .simplicity refers to the need to ma k e the clearest possible sta teme nt.... Avoid all unnecessary de tail. 34 Drawing Ma k e th e focal point of your pictu re stand ali t . Re frai n from filling every corne r with obj ects or shading.. .. Tra in y our hand and eye to put down on paper rapidly recogniza ble situ a tions: in the fewe st possible strok es. One significant de tail is worth far more tha n an un certain clu tter of lines tha t don 't really describe any thing. M a k e dozens of sma ll pic tures.. .draw ing directly in pen a nd ink so that the pen becom es a natural drawi ng instrument and no t som ething tha t can only be used to wor]: pain fully over ca refu lly prepa red pencil lines.(, T he ca rt oon is selective or d isc rim ina ting; it he lps yo u seek out th e esse n ce of a n exper ie nce. Figure 2-44 Sketc h exte nding a view derived from t he painting, Giovanni Arnofini and Hi s Bride, by Jan Va n Eyck. Figure 2-45 Drawing from imagination. Figure 2-46 Drawing from imagination. IMAGINATION tho se pa r ts of the roo m access ibl e only th rou gh your imagina tion . 2 . Draw a se t o f objects and th e n draw w hat you believe to be the view from the backsid e. 3. Sket ch a s im p le objec t su ch as a cube w ith d is tinc tive m ar kin gs. T he n im agine that you a re cu t tin g th e objec t and m ov ing the parts. Draw the di ffe ren t new configura tions. To m ove fr om gra p h ics in su p po r t o f obse rva tio n towa rd gra phic thinking th at supports d esigning , you must deve lop a nd stre tc h imagin ati on . Her e are so me simp le exe rc ises to sta rt: 1. Find a d rawing, p hotogra p h , or painting of a ro om th at show s a part of a space. O n a large sh eet of pap e r, draw the sc ene d epic ted a nd th en ex te n d th e drawing beyo nd it s or igin al fr am e to s ho w Imagination 35 Visual-Mental Games An en te rtaining way to im p rove ha nd - eye - mind coord ination and promote an ability to visualize is to play some simple games. 1. Show a few people four or five cuto uts of sim ple shapes arranged on a pi ece of paper (above , left ). Ou t of view of the ot hers, one p ers on m oves th e cut outs while verbally desc ribing the move. The oth ers attempt to d raw th e new ar ra nge me nt from the description . Th is is repeated a few tim es to see w ho can ke ep track of the pos ition of th e shape s. Aft er m aster ing th is exercise, have the persons draw ing try to form a men ta l picture of each new arrangem ent and then try to draw only th e final arran gemen t. In a sec ond version of this gam e, an object is su bstitu ted for the cut outs, an d it is ma n ip u late d , op ened , or taken apart. 2 . Form a circl e wi th a small gr ou p. Each pers on m akes a sim pl e sket ch a nd pa sses it to hi s righ t. 36 D raw ing Everyone tr ies to copy the sketch he has received an d in turn pa sses th e copy to th e righ t. This contin ues unti l the fin al copy is passed to the creator of the ori g in al sketch . Then all sketches are ar ra nge d on a w all or table in the order they were made. This ga m e illu s trates th e distinctiven ess of individ ual visual p ercep tion (above, cen ter). 3. Doodles, usin g an arch itectural or de sign th eme, are another form of puzzle. He re, th e obj ec tive is to provide just enough clues so the subj ect is ob vious once the title is given (above, right) . There are many visual p uzzles that exer cise our visual per cept ion. Try some of those sh ow n opposite; look for more puzzles , or invent some of your ow n . In th e sketches opposite, an arbitrary diagram is given and the cha llenge is to use it as a parti for di fferent bu ild ings by seeing it as standing for a section or plan view for starters. Figure 2-50 Visual puzzles. Figure 2-51 ExpLoring design based on a parti diagram. Imagination 37 \ \ \ " ,\ ' • • \ . t \ f "-, " \ .. '\ , •~ .. v, .', ·"~ .I'" \.~~\~ . ..... ,•~" .,." '"' '<, '~ . .... ... ':, " '~\~'f, ,'", I' \ \ .,\~. ~~~.~-- ~_ " .----1 • 3 ( nventions Represent: Call up by description or portrayal or imagination, figure, place, lik eness of be fore mind or senses, serve or be meant as likeness of ..stand for, be specimen 0(, fill place 0(, be subs titu te [or: hroughout history, represen tation and design have been closely lin ked . T he ac t of d esign in g grew directly out of m a n 's desire to see w ha t could or would be ach ieved b ef ore in vesti ng too much time, energy, or money. To crea te a clay p ot meant simply working directly with your han ds until the desired resu lt was ach ieved. Bu t m a king a go ld pot required expensive materia l, m uc h preparatio n , time, and energy. A representation , a design drawing, of the gold bowl was necessary befor e s ta rting th e project. Design became an important part of arch itec tural projects simply because of th eir sca le. Represen ting th e imag ined b u ild in g perm itted n ot only a view of the final result bu t the planni ng for labor and materials to assure completion of th e projec t. Figure 3- 2 The rep rese n ta tion al capacity of sketches is lim ited. We mus t recognize tha t eve n wi th th e m ost sophisticated techniques drawings are not a full sub stitute for the ac tua l experience of a n a rch it ec tural e nv ironment. On the other hand, th e capac ity o f sketches as thinking tools extends well beyond wh at is act ually con ta in ed in the sketc hes. Draw ings, as representations, should be seen as ex tensions of th e persorus] who uses them to aid in thinking. As Ru do lf Arnheim says: The world of im ages does no t simply im prin t itse lf upon a fai thfully sensitive organ. Rathel; in looking at an object, we reach out for it. W ith an in visible finger we move through space around us, go out to distant places where things are foun d, touc h the m , catch them, scan their surfaces , trace their borders, explore their texture. It is an eminently act ive occu poti on.' I find a great variation in the deg ree to whi ch architects rely on drawings to v isua lize designs. One probable explanation for this is experience in vis ua l izing and w ith the bui lding of th ese desig ns. For examp le, when architecture students look at a p la n view of a room, they likely see just an abstract di a gram, but some experienced arc hitects ca n vis ua lize a perspective view of the same room without having to draw it. Figure 3-3 Some bas ic types of re p rese n ta tion ske tc hes, which I feel a rch itects shou ld be a ble to understand, a re di scussed in th is ch apter. I do not intend to pres e n t a comprehensive exp lanation of the construction of basic d rawing co nven tions . Th er e are already sev era l good books on th at subject. Rather, th e emphasis will be on freehand techn iq ues w ithou t th e use of tri a n gles, sca les, a n d st raigh te dges, a llowing for rapid repres entation . 39 ',"/ Figure 3-4 Site plan. Figure 3-5 Axonometric. Figure 3-6 Partial elevation. Figure 3-7 Detail section. Ther e ar e a gr ea t n umber of th ings w e can repre sen t ab out a space or a build ing and many ways to represent them. Th e sketch ed subjects can ra nge in scale from a building and its surrou nding proper ty to a window or a light sw itch . We m ight be interest ed in how it looks or h ow it works or h ow to p ut it togeth er; we m ay be se arching for clarity or charac ter. Variations in drawings ra nge from the concrete to the abs tract , an d the convention s in clude sec tion or cut, eleva tio n , persp ect iv e, axonom etric, isometric, and projec tions . Med ia , techn iq ue, an d st yle acco unt for m any of th e other variations. Ma ny of these va ria tions are cove red in lat er chap ters. Th e elementary for ms of repres enta tio n discussed at this po int are : 40 Conventions 1. Comprehensive views- To st udy d esign s as com plete sy st ems , w e must have m odels that repre se n t the whole from some view point. 2. Concrete images- Dealing wit h th e m os t direct experience. Abs traction is covere d in Cha pte r 4. 3. Perceptual focus- Trying to involve th e vi ewe r in th e expe rien ce signi fied by th e draw ing. 4. Freehand sk etches-Decision -m ak in g in de sig n should in clude the consi derati on of m an y altern a tives. Represe n ta tion of altern atives is encouraged by th e speed of freehand ske tch ing, w here as the ted iou sn ess of "constr uc ted " hard-lin e d raw ings d iscourages it. BUI LDING A PERSPECTIVE. Rdure 9 1ane l1 otrzon L U1l Figure 3-8a Setting the pict ure plane and viewpoint. Fi gure 3-8b Starting grids. Figure 3-8c Setti ng cross-grids. Figure 3-9a Settin g the pict ure plane and viewpoint, plan view. Figure 3-9b Setting one grid, plan view. Figure 3-9c Setting t he cross-grids, plan view. PERSPECTIVE Pers pect ive sket ches ha ve a n eq ual stand ing w ith plan d raw ings, the starting poi n t of m ost d esign edu cation. O ne-poin t persp ec tive is the easiest and there fore , I fee l, th e mo st usefu l of pe rsp ect ive co nvent ions. I have fou nd th e follow ing th re e-step m ethod to be mo st succe ssful : 1 . Indicate th e pictur e plane in bot h elevation a nd pl a n ; it is usuall y a w a ll or a not he r fea ture th a t d efines the far li m its of th e immed ia te space to be view ed . Loca te the p oin t from w h ich the space is to be viewed, or view point (V P.). Vertically, th is po in t is usu ally abo u t 5.5 feet from th e bottom of the pi ctur e plan e. Horizon tally, it can be p laced just a bout any w her e in the sp ace w ith the un der standin g that pa rts of the sp ace outsi d e a 50 -d egree con e of v ision in fr on t of the view er tend to be di s torted in the per sp ect ive. T he horizon ta l line d raw n th rou gh th e V P. is called th e horizon line. 2 . Establish a grid on th e floor of the space. Draw th e sq ua re grid in p la n a nd co u n t th e n umbe r of spaces the v iew er is away fr om the pi cture p lane. Then , in th e perspec tive , loca te the d iago na l va nish ing point (D .V P.) on the hori zon line at the same d is ta nce from the vie w po int. Draw floor gr id lines in the perspect ive in one d irection com ing from th e view point; d raw a diagonal lin e fro m th e diagona l vanish ing poi nt th ro ugh the bot tom corner o f t he p ic ture p lane an d across the space. W here th e d iago nal int er sec ts the floor grid lines running in th e on e direc tion, hori zo n ta l lines can be d raw n to s how the other d irection of the floo r gr id. 3 . In d icate th e str uc ture of the basic eleme nts of the sp ace. Co n tinu e th e grid on the w alls and ceiling (if a pp ropriate ). Using th e gr ids as qu ick refer ence, place vertica l plan es an d openings as we ll as signifi can t d iv isions of the pla nes. Persp ec tive 41 Figure 3-10a Definition of space. Sketching straigh t lin es freeh a nd is an im p orta n t skill to ma st er for all ty pes of gra p h ic th in ki ng, an d p rac tice ma kes perfect. Once you begin to rely on a st raighted ge, the work slows dow n. Sta rt by con cen trat ing on w h ere the line begin s an d end s ra ther th a n on th e lin e itsel f. Place a d ot a t th e begin n ing a nd a d ot w h e re th e lin e s h ou ld e n d . As yo u re pea t th is exe rcise , let th e p en drag ac ross th e p ap e r be tw ee n the tw o dot s. T his sou nd s pret ty ele men ta ry, b u t it is su rprising how ma ny peop le have n ever bot he red to lea rn ho w to sketch a straigh t lin e. W ith th e ba sic p er sp ec ti ve a nd p la n com p le ted th e values, or tones, ca n now be ad d ed . Th e actu al col or of objec ts or p la n es, s h ad e, or s ha d ow s can ca use d iffe re nces in values; ind ica ting th ese chan ging valu es sh ow s th e in te raction of ligh t w ith th e sp ace, p rovid ing spa tial defini tion . Conve nt ions for castin g s hadow s a re presen ted w hen pla n draw in gs a re di s cu ssed . For now, it is en ough to n ote tha t shadow s ar e firs t cast in p lan and the n add ed to the perspect ive, 42 Conventions using th e square gr id as a ref eren ce. Sha de appea rs on objects on the side oppos ite to the su n or othe r so urce of light w here no direct light fa lls ; shaded sur fac es a re ge ne rally lighter in tone tl;an sha dows. As in sketchi ng exis ting build ings, I prefer to use pa ra lle l ha tch lin es to show tones (see Building a Sketch in C hapte r 2). Finally, de tai ls a nd objects ca n be add ed . Peop le ar e m ost importa n t because th ey esta bli sh th e sca le of the space an d in volve th e viewe r th roug h id entifi ca tion w ith th ese sketched figur es. Sim p licity, real is tic p roporti on s, and a sense of m ovemen t a re basic to good hu m a n figures such as th ese. T he squ a re grid s help in co ordi na tin g the p lacem e n t of hum an figures and ot h er objects in p la n a nd pe rs pective . Be sure to p lace p eo pl e a nd objects w he re th ey w ou ld really be ; the p ur pose of th e ske tc h is to u nd er stand the sp ace, n ot to ca mo u flage it. Fi gure 3-11 Casti ng shadows in plan. Fig ure 3-10b Adding ton es and shadows. Figure 3-12 Practice drawing straight lines. Figure 3-13 Practice drawing people. Figure 3-10c Completing details. Perspective 43 OY1::W'\~\ r~~ ?I~ 1t>r- \-f'O< lJIl ~~\Ve - -- - - )7f'- ' <, ' q ( " Cl - ~2 / - <, :s: / / :: ---- »> ./ »> 1------ -4'l\ ~/ / ( C\ (", ..... , / / / ---- -- \ l) i? I 1" I)b ./ /' / / \ \ Figure 3-14 Modification of a one-point perspective. Figure 3-15 Organization of a modified perspective. after Lockard. QUALITATIVE REPRESENTATION spec t ive , p ara llel wit h the horizon lin e , are now sligh tly slan ted in the di rect ion of th e imaginary sec ond poi n t. To m ake th e transition fro m one -poin t per spec tive , the top and bottom lin es of the pi cture pla ne can be given a sligh t slan t an d a new plane is estab lished ; by d rawing a new d iagona l, the new diagonal va n ishin g poin t can be set. A grid ca n also be app lied to this type of perspective to help in plac ing objects in the spa ce. At this p oin t w e are not in ter es ted in th e qualities of dr aw ing expressi on , such as style or tech niq ues; this is cover ed in Ch apt er 5. By q ua lita tive rep resen ta tion , I mean the rep resenta tion of the qualities of a space. I n hi s book Design D rawing W illia m Lock ard ma kes a very co nvi ncing arg um en t for the supe riority of p ersp ectives a s rep rese nt atio na l d raw ings. "Pers p ec tive s ar e m or e qualitat ive than quan titative. The ex per ien tial qua lities of an envi ro n m en t or ob ject can be perceived d irect ly fro m a p er sp ec tive.. .Th e q ua lities of th e space/tim e/ligh t con tin uum are much better re p rese n ted and u nderstood in p er spect ive (than by othe r co nven tions). " 3 Perspective s have the adva ntage of showing the re lationsh ip of all the elem en ts of a sp ac e in a way most sim ilar to how w e w ou ld ex perie nce it whe n b u ilt. Alt hough it is tr ue that bu ildings are not expe rie nc ed only through persp ectives, it is th e best way of sho w ing a d ire ct visua l experience of a specifi c space. Lockar d 's ch apter on representation has probably the best ex p lana tio n of th e use of p ersp ec tive sketc he s for re presentat ion . Locka rd illustrat es a per spective view that is close to one-p oin t perspective ; it in volv es an imagin ary seco nd perspe ct ive po in t added at som e dis ta nc e fr om the ske tc h (see Figur e 3 15). Lin es run n in g the wi dt h o f the one -po int pe r 44 Conventions To rep res en t th e q ua lities of an im agined space, w e have to know some thing abo u t th e q ua lit ies of sp aces. Th ough th is seem s obv ious, it is of ten ignored . As architect s, w e have to look for w hat gives spaces th eir special charac ter , th e d ifferen t kinds of ligh t, color , texture, pat tern , or sha pes possibl e and how they are combin ed . Con tin ua l sket ch ing in a sketch notebook is one sur e way of learn ing a bout the q ualiti es of spaces. Wh en th is know led ge is ap p lied to th e repres en ta tive pe rs pecti ve , w e must rem em ber to con vey th e t h ree-d im e nsiona l exp erie n ce of th e sp ace onto a tw o-di m ensional surface, the pa per. To d o this, w e need to illus tra te the effect s of dep th or d ist ance upon th os e thing s th at giv e th e sp ace its q ualiti es. Wit h an increase in d epth , ligh t se ems to p ro du ce few er grad at ion s of to ne ; d et ail is less ev i d en t; text u re and co lor are less v iv id ; ou tli n es or ed ges are less sha rp . Dep th can a lso be con veyed through overlap of object or con tou r. Figure 3-16a Set up of sketch perspective based on Lockard method. Figure 3-16b Completed sketch perspective. Qualita tive Representation 45 ~ ii Figure 3-17 Para lle l project ions. PARALLEL PROJECTIONS Cur re ntly in comm on use, the axono me tric sketch is an importa nt alte rnative to th e persp ect ive, plan, and section . The axonometri c is simp ly a projection fr om a p lan or sect ion in wh ich all p a rallel lines in the space are show n as para llel; t his is in con tra st to a persp ective wh ere parallel lines are show n as exte nd ing fr om a single point. The axonom etric techniq ue is traditio nal in Chi ne se d raw ings. Instead of p lacin g the viewer at a single poin t from w hich to view the scene, it gives the view er th e feel ing of being every w here in fr ont of the sc ene. The axonom etr ic has the 46 Conventions additi on al ad va nta ge of rep res ent ing th ree -d imen sional spa ce wh ile re taining the "tr ue" d im ensions of a p lan and sec tion . T h is las t ch aracterist ic makes a n axo n ome tric easy to draw be caus e all th ree dimens ions are show n at the sam e scale. Axo no metric p rojections forward or bac kward fr om p lan s or sections are convent ion ally ma de a t an gles of 30, 45, or 60 degrees, bu t in a sketch th e exact angle is no t imp ort an t as lon g as the proje cted lines rem ain p arallel. 1 r VERTICAL SECTION A vertical cut through a space is ca lled a sec tion. What was said abou t the plan sketc h also ap plies to the section sketch, excep t for the cas ting of shadow s. With sec tions, we can show depth of space by apply ing the one -poin t perspective co nventions explai ned earlier. Imagine you are looking at a cut m odel of the space; the point at which you loo k d irectly into the mode l is where the viewpoi n t (V. P.) wi ll be p laced . T he viewp oint is used to projec t th e pe rspect ive be hind the section. Figure 3-18 Section. Human figures are als o imp or ta n t for sec tion ske tches. Many designers ske tch in view lines for the people; this seems to make it easier to imagine being in the space a nd gives some se nse o f w hat can be seen from a particular posit ion in the space. Shadows can be ind icated to see the effect of sunlight within the space. Vertical Section 47 ~ ~ , ~.. Figure 3-19 Plan. PLAN SECTION Abs tract pl an d iagr ams suc h as th e one ab ove have m an y uses in the ea rly concep tu a l s tages of design . Th is is covered in d epth in Ch apt er 4 . However, m any architecture s t ud~nt s make th e m istake of try ing to use th ese plan d iagram s to rep resent th e m ore concrete decisions a bout th e format ion of space. Plan sketc hes of d esign ed sp aces mus t sho w w ha t is enclosed and wh at is no t, including scale, height, pat tern , and d etai l. A p lan is basicall y a horizontal cut or section th ro ugh th e spa ce. Thin gs th at are cut , su ch as w alls or columns , are ou tl ined in a heavy lin e wei gh t. T hings that can be see n bel ow th e pl ace w here the p lan w as cut are ind icated in a lighter line weight. Things such as a skyligh t th at ca n not be see n becau se they are abo ve the lev el of the cut ca n be show n w ith a heavy dashed lin e if d esired. The first stage of a r ep resent a tiv e pla n is the heavy ou tlini ng of wa lls clearl y show ing ope n ings. In th e secon d s tage, d oo rs, win d ow s, fu rn iture, an d other d eta ils a re ad d ed . Th e thi rd- sta ge ske tc h 48 Conventions inc lu des sha d ow s to sho w th e re lative he igh ts of p la ne s and objects. Th e p re vail ing co n ven tion for sha do ws casts th em on a 45-de gee angle, up and to the right. Th e sha dow s need onl y be as long as neces sary to clearly sho w th e relat ive heig h ts of the fu rn i tur e, wall s, etc. Finally, co lor, texture, or pattern can be ad d ed to exp la in fur ther the ch a racte r o f th e space. OTHER REPRESENTATIONS A variety of sk etche s ba sed on th e con ven tions of persp ective , pl a n , section , and axono me tric are shown on the next page. By m ean s of ske tches, we can cu t open, peel ba ck, p u ll apart, re constr uct, or m a ke co ncre te objects transpa ren t to see how th ey are arra nged or con structed . Th es e are jus t a few of th e poss ibl e ex tens ions of repr esen tation . As we use ske tches to v isu alize design s, w e sho uld al w ays be ready to inven t new too ls as need ed . Fi gure 3-20 Transparent sketch. Figure 3-21 By Th omas Truax. Structural systems illustrations, Boston City Ha ll, Kallman, McKinnell & Knowles, architects. ~ - -- + - - I I I , ~ -- -- Figure 3-22 Cut-away view, the Simon House, Barbara and J ulian Neski, architects. Figure 3-23 "Ex plodarnetric" drawing of a barn. Other Representa tions 49 , - /I » \ • I ,>I' - --1tr-- - - - -,~ ,~ / .1 .:% .f / ~ -~ f1~ : .: 1, _l"E;'-~--, : I_ "" '__~:_~..: _ ~<'~~ __ ~_'_:~ --f --- - <=.:. ~ _ ... ,t .i"" .. . t~~· - :I( _ . ~ :-~- I or , 'jd .~ ~ ' ~ - r'-:i?J~ - i::'"-~. t~ ~ ,,:.L..-<;. t:.t< \ l~~ ..., r , ' /, ~ ~ t6 ~ _ . Fi gure 3-24 By Helmut Jacoby. Boston Government Service Cente r, Paul Rudolph, coordinating archit ects. SKETCH TECHNIQUE ---1 11 Figure 3-25 By Helmut Jacoby. Ford Fo undation headquarters, Dinkerloo and Roche, architects. 50 Conventions Many arc hitects ha ve develop ed th eir ow n ske tc hing s tyles in an att emp t to q uickly rep rese n t str ucture, tones, and det ail with a mi nim u m of effor t. An espe cia lly effe ctive tech niqu e is that of He lm u t Jacoby, an ar chite ctur al d el in ea tor of int ern ational rep u tat ion ." Th e qu ick p relim in a ry studie s he uses to p lan th e fin al ren d erings p rovide remark able clari ty of spa tial d efinitio n wi th an ec on omy of m eans. Not ice how, w ith a range of tigh t an d loose squi ggly lines, he ca n de fine surfaces and th e rap id way fha t he suggests peo ple, tr ees, textur es, and ot her detail s. The under lyi ng structur e of the sk etch is usually quite simple, w it h w hi te areas u sed to hel p d efin e space an d objects. Ja coby is very aware of va riat ions in tone and th e effe cts of sha de and shadow w ith respect to the sur rou nd ing trees as w ell as the build ing . M ichael Ge b hard t sketches w it h an emp ha sis on tones and textur es, defin ing spa ce m ore through con trasts than line w or k . W ith a lo opi ng strok e, he is abl e to establish a consistency th at pu lls the drawing toget her and d irects att en tion to the su bj ect rat her th a n the med ia . In esta blish ing your own sty le , be sur e to exam in e closely the work of othe rs th at yo u adm ire ; th ere is no need to star t fro m scratch . Also kee p in m ind th at the objective in sket ching is speed and ease. \ Figure 3-26 By Brian Lee. Auto matic drawing done wit hout looking at the paper. It encourages fluidity of line and nat uralness of expression. Figure 3-27 By Michael F. Gebhardt . Jo hns-Manville World Headquarters, The Architects Collaborative. Ske tch Technique 51 ,A ,v~/' / ",L.-...-i __\. /~l=0 -c ': I'-l-LA.~ .. c::I " v, I ~-= \~ r l~ c~(~. . \..I;/ / 1/ -: "\ 1"--' -\. ~ '-"'1 ~ <: l_ . _ Fig ure 3-28 By Bret Dodd. Design ing d epend s heav ily upon representation ; to avoid d isappoin tm ent later, th e designer wa nts to see the p hys ica l e ffects of h is d ec is ion s. It is inevita ble that a student w ill tell m e that he is waitin g u nt il h e has d ecid ed w ha t to do before he d raw s it up . This is backward. In fact, he can no t dec ide wh at to do until he has drawn it. N ine time s out of ten inde cisiveness is the result otiack of evidence. Fur ther m ore, a decision imp lies a choice ; recogn izing th at th ere is m or e than on e possi ble d esign so luti on , it ma kes no sense w hatsoever to try to de term ine if one iso la ted solution is good . In stead , t he ques tion s hou ld b e w heth er thi s is the best of the know n alternat ives. To answe r this question , we must a lso be ab le to see the oth er designs. The grap hic thin king approach empha size s sketches tha t fe ed thin k ing and thoug h ts tha t feed sk etc hes; one is co ntin ua lly inform ing the other. For the begin ni ng d esign er , thes e po in ts can not be ove remphasi zed . There is no way to avoid the inten se, com pr ehen sive job of representation or mode ling in design . The only cho ice left is wh ether to m ak e t he j ob eas ie r throughou t a profes sional career by bec om in g a com pe tent illu strator now. Havi ng sa id tha t, I wo u ld ad d the w arn ing th a t draw ing an d thinki ng mu s t be alway s open to gr owt h . Clic hes in drawing lead to cli ches in thi n k ing. As John Gund elfing er says: 52 Conventions 1 never k now what a drawing will look lik e until it is finished. O nce yo u do, that's security, and secu rity is somet hing we ca n all do without in a drawing . It comes from working in a particul ar way or styl e th at enables you to control an y subjec t or situation you enco unter, a nd once you're in control, you stop learning The nervousne ss and a nxiety that precede a drawing are importa nt to the end result.' Architects who have been abl e to find adve n tur e and excite m en t in d raw ing w ill readily attend to the grea t boost it gives to th eir d esign' work and the ir th inking. Fina lly, I wan t to str ess tw o of my p r ej ud ices r egard ing represent ati ve d ra w ing. First , fr eeh and ab ility is v ital for effec tive use of rep resen tat ion in arch itec tura l d esign . You m ust be ab le to tu rn over idea s ra pid ly ; to do thi s req uires th e spo n ta n eous graph ic d isp lay tha t rapid sk etc h ing provid es. Second, a tte n tion sho u ld be p a id to m ak ing the s ketches fa ith full y re p resen t d esign id eas. Avoid ad d in g th in gs to a d raw ing s im p ly to im p rove the ap pea ra nce of the draw ing. Chan ges shou ld refle ct conscious chang es in the d esign . Kirb y Lockar d ca u tions, "Rem ember, th e best , m ost d irect and hon est per su asion for a d esign 's ac cep tance shou ld be th e design itself , and all suc cessful persua sion sho uld be based on com pe te n t a nd hon est r ep resenta tions of the des ign .:" Figure 3-29 Design development sketches. Ske tch Technique 53 • 4 Abstraction T he design process can be thou ght of as a series of tran sformations going from un certainty towa rds inform ation. The successive stages of the process are usu ally registe red by some kind of graphic model. In the final stages of the design process, designers use highly form alized gra ph ic languages such. as those provided by descriptive geometry. B ut this type of representation is hardly suita ble for the first stages, when designers lise quick ske tches and diagrams...It has been accep ted for years that becau se of the high level of abstraction of the ideas wh ich are ha ndled at the beginn ing of the design process, they mu st be expressed necessa rily by mean s of a rath er ambigu ous, loose graphic languag e-a private language w hich no one can properly understand excep t th e des igner himself .. the high level of abstraction of the inform ation which is handled mu st not prevent us from using a clea rly defi ned graphic language. Such a language would register the information exac tly at the level of abstraction it has, and it would facilitate com m unicat ion an d coopera tion among designe rs. I Yl1lZlA ]V1Wff//A :1 'Ii ?l12tZ~ o -JUA N PABLO BONTA y ow n vers ion of a grap h ic language is based on experience w it h student s in th e d esign studi o a nd r esearch in de sign p ro ces s co mm u n icati on s. It is p rese nted her e bec ause I am con vin ced th at a clearl y def ine d graphic lang uage is importan t bo th to design th ink ing and to communi cat ion betw een design ers. ¥waw~ M Figure 4-2 As Robert McKim poin ted out, "A langu age con sists of a set of rules by w hich sym bols can be related to represent larger m eanin gs. " 2 The di ffere nc e be tween verbal and grap hic languages is both in the sy m bols used an d in the w ays in w hi ch th e symbols are re lated . The sym bols for verbal languages are large ly rest ricted to word s, whereas gr ap hic la n guages incl ude im ages, signs, numbe rs , a nd w ords. M uch more significant , ver bal language is se q u en tial - it has a be ginn ing, a midd le, a nd a n end . Graph ic langu age is sim u ltaneous -all symbols and their rel ation sh ips are co ns idered at th e same tim e. The sim ulta ne ity a nd co m p lex in terre la tion sh ip of reali ty acc oun ts for th e specia l strength of grap hic language in addressing comp lex pro blems . 55 rY1 0 dl + , e ~ , -,( Figure 4-3a Sente nce diagram. -: ./ .--- --- -- ~ ---- --- / ( (d) ", I 5VI£;\J. 1\ no.",e ) , ' d.,f,! ,,~ (c) / I / I /- - - ,el"h01\ Sfl/p \ \ / ,/ -----B I - I- ... , (e) I /tj v'?t '; ' h"" ' ( ~ "---j ~ Fi gure 4-3b Graphic diagram. Figure 4-3c, d. e Graphic "sentences." GRAMMAR T he re are ot her ways of draw ing "graph ic se n tenc es" ; three alter natives ar e show n here: The grap hic language pr opose d here has gra m ma tical ru les compar ab le to thos e of ve rbal langu age. Th e d ia gram of the se ntence (Figur e 4-3a ) show s three basic parts: nou ns, ver bs, an d m od ifiers such as adjec tives, ad verbs, a nd p h rases. Nouns r epresent iden tities , verb s es ta blish re lations h ips betw een nouns, and the modifiers qualify or q uan tify the iden tities or the re la tionships betw een ident ities. In the grap h ic d iagram (Figure 4-3b), identities are shown as circl es, rela tion ships are show n as lin es, an d m od ifiers are show n by cha nge s in the cir cles or lines (heavier lines ind icate mor e importan t relation ship s and tones ind icat ing dif fer ence s in id en tities ). In th e sen tenc e d iagram , the verb shows a relat ionship that th e subject has to th e object: the d og ca ugh t the bo n e. T he lin e in th e graphic di agram is bi-directiona l; it says that the livin g room is co n nected to the kitchen and that the k itchen is con nec ted to the livi ng room . Th us the gr aphic d iagr am conta in s m any se n tences as : 1. Th e very im portan t liv ing room has a minor rela tions hip to th e garage (Figure 4-3c) . 2. The dini ng room must be con nected to th e special spaces , the kitchen and the deck (Figur e 4-3d ). 3. The fut ure gu esthouse w ill be related to the en try and indirectly to the pool (Figure 4-3e). 56 Abstraction 1. Position- An implied gri d is used to establish rela tion sh ips between id en tit ies; th e resulting orde r som et im es m a kes the di agra m easie r to read (Figur e 4-4a ). 2. Proximity- T he degree or in tensity of th e relation sh ips of ide n tities is ind ica ted by the re lative d is tan ces betw een th em. A sign ifica n t increase in d ista nc e can im pl
https://ar.b-ok.org/book/1049404/1968d9
CC-MAIN-2020-16
refinedweb
23,185
79.74
needed for solution development but it can’t be found and located in the repository explorer. A possible reason for that could be, that there is a Public Solution Model (PSM) release missing for that information. Even when you are sure that there is a missing PSM release, you end up with some missing information to get the release incident done quickly. For the incident you would like to provide all the needed information for SAP to get the PSM release done and with less as possible questions about a speculated name or position in the BO structure. Deactivate PSM Check To get an better understanding if you are right with the assumed name and position of the element you are searching for, you can deactivate the PSM check for an solution. This also brings you in the position to cross check the correct functionality before you create the incident. import AP.PlatinumEngineering.Public; Solution.PSMTurnOff("<Solution_Name>"); This deactivation also brings you very interesting insides into the BO structures of SAP by using the repository explorer. Activate PSM Check Now of course you do not want to work permanently without the activated Public Solution Model, so there is also a way to turn the check back on. import AP.PlatinumEngineering.Public; Solution.PSMTurnOn("<Solution_Name>"); I hope this will help you to find Business Object information easier and also to understand the structures a bit better. Hello Tobias, first of all, thank you for that information! I have a few questions: Thank you and best regards, Jürgen Hello Jürgen, I try to answer your questions: I updated the code snippet with the information about the solution name. Hello Nathanael, I’m not able to import and in the library Solution is missing and i am not able to find the methods described. Could you please provide a full code example (e.g. a screenshot where you whitened out all critical data?) Thanks and Kind Regards, Johannes Hi Johannes, the following code is an working code example out of an action for one of our solutions. I hope this will help you. Best regards Tobias Hello Tobias, with the exact same code (copy&paste) I get the error message, that the imported namespace is not valid. At this point I can’t help myself, I hope this information is kind of useful for you. Kind Regards, Johannes Hi Johannes, On which type of System did you tried to use this code? Eventually this could be the problem… Mass enabled ABSL Script to turn the PSM off for a given solution name in the BO (saves the PSM state also internally in the BO): Best regards Tobias Hello Tobias, it seems like the answer of stefan kiefer is correct. Our Tenant is not a BusinessByD Tenant. Thanks for all the afford anyways. Have a good day and kind regards, Johannes Hallo, I am the developer of this function. The function was created by me maybe two years back. It is published only and working only on Business By Design Tenants which might be a reason for some comments above. The description to use it is perfect. The intension of the function is to provide some temporary visibility to all attributes, actions, associations. With the many business objects in Business By Design there are still some gaps which may come up in a project. The function should help to see also the parts which are hidden by the PSM concept – and to try/test things out – in order to have than a fundament to request development to release it. There are three things to consider: Bringing these three points together the conclusion is that it should only be turned off for a short time – and you should not forget to turn it on after your test. In C4C this function is in my opinion much less required as in Business ByDesign because there are less business objects and most of them have been frequently used in projects because the development activities concentrate on this objects. So there is no plan to enable this feature for C4C. Best regards and many thanks to the author to start this blog Stefan Kiefer Hello Stefan, Thank for your reply and the clarification on this topic. Also a huge thanks for developing this reuse library :-). Best regards Tobias Kuhn Hi All, I saw the Questions and answers regarding the PSM, but i get ths meesage while trying to create a new web service for managing and updating the exchange rate table how this message relates to the PSM defintion ? Can i deactivate it and activate again after the web service has been created ? thank you
https://blogs.sap.com/2018/01/11/disable-psm-check-for-a-solution-in-sap-cloud-applications-studio/
CC-MAIN-2018-30
refinedweb
777
58.42
Red Hat Bugzilla – Bug 74643 ndbm.h isn't present in /usr/include Last modified: 2007-11-30 17:10:30 EST From Bugzilla Helper: User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827 Description of problem: The gdbm-devel package has gdbm.h and ndbm.h amongst its files and "man gdbm" says that they are included via <gdbm.h> and <ndbm.h>. However, ndbm.h is *not* in /usr/include (gdbm.h is, albeit a soft-link to /usr/include/gdbm/gdbm.h). Version-Release number of selected component (if applicable): How reproducible: Always Steps to Reproduce: 1. Install the gdbm-devel package 2. Look for the gdbm.h and ndbm.h files in /usr/include - the latter isn't present (former is a soft-link). 3. Despite the man page claiming that <ndbm.h> is good enough, the lack of ndbm.h in /usr/include will cause this to fail. Actual Results: No sign of ndbm.h in /usr/include Expected Results: Commercial UNIX distros and other Linux distros (e.g. SuSE) *do* have ndbm.h in /usr/include. Either Red Hat should too or at least correctly document how to include <ndbm.h> (either with <gdbm/ndbm.h> or with -I/usr/include/gdbm) if RH don't want to put an ndbm.h soft-link in /usr/include. Additional info: I would suggest a soft-link from /usr/include/ndbm.h to /usr/include/gdbm/ndbm.h to fix this problem (this was done for gdbm.h, but bizarrely not done for ndbm.h). This problem is present in Red Hat 7.2 and the beta 3 of Red Hat 8.0 ("null") - it's probably also present in 7.3, but I haven't checked that out. Confirmed... PHP 4.3.4 (not the Red Hat RPM) build breaks because of this symlink missing! Since this problem is still there in FC1, changing product and version number.... There is no way to satisy multiple ndbm emulations in various db packages with a single symlink. I'm a little surprised at Jeff's comment today because of the lack of details. Which db packages (other than gdbm of course) contain ndbm emulations which have their own ndbm.h and hence would cause an include clash? If Red Hat have decided that /usr/include shouldn't contain ndbm.h, then that's fair enough, but it's a shame that the "man gdbm" documentation will therefore remain incorrect when it states that <ndbm.h> is all that's needed to include that header file. Surely changing that to <gdbm/ndbm.h> can't be all that hard, especially if there are indeed multiple ndbm.h implementations? Basically, all databases similar to gdbm have a ndbm.h, and offer a NDBM emulation. Since it is unclear which ndbm.h should go as *THE* ndbm.h because each application has different needs, there can be no single /usr/include/ndbm.h, What is there instead is the ndbm.h for each database. E.g. here is the include file for the gdbm NDBM emulation: $ rpm -ql gdbm-devel | grep ndbm.h /usr/include/gdbm/ndbm.h So add -I/usr/include/gdbm if you wish to use the gdbm NDBM emulation. Since this is now marked as an FC2 issue, I thought I'd do a bit of research to answer my own question - namely, which RPM packages shipped on the FC2 DVD have an ndbm.h file present? With a bit of scripting to loop around with an "rpm -qlp", I discovered just one, predictably, namely: gdbm-devel-1.8.0-22.1.i386.rpm Hence, FC2, unlike some of the Red Hat releases (which used to have db1-devel and/or gnome-libs-devel containing ndbm.h), only ships one ndbm.h, namely /usr/include/gdbm/ndbm.h. So there is still a case for soft-linking ndbm.h in the same manner that gdbm.h is linked. To make things worse, I discovered that the "man-pages" RPM contains an ndbm.h man page, which is also wrong on this issue ("man ndbm.h" just says #include <ndbm.h> to include the file). If the decision is still not to soft-link ndbm.h, then can we please fix the two man pages ("man gdbm" and "man ndbm.h") to say #include <gdbm.h> or that -I/usr/include/gdbm should be used when compiling? Oops, I meant #include <gdbm/ndbm.h> in that last sentence on my most recent comment... Even though there may only be a single occurence of ndbm.h in FC2 does not mean that there aren't other NDBM emulations around, possibly packaged outside of FC2. Adding the symlin to FC2 packages also prevents end-user choice, where ln -s gdbm/ndbm.h /usr/include/ndbm.h might be a reasonable choice, or perhaps some other NDBM emulation. Whether -I/usr/include/gdbm is added to compile flags, or #include <gdbm/ndbm.h> is done is up to individual developers taste and style.
https://bugzilla.redhat.com/show_bug.cgi?id=74643
CC-MAIN-2017-09
refinedweb
850
79.26
On Mon, May 21, 2012 at 1:00 AM, Eric V. Smith eric@trueblade.com wrote:. Ah, I see. But I disagree that this is a reasonable constraint on sys.path. The magic __path__ object of a toplevel namespace module should know it is a toplevel module, and explicitly refetch sys.path rather than just keeping around a copy.. I'd like to hear more about this from Philip -- is that feature actually widely used? What would a package have to do if the feature didn't exist? I'd really much rather not have this feature, which reeks of too much magic to me. (An area where Philip and I often disagree. :-)
https://mail.python.org/archives/list/python-dev@python.org/message/KPUKYHWYGY7PYKZNKCEBG6UAYHIDBH7L/
CC-MAIN-2022-27
refinedweb
113
76.52
Ralf Baechle wrote: > On Mon, Oct 17, 2005 at 02:44:07PM -0700, David Daney wrote: > > > This patch fixes the lookup_dcookie for the MIPS o32 ABI. Although I > > only tested with little-endian, the big-endian case needed fixing as > > well but is untested (but what are the chances that this is not the > > correct fix?). > > > > This is the only patch I needed to get the user space oprofile > > programs to work for mipsel-linux. > > > > I am CCing the linux-mips list as this may be of interest there as well. > > Good catch. > > > 2005-10-17 David Daney <ddaney@avtrex.com> > > > > * daemon/opd_cookie.c (lookup_dcookie): Handle MIPS o32 for both big > > and little endian. > > > > Index: oprofile/daemon/opd_cookie.c > > =================================================================== > > RCS file: /cvsroot/oprofile/oprofile/daemon/opd_cookie.c,v > > retrieving revision 1.19 > > diff -p -a -u -r1.19 opd_cookie.c > > --- oprofile/daemon/opd_cookie.c 26 May 2005 00:00:02 -0000 1.19 > > +++ oprofile/daemon/opd_cookie.c 17 Oct 2005 21:29:13 -0000 > > @@ -60,12 +60,21 @@ > > #endif /* __NR_lookup_dcookie */ > > > > #if (defined(__powerpc__) && !defined(__powerpc64__)) || defined(__hppa__)\ > > - || (defined(__s390__) && !defined(__s390x__)) > > + || (defined(__s390__) && !defined(__s390x__)) \ > > + || (defined(__mips__) && (_MIPS_SIM == _MIPS_SIM_ABI32) \ > > + && defined(_MIPSEB)) > > Small nit - please use __MIPSEB__ rsp. __MIPSEL__; I think there are > some compilers floating around that don't define the single underscore > variant. AFAIR it's the other way, some compilers fail to define __MIPSEB__ and/or __MIPSEB but all have _MIPSEB. Thiemo
http://www.linux-mips.org/archives/linux-mips/2005-10/msg00165.html
CC-MAIN-2015-06
refinedweb
234
67.45
Collections¶ Streamz high-level collection APIs are built on top of streamz.core, and bring special consideration to certain types of data: streamz.batch: supports streams of lists of Python objects like tuples or dictionaries streamz.dataframe: supports streams of Pandas dataframes or Pandas series These high-level APIs help us handle common situations in data processing. They help us implement complex algorithms and also improve efficiency. These APIs are built on the streamz core operations (map, accumulate, buffer, timed_window, …) which provide the building blocks to build complex pipelines but offer no help with what those functions should be. The higher-level APIs help to fill in this gap for common situations. Conversion¶ You can convert from core Stream objects to Batch, and DataFrame objects using the .to_batch and .to_dataframe methods. In each case we assume that the stream is a stream of batches (lists or tuples) or a list of Pandas dataframes. >>> batch = stream.to_batch() >>> sdf = stream.to_dataframe() To convert back from a Batch or a DataFrame to a core.Stream you can access the .stream property. >>> stream = sdf.stream >>> stream = batch.stream Example¶ We create a stream and connect it to a file object file = ... # filename or file-like object from streamz import Stream source = Stream.from_textfile(file) Our file produces line-delimited JSON serialized data on which we want to call json.loads to parse into dictionaries. To reduce overhead we first batch our records up into 100-line batches and turn this into a Batch object. We provide our Batch object an example element that it will use to help it determine metadata. example = [{'name': 'Alice', 'x': 1, 'y': 2}] lines = source.partition(100).to_batch(example=example) # batches of 100 elements records = lines.map(json.loads) # convert lines to text. We could have done the .map(json.loads) command on the original stream, but this way reduce overhead by applying this function to lists of items, rather than one item at a time. Now we convert these batches of records into pandas dataframes and do some basic filtering and groupby-aggregations. sdf = records.to_dataframe() sdf = sdf[sdf.name == "Alice"] sdf = sdf.groupby(sdf.x).y.mean() The DataFrames satisfy a subset of the Pandas API, but now rather than operate on the data directly, they set up a pipeline to compute the data in an online fashion. Finally we convert this back to a stream and push the results into a fixed-size deque. from collections import deque d = deque(maxlen=10) sdf.stream.sink(d.append) See Collections API for more information.
https://streamz.readthedocs.io/en/latest/collections.html
CC-MAIN-2019-18
refinedweb
427
58.89
Files: The Mandelbrot example shows how to use a worker thread to perform heavy computations without blocking the main thread's event loop. The heavy computation here is the Mandelbrot set, probably the world's most famous fractal. These days, while sophisticated programs such as XaoS that provide real-time zooming in the Mandelbrot set, the standard Mandelbrot algorithm is just slow enough for our purposes. In real life, the approach described here is applicable to a large set of problems, including synchronous network I/O and database access, where the user interface must remain responsive while some heavy operation is taking place. The network/blockingfortuneclient example shows the same principle at work in a TCP client. The Mandelbrot application supports zooming and scrolling using the mouse or the keyboard. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), we put all the fractal computation in a separate worker thread. The thread emits a signal when it is done rendering the fractal. During the time where the worker thread is recomputing the fractal to reflect the new zoom factor position, the main thread simply scales the previously rendered pixmap to provide immediate feedback. The result doesn't look as good as what the worker thread eventually ends up providing, but at least it makes the application more responsive. The sequence of screenshots below shows the original image, the scaled image, and the rerendered image. Similarly, when the user scrolls, the previous pixmap is scrolled immediately, revealing unpainted areas beyond the edge of the pixmap, while the image is rendered by the worker thread. The application consists of two classes: If you are not already familiar with Qt's thread support, we recommend that you start by reading the Thread Support in Qt overview. We'll start with the definition of the RenderThread class:]; }; The class inherits QThread so that it gains the ability to run in a separate thread. Apart from the constructor and destructor, render() is the only public function. Whenever the thread is done rendering an image, it emits the renderedImage() signal. The protected run() function is reimplemented from QThread. It is automatically called when the thread is started. In the private section, we have a QMutex, a QWaitCondition, and a few other data members. The mutex protects the other data member. RenderThread::RenderThread(QObject *parent) : QThread(parent) { restart = false; abort = false; for (int i = 0; i < ColormapSize; ++i) colormap[i] = rgbFromWaveLength(380.0 + (i * 400.0 / ColormapSize)); } In the constructor, we initialize the restart and abort variables to false. These variables control the flow of the run() function. We also initialize the colormap array, which contains a series of RGB colors. RenderThread::~RenderThread() { mutex.lock(); abort = true; condition.wakeOne(); mutex.unlock(); wait(); } The destructor can be called at any point while the thread is active. We set abort to true to tell run() to stop running as soon as possible. We also call QWaitCondition::wakeOne() to wake up the thread if it's sleeping. (As we will see when we review run(), the thread is put to sleep when it has nothing to do.) The important thing to notice here is that run() is executed in its own thread (the worker thread), whereas the RenderThread constructor and destructor (as well as the render() function) are called by the thread that created the worker thread. Therefore, we need a mutex to protect accesses to the abort and condition variables, which might be accessed at any time by run(). At the end of the destructor, we call QThread::wait() to wait until run() has exited before the base class destructor is invoked. void RenderThread::render(double centerX, double centerY, double scaleFactor, QSize resultSize) { QMutexLocker locker(&mutex); this->centerX = centerX; this->centerY = centerY; this->scaleFactor = scaleFactor; this->resultSize = resultSize; if (!isRunning()) { start(LowPriority); } else { restart = true; condition.wakeOne(); } } The render() function is called by the MandelbrotWidget whenever it needs to generate a new image of the Mandelbrot set. The centerX, centerY, and scaleFactor parameters specify the portion of the fractal to render; resultSize specifies the size of the resulting QImage. The function stores the parameters in member variables. If the thread isn't already running, it starts it; otherwise, it sets restart to true (telling run() to stop any unfinished computation and start again with the new parameters) and wakes up the thread, which might be sleeping. void RenderThread::run() { forever { mutex.lock(); QSize resultSize = this->resultSize; double scaleFactor = this->scaleFactor; double centerX = this->centerX; double centerY = this->centerY; mutex.unlock(); run() is quite a big function, so we'll break it down into parts. The function body is an infinite loop which starts by storing the rendering parameters in local variables. As usual, we protect accesses to the member variables using the class's mutex. Storing the member variables in local variables allows us to minimize the amout of code that needs to be protected by a mutex. This ensures that the main thread will never have to block for too long when it needs to access RenderThread's member variables (e.g., in render()). The forever keyword is, like foreach, a Qt pseudo-keyword. int halfWidth = resultSize.width() / 2; int halfHeight = resultSize.height() / 2; QImage image(resultSize, QImage::Format_RGB32); const int NumPasses = 8; int pass = 0; while (pass < NumPasses) { const int MaxIterations = (1 << (2 * pass + 6)) + 32; const int Limit = 4; bool allBlack = true; for (int y = -halfHeight; y < halfHeight; ++y) { if (restart) break; if (abort) return; uint *scanLine = reinterpret_cast<uint *>(image.scanLine(y + halfHeight)); double ay = centerY + (y * scaleFactor); for (int x = -halfWidth; x < halfWidth; ++x) { double ax = centerX + (x * scaleFactor); double a1 = ax; double b1 = ay; int numIterations = 0; do { ++numIterations; double a2 = (a1 * a1) - (b1 * b1) + ax; double b2 = (2 * a1 * b1) + ay; if ((a2 * a2) + (b2 * b2) > Limit) break; ++numIterations; a1 = (a2 * a2) - (b2 * b2) + ax; b1 = (2 * a2 * b2) + ay; if ((a1 * a1) + (b1 * b1) > Limit) break; } while (numIterations < MaxIterations); if (numIterations < MaxIterations) { *scanLine++ = colormap[numIterations % ColormapSize]; allBlack = false; } else { *scanLine++ = qRgb(0, 0, 0); } } } if (allBlack && pass == 0) { pass = 4; } else { if (!restart) emit renderedImage(image, scaleFactor); ++pass; } } Then comes the core of the algorithm. Instead of trying to create a perfect Mandelbrot set image, we do multiple passes and generate more and more precise (and computationally expensive) approximations of the fractal. If we discover inside the loop that restart has been set to true (by render()), we break out of the loop immediately, so that the control quickly returns to the very top of the outer loop (the forever loop) and we fetch the new rendering parameters. Similarly, if we discover that abort has been set to true (by the RenderThread destructor), we return from the function immediately, terminating the thread. The core algorithm is beyond the scope of this tutorial. mutex.lock(); if (!restart) condition.wait(&mutex); restart = false; mutex.unlock(); } } Once we're done with all the iterations, we call QWaitCondition::wait() to put the thread to sleep by calling, unless restart is true. There's no use in keeping a worker thread looping indefinitely while there's nothing to do. uint RenderThread::rgbFromWaveLength(double wave) { double r = 0.0; double g = 0.0; double b = 0.0; if (wave >= 380.0 && wave <= 440.0) { r = -1.0 * (wave - 440.0) / (440.0 - 380.0); b = 1.0; } else if (wave >= 440.0 && wave <= 490.0) { g = (wave - 440.0) / (490.0 - 440.0); b = 1.0; } else if (wave >= 490.0 && wave <= 510.0) { g = 1.0; b = -1.0 * (wave - 510.0) / (510.0 - 490.0); } else if (wave >= 510.0 && wave <= 580.0) { r = (wave - 510.0) / (580.0 - 510.0); g = 1.0; } else if (wave >= 580.0 && wave <= 645.0) { r = 1.0; g = -1.0 * (wave - 645.0) / (645.0 - 580.0); } else if (wave >= 645.0 && wave <= 780.0) { r = 1.0; } double s = 1.0; if (wave > 700.0) s = 0.3 + 0.7 * (780.0 - wave) / (780.0 - 700.0); else if (wave < 420.0) s = 0.3 + 0.7 * (wave - 380.0) / (420.0 - 380.0); r = pow(r * s, 0.8); g = pow(g * s, 0.8); b = pow(b * s, 0.8); return qRgb(int(r * 255), int(g * 255), int(b * 255)); } The rgbFromWaveLength() function is a helper function that converts a wave length to a RGB value compatible with 32-bit QImages. It is called from the constructor to initialize the colormap array with pleasing colors. The MandelbrotWidget class uses RenderThread to draw the Mandelbrot set on screen. Here's the class definition:; }; The widget reimplements many event handlers from QWidget. In addition, it has an updatePixmap() slot that we'll connect to the worker thread's renderedImage() signal to update the display whenever we receive new data from the thread. Among the private variables, we have thread of type RenderThread and pixmap, which contains the last rendered image. const double DefaultCenterX = -0.637011f; const double DefaultCenterY = -0.0395159f; const double DefaultScale = 0.00403897f; const double ZoomInFactor = 0.8f; const double ZoomOutFactor = 1 / ZoomInFactor; const int ScrollStep = 20; The implementation starts with a few contants that we'll need later on. MandelbrotWidget::MandelbrotWidget(QWidget *parent) : QWidget(parent) { centerX = DefaultCenterX; centerY = DefaultCenterY; pixmapScale = DefaultScale; curScale = DefaultScale; qRegisterMetaType<QImage>("QImage"); connect(&thread, SIGNAL(renderedImage(const QImage &, double)), this, SLOT(updatePixmap(const QImage &, double))); setWindowTitle(tr("Mandelbrot")); #ifndef QT_NO_CURSOR setCursor(Qt::CrossCursor); #endif resize(550, 400); } The interesting part of the constructor is the qRegisterMetaType() and QObject::connect() calls. Let's start with the connect() call. Although it looks like a standard signal-slot connection between two QObjects, because the signal is emitted in a different thread than the receiver lives in, the connection is effectively a queued connection. These connections are asynchronous (i.e., non-blocking), meaning that the slot will be called at some point after the emit statement. What's more, the slot will be invoked in the thread in which the receiver lives. Here, the signal is emitted in the worker thread, and the slot is executed in the GUI thread when control returns to the event loop. With queued connections, Qt must store a copy of the arguments that were passed to the signal so that it can pass them to the slot later on. Qt knows how to take of copy of many C++ and Qt types, but QImage isn't one of them. We must therefore call the template function qRegisterMetaType() before we can use QImage as parameter in queued connections. void MandelbrotWidget::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); painter.fillRect(rect(), Qt::black); if (pixmap.isNull()) { painter.setPen(Qt::white); painter.drawText(rect(), Qt::AlignCenter, tr("Rendering initial image, please wait...")); return; } In paintEvent(), we start by filling the background with black. If we have nothing yet to paint (pixmap is null), we print a message on the widget asking the user to be patient and return from the function immediately. if (curScale == pixmapScale) { painter.drawPixmap(pixmapOffset, pixmap); } else { double scaleFactor = pixmapScale / curScale; int newWidth = int(pixmap.width() * scaleFactor); int newHeight = int(pixmap.height() * scaleFactor); int newX = pixmapOffset.x() + (pixmap.width() - newWidth) / 2; int newY = pixmapOffset.y() + (pixmap.height() - newHeight) / 2; painter.save(); painter.translate(newX, newY); painter.scale(scaleFactor, scaleFactor); QRectF exposed = painter.matrix().inverted().mapRect(rect()).adjusted(-1, -1, 1, 1); painter.drawPixmap(exposed, pixmap, exposed); painter.restore(); } If the pixmap has the right scale factor, we draw the pixmap directly onto the widget. Otherwise, we scale and translate the coordinate system before we draw the pixmap. By reverse mapping the widget's rectangle using the scaled painter matrix, we also make sure that only the exposed areas of the pixmap are drawn. The calls to QPainter::save() and QPainter::restore() make sure that any painting performed afterwards uses the standard coordinate system. QString text = tr("Use mouse wheel or the '+' and '-' keys to zoom. " "Press and hold left mouse button to scroll."); QFontMetrics metrics = painter.fontMetrics(); int textWidth = metrics.width(text); painter.setPen(Qt::NoPen); painter.setBrush(QColor(0, 0, 0, 127)); painter.drawRect((width() - textWidth) / 2 - 5, 0, textWidth + 10, metrics.lineSpacing() + 5); painter.setPen(Qt::white); painter.drawText((width() - textWidth) / 2, metrics.leading() + metrics.ascent(), text); } At the end of the paint event handler, we draw a text string and a semi-transparent rectangle on top of the fractal. void MandelbrotWidget::resizeEvent(QResizeEvent * /* event */) { thread.render(centerX, centerY, curScale, size()); } Whenever the user resizes the widget, we call render() to start generating a new image, with the same centerX, centerY, and curScale parameters but with the new widget size. Notice that we rely on resizeEvent() being automatically called by Qt when the widget is shown the first time to generate the image the very first time. void MandelbrotWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Plus: zoom(ZoomInFactor); break; case Qt::Key_Minus: zoom(ZoomOutFactor); break; case Qt::Key_Left: scroll(-ScrollStep, 0); break; case Qt::Key_Right: scroll(+ScrollStep, 0); break; case Qt::Key_Down: scroll(0, -ScrollStep); break; case Qt::Key_Up: scroll(0, +ScrollStep); break; default: QWidget::keyPressEvent(event); } } The key press event handler provides a few keyboard bindings for the benefit of users who don't have a mouse. The zoom() and scroll() functions will be covered later. void MandelbrotWidget::wheelEvent(QWheelEvent *event) { int numDegrees = event->delta() / 8; double numSteps = numDegrees / 15.0f; zoom(pow(ZoomInFactor, numSteps)); } The wheel event handler is reimplemented to make the mouse wheel control the zoom level. QWheelEvent::delta() returns the angle of the wheel mouse movement, in eights of a degree. For most mice, one wheel step corresponds to 15 degrees. We find out how many mouse steps we have and determine the zoom factor in consequence. For example, if we have two wheel steps in the positive direction (i.e., +30 degrees), the zoom factor becomes ZoomInFactor to the second power, i.e. 0.8 * 0.8 = 0.64. void MandelbrotWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) lastDragPos = event->pos(); } When the user presses the left mouse button, we store the mouse pointer position in lastDragPos. void MandelbrotWidget::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { pixmapOffset += event->pos() - lastDragPos; lastDragPos = event->pos(); update(); } } When the user moves the mouse pointer while the left mouse button is pressed, we adjust pixmapOffset to paint the pixmap at a shifted position and call QWidget::update() to force a repaint. void MandelbrotWidget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { pixmapOffset += event->pos() - lastDragPos; lastDragPos = QPoint(); int deltaX = (width() - pixmap.width()) / 2 - pixmapOffset.x(); int deltaY = (height() - pixmap.height()) / 2 - pixmapOffset.y(); scroll(deltaX, deltaY); } } When the left mouse button is released, we update pixmapOffset just like we did on a mouse move and we reset lastDragPos to a default value. Then, we call scroll() to render a new image for the new position. (Adjusting pixmapOffset isn't sufficient because areas revealed when dragging the pixmap are drawn in black.) void MandelbrotWidget::updatePixmap(const QImage &image, double scaleFactor) { if (!lastDragPos.isNull()) return; pixmap = QPixmap::fromImage(image); pixmapOffset = QPoint(); lastDragPos = QPoint(); pixmapScale = scaleFactor; update(); } The updatePixmap() slot is invoked when the worker thread has finished rendering an image. We start by checking whether a drag is in effect and do nothing in that case. In the normal case, we store the image in pixmap and reinitialize some of the other members. At the end, we call QWidget::update() to refresh the display. At this point, you might wonder why we use a QImage for the parameter and a QPixmap for the data member. Why not stick to one type? The reason is that QImage is the only class that supports direct pixel manipulation, which we need in the worker thread. On the other hand, before an image can be drawn on screen, it must be converted into a pixmap. It's better to do the conversion once and for all here, rather than in paintEvent(). void MandelbrotWidget::zoom(double zoomFactor) { curScale *= zoomFactor; update(); thread.render(centerX, centerY, curScale, size()); } In zoom(), we recompute curScale. Then we call QWidget::update() to draw a scaled pixmap, and we ask the worker thread to render a new image corresponding to the new curScale value. void MandelbrotWidget::scroll(int deltaX, int deltaY) { centerX += deltaX * curScale; centerY += deltaY * curScale; update(); thread.render(centerX, centerY, curScale, size()); } scroll() is similar to zoom(), except that the affected parameters are centerX and centerY. The application's multithreaded nature has no impact on its main() function, which is as simple as usual: int main(int argc, char *argv[]) { QApplication app(argc, argv); MandelbrotWidget widget; widget.show(); return app.exec(); }
http://doc.trolltech.com/4.4/threads-mandelbrot.html
crawl-002
refinedweb
2,769
57.87
We're making it easier to implement safe area and large titles for iOS 11 in a new service release candidate of Xamarin.Forms. Try out the package and let us know your feedback. If testing goes well the next few days, we'll promote this to NuGet shortly. Comment below. Happy to see Large titles getting treatment on Xamarin.Forms. Seems to work otherwise great, but NavigationPage within TabbedPage has issue. Not sure is it something app developer should take care of or should it be part of default behaviour. When scrolling up the page in NavigationPage, the title gets smaller as it should. However, bottom of the page gets moved up and navigation page background becomes visible. Here is how it looks: It's easy to replicate with this simple Forms app: `using System; using Xamarin.Forms; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; namespace LargeTitlesWithTabs { public class App : Application { public App() { var navigationPage = new Xamarin.Forms.NavigationPage(new HighPage()) { BackgroundColor = Color.Red }; navigationPage.On<Xamarin.Forms.PlatformConfiguration.iOS>().SetPrefersLargeTitles(true); }` Sorry about the code. Can't get the formatting work correctly here. Hi. When do think the new version will be on nuget? Cheers Philipp Is it launched or not yet? Recently just keep so many version update and making me have to update others third party to suit it. We've fixed a ListView issue with HasUnevenRows that was reported on SR4, and we'll investigate the issue raised above. Hope to have this on NuGet asap. @DavidOrtinau Awesome! Keep us posted. Semms like viewcell has a hardcoded left padding on iOS 11. This is a dealbreaker for all my apps if i cant get around it. Posted a comment about it here This is the result of code below (nested in a navigationpage with largetitle) This is pretty bad indeed. Did you create a bug for this? not yet @BjornB I can confirm this same behavior. Unfortunately the class is internal so we cannot modify it. We are aware and working on a fix ASAP Is there any way to apply the safe area only to a child element? I would like to use the safe area for my list view but it is not the root element on that page... Have had no joy with safe areas. If I simplify my app to load into a ContentPage and set SetUseSafeAreas to false, the app still shows 'boxed' with black areas to the top and bottom of the screen on iPhone X. The splash screen is also displaying in the same manner. EDIT: Found the issue, wasn't using a LaunchScreen.storyboard which causes the app to run in Compatability Mode. Adding this solves the problem. ` protected override void OnAppearing() { base.OnAppearing(); } ` Setting custom inset values in the on appearing method is weird,,, as it first displays the default safe area insets provided by the system and then it changes. How to avoid the transition, so that users can see the custom safe insets in the first place.. Can't use ViewWillAppear,, as there is no setter to set safe area insets in the page renderer. Hi @DavidOrtinau , Can we use this to detect whether the app is running on iPhone X or other devices? It seems that the value of SafeAreaInsets are always 0. Hi @DavidOrtinau , Tried out as mentioned in blog, but didn’t know how to access SetPrefersLargeTitles under Xamarin forms content page in below line mentioned in above link. On<Xamarin.Forms.PlatformConfiguration.iOS>().SetPrefersLargeTitles(true); Current scenario: Excepted scenario: VS Configuration: Visual Studio 2017 (Community) for Mac 7.2.2(build 7) Xamarin.iOS 11.8.0.20 Also Xamarin.Forms 2.5.0.280555 version packages used in my project. Is any update need to install to achieve this? Please help me to resolve this. Regards, Cheran Hi @DavidOrtinau , I have exactly the same issue as @cherant. I also use Xamarin.Forms 2.5.0.280555 version packages in my project. Can you help me? Thanks, Regards, Thomas Hi @Thomassss , The issue occurs because of launch image not set for iPhone X separately. In Assets.Xcassets iPhone X option not shown in it. As mentioned in below link update Visual Studio for Mac with latest version 7.4 and iPhone X launch option show in it. Now above mentioned issue resolved resolved. You can use safe area to set top and bottom spacing as your requirement. Regards, Cheran Hmm, sorry for not seeing these messages earlier. For those having any issues with large titles or safe area insets, keep an eye on the nightly builds where the team is continuing to improve the support. I added: <Xamarin.Forms.PlatformConfiguration.iOS>().SetLargeTitleDisplay(LargeTitleDisplayMode.Never); to my main content page as follows: public MainMenu () { InitializeComponent (); On<Xamarin.Forms.PlatformConfiguration.iOS>().SetLargeTitleDisplay(LargeTitleDisplayMode.Never); } However, the navigation bar is still very large - like the pic in your blog post ("Large Titles"). Any ideas on what I might be doing wrong or missed? (I tried to include a pic of my iOS emulator output, but I "haven't been a user long enough"). I am using VS2017, and all my Xamarin components are updated, and I did grab the 2.4.0, sr4 from the link (in the blog). Thanks, Stephen Is there a way to left align a non large title? The large title max chars is like 17-20 and if I try switch to a non-large one, things get ugly, because now the title is centered. Also, is there a way to set the indentation of the right aligned large title? Without the above described two, the use of the package is minimal in my opinion. This is not working in tabbed page. @DavidOrtinau Safe area insets appear to be 0 in the constructor of the main page because ViewSafeAreaInsetsDidChange()fires after the page is constructed. Unfortunately, setting custom padding in OnAppearing()is not ideal because sometimes iOS/Forms will render the page before the padding is set and update the layout afterwards. @DavidOrtinau The workaround I came up with was creating a custom renderer and overriding ViewWillLayoutSubviews(). After ViewSafeAreaInsetsDidChange()is called, iOS will trigger another layout and we can set main page control heights there instead of using OnAppearing(). Not a very ideal solution, but it works at least. xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" ios:Page.UseSafeArea="true" It worked, after adding this in XAML simulator automatically handling the notch, do I need to add this tag on each content page? or is there any way I can implement it globally for entire application? One more thing, in my application I have used CarouselPage as well, above mention code is not working with CarouselPages, is there any other way to handle notch for CarouselPages?
https://forums.xamarin.com/discussion/comment/311140/
CC-MAIN-2019-22
refinedweb
1,131
58.08
Hi, I have an issue I need to find a solution to: I need to click on a random directory : and afterwards click on a random file: How can I choose a random object with ranorex? Thx! Random object choosing Class library usage, coding and language questions. Re: Random object choosing Ranorex is built on .NET. You can use the .NET Random class to choose a number between 0 and 1 and then multiply by the number of items in the list. This will give you the zero-based index of the folder to pick. Then add 1 (XPath uses 1 based indexing) and store the result in a module variable. You can use that variable in your item's path like ".//element[$FolderIndex]". Shortcuts usually aren't... Re: Random object choosing I would like to add some hint on directories: First make sure, that the proper dll-s are used: First make sure, that the proper dll-s are used: using System; using System.IO;To count the numbers of directories in C:\ directory int countDir = System.IO.Directory.GetDirectories.("C:\").Length;To count the files in a directory: string targetDirectory = "C:\"; string [] fileEntries = Directory.GetFiles(targetDirectory ); int countFiles = filEntries.Length;
https://www.ranorex.com/forum/random-object-choosing-t6414.html
CC-MAIN-2019-51
refinedweb
202
65.52
Cloudflare has been a long time supporter of AMP, an open-source markup language 1.5 billion web pages are using to accelerate their mobile web performance. Cloudflare runs Ampersand, the only alternative to Google’s AMP cache, and earlier this year we launched Accelerated Mobile Links, a way for sites on Cloudflare to open external links on their site in AMP format, as well as Firebolt, leveraging AMP to speed up ad performance. One of the biggest challenges developers face in converting their web pages to AMP is testing their AMP pages for valid AMP syntax before deploying. It's not enough to make the templates work at dev time, you also need to validate individual pages before they’re published. Imagine, for example, a publishing company where content creators who are unfamiliar with AMP are modifying pages. Because the AMP markup language is so strict, one person adding an interactive element to a page can all of a sudden break the AMP formatting and stop the page from validating. We wanted to make it as easy as possible to move webpages and sites to AMP so we built an AMP linter API for developers to check that their AMP pages are formatted correctly, even before they are deployed. To check if a webpage’s AMP markup is correct, just send the AMP page to the endpoint like this: curl { "source": "", "valid": true, "version": "1488238516283" } The API has options to send just the markup content, or point the linter to the live site. To send a file, add the --data-binary flag: curl -X POST --data-binary @amp_page.html -H 'Content-Type: text/html; charset=UTF-8' If you send an AMP page with invalid AMP syntax, the message returned will tell you exactly what breaks your AMP page, and will point you to the specific place in the AMP reference where you can see the implementation guide for the broken element. curl -X POST --data-binary @invalid_amp.html -H 'Content-Type: text/html; charset=UTF-8' { "errors": [ { "code": "MANDATORY_TAG_MISSING", "col": 7, "error": "The mandatory tag 'link rel=canonical' is missing or incorrect.", "help": "", "line": 13 } ], "source": "POST", "valid": false, "version": "1485227592804" } Here’s a reference in python, and if you want to send html directly instead of a live webpage, replace line two with r = requests.post("', data=html) import requests u = '' r = requests.get('' + u) validation = r.json() if validation['valid']: print u, 'is valid' else: print u, 'failed!' for e in validation['errors']: print e Let us know what you think - you can send us feedback at amp-publisher@cloudflare.com. Whether you embed this tool into your build and continuous integration processes, or into your CMS workflows, we’re excited to hear how you use it.
https://blog.cloudflare.com/amp-validator-api/?utm_source=mobilewebweekly&utm_medium=email
CC-MAIN-2018-17
refinedweb
461
57
PIL vs OpenCV As I’m standing on the precipice of doing a bunch of image processing/classification, it occurs to me that I don’t know a whole lot about the available tools and packages for working with images. The following is a look at the two more-popular libraries. PIL and cv2 both support general image processing, such as: - Conversion between image types - Image transformation - Image filtering PIL (Pillow) The Python Image Library - Easy to use - Lightweight Use when you want to cut and resize images, or do simple manipulation. Installing Although you import the library as PIL, you have to install it using pip install Pillow Use from PIL import Image im = Image.open('images/daisy.jpg') im Documentation cv2 (Open CV) Used for Computer Vision, hence is a much more robust package. - Loaded with algorithms well-suited for data science and vision-based robotics. Although, it bears a warning that the library, annoyingly, defaults to reading/writing everything as BGR, instead of the intuitive RGB, because “reasons.” Here’s an excellent post trying to explain why. Installing Not to be outdone, getting ahold of cv2 is even more cryptic than PIL. pip install opencv-python Use Whereas PIL reads an image to an Image, cv2 cuts right to the chase and stores it as a np.array import cv2 im = cv2.imread('images/daisy.jpg') im.shape (533, 400, 3) Requiring us to lean on matplotlib to inspect the image %pylab inline plt.imshow(im) plt.axis('off'); Populating the interactive namespace from numpy and matplotlib Documentation Benchmarking This kaggle post illustrates that OpenCV blows Pillow out of the water when performing multiple, repeated transformations over multiple files.
https://napsterinblue.github.io/notes/python/images/libs/
CC-MAIN-2021-04
refinedweb
282
51.28
Barebones OpenGL Example All of the code referenced in this post can be found on GitHub. Back in college, my favorite class ended up being a graphics course caught by Colonel Eugene Ressler. In my entire life, I’d never seen anyone get so excited about the dot product. The class focused on a lot of theory behind graphics processing, and I unfortunately didn’t pick up what was taught well enough to be able to write an OpenGL program from scratch without referencing any other documents. Since then, when I’ve made the time to write a graphics program, I’ve usually just googled around until I found an existing program, and I would cut out what I didn’t need using a systematic yet ignorant approach. Furthermore, most of the online tutorials seem to be taught by people much smarter than me, and the examples rarely seem to be the absolute basics, and the language used is generally erudite. I would end up with a whole bunch of commands where I didn’t know what they did or if they were even necessary. I went ahead and made a very basic OpenGL program to be used as a template and a starting point for anyone looking to get started with OpenGL using the language I’m most acquainted with at this point (Python). The process at its most high level is to initialize a matrix, enslave humanity and use the heat their bodies generate to harvest power, define basic setup parameters, establish event callbacks for OpenGL, and start a main loop. Below I have the bare minimum necessities to set up a 3D program. I omitted as many default options as possible. Here is a barebones init function in its entirety: def init(self): glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(WIDTH, HEIGHT) glutCreateWindow("This is the window name") glClearColor(.1, .1, .1, 1.0) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) lightZeroColor = [0.0, 2.0, 0.8, 1.0] glLightfv(GL_LIGHT0, GL_AMBIENT, lightZeroColor) glMatrixMode(GL_PROJECTION) gluPerspective(60.0, WIDTH / HEIGHT, 1., 800.) glMatrixMode(GL_MODELVIEW) glutDisplayFunc(self.display) glutKeyboardFunc(self.key_pressed) glutTimerFunc(0, self.loop_func, 0) glutMainLoop() If we step through each individual component, we can dissect what everything is: Initialize the GLUT library: glutInit() Initialize with double buffering and a depth buffer. The depth buffer is used to determine what gets rendered on top of what. Otherwise objects will be shown in the order they are drawn with no regard to the Z axis: glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH) Create a window of size WIDTH by HEIGHT with the specified window name: glutInitWindowSize(WIDTH, HEIGHT) glutCreateWindow("This is the window name") Set the default background color for when we clear the screen: glClearColor(.1, .1, .1, 1.0) Render items with the Z axis considered (Enable the Z-axis that we initialized from glutInitDisplayMode): glEnable(GL_DEPTH_TEST) Enable lighting. Otherwise all of the shapes will be nothing but black and white: glEnable(GL_LIGHTING) Add ambient lighting to the scene. This is an absolute basic use of lighting. More lights can be added with GL_LIGHT1, etc, and more things can be done to establish the position and intensity of the light. There’s also different kinds of light, but I’m no light scientist: glEnable(GL_LIGHT0) lightZeroColor = [0.0, 2.0, 0.8, 1.0] glLightfv(GL_LIGHT0, GL_AMBIENT, lightZeroColor) Map points in a cube-like x, y, z area to a warped perspective view: glMatrixMode(GL_PROJECTION) gluPerspective(60.0, WIDTH / HEIGHT, 1., 800.) glMatrixMode(GL_MODELVIEW) All subsequent calls will now be applied to the MODELVIEW matrix stack. Now, define OpenGL event callbacks. OpenGL will call the respective functions once a particular event is triggered: glutDisplayFunc(self.display) glutKeyboardFunc(self.key_pressed) in 0 milliseconds, call self.loop_func with arbitrary value -1 (unused here): glutTimerFunc(0, self.loop_func, -1) Start the infinite event loop and call respective callbacks. And never return…. glutMainLoop() And that’s it! Sort of. The entire repository on GitHub has additional context, but from here, we’re free to draw as we please and do whatever. Here are the definitions of the callbacks I’d referenced earlier, starting with the display method: def display(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glPushMatrix() self.update_eye() for obj in self.all_drawable_objects: obj.draw() glPopMatrix() glutSwapBuffers() The process here is to clear the screen with our background color and clear the depth buffer. Clearing the background color is straightforward, but clearing the depth buffer needs to happen so that objects have a clean slate so that there is nothing “in front of them” blocking them from being rendered. glPushMatrix() and glPopMatrix() are used in conjunction with each other to push and pop the state of the matrix’s stack, represented as a stack. When we push items onto the matrix, any subsequent transformations are only applied to items rendered after the push. We can enlarge items, rotate them, add additional lights, etc, and those manipulations will only affect what is contained between the pushing and popping. Popping the matrix will return to the previous state. Keep in mind that the order of your transformations matter. glutSwapBuffers() is needed when we’re using double buffering. That is, items are not displayed on the screen until everything is ready to be rendered, and in the process of clearing and redrawing, we avoid any sort of blinking on the screen. update_eye() is another method defined below: def update_eye(self): # camera point # target point # up vector gluLookAt(SCALAR * math.cos(degrees_to_radians(self.ticks)), 5.0, # Z height SCALAR * math.sin(degrees_to_radians(self.ticks)), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) To me, this is one of the coolest things about OpenGL because we can easily create some sort of first person view. This simply defines a camera that we can move around that defines the perspective from which everything is rendered. We pass in the position, the point at which we’re looking at, and an x, y, z vector that defines what direction up is. The next callback I defined was to handle key presses: def key_pressed(self, key, x, y): if key == 'q' or ord(key) == 27: glutDestroyWindow(1) exit(0) Fairly self-explanatory. We can do whatever we want given the key that’s pressed. In this case, we quit if ‘q’ or ESC is hit. Finally, we defined a loop function that’s repeatedly called by OpenGL: def loop_func(self, value): if random.random() < 0.08: self.all_drawable_objects.append(Coin()) for obj in self.all_drawable_objects: obj.tick() self.all_drawable_objects = [obj for obj in self.all_drawable_objects if obj.y_offset < 50] self.ticks += TICK_INCR glutPostRedisplay() glutTimerFunc(30, self.loop_func, 0) I added some of my own logic here, but the relevant takeaway is that we call glutPostRedisplay() to re-render everything on the scene. The output of this program simply draws a bunch of three dimensional disks that float up and rotate about their respective axes. The camera rotates around the floating disks:
http://scottlobdell.me/2014/05/barebones-opengl-example/
CC-MAIN-2019-26
refinedweb
1,159
54.52
Shopify Shopify is one of the best and very popular eCommerce platforms on the market today. COVID-19 pandemic accelerated shift to eCommerce by 5 years and most analysts predict that the growing trend of online shopping will stay even when the pandemic is over. Happy accident Like so many business success stories, Shopify's creation was something of a happy accident. This is the story: Founder Tobi Lutke opened an online snowboard shop in 2004 but found that the available e-commerce software at the time was unwieldy and expensive, so he made his own. Two years later, after receiving positive feedback from other online entrepreneurs who had asked to license the software, Shopify was born and Lutke pivoted from snowboards to e-commerce software. Since its Initial public offering (IPO) five years ago, the stock has returned nearly 5,000%, full story can be found here Nasdaq. Shopify offers plugins and APIs, including "Storefront API"( Shopify's modern GraphQL API) that can be used to implement shopping, account management, and checkout flow in a portable frontend. Shopify also offers multiple responsive themes out of the box, based on Liquid templating. Liquid - template language The Liquid is an open-source template language created by Shopify and written in Ruby. It is the backbone of Shopify themes and is used to load dynamic content on storefronts. Liquid is used in many different environments, created for use in Shopify stores but also used extensively on Jekyll (static site generator) websites and many hosted web applications such as Zendesk, Salesforce desk, 500px, the full list can be found here. Shopify Themes Shopify is considered one of the easiest platforms. It supports the headless context of the eCommerce approach via the Storefront API. The Storefront API provides unauthenticated access to customers, checkouts, product collections, and other store resources that you can use to build purchasing experiences on merchant storefronts. Shopify Themes control the appearance of merchants’ online stores. Liquid is required to work on Shopify Themes and developers use it along with standard HTML, CSS, and JavaScript, to create any look and feel their clients want. Step 1: Install Theme Kit Installation macOS Installation Use Homebrew to install Theme Kit by running the following commands. brew tap shopify/shopify brew install themekit Node Package If you want to integrate Theme Kit into your build process, there is a Node wrapper for Theme Kit on npm: npm install @shopify/themekit Step 2: Setting up API credentials Get API Access Once Theme Kit is installed, we’ll need a few things to connect our local theme to your existing Shopify store. We’ll need an API key, password, and theme ID. NYC Candy Store Once login to the Shopify account I created NYC Candy Store and those are account details: URL: nyc-candy-store.myshopify.com Login: nyc-candy-store.myshopify.com/admin Adding free Brooklyn Theme: This is the NYC Candy Store Layout : Brooklyn Theme documentation can be found here. As we mention above Liquid is required to work on Shopify Themes and this is the section where we need to edit and customize: Liquid syntax Liquid has a syntax that interacts with variables and includes constructs such as output and logic. Liquid constructs are easy to recognize, and can be distinguished from HTML by two sets of delimiters: the double curly brace delimiters {{ }}, which denote output, and the curly brace percentage delimiters {% %}, which denote logic and control flow. There are three main features of Liquid code: Objects, Tags and Filters. Objects In a theme template, objects are wrapped in double curly brace delimiters {{ }}, and look like this: {{ product.title }} In this example, the product is the object, and the title is the property of that object. Each object has a list of associated properties. The {{ product.title }} Liquid object can be found in the product template of a Shopify theme.: $19.99</h2> {% else %} <h2 class="sold-out">Sorry, this product is sold out.</h2> {% endif %} Filters Liquid filters are used to modify the output of numbers, strings, objects, and variables. They are placed within an output tag {{ }}, and are denoted by a pipe character |. A simple example is the capitalize string filter: {{ 'hello!' | capitalize }} The filter modifies the string by capitalizing it. The output will be: Hello! Here is Shopify for Developers documentation. To connect with me Please check my Github, LinkedIn and follow me on Twitter. Thanks for reading! Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/ivanadokic/shopify-theme-ecommerce-4114
CC-MAIN-2021-25
refinedweb
740
52.49
More RSS for Java In my previous article, we looked at the creation of a simple RSS feed using the Informa API. In this article, we are going to refine the earlier solution and look at some other aspects of the Informa API and the RSS specification, and take a brief look at the OPML format. Handling Updates the RSS Way One of the main problems with the solution proposed in the first article is that whenever a feed was requested, the RSS file was downloaded from the source server and parsed before being displayed. A more sensible approach would be to cache loaded feeds and periodically update them. Now, we could just take a guess and assume that a feed will update every hour and handle the update ourselves, and indeed this would be a sensible approach to take, if not for the fact that some RSS feeds can provide this information for us. With the RSS 0.91 specification, three update-related elements were added: <ttl>, <skiphours>, and <skipdays>. The <ttl> element specifies the time-to-live for the feed – the number of minutes that a feed can be cached before updating the feed. The <skiphours> and <skipdays> elements defined on which hours and days a feed will not be created. Let's look at a fragment of an RSS 0.91 file for how these elements might be used: <ttl>60</ttl> <skiphours> <hour>0</hour> <hour>1</hour> <hour>2</hour> <hour>3</hour> <hour>4</hour> <hour>5</hour> <hour>6</hour> <hour>22</hour> <hour>23</hour> </skiphours> <skipdays> <day>Saturday</day> <day>Sunday</day> </skipdays> Here, the <ttl> value of 60 specifies that the feed may be cached for 60 minutes. The nested <hour> elements inside of the <skiphours> elements tells us that no feed will be generated between 10 at night and six in the morning, and the <skipdays> that no feed will be generated on Saturday or Sunday. Seems simple so far? Well, RSS gives us another way to specify this kind of information in the form of an external module. Modules enable an RSS file (conforming to 1.0 or greater of the RSS specification) to be extended with additional elements that can add extra functionality to a feed. The Syndication module ( sy) adds information concerning update-frequency information. Let's look at a snippet from an RSS file using the Syndication module: <rss version="2.0" xmlns:sy="" xmlns: … <sy:updatePeriod>daily</sy:updatePeriod> <sy:updateFrequency>4</sy:updateFrequency> <sy:updateBase>2003-08-03T12:00</sy:updateBase> … The xmlns:sy= line imports the Syndication module into the sy namespace (much as you would import a taglib into a JSP); all Syndication module tags will now be prefixed with an sy:. The <sy:updatePeriod>daily</sy:updatePeriod> and <sy:updateFrequency>4</sy:updateFrequency> tags let us know that the file is updated four times daily, with <sy:updateBase>2003-08-03T12:00sy:updateBase> giving us a base time from which to work out the updates. So why do we have two different ways of letting us know the same thing? Well, the Syndication module was introduced as it was felt that the existing <skiphours> and <skipdays> elements were overly verbose and not really flexible enough. These older elements are unlikely to be removed from the specification, but it's likely that newer RSS feeds will start to phase out their use in favor of the features provided by the Syndicaton module. Handling Subscription Updates with Informa The tag detailed in the previous article had a major flaw – each time the tag was requested, the feed was downloaded and parsed. We are going to add a new class to handle the selective updating of feeds based on the provided update information. Support for <ttl>, <skiphours>, and <skipdays> may be added in a future version of Informa, but it already supports the newer Syndication module tags. You should be familiar with the basics of the ChannelIF interface from the previous article. The 0.3.0 Informa release added new methods to match the tags provided by the Syndication module -- getUpdateBase(), getUpdateFrequency(), and getUpdatePeriod(). Now in and of itself, this wouldn't give us too much in the way of functionality -- we still need something that can use these attributes accordingly. Luckily, the latest version of Informa adds a new FeedManager to manage multiple classes, which also handles the caching of requested feeds. It's worth noting that if the feed in question doesn't supply time-to-live information, then sensible defaults are used. Let's take a look at some of the FeedManager methods in a little more detail. public static void setChannelBuilder(ChannelBuilderIF chBuilder) public ChannelBuilderIF getChannelBuilder() These methods set and return the ChannelBuilder to be used when loading a feed. As you may remember from the previous article, different ChannelBuilderIF implementations can be used to create storage for the feed (0.3.0 added a Hibernate implementation). We won't have to worry too much about this at present -- by default, the FeedManager uses the default implementation, which creates a an in-memory feed. public FeedIF addFeed(String feedUri) throws FeedManagerException public void removeFeed(String feedUri) The addFeed method adds a feed to the manager and returns it. If there is a problem finding or parsing the file specified, then a FeedManagerException will be thrown. public FeedIF getFeed(String feedUri) throws FeedManagerException Finally, the getFeed method returns a managed feed. So far, this looks like a simple store for a series of RSS feeds. However, behind the scenes, the FeedManager class is actually taking into account any defined time-to-live parameters. After the initial request for a feed, the FeedManager maintains a cache of the feed. If another request is made for the feed before it should be refreshed, the cached copy is returned; otherwise, the feed is reloaded and parsed. It's worth noting here the use of the FeedIF class -- the FeedIF class contains metadata concerning a Channel, information such as the last time the data was updated, or the copyright of the Channel. The FeedManager class will update the lastUpdated property of the FeedIF when it reloads the channel. This makes it easy for you to display the last-update times in your applications. Now we'll look at how our custom tag from the last article will look after being updated to use the FeedManager: public class ManagedRssFeedTag extends TagSupport { private String uri; private String var; private ChannelIF channel; private static FeedManager feedManager = new FeedManager(); /** * Returns the name of the bean used to store * the Rss Feed */ public String getVar() { return var; } /** * Specifies the name of the bean that will * hold the channel */ public void setVar(String var) { this.var = var; } /** * Retrieves the URI for the feed */ public String getUri() { return uri; } /** * Sets the URI for the feed */ public void setUri(String uri) { this.uri = uri; } public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); try { FeedIF feed = feedManager.addFeed(getUri()); pageContext.setAttribute(getVar(), feed); } catch (FeedManagerException e) { throw new JspException(e); } return EVAL_BODY_INCLUDE; } } Comparing this to the previous version of this tag, you can see that the only major code changes are that we are now using the FeedManager to get the feed, rather than parsing it directly in the doStartTag method, and that we are now dealing with a FeedIF object rather than the previous use of the ChannelIF code. This greatly simplifies the tag's code itself, and also has the effect of giving us the efficiencies provided by using the FeedManager. The changes to the JSP are likewise quite trivial: <rss:readFeed <IMG src="<c:out"> <A HREF="<c:out"> <strong><c:out</strong></A> <ol> <c:forEach <li><A HREF="<c:out"> <c:out</A></li> </c:forEach> </ol> [Last Updated: <c:out] </rss:readFeed> Here we display a list of the posts made in the channel as before; however, to access the channel itself, we are now going via the feed bean. As we have the metadata associated with the channel, we also display the time the channel was last loaded -- as we covered before, the FeedManager will only reload the feed according to the time-to-live parameters specified in the RSS file itself. Let's see how our finished tag looks in a web page. Figure 1 shows the latest software releases from Freshmeat: Figure 1. Output from RSS tag OPML Overview The Outline Processor Markup Language (OPML) was developed by UserLand Software in 2000. This XML format has been designed to allow the transfer of outline-structured information, such as MP3 playlists, and can even be used for editing documents (see outliners.com for more detail). One of the major uses for the OPML format has been to manage a collection of RSS feeds -- this is unsurprising, given UserLand Software's involvement in the RSS specification. We will look at processing an OPML file used to describe a list of RSS feeds to which someone has subscribed. For example, the FeedDemon aggregator program allows the export and import of OPML files -- this can be handy when moving between different aggregator services, or keeping desktop aggregators in sync between the office and home. Let's take a look at an OPML file produced from FeedDemon: <?xml version="1.0"?> <opml version="1.1"> <head><title>Favorite Channels</title></head> <body> <outline text="Java.net" title="Slashdot" type="rss" version="RSS" xmlUrl="" htmlUrl="" description="Java.net"/> <outline text="Wired News" title="Wired News" type="rss" version="RSS" xmlUrl="" htmlUrl="" description="Wired"/> </body> </opml> As you can see, it's very simple indeed. Each feed is detailed in an outline element. The type field lets us know what kind of data we're referencing -- here it's RSS, but could be an MP3 audio format. The xmlUrl gives us a pointer to where the XML format of the data can be found (the URL for the RSS of the feed), with the htmlUrl element describing where the HTML format of the feed can be found. Finally, the text attribute details how the outline should be displayed, with the description attribute giving more detailed information. Informa OPML Support Informa adds some simple support for loading OPML files. The OPMLParser is capable of parsing an OPML file and producing a series of FeedIF objects. Let's look at a simple piece of code to load and list the feeds and their URLs referenced in the file above. try { Collection feeds = OPMLParser.parse(""); for (Iterator iter = feeds.iterator(); iter.hasNext(); ) { FeedIF feed = (FeedIF) iter.next(); System.out.print("Feed: " + feed.getTitle()); System.out.println(" ," + feed.getLocation().toString()); } } catch (Exception e) { e.printStackTrace(); } As we saw earlier, using the FeedManager class can greatly simplify the handing of multiple feeds. The FeedManager class adds a convenience method to allow us to add all of the feeds detailed in an OPML file into the manager at once. The addFeeds method takes as its argument the URI of an OPML file. It parses the file, identifies all of the referenced RSS feeds, and then parses and loads them into the FeedManager: public Collection addFeeds(String opmlFileUri) We will be using this method to create a new JSP tag. A Blog Roll Tag We are now going to use the FeedManager class to create a Blog Roll tag. A Blog Roll is a list of Blogs that someone reads regularly; adding a tag to a web site can be a great way of personalizing a portal. Before we look closely at its implementation, let's look how our tag is going to be used: <rss:blogRoll <c:forEach <li> <a href="<c:out"> <c:out</a>, Last Updated: <c:out </li> </c:forEach> </rss:blogRoll> The blogRoll tag creates as its output a Collection holding FeedIF beans, each one representing an RSS Channel and some metadata concerning the Channel itself. The required var attribute specifies the name of the created Collection. Now, once we've loaded the feeds, we could process them in a series of ways. Here, we use the JSTL forEach tag to loop through the feeds, creating a list of links to the home pages for the feeds. For good measure, we also print the dates of the feeds, so we can see when each one was last updated. The implementation of this tag is almost trivially simple. public class BlogRollTag extends TagSupport { private static FeedManager feedManager = new FeedManager(); private String opmlUri; private String var; private ChannelIF channel; /** * Returns the name of the bean used to store the Feeds */ public String getVar() { return var; } /** * Specifies the name of the bean that will * hold the feeds */ public void setVar(String var) { this.var = var; } /** * Retrieves the URI of the OPML file to read */ public String getOpmlUri() { return opmlUri; } /** * Sets the URI of the OPML file to read */ public void setOpmlUri(String uri) { this.opmlUri = uri; } public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); try { Collection feeds = feedManager.addFeeds(getOpmlUri()); pageContext.setAttribute(getVar(), feeds); } catch (FeedManagerException e) { throw new JspException(e); } return EVAL_BODY_INCLUDE; } } The call to FeedManager.addFeeds accesses the OPML file specified in the opmlUri attribute, loads all of the referenced feeds (or simply retrieves the already loaded feeds in the FeedManager itself), and returns the collection. We then store the returned Collection so it can be accessed in the page. The result is shown in Figure 2. Figure 2. The Blog Roll tag Note that, depending on how many feeds you have in your OPML file, the tag could take a while to run the first time. This is because each RSS file is being downloaded, parsed, and added to the FeedManager. Subsequent calls to load the same OPML file will be very quick, as the FeedManager only reloads the feeds after a certain period of time. When the feeds get reloaded, the Last Updated time will change accordingly. A sensible approach might be to load the OPML file into your FeedManager on startup to eliminate this delay when the user first accesses the page. Conclusion We have looked at Informa's FeedManager class and seen how it can ease the management of multiple feeds. We have also taken a brief look at the OPML file format and how it can be used with Informa to manage a series of blogs. Next time, we'll look at some of the features of Informa that are focused more on the authors of feed aggregators, and see how they can be used to enrich a web application. - Login or register to post comments - Printer-friendly version - 4170 reads
http://today.java.net/pub/a/today/2003/10/30/rss.html
crawl-003
refinedweb
2,434
58.42
Abandoning a package From HaskellWiki If you are the author or maintainer of a package, and wish to step down, there are a few steps. To just orphan a package, you can use the maintainers page (at) to edit the maintainers group to remove all maintainers including yourself. If you think the package should no longer be used by anyone, you can deprecate the package, optionally providing a list of other packages which you think supersede it. You may wish to also orphan it in this case, to allow others to take it over or claim the namespace. Finally, if you think that the package is still good and useful, but no longer have the time to maintain it, you can reach out via the usual community channels (the haskell-cafe mailinglist available via, reddit, etc.) to solicit volunteers to step in. Once you've found volunteers to step in, you should add them to the maintainers group to allow them upload rights.
https://wiki.haskell.org/index.php?title=Abandoning_a_package&oldid=61226
CC-MAIN-2018-09
refinedweb
163
65.05
Inside .NET Managed Providers Dino Esposito Wintellect October 9, 2001 When compared to full-fledged OLE DB providers, Microsoft .NET managed providers have a lot to offer. First off, they deliver a simplified data access architecture that often results in improved performance without the loss of functional capabilities. Furthermore, .NET managed providers directly expose provider-specific behavior to consumers through methods and properties. They also involve a much smaller set of interfaces than OLE DB providers. Last but not least, .NET managed providers work within the boundaries of the Common Language Runtime (CLR) and require no COM interaction. For SQL Server 7.0 and SQL Server 2000, the managed provider hooks up directly to the wire level, gaining a substantial performance advantage. The functionalities that a .NET data provider supplies may fall into a couple of categories: - Support of the DataSet class through an implementation of the methods of the IDataAdapter interface - Support of connected data access, which includes classes representing connections, commands, and parameters The simplest flavor of a data provider interacts with callers only through the DataSet, both in reading and writing. In the other case, you can control connections, transactions, and execute direct commands, regardless of the SQL language. The figure below shows the class hierarchy of the two standard managed providers in .NET—OLE DB providers and for SQL Server. Figure 1. Managed providers connect, execute commands, and get data in a data source-specific way. The objects that wrap connections, commands, and readers are provider-specific and may result in a slightly different set of properties and methods. Any internal implementation is rigorously database-aware. The only class that is out of this schema is the DataSet. The class is common to all providers and works as a generic container for disconnected data. The DataSet class belongs to a kind of super-namespace called System.Data. Classes specific of a data provider belong to the specific namespace. For example, System.Data.SqlClient and System.Data.OleDb belong to a specific namespace. The schema in the figure above is rather basic, though not simplistic. It is simplified because it does not include all the classes and the interfaces involved. The figure below is a bit more accurate. Figure 2. Classes involved with a managed provider The table below shows the list of the interfaces that make a .NET provider. Of all of interfaces, only IDataAdapter is mandatory and must be present in every managed provider. If you don't plan to implement one of the interfaces, or one method of a given interface, expose the interface anyway, but throw a NotSupportedException exception. Wherever possible, avoid providing no-op implementations of methods and interfaces as this may result in data corruption, particularly with the commit/rollback of transactions. For example, providers are not required to support nested transactions even though the IDbTransaction interface is designed to allow also for this situation. Before going any further with the explanation of the role that each class plays in the overall workings of a .NET provider, let me say a few words about the naming convention that a managed provider is recommended to utilize. This is useful if you happen to write your own providers. The first guideline regards the namespace. Make sure you assign your own managed provider a unique namespace. Next, prefix classes with a nickname that identifies the provider throughout any internal and client code. For example, use class names like OdbcConnection, OdbcCommand, OdbcDataReader, and so on. In this case, the nickname is Odbc. In addition, try to use distinct files to compile distinct functionalities. Implementing a Connection The provider connection class inherits from IDbConnection and must expose the ConnectionString, State, Database, and ConnectionTimeout properties. The mandatory methods are Open, Close, BeginTransaction, ChangeDatabase, and CreateCommand. You are not strictly required to implement transactions. The following code snippet gives you an idea of the code used to implement a connection. namespace DotNetMyDataProvider { public class MyConnection : IDbConnection { private ConnectionState m_state; private String m_sConnString; public MyConnection () { m_state = ConnectionState.Closed; m_sConnString = ""; } public MyConnection (String connString) { m_state = ConnectionState.Closed; m_sConnString = connString; } public IDbTransaction BeginTransaction() { throw new NotSupportedException(); } public IDbTransaction BeginTransaction(IsolationLevel level) { throw new NotSupportedException(); } } } You should provide at least two constructors, one being the default that takes no argument. The other recommended constructor would accept only the connection string. When returning the connection string through the ConnectionString property, make sure you always return exactly what the user set. The only exception might be constituted by any security-sensitive information that you might want to remove. The items you recognize and support in the connection string are up to you, but standard names should be used whenever it makes sense. The Open method is responsible for opening the physical channel of communication with the data source. This should happen not before the Open method is called. Consider using some sort of connection pooling if opening a connection turns out to be an expensive operation. Finally, if the provider is expected to provide automatic enlistment in distributed transactions, the enlistment should occur during Open. An important point that makes ADO.NET connections different from, say, ADO connections, is that you are requested to guarantee that a connection is created and opened before any command can be executed. Clients have to explicitly open and close connections, and no method will open and close connections implicitly for the client. This approach leads to a sort of centralization of security checks. In this way, checks are performed only when the connection is obtained, but the benefits apply to all other classes in the provider that happen to work with connection objects. You close the connection with the method Close. In general, Close should simply detach the connection and return the object to the pool, if there is a pool. You could also implement a Dispose method to customize the destruction of the object. The state of a connection is identified through the ConnectionState enum data type. While the client works over the connection, you should ensure that the internal state of the connection matches the contents of the State property. So, for instance, when you are fetching data, set the connection's State property to ConnectionState.Fetching. The ODBC Connection Let's see how a concrete .NET managed provider turns these principles into practice. For this example, I'll take into account the newest managed provider that appeared, though only in early beta releases. I'm talking about the .NET provider for ODBC data sources. You probably noticed already that the .NET provider for OLE DB does not support the DSN token in the connection string. Such a name is required to automatically select the MSDASQL provider and go through ODBC sources. The following code is how ODBC.NET declares its connection class: The OdbcConnection object utilizes ODBC-typical resources, such as environment and connection handles. These objects are stored internally using class private members. The class provides for both Close and Dispose. In general, you can close a connection with either method, but do it before the connection object goes out of scope. Otherwise, the freeing of internal memory (that is, ODBC handles) is left to the garbage collector, whose timing you cannot control. For connection pooling, the OdbcConnection class relies on the services of the ODBC Driver Manager. To play with the ODBC.NET provider (currently in beta 1), you should include System.Data.Odbc. At this time, the provider is guaranteed to work with drivers for JET, SQL Server, and Oracle. Implementing a Command The command object formulates a request for some actions and passes it on to the data source. If results are returned, the command object is responsible for packaging and returning results as a tailored DataReader object, a scalar value, and/or through output parameters. According to the special features of your data provider, you can arrange results to appear in other formats. For example, the managed provider for SQL Server lets you obtain results in XML format if the command text includes the FOR XML clause. The class must support at least the CommandText property and at least the text command type. Parsing and executing the command is up to the provider. This is the key aspect that makes it possible for a provider to accept any text or information as a command. Supporting command behaviors is not mandatory and, if needed, you can support more, completely custom behaviors. Within a command, the connection can be associated with a transaction. If you reset the connection—and users should be able to change the connection at any time—then first null out the corresponding transaction object. If you support transactions, then when setting the Transaction property of the command object, consider additional steps to ensure that the transaction you're using is already associated with the connection the command is using. A command object works in conjunction with two classes representing parameters. They are xxxParameterCollection, which is accessed through the Parameters property, and xxxParameter, which represents a single command parameter stored in the collection. Of course, the xxx stands for the provider-specific nickname. For ODBC.NET, they are OdbcParameterCollection and OdbcParameter. You create provider-specific command parameters using the new operator on the parameter class or through the CreateParameter method of the command object. Newly created parameters are populated and added to the command's collection through the methods of the Parameters collection. The module that provides for command execution is then responsible for collecting data sets through parameters. Using named parameters (as the SQL Server provider does) or the ? placeholder (similar to the OLE DB provider) is up to you. You must have a valid and open connection to execute commands. Execute the commands using any of the standard types of commands, which are ExecuteNonQuery, ExecuteReader, and ExecuteScalar. Also, consider providing an implementation for the Cancel and Prepare methods. The ODBC Command The OdbcCommand class does not support passing named parameters with SQL commands and stored procedures. You must resort to the ? placeholder instead. At least in this early version, it does not support Cancel and Prepare either. As you can expect, the ODBC .NET provider requires that the number of command parameters in the Parameters collection matches the number of placeholders found within the command text. Otherwise, an exception is thrown. The line below shows how to add a new parameter to an ODBC command and assign it at the same time. Notice that the provider defines its own set of types. The enumeration OdbcType includes all and only the types that the low-level API of ODBC can safely recognize. There is a close match between the original ODBC types, such as SQL_BINARY, SQL_BIGINT, or SQL_CHAR, and the .NET types. In particular, the ODBC type SQL_CHAR maps to the .NET String type. Implementing a DataReader A data reader is a kind of connected, cache-less buffer that the provider creates to let clients read data in a forward-only manner. The actual implementation of the reader is up to the provider's writer. However, a few guidelines should be taken into careful account. First off, when returned to the user, the DataReader object should always be open and positioned prior to the first record. In addition, users should not be able to directly create a DataReader object. Only the command object must create and return a reader. For this reason, you should mark the constructors as internal. You should use the keyword internal in C# and the keyword friend in Visual Basic® .NET The DataReader must have at least two constructors—one taking the result set of the query, and one taking the connection object used to carry the command out. The connection is necessary only if the command must execute with the CommandBehavior.CloseConnection style. In this case, the connection must be automatically closed when the DataReader object is closed. Internally, the resultset can take any form that serves your needs. For example, you can implement it as an array or a dictionary. A DataReader should properly manage the property RecordsAffected. It is only applicable to batch statements that include inserts, updates, or deletes. It normally does not apply to query commands. When the reader is closed, you might want to disallow certain operations and change the reader's internal state, cleaning up internal resources like the array used to store data. The DataReader's Read method always moves forward to a new valid row, if any. More importantly, it should only place the internal data pointer forward, but makes no reading. The actual reading takes place with other reader-specific methods, such as GetString and GetValues. Finally, NextResult moves to the next result set. Basically, it copies a new internal structure into a common repository from which methods like GetValues read. The ODBC DataReader As all the reader classes, OdbcDataReader is sealed and not inheritable. Methods of the class that have access to column values automatically coerce the type of data they return to the type of data that was initially retrieved from that column. The type used the first time to read one cell from a given column is used for all the other cells of the same column. In other words, you cannot read data from the same column as string and long in successive times. When the CommandType property of a command object is set to StoredProcedure, the CommandText property must be set using the standard ODBC escape sequence for procedures. Unlike other providers, the simple name of the procedure is not enough for the ODBC.NET provider. The following pattern represents the typical way of calling stored procedures through ODBC drivers. The string must be wrapped by {...} and have the keyword call to precede the actual name and the list of parameters. Implementing a DataAdapter A full-fledged .NET data provider supplies a data adapter class that inherits both IDbDataAdapter and DbDataAdapter. The class DbDataAdapter implements a data adapter designed for use with a relational database. In other cases, though, what you need is a class that implements the IDataAdapter interface and copies some disconnected data to an in-memory programmable buffer like the DataSet. Implementing the Fill method of the IDataAdapter interface, in fact, is in most cases sufficient to return disconnected data through a DataSet object. Typical constructors for the DataAdapter object are: Classes that inherit from DbDataAdapter must implement all the members, and define additional members in case of provider-specific functionality. This ends up requiring the implementation of the following methods: The required properties are: - TableMappings (which defaults to the empty collection) - MissingSchemaAction (which defaults to Add) - MissingMappingAction (which defaults to Passthrough) You can provide as many implementations of the Fill method as needed. Table mappings govern the way in which source tables (that is, database tables) are mapped to DataTable objects in the parent DataSet. Mappings take into account table names as well as columns names and properties. Schema mapping, instead, regards the way in which columns and tables are treated when it comes to adding new data to existing DataSets. The default value for the missing mapping property tells the adapter to create in-memory tables that looks like source tables. The default value for the missing schema property handles possible issues that arise when the DataTable objects are actually populated. If any of the mapped elements (tables and columns) are missing in the target DataSet, then the value of MissingSchemaAction suggests what to do. In a certain way, both MissingXXX properties are a kind of exception handler. The value Add forces the adapter to add any table or column that proves to be missing. No key information is added unless another (AddWithKey) value is assigned to the property. When an application calls the Update method, the class examines the RowState property for each row in the DataSet and executes the required INSERT, UPDATE, or DELETE statement. If the class does not provide UpdateCommand, InsertCommand, or DeleteCommand properties, but implements IDbDataAdapter, then you can try to generate commands on the fly or raise an exception. You could also provide a made-to-measure command builder class to help with the command generation. The ODBC provider supplies the OdbcCommandBuilder class as a means of automatically generating single-table commands. The OLE DB and SQL Server providers have provided similar classes. If you need to update cross-referenced tables, then you might want to use stored procedures or ad-hoc SQL batches. In this case, just override the InsertCommand, UpdateCommand, and DeleteCommand properties to make them run the command object you indicate. Summary The functionality that a .NET data provider offers can be divided into two main categories: - Support for the disconnected DataSet object - Support for connected data access, including connections, transactions, commands, and parameters Data providers in .NET support DataSet objects through an implementation of the IDataAdapter interface. They may also support parameterized queries by implementing the IDataParameter interface. If you can't afford disconnected data, then use .NET data readers through the IDataReader interface.
http://msdn.microsoft.com/en-us/library/ms810268.aspx
CC-MAIN-2013-20
refinedweb
2,830
55.84
Hello all, I am having problems figuring out a C++ homework problem. He wanted us to include a flag controlled while loop - which is the part I'am struggling with. He wants an invalid out put for lower case options. I am using Microsoft VS 2012. The program is not crashing but when I get to the hours, it just keeps prompting the user to 'Enter hours" I think I have specified what my true and false scenarios are for the "while loops" My program compiles and builds I just cant get past the hours option. I am new so I am sure there are errors, I described this in as much detail as I could. Thank you in advance for yall's help! The problem description is : An Internet service provider has three different subscription packages for its customers: Package A: For $15 per month with 50 hours of access provided. Additional hours are $2.00 per hour over 50 hours. Assume usage is recorded in one-hour increments, Package B: For $20 per month with 100 hours of access provided. Additional hours are $1.50 per hour over 100 hours. Package C: For $25 per month with 150 hours access is provided. Additional hours are $1.00 per hour over 150 hours Assume a 30-day billing cycle. Code://Internet Service Providers Program3 #include <iomanip> #include <iostream> using namespace std; int main() { //Variables char pkg(0); int hrs(0); double total, charges(0); //Input cout<<"Enter the Internet Package you choose: "; //Select Package cin>>pkg; bool flag = true; if(pkg == 'A'||pkg == 'B'|| pkg == 'C') { flag = true; } else if(pkg == 'a' || pkg =='b' || pkg== 'c') { flag = false; } while (flag == true) { if(pkg == 'A'|| pkg == 'B'|| pkg == 'C') cout<<"Enter hours: "; cin>>hrs; } while (flag == false) { if(pkg == 'a' || pkg =='b' || pkg== 'c') cout<<"Invalid package option: Enter valid package: "; cin>>pkg; } //Plan A if(pkg == 'A' && hrs>=50) { charges = 15.00*50; total = charges + (hrs-50)*2.00; cout<<"Your total for Plan A is: $ "<<total << "\n\n"; } //Plan B else if (pkg == 'B' && hrs>=100) { charges=20.00*100; total = charges + (hrs-100)*1.50; cout<<"Your total for Plan B is: $ "<<total << "\n\n"; } //Plan C else if (pkg == 'C' && hrs>=150) { charges=25.00*150; total = charges + (hrs-150*1.00); cout<<"Your total for Plan C is: $ "<<total <<endl<<endl; } else; return 0; }
http://forums.devshed.com/programming/951748-help-homework-last-post.html
CC-MAIN-2018-13
refinedweb
399
72.97
Opened 9 years ago #5583 new defect No graph when no components are defined Description If there are no components defined there will be no burndown visible. That's very surprising and difficult to figure out without looking at the code. Would be nice to have a fix for that. Code (burndown.py), problem marked by XXX: def update_burndown_data(self): db = self.env.get_db_cnx() cursor = db.cursor() # today's date today = format_date(int(time.time())) milestones = dbhelper.get_milestones(db) components = dbhelper.get_components(db) for mile in milestones: if mile['started'] and not mile['completed']: # milestone started, but not completed XXX PROBLEM>>> for comp in components: XXXXX HERE: WHAT IF NO COMPONENTS?? XXXXX sqlSelect = "SELECT est.value AS estimate, ts.value AS spent "\ "FROM ticket t "\ Thanks! Attachments (0) Change History (0) Note: See TracTickets for help on using tickets.
https://trac-hacks.org/ticket/5583
CC-MAIN-2018-09
refinedweb
139
53.58
BioSQL is a Bioperl-based system for storing record-oriented biological objects, including GenBank/EMBL sequences and PubMed records, in a relational database. GBrowse provides support for viewing sequence annotation data stored in BioSQL. The support is functional, but not heavily tested, so it may still contain bugs. Make sure that Gbrowse is correctly installed. Make sure that you have the latest version of Bioperl-db. Make sure that you have the latest version of Bioperl-schema. You need to have a database (MySQL, Postgresql, Oracle) that is supported by the Perl DBI interface. If you plan to use MySQL, run create_mysql_db.pl (it is included in the bioperl-schema distribution). Other databases would use similar SQL commands. Take a Genbank file and call the script load_seqdatabase.pl from the bioperl distribution to load the data. For example, load_seqdatabase.pl --host somewhere.edu --dbname biosql \ --namespace bioperl --format genbank \ your_genbank_file The value of "namespace" is arbitrary. Point a gbrowse configuration file to this database. See include 06.biosql.conf for an example. The only nontrivial parameters in it are "namespace" and "version". For namespace, use the same value that you specified when you uploaded data. The version number is contained in the Genbank file. Until these files are uploaded into the bioperl CVS, put the attached files on your system in a directory accessible to Perl, for example, into /usr/lib/perl5/site_perl/5.8.1/ Please send requests for help to simonf@cshl.edu Vsevolod (Simon) Ilyushchenko simonf@cshl.edu
http://search.cpan.org/~lds/GBrowse-2.55/docs/pod/BIOSQL_ADAPTER_HOWTO.pod
CC-MAIN-2016-18
refinedweb
251
53.37
Hash table (Java) This is an implementation of a hash table. For all practical purposes, you should use Java's HashMap class instead. [edit] Description This implementation uses generics to allow keys and values to be any class type. The size is specified when creating the hash table. The hash function used is the default hashCode() method in Java. To handle hash collisions, each entry in the table is a reference to a linked list, so that multiple values with the same hash can be stored. Automatic resizing is not included in this implementation. A function for manual resizing is provided. [edit] Structures and functions Hashtbl is the class for the hash table. It contains all information necessary to manipulate and look up the elements. All hash table functions are methods of Hashtbl. <<Hashtbl class>>= public class Hashtbl<K,V> { private Hashnode<K,V>[] nodes; Hashtbl methods main method } The nodes member of Hashtbl is an array of references to the first element of a linked list. This element is represented by the class Hashnode: <<Hashnode class>>= class Hashnode<K,V> { K key; V data; Hashnode<K,V> next; public Hashnode(K k, V v, Hashnode<K,V> n) { key = k; data = v; next = n; } } These are the functions used to manipulate and look up the hash table: <<Hashtbl methods>>= Hashtbl constructor get index method insert method remove method get method resize method <<Hashtbl.java>>= Hashnode class Hashtbl class [edit] Initialisation The constructor of Hashtbl sets up the initial structure of the hash table. The user specified size will be allocated and elements are automatically initialized to null. <<Hashtbl constructor>>= @SuppressWarnings("unchecked") public Hashtbl(int size) { nodes = new Hashnode[size]; } (Due to issues with how arrays were designed, we cannot create an array of a generic type, so we perform an unchecked conversion, and then suppress the warning.) [edit] Adding a new element We will add a method for obtaining the index into our table for a particular hash key. To make sure the hash value is not bigger than the size of the table, the result of the user provided hash function is used modulo the length of the table. We need the index to be non-negative, but the modulus operator (%) will return a negative number if the left operand (the hash value) is negative, so we have to test for it and make it non-negative. <<get index method>>= private int getIndex(K key) { int hash = key.hashCode() % nodes.length; if (hash < 0) hash += nodes.length; return hash; } <<insert method>>= public V insert(K key, V data) { int hash = getIndex(key); We have to search the linked list to see if data with the same key has been inserted before, in which case we just replace the data member of the Hashnode object. <<insert method>>= // System.err.printf("insert() key=%s, hash=%d, data=%s\n", key, hash, data); for (Hashnode<K,V> node = nodes[hash]; node != null; node = node.next) { if (key.equals(node.key)) { V oldData = node.data; node.data = data; return oldData; } } If we didn't find the key, we insert a new element at the start of the linked list. <<insert method>>= Hashnode<K,V> node = new Hashnode<K,V>(key, data, nodes[hash]); nodes[hash] = node; We return the previous value associated with the key, or null if there was no such key. <<insert method>>= return null; } [edit] Removing an element To remove an element from the hash table, we just search for it in the linked list for that hash value, and remove it if it is found. We return true if it was found; ff it was not found, we return false. <<remove method>>= public boolean remove(K key) { int hash = getIndex(key); Hashnode<K,V> prevnode = null; for (Hashnode<K,V> node = nodes[hash]; node != null; node = node.next) { if (key.equals(node.key)) { if (prevnode != null) prevnode.next = node.next; else nodes[hash] = node.next; return true; } prevnode = node; } return false; } [edit] Searching Searching for an element is easy. We just search through the linked list for the corresponding hash value. null is returned if we didn't find it. <<get method>>= public V get(K key) { int hash = getIndex(key); // System.err.printf("get() key=%s, hash=%d\n", key, hash); for (Hashnode<K,V> node = nodes[hash]; node != null; node = node.next) { if (key.equals(node.key)) return node.data; } return null; } [edit] Resizing The number of elements in a hash table is not always known when creating the table. If the number of elements grows too large, it will seriously reduce the performance of most hash table operations. If the number of elements are reduced, the hash table will waste memory. That is why we provide a function for resizing the table. Resizing a hash table is not as easy as a copying to a larger array. All hash values have to be recalculated and each element must be inserted into their new position. We create a temporary Hashtbl object (newtbl) to be used while building the new hashes. This allows us to reuse insert() and remove() methods, when moving the elements to the new table. After that, we can just copy the elements from newtbl to the current table. <<resize method>>= public void resize(int size) { Hashtbl<K,V> newtbl = new Hashtbl<K,V>(size); for (Hashnode<K,V> node : nodes) { for ( ; node != null; node = node.next) { newtbl.insert(node.key, node.data); remove(node.key); } } nodes = newtbl.nodes; } [edit] Test To test that it works, we create a hash table containing some European countries mapped to their respective capitals. <<main method>>= public static void main(String[] args) { Hashtbl<String,String> hashtbl = new Hashtbl<String,String>(16); hashtbl.insert("France", "Paris"); hashtbl.insert("England", "London"); hashtbl.insert("Sweden", "Stockholm"); hashtbl.insert("Germany", "Berlin"); hashtbl.insert("Norway", "Oslo"); hashtbl.insert("Italy", "Rome"); hashtbl.insert("Spain", "Madrid"); hashtbl.insert("Estonia", "Tallinn"); hashtbl.insert("Netherlands", "Amsterdam"); hashtbl.insert("Ireland", "Dublin"); System.out.println("After insert:"); String italy = hashtbl.get("Italy"); System.out.println("Italy: " + (italy != null ? italy : "-")); String spain = hashtbl.get("Spain"); System.out.println("Spain: " + (spain != null ? spain : "-")); We use remove() on the "Spain" element, and use get() to ensure it has actually been removed. <<main method>>= hashtbl.remove("Spain"); System.out.println("After remove:"); spain = hashtbl.get("Spain"); System.out.println("Spain: " + (spain != null ? spain : "-")); To test resizing, we call resize(), and then get() to see if the hash table still works. <<main method>>= hashtbl.resize(8); System.out.println("After resize:"); italy = hashtbl.get("Italy"); System.out.println("Italy: " + (italy != null ? italy : "-")); } The output is, as expected: After insert: Italy: Rome Spain: Madrid After remove: Spain: - After resize: Italy: Romehijackerhijacker
http://en.literateprograms.org/Hash_table_(Java)
CC-MAIN-2015-18
refinedweb
1,116
58.79
Today is The Building Coder's ninth birthday. The first welcome post was published August 22, 2008. We'll celebrate by discussing the pretty fundamental issue of XYZ points versus vectors, and how to distinguish different points: XYZ Point versus Vector This question was raised in the Revit API discussion forum thread on XYZ question: Question: I find the XYZ class very confusing because it can be a point or a vector. Does anybody know any good guide on how to use them? Or some documentation. Also, I have a specific question: how does one extract start and end points of a XYZ vector? Answer: The documentation is right there where it belongs, in the Revit API help file RevitAPI.chm section on the XYZ class. You are perfectly right, the XYZ class can represent either a point or a vector, depending on how you use it. If you have a XYZ object and run an angle method, you're in fact handling a vector information... but if you just get a coordinate, then a point. In some cases, a vector doesn't have a start or end point, for instance, if it is used to represent a pure direction, not a line. If you need a line, use the Curve/Line object. Bobby Jones suggested rolling your own Point and Vector wrappers around it, making your code much easier to maintain. The XYZ class defines methods that are specific to the concept of both points and vectors. Sometimes, it is difficult to know which concept it is dealing with at any given time. Another benefit of providing your own point and vector wrappers is that you can limit their interface to only methods that make sense. The following code compiles, but none of it makes any sense: void PointAndVectorExample( Line revitLine ) { var o = revitLine.Origin; var whatIstheLengthOfaPoint = o.GetLength(); var howIsaPointaUnitLength = o.IsUnitLength(); var lineDirection = revitLine.Direction; var whatDoesThisRepresent = lineDirection.CrossProduct( o ); var thisDoesntMakeSense = lineDirection.DistanceTo( o ); } Here are some PARTIAL Point3D and Vector3D classes to give you the idea, and some helper extensions to make them easier to use. You can take these and wrap the appropriate XYZ methods for each as well as define additional methods of your own. And even implement additional interfaces, such as IEquatable. public class Point3D { public Point3D( XYZ revitXyz ) { XYZ = revitXyz; } public Point3D() : this( XYZ.Zero ) { } public Point3D( double x, double y, double z ) : this( new XYZ( x, y, z ) ) { } public XYZ XYZ { get; private set; } public double X => XYZ.X; public double Y => XYZ.Y; public double Z => XYZ.Z; public double DistanceTo( Point3D source ) { return XYZ.DistanceTo( source.XYZ ); } public Point3D Add( Vector3D source ) { return new Point3D( XYZ.Add( source.XYZ ) ); } public static Point3D operator +( Point3D point, Vector3D vector ) { return point.Add( vector ); } public override string ToString() { return XYZ.ToString(); } public static Point3D Zero => new Point3D( XYZ.Zero ); } public class Vector3D { public Vector3D( XYZ revitXyz ) { XYZ = revitXyz; } public Vector3D() : this( XYZ.Zero ) { } public Vector3D( double x, double y, double z ) : this( new XYZ( x, y, z ) ) { } public XYZ XYZ { get; private set; } public double X => XYZ.X; public double Y => XYZ.Y; public double Z => XYZ.Z; public Vector3D CrossProduct( Vector3D source ) { return new Vector3D( XYZ.CrossProduct( source.XYZ ) ); } public double GetLength() { return XYZ.GetLength(); } public override string ToString() { return XYZ.ToString(); } public static Vector3D BasisX => new Vector3D( XYZ.BasisX ); public static Vector3D BasisY => new Vector3D( XYZ.BasisY ); public static Vector3D BasisZ => new Vector3D( XYZ.BasisZ ); } public static class XYZExtensions { public static Point3D ToPoint3D( this XYZ revitXyz ) { return new Point3D( revitXyz ); } public static Vector3D ToVector3D( this XYZ revitXyz ) { return new Vector3D( revitXyz ); } } public static class LineExtensions { public static Vector3D Direction( this Line revitLine ) { return new Vector3D( revitLine.Direction ); } public static Point3D Origin( this Line revitLine ) { return new Point3D( revitLine.Origin ); } } Many thanks to Bobby for sharing this! How to Distinguish XYZ Points Another Revit API discussion forum thread that Bobby also helped out with deals with Distinct XYZ: Question: I have a list of XYZ points obtained from MEP connectors. How can I clean it of duplicates, i.e., eliminate points with identical coordinates? I am trying to do it like this: var distinctElementConnectors = MyMepUtils.GetALLConnectors( elements ) .Where( c => c.IsConnected ) .Distinct( c => c.Origin ) .ToHashSet(); The call to Distinct(c => c.Origin) doesn't work, because Distinct doesn't know how to compare XYZs (or does it?). Answer: You are absolutely correct: The .NET API does not have any built-in mechanism to compare the Revit API XYZ objects. However, it is easy to implement, and I have done so several times in different discussion published by The Building Coder. Here are the first and last mentions so far: Furthermore, you can take a look at The Building Coder samples class XyzEqualityComparer, defined there in three different modules. Another direction to go, again suggested by Bobby, assuming you implemented your own Point3D and Vector3D wrapper classes, is to have those classes implement the IEquatable interface. Here's a shell of the Point3D class showing an implementation: public static class DoubleExtensions { private const double Tolerance = 1.0e-10; public static bool IsAlmostEqualTo( this double double1, double double2 ) { var isAlmostEqual = Math.Abs( double1 - double2 ) <= Tolerance; return isAlmostEqual; } } public class Point3D : IEquatable<Point3D> { public Point3D( XYZ revitXyz ) { XYZ = revitXyz; } public XYZ XYZ { get; } public double X => XYZ.X; public double Y => XYZ.Y; public double Z => XYZ.Z; public bool Equals( Point3D other ) { if( ReferenceEquals( other, null ) ) return false; if( ReferenceEquals( this, other ) ) return true; return X.IsAlmostEqualTo( other.X ) && Y.IsAlmostEqualTo( other.Y ) && Z.IsAlmostEqualTo( other.Z ); } public override bool Equals( object obj ) { if( ReferenceEquals( null, obj ) ) return false; if( ReferenceEquals( this, obj ) ) return true; if( obj.GetType() != GetType() ) return false; return Equals( (Point3D) obj ); } public override int GetHashCode() { return Tuple.Create( Math.Round( X, 10 ), Math.Round( Y, 10 ), Math.Round( Z, 10 ) ). GetHashCode(); } } Storing Point3D instances in a hashset will give you your distinct set of points. var distinctElementConnectors = MyMepUtils.GetALLConnectors( elements ) .Where( c => c.IsConnected ) .Select( c => c.Origin.ToPoint3D() ) .ToHashSet(); Yet another solution to address this directly is to define a comparer class for native Revit API Connector objects, such as the ConnectorXyzComparer one provided in at The Building Coder samples Util.cs module: /// <summary> /// Compare Connector objects based on their location point. /// </summary> public class ConnectorXyzComparer : IEqualityComparer<Connector> { public bool Equals( Connector x, Connector y ) { return null != x && null != y && IsEqual( x.Origin, y.Origin ); } public int GetHashCode( Connector x ) { return HashString( x.Origin ).GetHashCode(); } } /// <summary> /// Get distinct connectors from a set of MEP elements. /// </summary> public static HashSet<Connector> GetDistinctConnectors( List<Connector> cons ) { return cons.Distinct( new ConnectorXyzComparer() ) .ToHashSet(); } I implemented that in The Building Coder samples release 2018.0.134.1. Here is the diff to the preceding release. Thanks again to Bobby, and Happy Birthday coding, everybody!
https://thebuildingcoder.typepad.com/blog/2017/08/birthday-post-on-the-xyz-class.html
CC-MAIN-2020-05
refinedweb
1,134
59.19
. The Principle of Scenario-Driven Design. 2.1.1.1 Usability Studies. Hmmm, sounds like (T)est (D)riven (D)esign 🙂 Having a book getting written on this subject is definitely good news! As a long time Design Guidelines reader and spreader, I think this subject will become even more important now that so many people are (and will be) designing APIs for consumption via Web Services. Not that a local assembly doesn’t also deserve such attention. Things I would like to see covered: - API Usability Testing - What it is. - How it is done - Tools (even if with spreadsheets, forms, etc) - Global API design naming conventions - Names in foreign languages - Non-ASCII 7 bit characters usage - Stories on design decisions and changes made on .NET since prior to the version 1. - Examples of good and bad decisions on FCL 1.0, Everett, Whidbey and maybe a glimpse on Orcas. - Breaking Changes - How to minimize the need for - How to do them when needed - Web Services - XML Schemas - Mockup techniques - How to use IDEs so early? - Progressive APIs. What they are and how to design them. - Exposing auto-generated code in public APIs (Maybe not a good idea) - Designing for performance - Versioning - Security (threat models, etc) - Using tools such as FxCop, UML, etc. - Naming database objects. - This is coming more important each day since tools are becoming more and more used to auto-generate objects in various tiers and maintaining a consistent naming when possible is an important issue. - Name mappings when it is not possible or desired a direct naming correspondence. - API review process - Committee, workgroup, single person? - Roles - Skills needed Probably I forgot a dozen of other topics I’d like to see covered. Do you already have an overview of what is going to be covered? Krzysztof spilled the beans… He and I are working on bringing all the goodness of the Framework Design... Thanks very much for sharing your insights on the scenario-driven framework design! You and your team are doing a great job providing .NET framework best-practices and guidelines to the developer community! In this post, you are referring to a scenario-driven API specification. How would a typical document look like? Is there any available template that a framework API designer could use? Or would an MSDN-like API-documentation be sufficient to start with? Also, is there anything special about the functional specification when designing a framework as opposed to design of an application. Thanks in advance! P.S. The design guidelines book is a great idea! Adam, I think it's similar to TDD (test/tutorial driven design), but I would say SDD has slightly different motivation and is lighter weight. Alfred, it's a great list of questions/topics to either cover in the book or in the blog. I started with a post with some pointers to usability study resources. See. George, I have good news for you. I am trying to get an appendix added to the book that would contain a sample API specification that we used to design a simple Framework API (Stopwatch). As, to designing APIs for apps vs. frameworks, there are some differences. They get larger if the app interfaces are not publicly exposed and get smaller for public app plugin APIs. The main reason is that framework APIs really cannot be changed after they ship. Other differences stem from the fact that usual application APIs (even public) usually are used by smaller group and less diversified group of developers (this is a generalization but on average this is true). Anyway, this is a big topic in itself. I will put it on my "to blog" list. Something along these lines that I would like to see, is VS project and item templates to simplify applying these design guidelines. For example, a sample of the above scenario-driven design doc could be included in the class library project, or as a sub-item to a class item. In VS2005 this should be a good deal easier. Oh, what a great day… I *just* finished doing the final page proofs for the design guidelines book that... Hi. I had a look into the book's TOC at Addison Wesley website. What I'm missing are naming guidelines for ASP.NET, especially for classes inheriting System.Web.UI.Page and System.Web.UI.UserControl, the types which have related as?x files. Maybe you can tell me what is the best way for naming this example type: a) public class UserPage : System.Web.UI.Page { } // in file UserPage.aspx or b) public class User : System.Web.UI.Page { } // in file User.aspx Thanks, Marco
https://blogs.msdn.microsoft.com/kcwalina/2005/05/05/design-guidelines-book-the-principle-of-scenario-driven-design/
CC-MAIN-2017-30
refinedweb
779
66.64