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
_size must be greater than the value returned by thr_min_stack(). In general, you do not need to allocate stack space for threads. The system allocates 1 megabyte of virtual memory for each thread's stack with no reserved swap space. The system.C). Solaris threads as thread-specific data is for POSIX threads. The synopses for the_setspecific(3C) binds value to the thread-specific data key, key, for the calling thread. For POSIX threads, see pthread_setspecific Syntax. #include <thread.h> int thr_setspecific(thread_key_t key, void *value); thr_setspecific() returns 0 if successful. When any of the following conditions is detected, thr_setspecific() fails and returns the corresponding value. ENOMEM.
https://docs.oracle.com/cd/E19963-01/html/821-1601/sthreads-17757.html
CC-MAIN-2018-09
refinedweb
107
58.79
Many processes that involve processing XML involve the "chaining" of XML technologies. In fact, some specifications, like XInclude, have been developed intending to be supporting pre-processing steps or layers upon which other XML specifications can rely. In all these cases, there are a number of technical issues that must be resolved for these chaining of processes to work together in a beneficial way. Still, we envision a world in which XML processes are chained together in this way, where some of the manipulations result from W3C standard operations, operations standardized elsewhere, or operations specific to a particular application--all of which work together to produce the final, correct result. Within this paper we will outline the issues surrounding chaining XML processing that involves transclusion, transformations, and validations, with schemata and document infosets. We do not intend to propose a solution to these issues nor is this paper supposed to be a definitive list of all the issues. Essentially, the issues outlined are of a more serious fundamental nature to lay a foundation for chaining XML processing. In certain cases some of the issues represent a philosophical question of which idiom one chooses. When we have formed an opinion we have stated the opinion as "Our Position" to offset it from the issue in general. It may be tempting to resolve questions relating to the interaction of chained XML technologies by declaring a fixed ordering. For example, XInclude must be processed before XML Schema and after XPointer resolution. This order would then be defined in some all encompassing and governing specification. In contrast, one could say that this order is defined by a using application or user. This gives the using application the choice of order without violating a specification. A result might be that the original author of some XML instances may not get the desired result within some receiving application. We believe any such fixing of the processing order to represent a mistake. One of the main justifications for this position is an understanding that the advantage to XML technologies, and in particular to defining certain XML technologies using XML, lies in their flexibility. Thus, if there were a fixed order, we have lost flexibility and installed a rigid framework for processing instead. For example, if XInclude were to be fixed in the processing sequence to fall between XML parsing and schema validation, there would be no compelling reason to adopt it over external entities besides a preference of syntax. When XML processing steps are chained in flexible ways, infosets flow from one step through the next, building on what happened at each step. Flexibility of chaining leads, as a matter of reasonable software engineering practice, to permitting the components for each step to operate as independently of global context as possible. A general consideration is that given an infoset and an XML process step, you have to be able to either (a) perform the process or (b) not, because the infoset lacks what you need, and (c) tell the difference easily. There ought to be a way to know right away if an infoset has the extensions you need and get a definitive answer. For example, I need PSVI for this step and so I must check that it is there. It would be best of there were a standardized way of inquiring about which infoset extensions are available in a particular infoset. For example, in the current draft of the XInclude specification, XInclude processing may damage the PSVI, but it leaves no clue that it has done so, or even that it has occurred, so an independent software component engaging in further processing has no way of knowing whether it is going to get consistent results or not, or if re-validation is necessary. Reasonable software engineering practice demands that components implementing particular XML processing steps that might be chained together not be required to know about global context in order to operate. Maintaining independence means putting enough into the infoset to ensure that each component has what it needs to operate or fail reliably. Steps that modify an infoset should either (a) add to the infoset (leave original intact and add on new stuff) (b) modify it in a way that is consistent with the infoset you would get by directly parsing the equivalent XML file. The point here is that you want to be able to put something through a subprocess without having to do different things depending on where it came from. You want to be able to treat each step as independently as possible. Implications: The text in the Infoset specification that countenances synthetic infosets that violate consistency constraints is actively harmful and should be removed. If you choose option (b) that says that you need to strip out extension properties in the infoset you don't understand, else you're violating the extension's consistency constraints. Choice (a) is better, because it allows for greater independence and avoids repeating steps needlessly. Note: we distinguish here between creating a new infoset and modifying an existing one in situ. XInclude and XML Schema modify; XSLT creates new ones. In general, we envision a world where there are chains of infoset manipulations of various sorts, some of which are W3C standards and some of which are not. Means of accessing these extended infosets are necessary, as are means of referring to them as whole units for feature testing. The DOM provides (or will provide) for accessing specific extended infosets, such as the PSVI, but not for infoset extensions in general. Where many extensions may be applied, name collisions are inevitable. We believe it is useful to have a generic extended infoset API in the DOM. Steps should be take to provide the means for avoiding name collisions, but providing a standard way of 'namespacing' property names and whole bundles of properties (extensions, such as the PSVI). Whether these 'namespaces' are namespaces or not, or something more akin to the identification of extensions in XSL or SAX matters less that having them at all, although having them have some relation to XML namespaces makes for some interesting possibilities with respect infoset reflection into XML. In this vision of chained infoset processing, the output infoset from one step becomes the input infoset to the next. Yet many specifications insist that the input be identified by a URI. What is the URI of a partially processed infoset? High performance processing demands that intermediate results not have to be written to a file or accessed through intermediate dereferencing of meaningless URIs. Let infosets be infosets. We do not believe a partially processed infoset has a URI or needs one. We do believe that specifications need to acknowledge and accommodate infosets as input that never came from a web server or a file, or that didn't come from one recently (for performance reasons). We believe that specifications need to acknowledge and accommodate infosets as output that will never hit a file system. The XML Schema specification was carefully constructed so that such applications were possible and so this should also be taken into consideration. We consider this a good model to follow. As steps in some chaining process are completed, the traceability of the origin of certain generated results may become important. (i.e. what caused the result to be generated: "what xinclude element? where?"). For example, if an xinclude element causes an inappropriate element to be included into the resulting document and that element causes an error further down the chain, there should be enough remnants in the resulting infoset to understand what originated the error--essentially, identifying which process applied and where. While, in general, processing steps should be as independent as possible, handling exceptional conditions require traceability to the source of the problem. Patching up infosets after applying processes that did not understand a certain extension requires knowing what those processes were and what they did. Ensure that W3C processes that manipulate infosets leave behind sufficient traces of their actions that traceability is possible. We cannot make arbitrary non-standard infoset processing abide by such rules, but we can show leadership and provide the tools to do so. When schema validation outcomes are involved in a chain of process a number of tricky issues arise. Essentially, not only does the fact that a schema is available change the resulting infoset, but user option as to what should and should not be validated affects it as well. The follow sections are a non-exhaustive list of issues to be considered: When a document is processed (or an infoset is re-processed) how does one control and process against the availability of a schema? There may be many places from which the schema is available. Considerations of what is appropriate give the source, locale, and system or user option must be taken into account. The XML Schema recommendation defines the infoset properties that are added when schema processing is applied. But it remains unclear what happens if schema processing is chained, applying different schemata covering the same namespaces. It is by no means obvious that the correct answer is to completely replace one PSVI with another. For example, consider the case where at one point in the life cycle of the infoset, a schema validation episode applied a schema in which the contents of the userExtension element were left as a wildcard with validation skipped. If, later on in the history of that infoset, processing determines which specific user extension schema to apply in that spot (which schema has no constraints for anything else) and another schema validation episode ensues. A plausible argument could be made that the PSVI for the rest of the document is still useful and should be retained. When an XML document is processed against a schema an the PSVI is produced, it is possible to conceive a step in a chain of processes where the simple typed information is manipulated or produced and will then be reproduced in a lexical form within an XML document. In this case, there should be control over the formatting of these types. NOTE: While a minor point it is important for readability and, in some cases, the efficiency of some subsequent application. XML processing chains result frequently involve transformations that accomplish aggregation and disaggregations. In many cases, at any point, there is the issue of multiple input and output documents. How will these be handled within a chain of processes? Subsequently, there a number of other issues that arise. The main issues is in the case of disaggregation, what happens to the next step in the chain? Are there sub-chains initiated or does the next step receive all the resulting documents? Also, in general, what happens when a transformation result is not necessarily and XML result? This is certainly quite possible with XSLT. The issue of referring to intermediate results comes into play here as well: The document() function in XSLT requires a URI, but we envision situations where the XSLT step is being applied to a set of intermediate results, none of which has a URI. It is necessary that a chain of processes "know" what to do when errors occur. While the most draconian position is to simply stop, it is easy to consider that there are many other ways of dealing with errors. Some, in fact, may be errors to the overall application but a valid result for the chained processes. In fact, this is the position that taken by XML Schema processing. It is important to also distinguish between the errors and error handling that happens inside a process that is being chained and the error handling of the chain. That is, there are two questions: what does the specific process (or standard) say about errors and error handling and what does the chaining language say itself. For example, what should XInclude say about error processing and what should the chaining process do about those error conditions once they occur. For the process itself, the simplest issue is what is an error? Is it invalid input or output at some point in the chain? Or is it an invalid state within the chain? These all must be defined before error handling can be discussed. Subsequently, for the governing chain, what happens when there is an error? Some errors may be classified as necessitating draconian measures because of conformance while others may need to be reported somewhere. One may also want to cascade an alternative process based on the error. For example, a web server probably should always respond with an message regardless of the success of the process. Thus, any error should be caught and, at least, result in the generation of an error message to be returned for the service. This then leads to whom they are reported and at what level. It may be sufficient for some errors to be reported to the hosting system. In some cases it may be necessary that they are under user control so that the error can be corrected or processed within the chain producing an alternative result. We believe that we need both proper constraints on what a process should dictate about errors and controls at the chaining level for errors. That is, a single process should not dictate that processing should stop. Instead, it should signal the error and continue, if possible, letting the controls within the chain dictate what happens next. With that said, the implication is that specifications that govern particular processes (e.g. XInclude) should not dictate that a processing stop. They must be able to signal a severe error (or error in general) and let the chain's controls decide what to do. In the simplest of cases, halting the chain would result. In this paper we have outlined a number of areas where there are serious issues that need to be addressed in the architecture of chaining XML processes. While we could forge ahead with some seemingly simple solution we will probably be tying our hands in the future for dealing with more complex situations. Thus, it is important that we discuss these issues and develop a solid foundation before settling on a solution.
http://www.w3.org/XML/2001/07/xmlpm-holstege-milowski.html
CC-MAIN-2016-40
refinedweb
2,368
50.16
If you want to connect Flash to PHP code via AMFPHP, you need to write your PHP code as a PHP class. The remote methods that your ActionScript code calls are the methods of your custom classes. A PHP class uses the following syntax: class MyClass { var local1 = 1; var local2 = 2; function MyClass ( ) { // do something } function someMethod ($val) { // do something else } function someOtherMethod ($val0, $val1) { // and something else } } In this case, local1 and local2 are instance variables (unique variables associated with each instance of this class). The function MyClass( ) is this class's constructor, which runs when an instance of this class is first created. This method performs necessary setup for an instance of this class. Finally, someMethod( ) and someOtherMethod( ) are two sample methods to which all instances of this class have access. For AMFPHP to work properly, each class must be defined in its own file and the file must have the same name (including capitalization) as the class. In addition, the class's constructor must include a method table, specific code to define the signatures and permissions of all methods of the class. This information is used primarily by the Service Browser in Flash MX to help you write the correct ActionScript, but the permission information is used by AMFPHP to limit which methods of your class are accessible via Flash Remoting. This approach lets you define private methods that can be called internally only. An example method table is shown in Example 9-2, along with methods for the class. This code should be placed in MyClass.php. class MyClass { function MyClass ( ) { // Create the method table for AMFPHP $this->methodTable = array( "someMethod" => array( "description" => "Retrieve the list of countries", "roles" => "list", "access" => "remote", "arguments" => array("state") ), "someOtherMethod" => array( "description" => "Retrieve a list of companies in a given country", "roles" => "list", "access" => "remote", "arguments" => array("country", "postalCode") ) ); } function someMethod ($val) { // Just echo back the value return $val } function someOtherMethod ($val0, $val1) { // and something else } } As you can see, this code defines a variable named methodTable that is an array of all the methods this services supports, along with information about each method. The access property can be set to "remote", "public", or "private". AMFPHP closely mirrors ColdFusion in the way that method permissions are set. If you want your method accessible only to this class, define its access property as "private". If you want the method accessible to other classes, declare access as "public". Finally, if you want the method to be callable via Flash Remoting, set access to "remote". Refer to Section 5.3.3.4 for more information about the access property. Although Version 0.5.1 of AMFPHP doesn't use the roles property, by the time you read this AMFPHP will most likely use the roles property to implement a security system similar to how ColdFusion works (see "Using Role-Based Security with ColdFusion Components" in Chapter 5 for related information). In general, if you don't plan on using the roles information, simply leave the roles property out of your code. The two remaining properties, description and arguments, provide a description of the method and the arguments that the method accepts. At this time, the arguments property is used only for documentation purposes and won't cause an error if it doesn't match the actual arguments specified in the method declaration. If there are any syntax errors in your class constructor, Flash Remoting displays an error, usually one that doesn't provide a lot of information about the problem. However, you can check for syntax errors easily by opening a web browser to the URL of your service (i.e., the URL of the .php file). Any syntax errors are displayed along with their line numbers. If no syntax errors exist but you are still receiving an error in Flash (often the Bad Version error), make sure that AMFPHP is properly installed and that your class isn't accidentally outputting any extra characters, such a spaces, tabs, or other whitespace directly around your <?php> tag. Once you have created a PHP class, you need to write the client-side ActionScript to connect to it. The URL you give for the gateway is just the normal URL to your gateway.php file. However, the URL you specify for your service is a bit different. Instead of being a URL delimited by slashes, it is a dotted path to your PHP class's file, starting from the directory that you specified to be the base path of your classes in your gateway.php file. For example, if you specified your classpath as: /usr/local/apache/htdocos/frdg/services/ and your actual PHP class is located at: /usr/local/apache/htdocos/frdg/services/stuff/MyClass then the URL of the class would be: stuff.MyClass Example 9-3 shows the client-side ActionScript code to access MyClass. #include "NetServices.as" onResult = function (result) { trace("Received result: " + result); }; gatewayURL = ""; serviceURL = "stuff.MyClass"; gateway = NetServices.createGatewayConnection(gatewayURL); service = gateway.getService(serviceURL); service.someMethod(this, {testString:"Testing..."});
http://etutorials.org/Macromedia/Fash+remoting.+the+definitive+guide/Part+II+The+Server-Side+Languages/Chapter+9.+Flash+Remoting+and+PHP/9.5+Using+AMFPHP+with+PHP+Classes/
CC-MAIN-2020-10
refinedweb
840
50.87
bloc_stream 7.0.3 bloc_stream: ^7.0.3 copied to clipboard A simple package that helps you to implement the BLoC pattern in your applications. The BlocStream class is simply a Stream<State>, with a value property. A BlocStream is also a sink of actions. By calling add with an action function ( Action<Bloc, State>), the bloc will then call that action and merge the resulting State's into the output stream. Here is an example BLoC that provides a list of events: import 'package:bloc_stream/bloc_stream.dart'; import 'package:example/event_repository.dart'; // Actions BlocStreamAction<List<Event>> fetch(EventRepository repo) => (currentValue, add) async => repo.list().then(add); // Bloc class EventsBloc extends BlocStream<List<Event>> { EventBloc() : super([]); } Usage with Flutter # See flutter_bloc_stream. You can also use this package in combination with Provider and StreamBuilder. You could also use a StreamProvider from the Provider package.
https://pub.dev/packages/bloc_stream
CC-MAIN-2022-40
refinedweb
143
51.75
My Account Community Books & Videos Safari Books Online Conferences Training School of Technology About Complete List Bestsellers New Releases Rough Cuts Upcoming Titles Ebooks By Publisher By Series Out of Print Order Info Search Search Tips Tell a friend Enterprise SOA Designing IT for Business Innovation By Dan Woods , Thomas Mattern April 2006 Pages: 452 | Table of Contents | Index | Sample Chapter Table of Contents THE CONTEXT FOR ESA Chapter ONE ESA in the World of Information Technology Who is this book for? Why so many questions? What forces created ESA? What is ESA? How will ESA change how applications are designed and built? What supporting infrastructure does ESA require? Is ESA compatible with event-driven architecture? What is the promise of ESA? How will the transition to ESA occur? How can ESA be addressed at a tactical level? Why does ESA matter? What are the core values of ESA? Where can we go for more answers? ESA in action: Mitsui Chapter TWO The Business Case for ESA What attributes must ESA embody? What principles should be driving my IT decisions? What happens when core eventually becomes context? How does ESA enable consolidation and reuse? What kind of innovation should companies pursue, and how will ESA help them? What are ESA's practical implementation issues? What's the long-term adoption path of ESA? How quickly will I see ROI, and what form will it take? What is ESA's long-range impact on corporations? ESA in action: Nordzucker AG Chapter THREE Evolving Toward ESA Conceiving Consuming Composing Creating Controlling Just how much and what kind of change will ESA involve? What is IT's role within ESA? What do you mean by "business process?" That's a good point, but how do you bring the two sides together in the first place? What is IT's role if all of this comes to pass? What does my company look like then? What stages will we go through on the way there? What skills will we have to develop? What kind of architecture skills does ESA call for? How does a cultural transformation happen in the real world? What can SupplyOn tell us about how to manage the change inherent in ESA? How will IT change in an ESA world? What will the shift to a model-driven world mean for IT, and where will these business analysts come from? How will governance function within ESA? How and where should I begin evolving toward ESA? How will modeling translate between enterprises with different architectures? Will a standards body evolve to resolve potential conflicts? What do the analysts think, and what trouble do they foresee? What kind of company will we be after ESA? CONCEIVING A VISION FOR ESA Chapter FOUR ESA Fundamentals: Learning to Think ESA What is architecture and why is it important? What is enterprise architecture and how will ESA change it? What motivated the creation of ESA? What are the architectural challenges of ESA? How does ESA meet those challenges? Does ESA make all my existing systems worthless? What are systems of record? What are transactional systems? What are web services? What is the difference between a web service and an enterprise service? What is service-oriented architecture? What is the difference between ESA and other approaches to SOA? What are composite applications? What are service consumers? What are service providers? What are xApps? What role does the mySAP Business Suite play in ESA? What role does SAP NetWeaver play in ESA? What are IT practices and IT scenarios? What is event-driven architecture? Why are analytics so important to ESA? How does ESA provide for easier adaptation and a better requirements fit? What is the basic structure of an enterprise service? What are global data types? Why is XML messaging so important to ESA? What is the difference between a frontend and a backend application? What is service composition? What is the role of business objects in ESA? How does persistence change in ESA? Why does modeling matter? Isn't it just another form of coding? Will modeling replace coding? How are patterns used in ESA and what value do they provide? What is process orchestration? What is process integration? How will ESA change the way applications are packaged and delivered? What are the special needs of composite applications? What is the relationship between ESA, standards, and commoditization? Is buy versus build a false tradeoff in ESA? Why is an ecosystem of companies and standards so important to ESA? Chapter FIVE The Structure of ESA Basics of ESA applications The ESA stack, layer by layer The enterprise services layer The business objects layer The process orchestration layer The UI layer The persistence layer Chapter SIX The Enterprise Services Community What is the ES-Community? What is the value of the ES-Community? What is a Definition Group? Who can join? What does the ES-Community contribute? Will the ES-Community create new standards? How are enterprise service definitions created within the ES-Community? What is the organizational structure of a Definition Group? What is certification? Is it mandatory? What is ES-Ready? How can partners use this brand? How does the ES-Community balance efficiency with open participation? What is required to participate in the ES-Community? How is intellectual property (IP) treated in the ES-Community? How will the ES-Community differ from SAP's other partner and customer efforts? How does participation in the ES-Community benefit customers? What should a company do to get involved in the community process? Chapter SEVEN Creating a Roadmap with the ESA Adoption Program Why the roadmap approach? What challenges do companies face in adopting ESA? How does SAP help customers adopt ESA? Is there more to success with ESA than just analyzing technologies and preparing roadmaps? How have companies put SAP's ESA Adoption Program to work? CONSUMING SERVICES Chapter EIGHT The Enterprise Services Repository and the Enterprise Services Inventory What is the Enterprise Services Repository? What is the Enterprise Services Inventory? ESA in action: Elsag ESA in action: Kimberly-Clark ESA in action: CSA International Chapter NINE Project Mendocino: A Product Based on Consuming Enterprise Services What is the goal of Project Mendocino? How does Project Mendocino use ESA? Project Mendocino applications The Project Mendocino architecture ESA in action: Agile Solutions Ltda Chapter TEN ESA at Work: Examples from the Field ESA in consumer products Store-specific pricing ESA inCustomer Relationship Management (CRM)ESA in CRM:ESACRM service request processing ESA in the chemical industry: e-VMI at Solvay ESA for logistic service providers ESA for professional service providers ESA in manufacturing ESA in the chemicals industry COMPOSING SERVICES Chapter ELEVEN SAP xApps Composite Applications for Analytics How do SAP xApp Analytics help business users? How hard is it to deploy SAP xApp Analytics? What are the different parts of an analytic composite application? In which application and process areas are analytic composites being created? How do ESA and SAP NetWeaver help create analytic composites? What are the benefits of SAP analytics? Chapter TWELVE The Architecture and Development Tools of Composite Applications The architecture of composite applications Development tools for composite applications ESA in action: Asian Paints ESA in action: Zuger Kantonalbank Chapter THIRTEEN Supporting Composite Applications How are composite applications different from the previous generation of applications? SAP NetWeaver MDM SAP NetWeaver Business intelligence SAP NetWeaver Knowledge Management and Collaboration SAP NetWeaver Mobile ESA in action: Arla Foods CREATING SERVICES Chapter FOURTEEN Web Services Basics What are web services and why do we care? What are some examples of web services? What are services? What is service-oriented architecture? Why is service orientation better than object orientation? What are the main components of web services? What is XML? What is XML schema? What are XML namespaces? What is SOAP? What is WSDL? What is UDDI and how does it relate to SAP? How can we ensure that web services will interoperate? What about web services security? Chapter FIFTEEN Creating Enterprise Services in ABAP Can I start creating enterprise services today, or should I wait? How do web services and enterprise services compare? What are two ways to create services in ABAP? What is SAP NetWeaver's role in creating enterprise services? What is the role of the SAP NetWeaver Application Server? What is SAP NetWeaver XI's role as an integration broker? What steps are involved with web services brokering using SAP NetWeaver XI? How can services be adapted to reflect changing customer needs? What does the future hold for creating enterprise services? Chapter SIXTEEN Creating and Consuming Services in Java What development tools are available for Java developers? How do you create a service provider in Java? How do you create a service consumer using Web Dynpro for Java? ESA in action: Arcelor ESA in action: TRW CONTROLLING SERVICES Chapter SEVENTEEN ESA and IT Governance What are typical models for IT governance? What are the challenges and problems with existing models? How does ESA decrease the need for IT governance? How does ESA improve the relationship between business and IT? Who owns enterprise services? Who makes a decision about creating new services? What processes make sense for approving new enterprise services? ESA in action: Whirlpool Corporation Chapter EIGHTEEN ESA Life Cycle Management and Operations Which operations and management problems will ESA actually solve? What is life cycle management? What is life cycle management in the context of ESA? What are the challenges for life cycle management in the context of ESA? How will services be monitored in an ESA landscape? Where will the necessary metadata come from? How does ESA affect implementation issues? How are operations affected by ESA? How will ESA affect change management and software logistics? What is adaptive computing and how does it relate to ESA? What does the introduction of ESA and its impact on life cycle management mean for IT departments? Will life cycle management capabilities be available to ISVs? What additional capabilities does ESA offer in terms of allowing business analysts to determine which revenue-generating services should receive additional resources? Chapter NINETEEN ESA Security What security challenges face enterprise architects? What are identity management and authentication? How does identity management change within ESA? What is access management? How does access management change within ESA? How are messages that are sent from enterprise services secured? What standards have been developed? How do you develop secure composite applications without weaknesses? How will security between companies function and evolve in an ESA environment? Chapter TWENTY Standards and ESA How do standards relate to ESA? What are semantic standards, and how do they help build IT solutions? Which technology standards does SAP support, and how do they help build IT solutions? Which technology standards does SAP NetWeaver support? Colophon Return to Enterprise SOA
http://oreilly.com/catalog/9780596102388/toc.html
crawl-002
refinedweb
1,801
61.22
Today I want to share this information with you, in the hope that it will help you in your future projects. The wantsJson() method checks the Accept HTML header for the string application/json and returns true if it is set. The isJson() method checks that the HTML header CONTENT_TYPE contains the string /json and returns true if it is found. Both methods are found in vendor/laravel/framework/src/Illuminate/Http/Request.php use Illuminate\Http\Request; If you want to check if response needs to be JSON If you want to check if request is of JSON type <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function index(Request $request) { dd($request->wantsJson()); // output:- false } } Not all AJAX requests expect a JSON response, so utilizing request()->ajax() is useful where you want to determine if the request was an XmlHttpRequest or not, but the response doesn't care about JSON or not. Not all requests that contain JSON expect a JSON response. so if you don't care about whether or not the response wants JSON back, but want to determine if JSON was sent in the request, then isJson() is useful for you. Not all requests that want JSON responses are AJAX driven, so wantsJson is useful in the case where you want to return JSON data, but you don't care how the request came to your server. I hope you enjoyed the code. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/morcosgad/laravel-request-wantsjson-isjson-22c8
CC-MAIN-2022-21
refinedweb
246
65.56
Planning a testing methodology venzen opened this issue · comments I generally adhere to the Python philosophy that it is better to ask forgiveness than permission. However, in this case it makes sense to gauge the opinions of @davidrmiller and other active contributors. Before I start coding on new or additional functionality, it will be useful to consider implications, best practice and David's vision for this project. I have a few proposals to facilitate the user experience and put shoulder-to-wheel with some TODO items I noticed in the code: - Hard-coded filenames such as epoch-log.txt (mentioned by David in analysis.cpp) can be specified in the config file. Additional parameters will need to be added. - Optional Automation of tool scripts. As is currently the case with graphlog.gp, it is also possible to automate the genome plotting done by graph-nnet.py. It will entail a similar workflow: Indiv::printGenome()outputs genome plotting instructions to ./logs/net.txt (and console, if desired) and endOfGeneration()(for example) can call Python to draw a sample genome. This will also require a parameter in the config file - to enable or disable this functionality - and to specify a filename and system command. It is, therefore, possible to provide hooks for arbitrary tool scripts the user may choose to run during a simulation. - Parameter records. When running simulations systematically for research it will be valuable to keep a record of the parameters being used for successive or specific simulations. I propose a config file parameter that enables/disables output of parameters to a user specified file. This file should also record any changes to parameters during the course of a simulation - value change, sim generation at time of change, and a date and timestamp. - Convert asserts to useful output. assert()statements are useful during development but are misleading for users. Some people have complained about "segmentation faults" while these are simply code asserts that correctly (and meaningfully) trigger. Unless critical, asserts should be replaced with useful console output that users can report, but that allows sim execution to continue. A stack of errors encountered during execution can be logged (during execution) and dumped to the console at the end of code execution. - Baseline params for barebones simulation. When running biosim without any config file (minus biosim4.ini too) it should execute a short minimal simulation that, ideally, never fails. The current set of hard-coded parameters seems to achieve this. I only had to get rid of an assert()statement in the genome comparator function to achieve a reliable, repeatable minimal simulation. The reason why I mention this is that future code changes should not break this baseline state. I have a few other ideas, such as coding a Python matplotlib tool and genome editor, but the above list of items will provide the foundation for that, while resolving some of the self-evident current issues. Let's hear some feedback and opinions. . Testing is important and I think it is prudent to get some baseline checks and balances in place before extending functionality. I want to point out that my skill in Python is magnitudes better than in C++, so where possible I'd prefer writing Python unit tests. Let's discuss the testing methodology. I have some hours every week to contribute to that. I'll wait for you to give your thoughts on the most important areas/functionality to test. Automating the testing process makes sense, although the initial unit tests will have to be manual until some stability and familiar process is achieved. Go ahead and share your thoughts, I'm interested to know what needs testing, about the envisioned process and to spend a few days thinking about that Python is awesome. A python program could construct a biosim4.ini config file, kick off a simulation that runs for a minute, then inspect logs/epoch-log.txt to see if the final numbers are within sensible ranges. It could also capture stdout and check for anything suspicious. We could start with a small number of biosim4.ini configurations that have extreme, stressful, or problematic parameters, then empirically determine what sort of output to expect from them. Couldn't the simulation be made deterministic, by making any random generation used inside deterministic using a set seed value? The program could take the seed value as a parameter, and would always produce the same output for the same seed value (provided other inputs are the same as well of course). Multithreaded retrieval of random values is the only problem I can see with this approach, but it could at least make single threaded tests very simple. Am I missing something? @apatho, that's a good observation. A small modification to the random number generation would let us make a nice, deterministic single-threaded smoke test. That could be a valuable component in a testing process. The advantage of testing with non-deterministic execution is that, over time, uncommon edge-case errors will appear and inform us of problems we would otherwise miss. @davidrmiller @apatho A "deterministic single-threaded smoke test" can be one of the tests. A few non-deterministic stress tests will reveal edge cases. as David mentions. Agree that both are required. To proceed I suggest: - A tests directory with subdir configs containing a few .ini files with extreme params. @davidrmiller you should probably create these since you have a better idea of what "extreme" params you want to test. - Provide a modified RND number generator for crafting a deterministic baseline test. - I will start work on a Python script that does what David suggests above: - construct a biosim4.ini config file - kick off a simulation that runs for a minute (approx). - inspect logs/epoch-log.txt to see if the final numbers are within sensible ranges - capture stdout and check for anything suspicious (assert failures, error output, etc) I will take a few days to think about the testing process and methodology. In the meantime it will be useful to ask questions and bounce ideas toward consensus. BTW, having biosim4 internal time for outputting timestamps will be useful. I've activated lastModTime in params.cpp for each config file read. Shall I PR this? While running and monitoring a series of fast sims, an issue emerged: sometimes the pace of sim execution is faster than the monitoring can keep up with. This may be a result of disk I/O or Python's inherent lag. Having a param that specifies a wait time between generations (at spawnNewGeneration() or at genomeAnalysisStride) could be the solution. I use a wait time like that on a particular laptop to keep it from overheating :-) But maybe there's another way. There's a parameter in biosim4.ini that sets the maximum number of generations to simulate, after which the simulator exits. Can the python program invoke the simulator with stdout and stderr redirected to a file? That would allow the OS to capture the output while the simulator runs full speed. The python program can wait quietly until the simulator exits, then peek at the captured stdout, stderr, and log files. Perhaps a timeout is also needed so the python program can force-kill the simulator if it doesn't terminate within a reasonable time. Yes, Python's suprocess.Popen() allows stdout and stderr to be captured and I think this is the best way to run tests. What is causing issues is the updating of graphlog.gp when running fast sims. However, probably best not to draw graphs for these tests (because we're not testing graphing right now). We'll cross that bridge when we get there. A small modification to the random number generation would let us make a nice, deterministic single-threaded smoke test. The option already exists, RandomUintGenerator takes a bool for whether to run deterministically or not, maybe just add an option to biosim4.ini to decide which mode it uses? When I've been profiling, setting that and numThreads = 1 has been enough to get a reproducible output. I think allowing a user-set seed would be good, that would just mean replacing std::mt19937 generator(time(0)); with std::mt19937 generator(seed); on line 38 of random.cpp in the case that the user passes a seed. @Asa-Hopkins Thanks for the explanation. Is there any specification for the format of the seed? The specification says that either a result_type or a Sseq& are viable, I'm not entirely sure what those are but the examples give both an unsigned int and a str as possible seeds, so it seems fairly versatile. Sure, I'm reading the PDF linked in random.cpp and it mentions: Avoid setting the seeds to zero or small numbers in general – try to choose large “complex” seed values (see discussion below on warming up RNGs). I'll read further. I like where this is going. There is even a slight possibility for deterministic multi-threaded program execution (with some performance penalty), but this will require investigation into the options for configuring OpenMP thread scheduling. I can elaborate more later. Thinking about the config file, here is an initial stab at how the parameters might look in the default biosim4.ini file with descriptions that match the language and style of the other parameters: # If true, then the random number generator (RNG) will be seeded # by the value in RNGSeed, causing each thread to receive a # deterministic sequence from the RNG. If false, the RNG will be # randomly seeded and program output will be non-deterministic. deterministic = false # If deterministic is true, the random number generator will be seeded # with this value. If deterministic is false, this value is ignored. RNGSeed = 1234567 @davidrmiller I'm working on a Python unit test of RNG functionality. This requires a separate compilation of random.cpp in the tests directory where all tests can be run. The config file options that you posted, above, make sense and can be included in biosim4.ini once we are satisfied with testing. On this same topic, I propose that we use the tried-and-tested ConfigParser module in Python unit tests. It already contains all the functionality to read, write and validate .INI files and with a lot of future flexibility. The caveat is that biosim4.ini will have to contain at least one [section] declaration. Like this: [DEFAULT] # numThreads must be 1 or greater. Best value is less than or equal to # the number of CPU cores. numThreads = 10 # sizeX, sizeY define the size of the 2D world. Minimum size is 16,16. # Maximum size is 32767, 32767. sizeX = 128 sizeY = 128 Similar to # comments we tell updateFromConfigFile() to ignore lines starting with a square bracket. This allows Python to manipulate config files for testing. You may choose to group params in logical sections - or not. The single [DEFAULT] section declaration is sufficient. Here is the configparser documentation: Waiting for your feedback before proceeding with this. It's reasonable to add a section declaration at the top of the config file to facilitate Python parsing. Also, as you suggested earlier, I'm creating a few biosim4.ini config files for future use in non-deterministic testing. Each one runs a simulation that lasts a minute or two. I'm trying to characterize their results by running each one 500 times. So far, the best way I can see to determine if a run is successful is to check that there is no output on stderr and that the numbers in the last line of logs/epoch-log.txt are within certain ranges. . I believe we'd need to add mpi into the Dockerfile to accomplish parallel testing. How can I verify that parallelism works? I've messed with the threads options but assume nothing happens because mpi is missing? PS +100 for this discussion, I need to turn on notifs for this repo... I've extensive experience with designing tests for nondeterministic processes, and the approach proposed by @davidrmiller of checking ranges is definitely suitable and common practice, just expect the occasional one to fail and have to re-run the github action. @Asa-Hopkins I'm trying to compile a standalone executable of random.cpp. This is for local testing and profiling of the RNG. However, my lack of knowledge of C has me stumbling in the dark. Perhaps you can assist if it is an easy fix... So, I have left random.h unchanged, and have added a main() function after (and outside) namespace BS{} in random.cpp that allows reading of command line arguments: bool getBoolVal(const std::string &s) { if (s == "true" || s == "1") return true; else if (s == "false" || s == "0") return false; else return false; } int main(int argc, char **argv) { bool thisbool = getBoolVal(argv[1]); BS::RandomUintGenerator(thisbool); std::cout << "RNG " << BS::randomUint() << std::endl; return 0; } The objective is to pass a bool as a command line arg that enables deterministic or non-deterministic RNG. The next step would be to pass a seed in argv[2] to randomize() as you previously described. However, now, attempting only bool argv[1] I am getting compilation errors. Excuse my inexperience with this basic skill. Perhaps the solution is simple and self-evident. @venzen, I just peeked inside random.h and random.cpp and it's quite a mess. It's got remnants of code from several experimental implementations before I settled on the Jenkins algorithm (it's quite fast). The system's built-in std::mt19937 generator is used only to randomly seed Jenkins. Marsaglia is no longer used. And in random.cpp, it looks as though "omp.h" is included for no reason. Good luck hacking on that mess and let me know if you have any questions. I also noticed that initializing the global RNG object with a deterministic seed would be a little tricky because it had to be done only after the parameters are read instead of at object construction time. So I went ahead and created a branch to do that. Deterministic seeding seems to work in single-threaded mode. Maybe we should output a warning on stderr if deterministic == true and numThreads > 1. Comments are welcome. Yes, I tried to port RandomUintGenerator to Python using the pybind11 module. I got a big headache that lasted all night Look forward to reviewing the branch this evening... This is for local testing and profiling of the RNG. Personally what I've been doing is just editing main.cpp for those kinds of tests, rather than trying to make a new main function elsewhere. PR #30 is more along the lines of what I was thinking, with the values being read from biosim4.ini rather than from the command line. @Asa-Hopkins, sure, and David's latest PR 'deterministic' implements this in a similar good way. My attempt to compile the RNG in isolation is a personal exercise and an attempt to test and interrogate the RNG directly. I'll give it another try with the new code. Thinking about a test script. That little example shell script example above (or a Python equivalent) needs to allow the user to select a test from among a collection of tests. I'm wondering how to store the test parameters and expected results for a collection of tests. The possibilities fall into two categories: store the data inside the test script, or store them in a separate file. To illustrate the latter, here is a possible JSON format for specifying tests. Just one test is shown, but more can be added. The test script could take the name of the test as argument e.g., ./tests/test.py quicktest. Specifying the test config in a separate file seems cleaner in some sense. On the other hand, encoding the same information inside the test script in data structures has advantages: it avoids a dependency on a parser and consolidates the testing framework into a single file. Comments are welcome. { "tests": { "quicktest": { "description": "Quick test that only runs a few seconds", "parameters": [ "stepsPerGeneration=100", "maxGenerations=2" ], "results": { "generations": 2, "survivors": { "min": 980, "max": 1050 }, "diversity": { "min": 0.98465, "max": 0.999 } } } } } @davidrmiller the above outline makes sense and I will provide a Python example in a few days when I have more time. @davidrmiller I discovered that in Python3 the configparser module is native - it does not need to be installed. This is good because it means we can easily read, write, parse and filter .ini files, biosim4.ini included. Regarding the design you outlined above, my personal preference would be to store and retrieve data from a file. It is both easier to update/manage and more flexible in case of format/parameter/test-scenario changes. If we choose this route then this is how it might work: The Python test app has a config file for both its own internal settings, as well as, various test cases. It can read the default biosim4.ini configfile in the parent directory tests/configs/. It can also write/update params in those files using std .ini format. ../as well as its own (or any arbitrary) configfile in We should choose the structure of the test app's config file. Two potential options are displayed further down the page. The same constraint I mentioned before applies. There should be, at least, a [DEFAULT] section header at the top of each file. Of course, there can be any number of sections, and these allow us to structure the file contents. However, there is no support for sub-sections such as those in JSON format that you describe above. However, this is not necessarily an obstacle because the config file keys can have descriptive names that allow the code to discern sub-structures. Here are 2 options, created by the test proto-app from the JSON you provided: Option 1: multiple sections to order data hierarchy $ cat configs/biosim4test.ini [internal] name = biosim4-test version = 21.12.03 url = [quicktest] description = Quick test that only runs a few seconds [quicktest-params] stepspergeneration = 100 maxgenerations = 2 [quicktest-results] generations = 100 [quicktest-results-survivors] min = 980 max = 1050 [quicktest-results-diversity] min = 0.98465 max = 0.999 [slowtest] description = Slow test that runs for years [slowtest-params] stepspergeneration = 10000 Option 2: few sections with descriptive key names: $ cat configs/biosim4test.ini [internal] name = biosim4 version = 21.12.03 github_url = [quicktest] description = Quick test that only runs a few seconds param-stepspergeneration = 100 param-maxgenerations = 2 result-generations = 100 result-survivors-min = 980 result-survivors-max = 1050 result-diversity-min = 0.98465 result-diversity-max = 0.999 [slowtest] description = Slow test that runs for years param-stepspergeneration = 10000 I prefer option 2 and it follows nicely from your requirement that the user be able to specify a test name as arg to the script. Passing quicktest would tell the script to look for a section with that name and it would then parse config params accordingly. Given how the configparser is geared to the task of filtering and manipulating keys, option 2 is easier to implement and more efficient. Feedback and thoughts? Very nice. I like option 2 as well. It's visually easy to parse.
https://giters.com/davidrmiller/biosim4/issues/25
CC-MAIN-2022-21
refinedweb
3,211
57.16
In part 1, I discussed the String class, its methods and properties and how to use them using C# language. Part 2 revolved around the StringBuilder class. In both parts, I used C# language. In this part, I will not discuss theory of classes and their methods and properties. In this part, I will show you a VB.NET version of part 1 and part 2.Comparing StringsThe Compare method compares two strings and returns an integer value. The return value of Compare method can be less than zero, greater than zero or equals to following source code concatenate two strings. The following source code concatenates one string and one object. Dim obj As Object = 12strstr StringsTDimYouDim name As String = "Mr. John"Dim num As Double = 45.06FDim str As String = String.Format("Days Left : {0}. Current DataTime: {1:u}. \n String: {2}, Float: {3}", val, DateTime.Now, name, num)Console.WriteLine(str) The output of Listing 1 is shown Figure 1. Figure 1Trimming and Removing Characters from StringsT StringsTUsing StringBuilder ClassThe StringBuilder class represents a mutable string of characters. It's called mutable because it can be modified once it has been created by using Append, Insert, Remove, and Replace methods.The StringBuilder class is defined in the System.Text namespace. Before you use the StringBuilder class make sure you add the following line in your application:imports System.TextTable()) The output of Listing 4 is shown in Figure 3. Figure 3 About Source Code:Download and unzip the attached vb files. Create a Windows console application using VS.NET and type the code. Make sure you add reference to the System.Text references when compiling StringBuilder sample. SummaryIn this article you saw some methods and properties of String class. I also discussed some methods of String, basics of StringBuilder class and how to use StringBuilder class to add, insert, append and remove items from strings. ©2016 C# Corner. All contents are copyright of their authors.
http://www.c-sharpcorner.com/article/working-with-strings-in-VB-Net/
CC-MAIN-2016-44
refinedweb
327
69.89
I'm fairly sure this is something that comes up fairly regularly; however, I think as with Perl, people's tastes with regard to it change fairly regularly as well. A couple of nodes (fairly) recently have looked at the namespace issue from both sides, from an implementation point of view, but nothing as yet has come up regarding the more theoretical side, which is what I'm interested in here. My original impression, from reading a number of previous posts here, and from looking through the Camel and Black Book, was that automatically importing subroutines, variables and other symbols from a module to user-code was considered a Bad Thing, something to be avoided. Having said that, though, I can see that it can, on occasion, be a very useful thing if, for example, importing a module exports a set of common subroutines, or secondary modules, to the user's namespace, saving a user of the module from having to figure out exactly which methods or modules in the suite he actually needs. Going from one extreme to the other, though, it's also (in my opinion) a very nice thing to be able to call, for example, Date::Calc with a string of simply the subs you actually want to use. For larger, more complex modules, I can't help but think that it makes more sense to import what's needed rather than everything that's available. I think that my personal preference/solution when I'm both writing and using module code is to have an option of either: if the module is used without arguments, or with an :all flag, a "default" set of subs is exported, but if a list of specific subs is given, only those are imported into the module user's namespace. This, I think, gives maximum flexibility for larger apps, and for future expandability of both the module and for the code using that module. I'm interested to know what others think of this: is there a set "right or wrong" with regard to something like this? I tend to strive to not export anything I don't specifically need: do people think this the best way to go? Any comments and opinions are welcome :) -- Foxcub A friend is someone who can see straight through you, yet still enjoy the view. (Anon) # Under Construction [download] 1. If the module in question inherits its import() subroutine from the Exporter.pm you are right you do not lose anything. If on the other hand the module has its own import(), you may get a nasty surprise. The module may expect it's import() to be called. 2. While MyModule::foo(); doesn't sound too bad, but imagine you'd have to prepend each and every constant with the package name: my $Array = Win32::OLE::Variant->new(VT_ARRAY|VT_R8, [1,2], 2); vs. my $Array = Win32::OLE::Variant->new(Win32::OLE::Variant::VT_ARRAY|Win +32::OLE::Variant::VT_R8, [1,2], 2); [download] Jenda Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Rick Osborne Edit by castaway: Closed small tag in signature $ perl -we'sub x { &foo } sub x { &bar }' Subroutine x redefined at -e line 1.
http://www.perlmonks.org/?node_id=255687
CC-MAIN-2015-18
refinedweb
548
52.73
Introduction The goal of this article is to make it easy for you to get started with IBM® WebSphere® MQ on Linux®. Because most Linux servers do not have graphical user interfaces, the article will show you how to install and configure WebSphere MQ on Linux using command-line tools. The article will show you how to create two sample Java™ applications u using the WebSphere MQ Java API: MQSend to send messages to a queue and MQGet to receive messages from a queue. Prerequisites - WebSphere MQ V6 install packages. - One or two machines with Linux installed.This article used two machines with Suse Linux Enterprise Server V9, you can do everything on one machine. - Linux administration skills. - Experience in Java development is helpful but not necessary because pre-compiled Java sample applications are provided for you to download and use from the command line. WebSphere MQ WebSphere MQ provides a foundation for SOA by providing a connectivity layer and reliable integration for applications. Major WebSphere MQ features include: - Assured message delivery - Reliable queue-based messaging ensures that messages are not lost or duplicated. - Standards-based development - Using Java Message Service (JMS) API and Message Queue Interface (MQI). - End-to-end security - Secure Sockets Layer (SSL) for authentication, message integrity checking, and data encryption. - Web services support - Simple Object Access Protocol (SOAP) for Web services transport and reliability. - Asynchronous processing - Decoupling of applications in order to enable time-independent processing. - Multi-platform support - Support for over 80 platform configurations. For more information about WebSphere MQ, see resources at the bottom of the article. Installing WebSphere MQ Installing WebSphere MQ is a breeze -- simply unpack the install packages to a directory (this article uses mq_install under the root home directory) You can install all of the RPM install packages but this article requires only. Here are the packages and directories included in WebSphere MQ V6: IBMJava2-SDK-1.4.2-0.0.i386.rpm MQSeriesClient-6.0.0-0.i386.rpm MQSeriesConfig-6.0.0-0.i386.rpm MQSeriesFTA-6.0.0-0.i386.rpm MQSeriesIES30-6.0.0-0.i386.rpm MQSeriesJava-6.0.0-0.i386.rpm MQSeriesKeyMan-6.0.0-0.i386.rpm MQSeriesMan-6.0.0-0.i386.rpm MQSeriesMsg_Zh_CN-6.0.0-0.i386.rpm MQSeriesMsg_Zh_TW-6.0.0-0.i386.rpm MQSeriesMsg_de-6.0.0-0.i386.rpm MQSeriesMsg_es-6.0.0-0.i386.rpm MQSeriesMsg_fr-6.0.0-0.i386.rpm MQSeriesMsg_it-6.0.0-0.i386.rpm MQSeriesMsg_ja-6.0.0-0.i386.rpm MQSeriesMsg_ko-6.0.0-0.i386.rpm MQSeriesMsg_pt-6.0.0-0.i386.rpm MQSeriesRuntime-6.0.0-0.i386.rpm MQSeriesSDK-6.0.0-0.i386.rpm MQSeriesSamples-6.0.0-0.i386.rpm MQSeriesServer-6.0.0-0.i386.rpm MQSeriesTXClient-6.0.0-0.i386.rpm PreReqs READMEs copyright gsk7bas-7.0-3.15.i386.rpm lap licenses Here are the installation steps: - Set up a Linux server. This article uses hostnames WMQ1and WMQ2. IP address of WMQ1is 192.168.28.71 and IP-address of WMQ2is 192.168.28.72. - Before installing WebSphere MQ, you must execute ./mqlicense.shto read and accept the license. - Install the required MQ packages and also the WebSphere MQ Java and IBM Java SDK packages, so that you can develop Java clients for WebSphere MQ: wmq1:~/mq_install # rpm -ivh IBMJava2-SDK-1.4.2-0.0.i386.rpm wmq1:~/mq_install # rpm -ivh MQSeriesRuntime-6.0.0-0.i386.rpm wmq1:~/mq_install # rpm -ivh MQSeriesServer-6.0.0-0.i386.rpm wmq1:~/mq_install # rpm -ivh MQSeriesJava-6.0.0-0.i386.rpm WebSphere MQ is now installed, with a user and group called mqm that are used for configuration. By default, WebSphere MQ is installed in /opt/mqm and queues and other configuration information is located in the home directory of user mqm. The Java SDK is installed in /opt/IBMJava2-142 and the Java interpreter is located in /opt/IBMJava2-142/bin. The next step is configuration. This article uses one queue manager with local and remote queues for both machines, which are used to test the sample applications. Configuring WebSphere MQ Configuration consists of following steps: - Create queue manager. - Start queue manager. - Create queues and channels. - Start command server, listener, and channels. These steps are required on both WebSphere MQ machines. The sections below show configuration only on WMQ1, but the same steps are required on WMQ2 also. Create and start queue managers Log in to WMQ1 using root and then change to user mqm by typing su - mqm. Create queue manager for the WMQ1 machine using the following command: mqm@wmq1:~/ # crtmqm WMQ1QM Start the queue manager using following command. mqm@wmq1:~/ # strmqm WMQ1QM Create queue and channels Configure WebSphere MQ using command-line tools. A configuration script for WMQ1 is below. The script defines local queue, remote queue, transmission queue, sender channel, and receiver channel.Save the script as WMQ1QM.conf: DEFINE QLOCAL ('WMQ1InputQ') + REPLACE DEFINE QLOCAL ('WMQ2QMXmitQ') + DESCR('Transmission Queue to WMQ2QM') + USAGE(XMITQ) + TRIGGER + TRIGTYPE(FIRST) + TRIGDPTH(1) + TRIGDATA('WMQ1QM.WMQ2QM') + INITQ('SYSTEM.CHANNEL.INITQ') + REPLACE DEFINE QREMOTE ('WMQ1OutputQ') + XMITQ('WMQ2QMXmitQ') + RNAME('WMQ2InputQ') + RQMNAME('WMQ2QM') + REPLACE DEFINE CHANNEL ('WMQ1QM.WMQ2QM') CHLTYPE(SDR) + TRPTYPE(TCP) + CONNAME('192.168.28.72(1414)') + XMITQ('WMQ2QMXmitQ') + REPLACE DEFINE CHANNEL ('WMQ2QM.WMQ1QM') CHLTYPE(RCVR) + TRPTYPE(TCP) + REPLACE DEFINE CHANNEL ('SYSTEM.ADMIN.SVRCONN') CHLTYPE(SVRCONN) + TRPTYPE(TCP) + DESCR(' ') + HBINT(300) + MAXMSGL(4194304) + MCAUSER('MUSR_MQADMIN') + RCVDATA(' ') + RCVEXIT(' ') + SCYDATA(' ') + SCYEXIT(' ') + SENDDATA(' ') + SENDEXIT(' ') + REPLACE The configuration script above can be used as a template for other WebSphere MQ installations. Only the names in bold need to be changed to set up queues and channels in other WebSphere MQ installations. There are lots of entries in the configuration script -- for more information about them, see the WebSphere MQ Information Center. Configure WebSphere MQ using the command below to create queues and channels: mqm@wmq1:~/ # runmqsc WMQ1QM < WMQ1QM.conf > qcreate.log The command runmqsc is used to issue WebSphere MQ commands. In this case, commands are read from the WMQ1QM.conf file and output is directed to qcreate.log. Open qcreate.log and verify that there were no syntax errors and all valid commands were processed. Start services The command server, listener, and channels need to be started and then everything is ready for developing and testing the sample applications: mqm@wmq1:~/ # strmqcsv WMQ1QM & mqm@wmq1:~/ # runmqlsr -m WMQ1QM -t TCP & Verify that the queue managers and listeners are running on both machines, then start the channels: mqm@wmq1:~/ # runmqchl -m WMQ1QM -c WMQ1QM.WMQ2QM & mqm@wmq1:~/ # runmqchl -m WMQ1QM -c WMQ2QM.WMQ1QM & WebSphere MQ is now installed, configured, and ready to tested. The next section will show the source code of two Java-based applications to send messages to and receive messages from the queue. Sample applications The queue defined in the previous section can be used by the sample Java applications for putting messages in the queue (MQSend) and getting messages out (MQGet). These applications support String messages and are intended for testing and for examples of how to use WebSphere MQ from Java applications. Applications could be used from scripts, which enables all kinds of applications. Both MQSend and MQGet extend from MQConnector class, which provides WebSphere MQ connectivity, initialises WebSphere MQ, opens and closes a queue, and sends messages to and receives messages from a queue. MQConnector MQConnector is a superclass for sending and getting. This class handles opening the connection and sending and getting messages. You configure it using a properties file that specifies the host address, queue manager name, and queue name: queue.manager=WMQ1QM queue.manager.host=192.168.28.71 queue.name=WMQ1OutputQ Here is the MQConnector source code: package mqconn; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties;PutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager; public class MQConnector { protected String qManager = ""; // define name of queue manager protected String qManagerHost = ""; protected String queuName = ""; // define name of queue protected MQQueue mqQueue; protected MQQueueManager qMgr; public static boolean DEBUG = true; public MQConnector() { } public void initMq() { try { FileInputStream fis = new FileInputStream(new File("mqconnect.properties")); Properties props = new Properties(); props.load(fis); fis.close(); qManager = props.getProperty("queue.manager"); qManagerHost = props.getProperty("queue.manager.host"); queuName = props.getProperty("queue.name"); // Create a connection to the queue manager MQEnvironment.channel = "SYSTEM.DEF.SVRCONN"; MQEnvironment.hostname = qManagerHost; debug("Connecting to QueueManager " + qManager + " on " + qManagerHost); qMgr = new MQQueueManager(qManager); } catch (Exception e) { e.printStackTrace(); } } public void openQueue() throws MQException { // Set up the options on the queue we wish to open... // Note. All WebSphere MQ Options are prefixed with MQC in Java. int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT; // Now specify the queue that we wish to open, // and the open options... debug("Opening queue: " + queuName); try { mqQueue = qMgr.accessQueue(queuName, openOptions); } catch(MQException mqe) { //check if MQ reason code 2045 //means that opened queu is remote and it can not be opened as //input queue //try to open as output only if(mqe.reasonCode==2045) { openOptions = MQC.MQOO_OUTPUT; mqQueue = qMgr.accessQueue(queuName, openOptions); } } } public void putMessageToQueue(String msg) throws MQException { try { debug("Sending message: " + msg); MQPutMessageOptions pmo = new MQPutMessageOptions(); MQMessage mqMsg = new MQMessage(); mqMsg.write(msg.getBytes()); // put the message on the queue mqQueue.put(mqMsg, pmo); } catch (IOException e) { e.printStackTrace(); } } public String getMessageFromQueue() throws MQException { try { MQMessage mqMsg = new MQMessage(); MQGetMessageOptions gmo = new MQGetMessageOptions(); // Get a message from the queue mqQueue.get(mqMsg,gmo); //Extract the message data int len=mqMsg.getDataLength(); byte[] message = new byte[len]; mqMsg.readFully(message,0,len); return new String(message); } catch(MQException mqe) { int reason=mqe.reasonCode; if(reason==2033)//no messages { return null; } else { throw mqe; } } catch (IOException e) { e.printStackTrace(); return null; } } public void closeQueue() throws MQException { debug("Closing queue and disconnecting QueueManager..."); // Close the queue... mqQueue.close(); // Disconnect from the queue manager qMgr.disconnect(); } protected boolean hasArg(String arg, String[] args) { for(int i=0;i<args.length;i++) { if(args[i].equals(arg)) { return true; } } return false; } public void debug(Object msg) { if (DEBUG) { System.out.println(msg); } } } This class provides WebSphere MQ functionality to other applications. You can also use MQConnector in your own applications as a super class of your own class, or as a utility class. The following methods provide messaging capability to Java applications: - initMQ() - Reads properties and creates queue manager object. - openQueue() - Opens queue that is specified in properties file. - closeQueue() - Closes opened queue. - disconnectMq() - Disconnects queue manager. - putMessageToQueue(String) - Puts a string message to specified queue. - getMessageFromQueue() - Reads string message from specified queue. MQSend MQSend (shown below) uses MQConnector class and is used as a command-line program to send messages to a queue. Messages are specified as command-line arguments, and you can use it to send the contents of a file as a message: package mqconn; import java.io.BufferedReader; import java.io.FileReader; import com.ibm.mq.MQException; public class MQSend extends MQConnector { public MQSend() { } public void send(String[] args) throws MQException { boolean argsAreFiles = hasArg("-f", args); initMq(); openQueue(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-f")) continue; if (!argsAreFiles) { putMessageToQueue(args[i]); } else { try { // send file contents as message BufferedReader br = new BufferedReader(new FileReader(args[i])); StringBuffer msg = new StringBuffer(); for (String line = br.readLine(); line != null; line = br.readLine()) { msg.append(line); msg.append('\n'); } br.close(); putMessageToQueue(msg.toString()); } catch (Exception e) { System.out.println("Error while processing file " + args[i] + ": " + e.toString()); } } System.out.println("Message sent."); } closeQueue(); disconnectMq(); } public static void main(String[] args) { MQSend mqsend = new MQSend(); MQConnector.DEBUG = false; try { if (args == null || args.length == 0) { System.out.println("Usage: " + mqsend.getClass().getName() + " [-f] <file name | message> [<file name | message> ...]"); System.exit(0); } mqsend.send(args); } catch (Exception e) { System.out.println(e.toString()); System.out.println("Usage: " + mqsend.getClass().getName() + " [-f] <file name | message> [<file name | message> ...]"); } } } MQSend uses MQConnector to provide messaging and the actual MQSend program functionality is very simple. There are two modes of operation: - Send each command-line argument as a separate message. - Send file contents using the -f option. In this case, each command-line argument is a file name. MQGet MQGet class (shown below) is simple -- it retrieves one message from a specified queue and writes it to standard out. you can store the message in a file by using a redirect. package mqconn; import com.ibm.mq.MQException; public class MQGet extends MQConnector { public MQGet() { } public String getMessages(String[] args) throws MQException { String message=getMessageFromQueue(); return message; } public static void main(String[] args) { MQGet mqget = new MQGet(); MQConnector.DEBUG=false; try { mqget.initMq(); mqget.openQueue(); String msg=mqget.getMessages(args); if(msg!=null) { System.out.println(msg); } mqget.closeQueue(); mqget.disconnectMq(); } catch (Exception e) { e.printStackTrace(); System.out.println("Usage: "+mqget.getClass().getName()+" "); } } } MQGet uses the queue manager and queue specified in the mqconnect.properties file. The next section presents some sample use cases that you can use for testing. Sample use cases Here are a few use cases on how to use MQSend and MQGet applications, using WMQ1 as sender and WMQ2 as receive.r Preparations Before using the samples, you need to do some preparation such as setting up properties and making a couple of helper scripts. Use the following properties for the MQSend application in WMQ1: queue.manager=WMQ1QM queue.manager.host=127.0.0.1 queue.name=WMQ1OutputQ Use the following properties for the MQGet application in WMQ2: queue.manager=WMQ2QM queue.manager.host=127.0.0.1 queue.name=WMQ2InputQ To save typing, here are two scripts for sending and receiving /opt/IBMJava2-142/bin/java -cp .:com.ibm.mq.jar mqconn.MQSend "$@" /opt/IBMJava2-142/bin/java -cp .:com.ibm.mq.jar mqconn.MQGet "$@" Change the scripts into executables using chmod 755 mqsend and chmod 755 mqget. All classes and other files in this article are located in the /var/mqm/bin directory where /var/mqm is the home directory of mqm-user. Commands The first sample command sends message to a queue specified above. The sample listing provide the actual command and also the output of the command. mqm@wmq1:~/bin> ./mqsend "This is test message" MQJE001: Completion Code 2, Reason 2045 Message sent. MQJE001 is expected. Reason 2045 means in this case that the queue to be opened cannot be opened as an input queue because the queue is remote. MQJE001 is printed to standard error by WebSphere MQ classes. If you don't want to see these error message, redirect standard error to /dev/null ./mqsend "This is test message" 2> /dev/null. To find out what the reason code means, use mqrc 2045. On WMQ2, use the mqget command to receive the message: mqm@wmq2:~/bin> ./mqget This is test message If you execute mqget again, you get the expected MQJE001 message. mqrc 2033 shows that 2033 means "MQRC_NO_MSG_AVAILABLE." Retrieving the message removes it from the queue. Here is how to send multiple messages: mqm@wmq1:~/bin> ./mqsend "This is test message" This is another message MQJE001: Completion Code 2, Reason 2045 Message sent. Message sent. Message sent. Message sent. Message sent. Receiving messages is the same mqget command shown above. Here is how to receive multiple messages: mqm@wmq2:~/bin> ./mqget This is test message mqm@wmq2:~/bin> ./mqget This mqm@wmq2:~/bin> ./mqget is mqm@wmq2:~/bin> ./mqget another mqm@wmq2:~/bin> ./mqget message mqm@wmq2:~/bin> ./mqget MQJE001: Completion Code 2, Reason 2033 The next sample sends the contents of all Java files: mqm@wmq1:~/bin> ls -1 mqconn/*.java | awk '{print "mqsend -f "$1""}' | sh 2> /dev/null Message sent. Message sent. Message sent. The next sample reads messages and saves them to a file: mqm@wmq2:~/bin> ./mqget > msg1.txt The output of the mqget command is directed to msg1.txt. Conclusion This article showed you how to get started using WebSphere MQ on Linux. Only a few installation and configuration steps are required to get WebSphere MQ running, and these steps provide a good starting point for learning more about WebSphere MQ. The sample applications showed how easy it is to get programmatic access to WebSphere MQ and its messaging capabilities. The sample applications are also a good starting point for developing custom applications. Download trial download A no-charge trial download of WebSphere MQ V6. Includes limited online support for Windows® and Linux® installations at no charge during the trial period. - WebSphere MQ V6 information center A single Eclipse-basedPacs Downloadable code, documentation, and performance reports for the WebSphere MQ family of products. - WebSphere MQ public newsgroup A non-IBM forum where you can get answers to your WebSphere MQ technical questions and share your WebSphere MQ knowledge with other users. -.
http://www.ibm.com/developerworks/websphere/library/techarticles/0705_salkosuo/0705_salkosuo.html
CC-MAIN-2014-42
refinedweb
2,787
50.43
Scope of Global and Local variables This blog is about global and local variables in python Local variables can be accessed only inside the function where they are declared, but global variables can be accessed throughout the program body by all functions. Let’s take an example of code : def my_func(): var = 10 print("Value inside function:",var) This is creating the function. The next code block is calling it. var = 20 my_func() print("Value outside function:",var) The value of var is equal to 20 . The function my_func() changed the value of var to 10, but it did not affect the value outside the function because var is a local variable which is inside the function is different from the one outside which is a global variable. Even though they have the same names, they are two different variables with different scopes. To modify the value of variables outside the function, they must be declared as global variables using the keyword global. def my_func(): global var var = 10 print("Value inside function using global variable:",var)
https://navyapython7.medium.com/scope-of-global-and-local-variables-969402f5e700?source=post_internal_links---------2-------------------------------
CC-MAIN-2022-05
refinedweb
177
58.32
DIY! Since this post I've made an improved version. Read more about Home Energy Monitor V2 here. Goal Before jumping in, I set myself these goals for the project: - Make a non-invasive energy monitor for the entire apartment. Meaning: no wire-cutting and not putting a meter between every socket and light bulb. - Take measurements every second to get an accurate picture of electricity consumption. - Save all the data in the cloud for later use & analytics. - Have a simple app to visualize the data and analyze trends over time. With those in mind, I started building my own home energy monitoring device! The parts I started by looking for parts on AliExpress. I’m no expert in electrical circuits so I followed this guide from OpenEnergyMonitor and ultimately landed on these parts: The two most important components are obviously the ESP32 microcontroller and the CT sensor. ESP32 The ESP32 is a no-brainer for me because I’ve used it before on small projects. They are small, are easy to program (Arduino compatible), have a lot of power (240MHz dual-core processor, 520K memory) and have built-in WiFi which means they can directly connect to the internet. No hubs needed. CT Sensor The other important part is the CT sensor (Current Transformer). This sensor clamps over the main cable in your house and transforms the magnetic field around the cable into a voltage. I went for the YHDC SCT-013-030 which can measure up to 30 amps of current (almost 7000 watts). More than sufficient for my small apartment. This model will output a voltage between 0 and 1, which is easy to measure using the built-in ADC of the ESP32. Others I also ordered a small LCD display to show the electricity consumption in real-time on the device itself. And finally, I ordered some 3,5mm headphone jacks. Why? Well the CT sensor has a 3,5mm connector. My initial thought was to cut it off and connect the wires straight to the ESP. But then I figured it would be nicer to use an actual 3,5mm jack. That way I could swap my sensor, should it be required. Wiring Once the components arrived I wired everything up like this: Note: I used 2x 100kΩ resistors, but you can use any resistor value between 10k and 470k. Just make sure R1 and R2 are of the same value. I first tried it on a breadboard to verify that everything worked and moved it to a protoboard afterward: Designing a case in Fusion360 The protoboard doesn’t look very bad. But it’s not sexy either. So I fired up Fusion 360 with the intention of designing a case so that this could become a consumer product (spoiler alert: it won’t turn out like that). I started by designing a case that has two cutouts on the side. One for the micro USB connector (which is used to power everything) and one for the headphone jack (so that the CT sensor can be connected). I also added a number of standoffs in the middle to support the protoboard and the display. This is what I ended up with: And this is how the display mounts on top of the standoffs: In case you’re wondering: yes, I made dummy models of the display and screws. I like to see how everything fits together before sending it off to the 3D printer. To finish the case, I designed a top lid that is held in place with two screws and has a cutout for the display. Oh and the display sits flush with the top of the lid. Sweet! Ingesting data (with AWS) After that, it was time to think about how I wanted to get the readings into a system where I could analyze them. The people at OpenEnergyMonitor have an open source system called EmonCMS. It’s specifically designed to ingest data from energy monitors. It either runs on a Raspberry Pi that you host yourself or you can use their cloud service. Hosting my own Pi is out of the question. I’m not interested in having to manage it, taking backups and overcoming problems with corrupted SD cards. With their cloud service, you don’t have to do anything yourself and it only costs £1 per year per data feed. However, you can only post data once every 10 seconds and I wanted to store one data point per second. So I decided to make it a fun exercise and build myself a backend that can ingest this data. I’m quite an avid user of AWS and I have experience with their IoT service, Lambda, and DynamoDB. So going for AWS was a no-brainer! Before designing the architecture I set out some goals (again): - It has to be Serverless. I don’t want to manage servers. - No fixed costs (pay for what you use). - It must be able to handle multiple sensors (you never know what the future brings) - Must be able to handle any data rate (ideally 1 reading every second) - Never throw away data! Always archive it and keep it for the future. You never know what might be interesting. This is the architecture that I came up with: Let me explain: on the left side you see the monitoring device. Every 30 seconds it sends 30 readings over an MQTT connection to the AWS IoT service. Once the message is received, an IoT Rule is triggered that writes the raw reading to a DynamoDB table. This happens 2880 times a day (2 times per minute, 1440 minutes in a day). Small side note: by default AWS uses a message broker that dispatches messages coming from your devices to one or more “listeners” (eg a Lambda function). In this case, however, there aren’t multiple consumers. Data should go straight into Dynamo. So I can get away with using the Basic Ingest feature of AWS IoT (which is 25% cheaper). Archiving data Storing raw data in DynamoDB is great to be able to query the latest readings or to show an overview of the current day. It is, however, not the best long-term solution. The sensor is generating 2880 data points every single day. That means that if I want to get an overview of how much electricity was consumed last month, I need DynamoDB to return at least 30*2880 or 86.400 data points. This would consume a lot of read capacity units (RCU). Instead, I realized that older data doesn’t have to stay stored in DynamoDB. I could offload old data and store it on S3 instead! So, I made a Lambda function that is triggered at night and archives all readings from the past day to a single CSV file on S3: Timestamp,Watts 1561939171,115 1561939172,133 1561939173,132 1561939174,137 1561939175,145 1561939176,141 1561939177,132 ... (Uncompressed these files are 1.2MB in size, gzip compression reduces that to 280KB. Storing a year worth of data required at most 438MB or about 100MB compressed) This not only reduces my storage costs, but it also makes retrieving older data much more efficient. Getting all the readings from a particular day in the past is as simple as fetching 1 file from S3. After setting up this Lambda function, I enabled DynamoDB’s TTL feature so that raw readings are automatically removed from the table after 7 days. Calculating total consumption This nightly Lambda function also calculates the total amount of electricity (kWh) that was used during the previous day. This metric can then be used to visualize daily consumption over time. This calculated value is stored in DynamoDB so it can be quickly retrieved and doesn’t have to be recalculated ever again. This is a summary of what happens at the end of each day: DynamoDB: Raw readings, stored for 7 days | -> Archived to S3 every night | -> Total consumption written to DynamoDB (1 row) Costs The cost of all of this is exactly: $0. This entire architecture falls under the AWS free tier (until I have more than 5GB of archived data in S3 or more than 25GB stored in DynamoDB) Arduino software The cloud architecture is ready and waiting for sensor data! I now started working on the software to run on the ESP32. I decided to use the Arduino framework because the documentation is great and they have a bunch of libraries ready to go (also because using the Espressif SDK was a bit intimidating). Let’s break the code down into multiple sections. I started by importing all the libraries that I need and defining some configuration variables: #include <Arduino.h> #include <LiquidCrystal_I2C.h> #include "EmonLib.h" #include "WiFi.h" #include <driver/adc.h> #include "config/config.h" #include "classes/AWSConnector.cpp" // This is the device name as defined on AWS IOT #define DEVICE_NAME "xd-home-energy-monitor-1" // The GPIO pin were the CT sensor is connected to (should be an ADC input) #define ADC_INPUT 34 // The voltage in our apartment. Usually this is 230V for Europe, 110V for US. // Ours is higher because the building has its own high voltage cabin. #define HOME_VOLTAGE 247.0 // Define some variables to establish an MQTT connection with AWS IOT #define AWS_IOT_ENDPOINT "xxxxxxxxxxx.iot.eu-west-1.amazonaws.com" #define AWS_IOT_TOPIC "$aws/rules/xxxxxxxxxxx" #define AWS_RECONNECT_DELAY 200 #define AWS_MAX_RECONNECT_TRIES 50 // Force EmonLib to use 10bit ADC resolution #define ADC_BITS 10 #define ADC_COUNTS (1<<ADC_BITS) // Create instances AWSConnector awsConnector; EnergyMonitor emon1; // Wifi credentials const char *WIFI_SSID = "YOUR WIFI NETWORK NAME"; const char *WIFI_PASSWORD = "WIFI PASSWORD"; // Create instance for LCD display on address 0x27 // (16 characters, 2 lines) LiquidCrystal_I2C lcd(0x27, 16, 2); // Array to store 30 readings (and then transmit in one-go to AWS) short measurements[30]; short measureIndex = 0; unsigned long lastMeasurement = 0; unsigned long timeFinishedSetup = 0; Then I wrote two helper functions to write the current energy consumption and the IP address to the LCD display. That way I can re-use them in other parts of the code: void writeEnergyToDisplay(double watts, double amps){ lcd.setCursor(3, 1); // Start from column 3, first two are broken :/ lcd.print((int)watts); lcd.print("W "); lcd.print(amps); lcd.print("A "); } void printIPAddress(){ lcd.setCursor(3,0); lcd.print(WiFi.localIP()); } I want the ESP to continuously send readings to the cloud, so we’re going to need a WiFi connection. Again, I created a helper function for this. While trying to connect it will show WiFi... on the display. I also configured the ESP to use a custom hostname so I can quickly identify it on the network: void connectToWiFi() { lcd.clear(); lcd.setCursor(3, 0); lcd.print("WiFi... "); WiFi.mode(WIFI_STA); WiFi.setHostname("esp32-energy-monitor"); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Only try 15 times to connect to the WiFi int retries = 0; while (WiFi.status() != WL_CONNECTED && retries < 15){ delay(500); Serial.print("."); retries++; } // If we still couldn't connect to the WiFi, go to deep sleep for a // minute and try again. if(WiFi.status() != WL_CONNECTED){ esp_sleep_enable_timer_wakeup(1 * 60L * 1000000L); esp_deep_sleep_start(); } // If we get here, print the IP address on the LCD printIPAddress(); } Now it’s time for the setup() function. Here we initialize the ADC so that it listens to the signal coming from the CT sensor, initialize the display, connect to the WiFi, initialize the emonlib library and print AWS connect to the display: void setup() { adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11); analogReadResolution(10); Serial.begin(115200); lcd.init(); lcd.backlight(); connectToWiFi(); // Initialize emon library (30 = calibration number) emon1.current(ADC_INPUT, 30); lcd.setCursor(3, 0); lcd.print("AWS connect "); awsConnector.setup(); timeFinishedSetup = millis(); } Quick sidenote on emonlib: the CT sensor will produce a sin wave because it’s clamped to a wire carrying AC current. Emonlib is a library that will convert these raw, sinus wave readings into amps. And finally, the loop() function. This one is a bit more complex than your regular Arduino starter project. I only want to take a measurement once every second. Traditionally that would mean putting a delay(1000) at the end of our loop function. However, in my case, that would make the MQTT connection with AWS unstable. Instead, I keep track of when the last measurement was taken. If that was over 1000 milliseconds ago I take a new one. That way the loop function can go as fast as it wants and the MQTT connection stays stable: void loop(){ unsigned long currentMillis = millis(); // If it's been longer then 1000ms since we took a measurement, take one now! if(currentMillis - lastMeasurement > 1000){ double amps = emon1.calcIrms(1480); // Calculate Irms only double watt = amps * HOME_VOLTAGE; // Update the display writeEnergyToDisplay(watt, amps); lastMeasurement = millis(); // Readings are unstable the first 5 seconds when the device powers on // so ignore them until they stabilise. if(millis() - timeFinishedSetup < 10000){ lcd.setCursor(3, 0); lcd.print("Startup mode "); }else{ printIPAddress(); measurements[measureIndex] = watt; measureIndex++; } } // When we have 30 measurements, send them to AWS! if (measureIndex == 30) { lcd.setCursor(3,0); lcd.print("AWS upload.. "); // Construct the JSON to send to AWS String msg = "{\"readings\": ["; for (short i = 0; i <= 28; i++){ msg += measurements[i]; msg += ","; } msg += measurements[29]; msg += "]}"; awsConnector.sendMessage(msg); measureIndex = 0; } // This keeps the MQTT connection stable awsConnector.loop(); } Installing the sensor With the ESP programmed it was time to install the sensor! I opened my electrical box, looked for the biggest brown wire I could find (the main supply) and clamped the CT sensor over it. Then I routed the cable safely outside and connected it to the microcontroller. I then waited a few minutes, checked AWS and saw the data flowing into DynamoDB. Success! Exposing data with GraphQL With the data flowing into DynamoDB, I needed a way to access it. So I wrote a GraphQL API that runs on Lambda and lets me query the latest readings or readings between a given time range. I then wrote a simple web application (hosted in an S3 bucket) that visualizes the readings with Dygraphs. This was mainly for testing purposes until I had time to create an app. One shortcoming: right now my GraphQL API only reads data from DynamoDB. That means that data older than 7 days aren’t accessible via the API anymore. So I have to adapt the API so that it reads real-time data from Dynamo and historical data from S3. Ionic app Now that I had a GraphQL API, I wanted to create a simple app so I could check the readings on my phone. So, I broke out Ionic framework, interfaced with the same GraphQL API and this is what the app looks like: The homepage shows the current situation in a nutshell: how much electricity is being consumed right now, how much has been used today (so far) in total and the amount of “standby” power. The second tab shows the raw readings for the last 24 hours and the last tab shows our electricity consumption of the last 30 days. We’re currently consuming between 4 and 6kWh of electricity. It also breaks down how much electricity was consumed on day/night tariff. What readings look like After a couple of days of having the setup running, I started to see patterns in the data. Each appliance in the apartment generates a specific “signature” of electricity consumption. Here are just a few examples. This is our fridge (or freezer) periodically turning on the compressor (?): This is how our oven consumes energy. It initially uses 2000W for a couple of minutes to preheat. Then, once it gets up to temperature, starts to turn itself on/off to keep the temperature inside. Future improvements Before wrapping up, I want to talk about future improvements. This project is not completely finished and over time I would like to: - Automatically recognize appliances based on their consumption pattern. - Tweak the GraphQL API so it can read historical data from S3. - Investigate if I could put the ESP32 inside the electrical box on a DIN rail - Integrate with Google Home (if they provide device traits for energy monitors ;) ) Conclusion That’s a wrap! My home energy monitor has been running since January 2019 and it’s still going strong. Buying an existing sensor is certainly possible but I had way too much fun building one myself. I also learned a lot about electronics, ESP32 programming, and how to set up AWS for IoT purposes. What do you think about this project? Would you like to see more DIY projects? Let me know! Also check out the improved Home Energy Monitor V2. Downloads - Fusion360 files for the case + top lid - Full Source Code (ESP32 + AWS + App) available on GitHub
https://savjee.be/2019/07/Home-Energy-Monitor-ESP32-CT-Sensor-Emonlib/
CC-MAIN-2022-40
refinedweb
2,795
63.9
Exit Print View #include <sys/sunldi.h> int ldi_ev_get_cookie(ldi_handle_t lh, char *evname, ldi_ev_cookie_t *cookiep); Solaris DDI specific (Solaris DDI) A layered handle representing the device for which the event notification was requested. The string name of the event. A pointer to type ldi_ev_cookie_t. Contains a pointer to the event cookie on return. The ldi_ev_get_cookie() function accepts the string name of a state change event affecting the device represented by the layered driver handle “lh” and returns an opaque cookie on success. The call is successful if the framework supports event notification for the event named by “evname”. If successful, the function returns an opaque cookie through the “cookiep” parameter. The cookie is required in subsequent calls for registering callbacks on events. The following two LDI events are currently defined: The device is moving to the offline state. The device is moving to the degraded state. ldi_ev_get_cookie() also accepts the string name of any events defined for NDI event services. For such events, ldi_ev_get_cookie() replaces ldi_get_eventcookie(9F) (which is now obsolete). The return values for this function are: The event cookie was created successfully. An error occurred and the cookie was not created. This function can be called from user and kernel contexts only. ldi_ev_register_callbacks(9F), ldi_ev_remove_callbacks(9F)
https://docs.oracle.com/cd/E36784_01/html/E36886/ldi-ev-get-cookie-9f.html
CC-MAIN-2018-43
refinedweb
208
58.69
IN THIS ARTICLE The much-hyped Magic Leap One has taken the AR world by storm. In a nutshell, the Magic Leap One headset overlays digital objects on the physical world, creating another dimension to computing where digital respects the physical thanks to augmented reality. The possibilities of augmented reality are endless and exciting. Now is the time to get involved while the technology is still in its infancy and posed to become a fundamental technology. And the good news is, Magic Leap is investing in their developer community, and it’s something we’re excited to be a part of. This is part one of our Magic Leap series. Check out the other posts Controlling Internet-connected Devices with Magic Leap Hand Gestures and Create a Multiplayer Augmented Reality Game with Magic Leap and Unity. Why PubNub and Magic Leap? Developers have been building multiplayer games and other multi-user experiences with PubNub for years, and we definitely see AR as next on the horizon. PubNub is a natural fit in the AR world. Our technology is what. Multiuser experiences, or the relationship between the AR headset and the physical world around us, is where PubNub is required and excels. Which brings us to this getting started tutorial, and upcoming, more advanced tutorials in the future. Tutorial Overview In this tutorial, we’ll walk through how to: - Install the tools for Unity Video Game Engine development for Magic Leap - Integrate the PubNub Unity SDK and publish a “Hello World” message - Use the Magic Leap Remote and iterate in the simulator or on a device - Build and run apps on the Magic Leap One device. Be aware that the Magic Leap SDKs are changing as new features are added and some parts of this tutorial may change. The following steps were tested with Lumin SDK Version 0.17.0 and Unity Version: 2018.1.9f1-MLTP8.1. Requirements There are a few requirements before you can get started: - You’ll need a Magic Leap One (or you can just use the simulator). - Become a Creator. - A PubNub account (always free). - Once you sign up, you can get your unique PubNub keys from the PubNub Admin Dashboard. Install Lumin SDK and Unity Magic Leap Test Preview - Sign into your Creator account and get the Lumin SDK and Unity by downloading the Magic Leap Package Manager. - Run the Package Manager Installer. After installing, start the Magic Leap Package Manager application. - Select the Lumin SDK and the Magic Leap Unity Package for install. Apply the changes. - Download the Magic Leap Technical Preview Installer and install the Unity Editor (Download link is at the bottom). - See the Installing and Configuring Unity guide from Magic Leap for more information about how to install Lumin SDK and the Unity Magic Leap Test Preview. Create a New Unity App for Magic Leap - Start Unity and create a new project. - Change the product name, set the template to “Magic Leap”, and set the location for your project. Create the project. - Click “File” and then “Build Settings”. - In the “Platform” section: - Close the window. - See the Configuring a Magic Leap Project in Unity guide from Magic Leap for more information on creating a new Unity app for Magic Leap. Integrating PubNub Into a Unity Project. - Clone or download the PubNub Unity SDK. - Inside the “PubNubUnity” directory you should see another directory called “Assets”. Drag the “Assets” directory into the “Assets” directory of your unity project. Ignore the console errors for now. - Navigate inside the “Assets/Serialization” directory and then edit the “JSONSerializer.cs” script so that the second line is commented and the third line is uncommented. Save the file. The top of the file should look like this: #if((!USE_JSONFX_UNITY_IOS) && (!USE_MiniJSON)) //#define USE_JSONFX_UNITY_IOS #define USE_MiniJSON #endif - Click “Window” and then “Test Runner”. - Click on the dropdown menu in the top right corner and enable playmode tests. Close the window. - Click “Edit”, “Project Settings”, and then “Player”. - In the Inspector click “Settings for Lumin OS”. - Expand “Publishing Settings” and check the box next to “Internet”. - Expand “Other Settings” and change the “Scripting Runtime Version” to “.NET 4.x Equivalent”. Restart the editor. The console errors resulting from importing the PubNub Unity SDK should now be gone. - Click on “Main Camera” in the project hierarchy. - Click “Add Component”, scroll to the bottom of the list, and click “New script”. Name the script “HelloWorld”. - Edit the script and paste the code below. This script imports the PubNubAPI, configures a connection to PubNub, and sends a “HelloWorld” message to the “MagicLeap” channel once per second. using System.Collections; using System.Collections.Generic; using UnityEngine; using PubNubAPI; public class HelloWorld : MonoBehaviour { public static PubNub pubnub; private float sendTimeController; // Use this for initialization void Start () { PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.PublishKey = "YOUR_PUBNUB_PUBLISH_KEY_HERE"; pnConfiguration.SubscribeKey = "YOUR_PUBNUB_SUBSCRIBE_KEY_HERE"; pnConfiguration.Secure = true; pubnub = new PubNub(pnConfiguration); } // Update is called once per frame void Update () { if (sendTimeController <= Time.deltaTime) { // Restrict how quickly messages are sent. pubnub.Publish() .Channel("MagicLeap") .Message("HelloWorld") .Async((result, status) => { if (!status.Error) { Debug.Log(string.Format("Publish Timetoken: {0}", result.Timetoken)); } else { Debug.Log(status.Error); Debug.Log(status.ErrorData.Info); } }); sendTimeController = 1.0f; // Restrict how quickly messages are sent. } else { sendTimeController -= Time.deltaTime; // Update the timer. } } } - Get your unique PubNub keys from your PubNub Admin Dashboard. If you don’t have a PubNub account, sign up for a PubNub account for free. - Go to your PubNub Admin Dashboard, create or select your app, and then create or select a keyset. - Replace “YOUR_PUBNUB_PUBLISH_KEY_HERE” and “YOUR_PUBNUB_SUBSCRIBE_KEY_HERE” with your Publish Key and Subscribe Key. - Click “Debug Console” and create a client with “Default Channel” set to “MagicLeap”. Keep this window open when you test your app. The “HelloWorld” messages from the app will be received by this client. Using the Magic Leap Remote and Play Mode See the Launch Magic Leap Remote and Play Mode with Magic Leap Remote guides from Magic Leap for more information about using the Magic Leap Remote. You can change your code and see the results immediately while in play mode. If you do not have a device, play mode simulates the Lumin SDK API layers and composites the graphics with input from a virtual room. If you do have a device, play mode simulates the Lumin SDK API layers and then streams the rendered frames to the headset display. Windows - In Windows Explorer, navigate to the “VirtualDevice\bin\UIFrontend” directory inside your Lumin SDK location. - Double-click “MLRemote.exe”. macOS - In Finder, navigate to the “VirtualDevice/bin/UIFrontend” directory inside your Lumin SDK location. - Double-click “Magic Leap Remote.app”. Iterate on the Simulator - Click “Start Simulator”. - In the Simulator window, click the “Load Virtual Room” button on the toolbar. - Navigate to VirtualDevice\data\VirtualRooms\ExampleRooms and then open an example room file. Iterate on Device - Connect a device to your computer over USB. - The device should appear in the Magic Leap Remote window. - Click “Start Device”. Start Play Mode There is no UX for this app as this post focuses on getting started creating an app, sending messages to PubNub, and running an app. You won’t see anything if you look around in the simulator on a device. However, messages are being sent to PubNub while the app is running. See the Tutorial List from Magic Leap for projects that take advantage of the features offered by Magic Leap APIs. To use the Magic Leap Remote you will need to enable Magic Leap zero iteration mode. In Unity click “MagicLeap” and then “Enable Zero Iteration”. Restart the editor. - Go back to your Unity project. - Click “Edit” and then “Play”. - The app should start on the simulator or on the device. You should see debug messages from successful publishes to PubNub in the console in Unity. - Go to the Debug Console you started earlier in the PubNub Admin Dashboard. You should see “Hello World” being printed once per second. Testing On A Magic Leap Device There is no UX for this app as this post focuses on getting started creating an app, sending messages to PubNub, and running an app. You won’t see anything if you put the headset on. However, messages are being sent to PubNub while the app is running. See the Tutorial List from Magic Leap for projects that take advantage of the features offered by Magic Leap APIs. See Deploying a Unity App to the Device from Magic Leap for more information about deploying an app a device. - You’ll first need to follow the steps from Magic Leap to set up your device for development. - Connect a device to your computer over USB. - On the device navigate to “Settings”, “Device”, and then “Creator Mode”. - Select the following: - Enable Creator Mode – Make Creator Mode options available for selection. - Allow Untrusted Sources – Install apps signed with a development certificate. - Enable MLDB Access – Allow Magic Leap Device Bridge to connect to your device. - Navigate to the Magic Leap Creator Portal and click “Publish” and then “Certificates”. - Click “Create Certificate” or “Add New”. - Enter a name for the certificate and click generate. The “privatekey.zip” file will download. You can only download the private key at this step. You must generate a new certificate if you misplace this file. - The certificate takes a few minutes to generate. Refresh the page until the certificate status changes from “pending” to “active”. - When the certificate has generated, click the download button next to your certificate to download the file. - Extract the private key from the “privatekey.zip” file and move the “.privkey“ and “.cert” files into the same folder. - Go back to your Unity project. - Click “File” and then “Build Settings”. - Check the box next to “Sign Package”. - Close the window. - Click “Edit”, “Project Settings”, and then “Player”. - Expand “Publishing Settings” and set the path to “ML Certificate” to point to the certificate you downloaded. - Connect your device to your computer. - Click “File” and then “Build and Run”. - Save the .mpk. Unity will transfer the app to the device when the build has completed. - Put on the device. - The first time you install an app with your Magic Leap developer certificate, you are prompted to accept the certificate on the device. - If you do not accept the certificate, your app won’t install. - If you take too long to put on the device, the prompt will dismiss itself, and your app won’t install. - Go to the Debug Console you started earlier in the PubNub Admin Dashboard. You should see “Hello World” being printed once per second. Have suggestions or questions about the content of this post? Reach out at devrel@pubnub.com. This is part one of our Magic Leap series. Check out the other posts Controlling Internet-connected Devices with Magic Leap Hand Gestures and Create a Multiplayer Augmented Reality Game with Magic Leap and Unity.
https://www.pubnub.com/blog/getting-started-with-magic-leap-and-unity-developer-tutorial/
CC-MAIN-2019-51
refinedweb
1,808
59.3
JavaScript fundamentals before learning React After all my teachings about React, be it online for a larger audience or on-site for companies transitioning to web development and React, I always come to the conclusion that React is all about JavaScript. Newcomers to React but also myself see it as an advantage, because you carry your JavaScript knowledge for a longer time around compared to your React skills. During my workshops, the larger part of the material is about JavaScript and not React. Most of it boils down to JavaScript ES6 and beyond – features and syntax – but also ternary operators, shorthand versions in the language, the this object, JavaScript built-in functions (map, reduce, filter) or more general concepts such as composability, reusability, immutability, closures, truth tables, or higher-order functions. These are the fundamentals, which you don’t need necessarily to master before starting with React, but which will definitely come up while learning or practicing it. The following walkthrough is my attempt giving you an almost extensive yet concise list about all the different JavaScript functionalities that complement your React knowledge. If you have any other things which are not in the list, just leave a comment for this article and I will keep it up to date. Table of Contents - Entering React after learning JavaScript - React and JavaScript Classes - Arrow Functions in React - Functions as Components in React - React Class Component Syntax - Template Literals in React - Map, Reduce and Filter in React - var, let, and const in React - Ternary Operator in React - Import and Export Statements in React - Libraries in React - Async/Await in React - Higher-Order Functions in React - Shorthand Object Assignment - Destructuring in React - Spread Operator in React - There is more JavaScript than React The Road to learn React Build a Hacker News App along the way. No setup configuration. No tooling. No Redux. Plain React in 200+ pages of learning material. Pay what you want like 50.000+ readers.Get the Book Entering React after learning JavaScript When you enter the world of React, you are often confronted with a React Class Component: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} <h1> Hello React </h1> <a href=""> Learn React </a> </header> </div> ); } } export default App; In a React class component, there are lots of things to digest for beginners which are not necessarily React: class statements, class methods and inheritance due to being a class. Also JavaScript import statements are only adding complexity when learning React. Even though the main focus point should be JSX (React’s syntax) – everything in the return statement – in the very beginning, often all the things around demand explanations as well. This article is supposed to shed some light into all the things around, most of it JavaScript, without worrying too much about React. React and JavaScript Classes Being confronted with a React class component, requires the prior knowledge about JavaScript classes. One would assume that this is given knowledge, but it isn’t, because JavaScript classes are fairly new in the language. Previously, there was only JavaScript’s prototype chain which has been used for inheritance too. JavaScript classes build up on top of the prototypical inheritance giving the whole thing a simpler representation with syntactic sugar. In order to understand JavaScript classes, you can take some time learning about them without React: class Developer { constructor(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } getName() { return this.firstname + ' ' + this.lastname; } } var me = new Developer('Robin', 'Wieruch'); console.log(me.getName()); A class describes an entity which is used as a blueprint to create an instance of this entity. Once an instance of the class gets created with the new statement, the constructor of the class is called which instantiates the instance of the class. Therefore, a class can have properties which are usually located in its constructor. In addition, class methods (e.g. getName()) are used to read (or write) data of the instance. The instance of the class is represented as the this object within the class, but outside the instance is just assigned to a JavaScript variable. Usually classes are used for inheritance in object-oriented programming. They are used for the same in JavaScript whereas the extends statement can be used to inherit with one class from another class. The more specialized class inherits all the abilities from the more general class with the extends statement, and can add its specialized abilities to it: class Developer { constructor(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } getName() { return this.firstname + ' ' + this.lastname; } } class ReactDeveloper extends Developer { getJob() { return 'React Developer'; } } var me = new ReactDeveloper('Robin', 'Wieruch'); console.log(me.getName()); console.log(me.getJob()); Basically that’s all it needs to fully understand React class components. A JavaScript class is used for defining a React component, but as you can see, the React component is only a “React component” because it inherits all the abilities from the actual React Component class which is imported from the React package: import React, { Component } from 'react'; class App extends Component { render() { return ( <div> <h1>Welcome to React</h1> </div> ); } } export default App; That’s why the render() method is mandatory in React class components: The React Component from the imported React package instructs you to use it for displaying something in the browser. Furthermore, without extending from the React Component, you wouldn’t be able to use other lifecycle methods. For instance, there wouldn’t be a componentDidMount() lifecycle method, because the component would be an instance of a vanilla JavaScript class. And not only the lifecycle methods would go away, React’s API methods such as this.setState() for local state management wouldn’t be available as well. However, as you have seen, using a JavaScript class is beneficial for extending the general class with your specialized behavior. Thus you can introduce your own class methods or properties. import React, { Component } from 'react'; class App extends Component { getGreeting() { return 'Welcome to React'; } render() { return ( <div> <h1>{this.getGreeting()}</h1> </div> ); } } export default App; Now you know why React uses JavaScript classes for defining React class components. They are used when you need access to React’s API (lifecycle methods, this.state and this.setState()). In the following, you will see how React components can be defined in a different way without using a JavaScript class. After all, JavaScript classes welcome one using inheritance in React, which isn’t a desired outcome for React, because React favors composition over inheritance. So the only class you should extend from your React components should be the official React Component. Arrow Functions in React When teaching someone about React, I explain JavaScript arrow functions pretty early. They are one of JavaScript’s language additions in ES6 which pushed JavaScript forward in functional programming. // JavaScript ES5 function function getGreeting() { return 'Welcome to JavaScript'; } // JavaScript ES6 arrow function with body const getGreeting = () => { return 'Welcome to JavaScript'; } // JavaScript ES6 arrow function without body and implicit return const getGreeting = () => 'Welcome to JavaScript'; JavaScript arrow functions are often used in React applications for keeping the code concise and readable. I love them, teach them early, but always try to refactor my functions from JavaScript ES5 to ES6 functions along the way. At some point, when the differences between JavaScript ES5 functions and JavaScript ES6 functions become clear, I stick to the JavaScript ES6 way of doing it with arrow functions. However, I always see that too many different syntaxes can be overwhelming for React beginners. So I try to make the different characteristics of JavaScript functions clear before going all-in using them in React. In the following sections, you will see how JavaScript arrow functions are commonly used in React. Functions as Components in React React uses the best of different programming paradigms. That’s only possible because JavaScript is a many-sided programming language. On the object-oriented programming side, React’s class components are a great way of leveraging the abilities of JavaScript classes (inheritance for the React component API, class methods and class properties such as this.setState() and this.state). On the other side, there are lots of concepts from functional programming used in React (and its ecosystem) too. For instance, React’s function components are another way of defining components in React. The question which led to function components in React: What if components could be used like functions? function (props) { return view; } It’s a function which receives an input (e.g. props) and returns the displayed HTML elements (view). Under the hood, the function only needs to use the rendering mechanism of the render() method from React components: function Greeting(props) { return <h1>{props.greeting}</h1>; } Function components are the preferred way of defining components in React. They have less boilerplate, add less complexity, and are simpler to maintain than React class components. You can easily migrate your class components to function components with React Hooks. Previously, the article mentioned JavaScript arrow functions and how they improve your React code. Let’s apply these kind of functions to your function components. The previous Greeting component has two different looks with JavaScript ES5 and ES6: // JavaScript ES5 function function Greeting(props) { return <h1>{props.greeting}</h1>; } // JavaScript ES6 arrow function const Greeting = (props) => { return <h1>{props.greeting}</h1>; } // JavaScript ES6 arrow function // without body and implicit return const Greeting = (props) => <h1>{props.greeting}</h1>; JavaScript arrow functions are a great way of keeping your function components in React concise. Even more when there is no computation in between and thus the function body and return statement can be left out. React Class Component Syntax React’s way of defining components evolved over time. In its early stages, the React.createClass() method was the default way of creating a React class component. Nowadays, it isn’t used anymore, because with the rise of JavaScript ES6, the previously used React class component syntax became the default (only before React function components were introduced). However, JavaScript is evolving constantly and thus JavaScript enthusiast pick up new ways of doing things all the time. That’s why you will find often different syntaxes for React class components. One way of defining a React class component, with state and class methods, is the following: class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0, }; this.onIncrement = this.onIncrement.bind(this); this.onDecrement = this.onDecrement.bind(this); }> ); } } However, when implementing lots of React class components, the binding of class methods in the constructor – and having a constructor in the first place – becomes a tedious implementation detail. Fortunately, there is a shorthand syntax for getting rid of both: class Counter extends Component { state = { counter: 0, };> ); } } By using JavaScript arrow functions, you can auto-bind class methods without having to bind them in the constructor. Also the constructor can be left out, when not using the props, by defining the state directly as a class property. ( Note: Be aware that class properties are not in the JavaScript language yet.) Therefore you can say that this way of defining a React class component is way more concise than the other version. Template Literals in React Template literals are another JavaScript language specific feature that came with JavaScript ES6. It is worth to mention it shortly, because when people new to JavaScript and React see them, they can be confusing as well. When learning JavaScript, it’s the following syntax that you grow up with for concatenating a string: function getGreeting(what) { return 'Welcome to ' + what; } const greeting = getGreeting('JavaScript'); console.log(greeting); // Welcome to JavaScript Template literals can be used for the same which is called string interpolation: function getGreeting(what) { return `Welcome to ${what}`; } You only have to use backticks and the ${} notation for inserting JavaScript primitives. However, string literals are not only used for string interpolation, but also for multiline strings in JavaScript: function getGreeting(what) { return ` Welcome to ${what} `; } Basically that’s how larger text blocks can be formatted on multiple lines. For instance, it can be seen with the recent introduction of GraphQL in JavaScript, because GraphQL queries are composed with template literals. Also React Styled Components makes use of template literals. Map, Reduce and Filter in React What’s the best approach teaching the JSX syntax for React beginners? Usually I start out with defining a variable in the render() method and using it as JavaScript in HTML in the return block. import React from 'react'; const App = () => { var greeting = 'Welcome to React'; return ( <div> <h1>{greeting}</h1> </div> ); }; export default App; You only have to use the curly braces to get your JavaScript in HTML. Going from rendering a string to a complex object isn’t any different. import React from 'react'; const App = () => { var user = { name: 'Robin' }; return ( <div> <h1>{user.name}</h1> </div> ); } export default App; Usually the next question then is: How to render a list of items? That’s one of the best parts about explaining React in my opinion. There is no React specific API such as a custom attribute on a HTML tag which enables you to render multiple items in React. You can use plain JavaScript for iterating over the list of items and returning HTML for each item. import React from 'react'; const App = () => { var users = [ { name: 'Robin' }, { name: 'Markus' }, ]; return ( <ul> {users.map(function (user) { return <li>{user.name}</li>; })} </ul> ); }; export default App; Having used the JavaScript arrow function before, you can get rid of the arrow function body and the return statement which leaves your rendered output way more concise. import React from 'react'; const App = () => { var users = [ { name: 'Robin' }, { name: 'Markus' }, ]; return ( <ul> {users.map(user => <li>{user.name}</li>)} </ul> ); } export default App; Pretty soon, every React developer becomes used to the built-in JavaScript map() methods for arrays. It just makes so much sense to map over an array and return the rendered output for each item. The same can be applied for custom tailored cases where filter() or reduce() make more sense rather than rendering an output for each mapped item. import React from 'react'; const App = () => { var users = [ { name: 'Robin', isDeveloper: true }, { name: 'Markus', isDeveloper: false }, ]; return ( <ul> {users .filter(user => user.isDeveloper) .map(user => <li>{user.name}</li>) } </ul> ); }; export default App; In general, that’s how React developers are getting used to these JavaScript built-in functions without having to use a React specific API for it. It is just JavaScript in HTML. var, let, and const in React Also the different variable declarations with var, let and const can be confusing for beginners to React even though they are not React specific. Maybe it is because JavaScript ES6 was introduced when React became popular. In general, I try to introduce let and const very early in my workshops. It simply starts with exchanging var with const in a React component: import React from 'react'; const App = () => { const users = [ { name: 'Robin' }, { name: 'Markus' }, ]; return ( <ul> {users.map(user => <li>{user.name}</li>)} </ul> ); }; export default App; Then I give the rules of thumb when to use which variable declaration: - (1) don’t use varanymore, because letand constare more specific - (2) default to const, because it cannot be re-assigned or re-declared - (3) use letwhen re-assigning the variable While let is usually used in a for loop for incrementing the iterator, const is normally used for keeping JavaScript variables unchanged. Even though it is possible to change the inner properties of objects and arrays when using const, the variable declaration shows the intent of keeping the variable unchanged though. Ternary Operator in React But it doesn’t end with displaying JavaScript strings, objects, and arrays in React. What about an if-else statement for enabling conditional rendering? You cannot use an if-else statement directly in JSX, but you can return early from the rendering function. Returning null is valid in React when displaying nothing. import React from 'react'; const App = () => { const users = [ { name: 'Robin' }, { name: 'Markus' }, ]; const showUsers = false; if (!showUsers) { return null; } return ( <ul> {users.map(user => <li>{user.name}</li>)} </ul> ); }; export default App; However, if you want to use an if-else statement within the returned JSX, you can do it by using a JavaScripts ternary operator: import React from 'react'; const App = () => { const users = [ { name: 'Robin' }, { name: 'Markus' }, ]; const showUsers = false; return ( <div> {showUsers ? ( <ul> {users.map(user => ( <li>{user.name}</li> ))} </ul> ) : null} </div> ); }; export default App; Another way of doing it, if you only return one side of the conditional rendering anyway, is using the && operator: import React from 'react'; const App = () => { const users = [ { name: 'Robin' }, { name: 'Markus' }, ]; const showUsers = false; return ( <div> {showUsers && ( <ul> {users.map(user => ( <li>{user.name}</li> ))} </ul> )} </div> ); }; export default App; I will not go into detail why this works, but if you are curious, you can learn about it and other techniques for conditional rendering over here: All the conditional renderings in React. After all, the conditional rendering in React only shows again that most of React is only JavaScript in JSX and not anything React specific. Import and Export Statements in React Fortunately, the JavaScript community settled on one way to import and export functionalities from files with JavaScript ES6 with import and export statements. However, being new to React and JavaScript ES6, these import and export statements are just another topic which requires explanation when getting started with your first React application. Pretty early you will have your first imports for CSS, SVG or other JavaScript files. The create-react-app project already starts with those import statements: import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} <h1> Hello React </h1> <a href=""> Learn React </a> </header> </div> ); } export default App; It’s great for the starter project, because it offers you a well-rounded experience how other files can be imported and (exported). Also the App component gets imported in the src/index.js file. However, when doing your first steps in React, I try to avoid those imports in the beginning. Instead, I try to focus on JSX and React components. Only later the import and export statements are introduced when separating the first React component or JavaScript function in another file. So how do these import and export statements work? Let’s say in one file you want to export the following variables: const firstname = 'Robin'; const lastname = 'Wieruch'; export { firstname, lastname }; Then you can import them in another file with a relative path to the first file: import { firstname, lastname } from './file1.js'; console.log(firstname); // output: Robin So it’s not necessarily about importing/exporting components or functions, it’s about sharing everything that is assignable to a variable (leaving out CSS or SVG imports/exports, but speaking only about JS). You can also import all exported variables from another file as one object: import * as person from './file1.js'; console.log(person.firstname); // output: Robin Imports can have an alias. It can happen that you import functionalities from multiple files that have the same named export. That’s why you can use an alias: import { firstname as username } from './file1.js'; console.log(username); // output: Robin All the previous cases are named imports and exports. But there exists the default statement too. It can be used for a few use cases: - to export and import a single functionality - to highlight the main functionality of the exported API of a module - to have a fallback import functionality const robin = { firstname: 'Robin', lastname: 'Wieruch', }; export default robin; Leave out the curly braces for the import to import the default export: import developer from './file1.js'; console.log(developer); // output: { firstname: 'Robin', lastname: 'Wieruch' } Furthermore, the import name can differ from the exported default name. You can also use it in conjunction with the named export and import statements: const firstname = 'Robin'; const lastname = 'Wieruch'; const person = { firstname, lastname, }; export { firstname, lastname, }; export default person; And import the default or the named exports in another file: import developer, { firstname, lastname } from './file1.js'; console.log(developer); // output: { firstname: 'Robin', lastname: 'Wieruch' } console.log(firstname, lastname); // output: Robin Wieruch You can also spare additional lines and export the variables directly for named exports: export const firstname = 'Robin'; export const lastname = 'Wieruch'; These are the main functionalities for ES6 modules. They help you to organize your code, to maintain your code, and to design reusable module APIs. You can also export and import functionalities to test them. Libraries in React React offers state management and side-effect features, but apart from this, it is only a component library which renders HTML for your browser. Everything else can be added from APIs (e.g. browser API, DOM API), JavaScript functionalities (e.g. map, filter, reduce) or external libraries. It’s not always simple to choose the right library for complementing your React application, but once you have a good overview of the different options, you can pick the one which fits best to your tech stack. For instance, fetching data in React can be done with the native fetch API: import React, { Component } from 'react'; class App extends Component { state = { data: null, }; componentDidMount() { fetch('') .then(response => response.json()) .then(data => this.setState({ data })); } render() { ... } } export default App; But it is up to you to use another library to fetch data in React. Axios is one popular choice for React applications: import React, { Component } from 'react'; import axios from 'axios'; class App extends Component { state = { data: null, }; componentDidMount() { axios.get('') .then(response => this.setState({ data: response.data })); } render() { ... } } export default App; So once you know about your problem which needs to be solved, React’s extensive and innovative ecosystem should give you plenty of options solving it. There again it’s not about React, but knowing about all the different JavaScript libraries which can be used to complement your application. Async/Await in React In a React Function Component, fetching data looks slightly different with React Hooks: import React from 'react'; import axios from 'axios'; const App = () => { const [data, setData] = React.useState(null); React.useEffect(() => { const fetchData = () => { axios.get('') .then(response => setData(response.data)); }; fetchData(); }, []); return ( ... ); }; export default App; In the previous code snippet, we have used the most common way to resolve a promise with a then-block. The catch-block for error handling is missing for keeping the example simple. Please read one of the referenced tutorials to learn more about fetching data in React with error handling. Anyway, you can also use async/await which got introduced to JavaScript not long ago: import React from 'react'; import axios from 'axios'; const App = () => { const [data, setData] = React.useState(null); React.useEffect(() => { const fetchData = async () => { const response = await axios.get(''); setData(response.data); }; fetchData(); }, []); return ( ... ); }; export default App; In the end, async/await is just another way of resolving promises in asynchronous JavaScript. Higher-Order Functions in React Higher-order functions are a great programming concept especially when moving towards functional programming. In React, it makes total sense to know about these kind of functions, because at some point you have to deal with higher-order components which can be explained best when knowing about higher-order functions in the first place. Higher-order functions can be showcased in React early on without introducing higher-order components. For instance, let’s say a rendered list of users can be filtered based on the value of an input field. import React from 'react'; const App = () => { const users = [{ name: 'Robin' }, { name: 'Markus' }]; const [query, setQuery] = React.useState(''); const handleChange = event => { setQuery(event.target.value); }; return ( <div> <ul> {users .filter(user => user.name.includes(query)) .map(user => ( <li>{user.name}</li> ))} </ul> <input type="text" onChange={handleChange} /> </div> ); }; export default App; It’s not always desired to extract functions, because it can add unnecessary complexity, but on the other side, it can have beneficial learning effects for JavaScript. In addition, by extracting a function you make it testable in isolation from the React component. So let’s showcase it with the function which is provided to the built-in filter function. import React from 'react'; function doFilter(user) { return user.name.includes(query); } const App = () => { const users = [{ name: 'Robin' }, { name: 'Markus' }]; const [query, setQuery] = React.useState(''); const handleChange = event => { setQuery(event.target.value); }; return ( <div> <ul> {users.filter(doFilter).map(user => ( <li>{user.name}</li> ))} </ul> <input type="text" onChange={handleChange} /> </div> ); }; export default App; The previous implementation doesn’t work because the doFilter() function needs to know about the query property from the state. So you can pass it to the function by wrapping it with another function which leads to a higher-order function. import React from 'react'; function doFilter(query) { return function(user) { return user.name.includes(query); }; } const App = () => { const users = [{ name: 'Robin' }, { name: 'Markus' }]; const [query, setQuery] = React.useState(''); const handleChange = event => { setQuery(event.target.value); }; return ( <div> <ul> {users.filter(doFilter(query)).map(user => ( <li>{user.name}</li> ))} </ul> <input type="text" onChange={handleChange} /> </div> ); }; export default App; Basically a higher-order function is a function which returns a function. By using JavaScript ES6 arrow functions, you can make a higher-order function more concise. Furthermore, this shorthand version makes it more attractive composing functions into functions. const doFilter = query => user => user.name.includes(query); Now, the doFilter() function can be exported from the file and tested in isolation as pure (higher-order) function. After learning about higher-order functions, all the fundamental knowledge is established to learn more about React’s higher-order components, if you want to learn about this advanced technique in React. Moving functions around your code base is a great way to learn about the benefits of having functions as first class citizens in JavaScript. It’s powerful when moving your code towards functional programming. Shorthand Object Assignment There is one little addition in the JavaScript language which leaves beginners confused. In JavaScript ES6, you can use a shorthand property syntax to initialize your objects more concisely, like following object initialization: const name = 'Robin'; const user = { name: name, }; When the property name in your object is the same as your variable name, you can do the following: const name = 'Robin'; const user = { name, }; Shorthand method names are also useful. In JavaScript ES6, you can initialize methods in an object more concisely: // without shorthand method names var userService = { getUserName: function (user) { return user.firstname + ' ' + user.lastname; }, }; // shorthand method names const userService = { getUserName(user) { return user.firstname + ' ' + user.lastname; }, }; Finally, you are allowed to use computed property names in JavaScript ES6: // normal usage of key property in an object var user = { name: 'Robin', }; // computed key property for dynamic naming const key = 'name'; const user = { [key]: 'Robin', }; You are able to use computed property names to allocate values by key in an object dynamically, a handy way to generate lookup tables (also called dictionaries) in JavaScript. Destructuring in React Another language feature introduced in JavaScript is called destructuring. It’s often the case that you have to access plenty of properties from your state or props in your component. Rather than assigning them to a variable one by one, you can use destructuring assignment in JavaScript. const state = { counter: 1, list: ['a', 'b'] }; // no object destructuring const list = state.list; const counter = state.counter; // object destructuring const { list, counter } = state; That’s especially beneficial for React’s Function Components, because they always receive the props object in their function signature. Often you will not use the props but only its content, so you can destructure the content in the function signature. // no destructuring function Greeting(props) { return <h1>{props.greeting}</h1>; } // destructuring function Greeting({ greeting }) { return <h1>{greeting}</h1>; } The destructuring works for JavaScript arrays too: const list = ['a', 'b']; // no array destructuring const itemOne = list[0]; const itemTwo = list[1]; // array destructuring const [itemOne, itemTwo] = list; As you have already seen, React Hooks are using the array destructuring to access state and state updater function. import React from 'react'; const Counter = () => { const [count, setCount] = React.useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }; export default Counter; Another great feature is the rest destructuring. It is often used for splitting out a part of an object, but keeping the remaining properties in another object. const state = { counter: 1, list: ['a', 'b'] }; // rest destructuring const { list, ...rest } = state; console.log(rest); // output: { counter: 1 } console.log(list); // output: ['a', 'b'] Afterward, the list can be used to be rendered, for instance in a React component, whereas the remaining state (here counter) is used somewhere else. That’s where the JavaScript spread operator comes into play to forward the rest object to the next component. In the next section, you will see this operator in action. Spread Operator in React The spread operator comes with three …, but shouldn’t be mistaken for the rest operator. It depends on the context where it is used. Used within a destructuring (see above), it is as rest operator. Used somewhere else it is a spread operator. const userCredentials = { firstname: 'Robin' }; const userDetails = { nationality: 'German' }; const user = { ...userCredentials, ...userDetails, }; console.log(user); // output: { firstname: 'Robin', nationality: 'German' } The spread operator literally spreads all the key value pairs of an object. In React, it comes in handy when props are just being passed down to the next component. import React from 'react'; const App = () => { const users = [ { name: 'Robin', nationality: 'German' }, { name: 'Markus', nationality: 'American' }, ]; return ( <ul> {users.map(user => <li> <User name={user.name} nationality={user.nationality} /> </li>)} </ul> ); }; const User = ({ name, nationality }) => <span>{name} from {nationality}</span>; export default App; Rather than passing all properties of an object property by property, you can use the spread operator to pass all key value pairs to the next component. import React from 'react'; const App = () => { const users = [ { name: 'Robin', nationality: 'German' }, { name: 'Markus', nationality: 'American' }, ]; return ( <ul> {users.map(user => <li> <User {...user} /> </li>)} </ul> ); }; const User = ({ name, nationality }) => <span>{name} from {nationality}</span>; export default App; Also you don’t need to worry about the object’s structure beforehand, because the operator simply passes everything to the next component. There is more JavaScript than React In conclusion, there is lots of JavaScript which can be harnessed in React. Whereas React has only a slim API surface area, developers have to get used to all the functionalities JavaScript has to offer. The saying is not without any reason: “being a React developer makes you a better JavaScript developer”. Let’s recap some of the learned aspects of JavaScript in React by refactoring a higher-order component. function withLoading(Component) { return class WithLoading extends React.Coomponent { render() { const { isLoading, ...rest } = this.props; if (isLoading) { return <p>Loading</p>; } return <Component { ...rest } />; } } } This higher-order component is only used for showing a conditional loading indicator when the isLoading prop is set to true. Otherwise it renders the input component. You can already see the (rest) destructuring from the props and the spread operator in for the next Component. The latter can be seen for the rendered Component, because all the remaining properties from the props object are passed to the Component as key value pairs. The first step for making the higher-order component more concise is refactoring the returned React Class Component to a Function Component: function withLoading(Component) { return function ({ isLoading, ...rest }) { if (isLoading) { return <p>Loading</p>; } return <Component { ...rest } />; }; } You can see that the rest destructuring can be used in the function’s signature too. Next, using JavaScript ES6 arrow functions makes the higher-order component more concise again: const withLoading = Component => ({ isLoading, ...rest }) => { if (isLoading) { return <p>Loading</p>; } return <Component { ...rest } />; } And adding the ternary operator shortens the function body into one line of code. Thus the function body can be left out and the return statement can be omitted. const withLoading = Component => ({ isLoading, ...rest }) => isLoading ? <p>Loading</p> : <Component { ...rest } /> As you can see, the higher-order component uses various JavaScript and not React relevant techniques: arrow functions, higher-order functions, a ternary operator, destructuring and the spread operator. Basically that’s how JavaScript’s functionalities can be used in React applications in a nutshell. Often people say that learning React has a steep learning curve. But it hasn’t when only leaving React in the equation and leaving all the JavaScript out of it. React doesn’t add any foreign abstraction layer on top as other web frameworks are doing it. Instead you have to use JavaScript. So hone your JavaScript skills and you will become a great React developer.
https://www.robinwieruch.de/javascript-fundamentals-react-requirements/?fbclid=IwAR0U2EQu9Nb6xHbLmhbdiD6i3BV8a_4LddgqsIcTU1w1DAXks3Rg0sCVraE
CC-MAIN-2019-35
refinedweb
5,465
52.39
Learn about troubleshooting steps that you might find helpful if you run into problems using Google Kubernetes Engine (GKE). Debugging Kubernetes resources If you are experiencing an issue related to your cluster, refer to Troubleshooting Clusters in the Kubernetes documentation. If you are having an issue with your application, its Pods, or its controller object, refer to Troubleshooting Applications. The kubectl command isn't found First, install the kubectl binary by running the following command: sudo gcloud components update kubectl Answer "yes" when the installer prompts you to modify your $PATH environment variable. Modifying this variable enables you to use kubectl commands without typing their full file path. Alternatively, add the following line to ~/.bashrc (or ~/.bash_profile in macOS, or wherever your shell stores environment variables): export PATH=$PATH:/usr/local/share/google/google-cloud-sdk/bin/ Finally, run the following command to load your updated .bashrc (or .bash_profile) file: source ~/.bashrc kubectl commands return "connection refused" error Set the cluster context with the following command: gcloud container clusters get-credentials [CLUSTER_NAME] If you are unsure of what to enter for CLUSTER_NAME, use the following command to list your clusters: gcloud container clusters list kubectl commands return "failed to negotiate an api version" error Ensure kubectl has authentication credentials: gcloud auth application-default login The kubectl logs, attach, exec, and port-forward commands hang These commands rely on the cluster's master being able to talk to the nodes in the cluster. However, because the master isn't in the same Compute Engine network as your cluster's nodes, we rely on SSH tunnels to enable secure communication. GKE saves an SSH public key file in your Compute Engine project metadata. All Compute Engine VMs using Google-provided images regularly check their project's common metadata and their instance's metadata for SSH keys to add to the VM's list of authorized users. GKE also adds a firewall rule to your Compute Engine network allowing SSH access from the master's IP address to each node in the cluster. If any of the above kubectl commands don't run, it's likely that the master is unable to open SSH tunnels with the nodes. Check for these potential causes: The cluster doesn't have any nodes. If you've scaled down the number of nodes in your cluster to zero, SSH tunnels won't work. To fix it, resize your cluster to have at least one node. Pods in the cluster have gotten stuck in a terminating state and have prevented nodes that no longer exist from being removed from the cluster. This is an issue that should only affect Kubernetes version 1.1, but could be caused by repeated resizing of the cluster. To fix it, delete the Pods that have been in a terminating state for more than a few minutes. The old nodes are then removed from the master's API and replaced by the new nodes. Your network's firewall rules don't allow for SSH access to the master. All Compute Engine networks are created with a firewall rule called "default-allow-ssh" that allows SSH access from all IP addresses (requiring a valid private key, of course). GKE also inserts an SSH rule for each cluster of the form gke-<cluster_name>-<random-characters>-sshthat allows SSH access specifically from the cluster's master IP to the cluster's nodes. If neither of these rules exists, then the master will be unable to open SSH tunnels. To fix it, re-add a firewall rule allowing access to VMs with the tag that's on all the cluster's nodes from the master's IP address. Your project's common metadata entry for "ssh-keys" is full. If the project's metadata entry named "ssh-keys" is close to the 32KiB size limit, then GKE isn't able to add its own SSH key to enable it to open SSH tunnels. You can see your project's metadata by running gcloud compute project-info describe [--project=PROJECT], then check the length of the list of ssh-keys. To fix it, delete some of the SSH keys that are no longer needed. You have set a metadata field with the key "ssh-keys" on the VMs in the cluster. The node agent on VMs prefers per-instance ssh-keys to project-wide SSH keys, so if you've set any SSH keys specifically on the cluster's nodes, then the master's SSH key in the project metadata won't be respected by the nodes. To check, run gcloud compute instances describe <VM-name>and look for an "ssh-keys" field in the metadata. To fix it, delete the per-instance SSH keys from the instance metadata. It's worth noting that these features are not required for the correct functioning of the cluster. If you prefer to keep your cluster's network locked down from all outside access, be aware that features like these won't work. Metrics from your cluster aren't showing up in Stackdriver Ensure that you have activated the Stackdriver Monitoring API and the Stackdriver Logging API on your project, and that you are able to view your project in Stackdriver Monitoring. If the issue persists, check the following potential causes: Ensure that you have enabled monitoring on your cluster. Monitoring is enabled by default for clusters created from the Developers Console and the gcloudcommand-line tool, but you can verify by running the following command or clicking into the cluster's details in the Developers Console: gcloud container clusters describe cluster-name The output from the gcloudcommand-line tool should state that the "monitoringService" is "monitoring.googleapis.com", and Cloud Monitoring should be enabled in the Developers Console. If monitoring is not enabled, run the following command to enable it: gcloud container clusters update cluster-name --monitoring-service=monitoring.googleapis.com How long has it been since your cluster was created or had monitoring enabled? It can take up to an hour for a new cluster's metrics to start appearing in Stackdriver Monitoring. Is a heapsteror gke-metrics-agent(the OpenTelemetry Collector) running in your cluster in the "kube-system" namespace? This pod might be failing to schedule workloads because your cluster is running low on resources. Check whether Heapster or OpenTelemetry is running by calling kubectl get pods --namespace=kube-systemand checking for pods with heapsteror gke-metrics-agentin the name. Is your cluster's master able to communicate with the nodes? Stackdriver Monitoring relies on that. You can check whether this is the case by running kubectl logs [POD-NAME]If this command returns an error, then the SSH tunnels may be causing the issue. See this section. If you are having an issue related to the Stackdriver Logging agent, see its troubleshooting documentation. For more information, refer to the Stackdriver documentation. Error 404: Resource "not found" when calling gcloud container commands Re-authenticate to the gcloud command-line tool: gcloud auth login Error 400/403: Missing edit permissions on account Your Compute Engine default service account or the service account associated with GKE has been deleted or edited manually. When you enable the Compute Engine or Kubernetes Engine API, a service account is created and given edit permissions on your project. If at any point you edit the permissions, remove the account entirely, or disable the API, cluster creation and all management functionality will fail. The name of your Google Kubernetes Engine service account is: service-[PROJECT_NUMBER]@container-engine-robot.iam.gserviceaccount.com where [PROJECT_NUMBER] is your project number. To resolve the issue, you must re-enable the Kubernetes Engine API - this will correctly restore your service accounts and permissions. - Visit the APIs & Services page. - Select your project. - Click Enable APIs and Services. - Search for Kubernetes, then select the API from the search results. - Click Enable. If you have previously enabled the API, you must first disable it and then enable it again. It can take several minutes for the API and related services to be enabled. Alternatively, use the gcloud command-line tool: gcloud services enable container.googleapis.com Replicating 1.8.x (and earlier) automatic firewall rules on 1.9.x and later If your cluster is running Kubernetes version 1.9.x, the automatic firewall rules have changed to disallow workloads in a GKE cluster to initiate communication with other Compute Engine VMs that are outside the cluster but on the same network. You can replicate the automatic firewall rules behavior of a 1.8.x (and earlier) cluster by performing the following steps: First, find your cluster's network: gcloud container clusters describe [CLUSTER_NAME] --format=get"(network)" Then get the cluster's IPv4 CIDR used for the containers: gcloud container clusters describe [CLUSTER_NAME] --format=get"(clusterIpv4Cidr)" Finally create a firewall rule for the network, with the CIDR as the source range, and allow all protocols: gcloud compute firewall-rules create "[CLUSTER_NAME]-to-all-vms-on-network" --network="[NETWORK]" --source-ranges="[CLUSTER_IPV4_CIDR]" --allow=tcp,udp,icmp,esp,ah,sctp Restore default service account to your GCP project GKE's default service account, container-engine-robot, can accidentally become unbound from a project. GKE Service Agent is a Cloud Identity and Access Management (Cloud IAM) role that grants the service account the permissions to manage cluster resources. If you remove this role binding from the service account, the default service account becomes unbound from the project, which can prevent you from deploying applications and performing other cluster operations. You can check to see if the service account has been removed from your project by running gcloud projects get-iam-policy [PROJECT_ID] or by visiting the Cloud IAM & admin page in Google Cloud Console. If the command or the dashboard do not display container-engine-robot among your service accounts, the service account has become unbound. If you removed the GKE Service Agent role binding, run the following commands to restore the role binding: PROJECT_ID=$(gcloud config get-value project) PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" --format "value(projectNumber)") gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --member "serviceAccount:service-${PROJECT_NUMBER}@container-engine-robot.iam.gserviceaccount.com" \ --role roles/container.serviceAgent To confirm that the role binding was granted: gcloud projects get-iam-policy $PROJECT_ID If you see the service account name along with the container.serviceAgent role, the role binding has been granted. For example: - members: - serviceAccount:service-1234567890@container-engine-robot.iam.gserviceaccount.com role: roles/container.serviceAgent Cloud KMS key is disabled. GKE's default service account cannot use a disabled Cloud KMS key for application-level secrets encryption. To re-enable a disabled key, see Enable a disabled key version. Troubleshooting issues with deployed workloads GKE returns an error if there are issues with a workload's Pods. You can check the status of a Pod using the kubectl command-line tool or Google Cloud Console. kubectl To see all Pods running in your cluster, run the following command: kubectl get pods Output: NAME READY STATUS RESTARTS AGE [POD_NAME] 0/1 CrashLoopBackOff 23 8d To get more details information about a specific Pod: error status message. The following sections explain some common errors returned by workloads and how to resolve them. CrashLoopBackOff CrashLoopBackOff indicates that a container is repeatedly crashing after restarting. A container might crash for many reasons, and checking a Pod's logs might aid in troubleshooting the root cause. By default, crashed containers restart with an exponential delay limited to five minutes. You can change this behavior setting the restartPolicy field Deployment's Pod specification under spec: restartPolicy. The field's default value is Always. You can find out why your Pod's container is crashing using the kubectl command-line tool or Cloud Console. kubectl To see all Pods running in your cluster, run the following command: kubectl get pods Look for the Pod with the CrashLoopBackOff error. To get the Pod's logs, run: kubectl logs [POD_NAME] where [POD_NAME] is the name of the problematic Pod. You can also pass in the -p flag to get the logs for the previous instance of a Pod's container, if it exists. Logs tab. Check "Exit Code" of the crashed container You can find it in the output of kubectl describe pod [POD_NAME] in the containers: [CONTAINER_NAME]: last state: exit code field. - If the exit code is 1, the container crashed because the application crashed. - If the exit code is 0, verify for how long your app was running. Containers exit when your application's main process exits. If your app finishes execution very quickly, container might continue to restart. Connect to a running container Open a shell to the Pod: kubectl exec -it [POD_NAME] -- /bin/bash If there is more than one container in your Pod, add -c [CONTAINER_NAME]. Now, you can run bash commands from the container: you can test the network or check if you have access to files or databases used by your application. ImagePullBackOff and ErrImagePull ImagePullBackOff and ErrImagePull indicate that the image used by a container cannot be loaded from the image registry. You can verify this issue using Cloud Console or the kubectl command-line tool. kubectl To get more information about a Pod's container image, run the following command: Events tab. If the image is not found If your image is not found: - Verify that the image's name is correct. - Verify that the image's tag is correct. (Try :latestor no tag to pull the latest image). - If the image has full registry path, verify that it exists in the Docker registry you are using. If you provide only the image name, check the Docker Hub registry. Try to pull the docker image manually: SSH into the node: For example, to SSH into example-instancein the us-central1-azone: gcloud compute ssh example-instance --zone us-central1-a Run docker pull [IMAGE_NAME]. If this option works, you probably need to specify ImagePullSecrets on a Pod. Pods can only reference image pull secrets in their own namespace, so this process needs to be done one time per namespace. If you encounter a "permission denied" or "no pull access" error, verify that you are logged in and/or have access to the image. If you are using a private registry, it may require keys to read images. If your image is hosted in Google Container Registry, the service account associated with your node pool needs read access to the Google Cloud Storage bucket containing the image. See Google Container Registry documentation for further details. Pod unschedulable PodUnschedulable indicates that your Pod cannot be scheduled because of insufficient resources or some configuration error. Insufficient resources You might encounter an error indicating a lack of CPU, memory, or another resource. For example: "No nodes are available that match all of the predicates: Insufficient cpu (2)" which indicates that on two nodes there isn't enough CPU available to fulfill a Pod's requests. The default CPU request is 100m or 10% of a CPU (or one core). If you want to request more or fewer resources, specify the value in the Pod specification under spec: containers: resources: requests MatchNodeSelector MatchNodeSelector indicates that there are no nodes that match the Pod's label selector. To verify this, check the labels specified in the Pod specification's nodeSelector field, under spec: nodeSelector. To see how nodes in your cluster are labelled, run the following command: kubectl get nodes --show-labels To attach a label to a node: kubectl label nodes [NODE_NAME] [LABEL_KEY]=[LABEL_VALUE] For more information, refer to Assigning Pods to Nodes. PodToleratesNodeTaints PodToleratesNodeTaints indicates that the Pod can't be scheduled to any node because no node currently tolerates its node taint. To verify that this is the case, run the following command: kubectl describe nodes [NODE_NAME] In the output, check the Taints field, which lists key-value pairs and scheduling effects. If the effect listed is NoSchedule, then no Pod can be scheduled on that node unless it has a matching toleration. One way to resolve this issue is to remove the taint. For example, to remove a NoSchedule taint: kubectl taint nodes [NODE_NAME] key:NoSchedule- PodFitsHostPorts PodFitsHostPorts indicates that a port that a node is attempting to use is already in use. To resolve this issue, check the Pod specification's hostPort value under spec: containers: ports: hostPort. You might need to change this value to another port. Does not have minimum availability If a node has adequate resources but you still see the Does not have minimum availability message, check the Pod's status. If the status is SchedulingDisabled or Cordoned status, the node cannot schedule new Pods. To check the status of a node: kubectl To get statuses of your Nodes, run the following command: kubectl get nodes To enable scheduling on the Node, run: kubectl uncordon [NODE_NAME] Console Perform the following steps: Visit the GKE Workloads dashboard in Cloud Console. Visit the GKE Clusters dashboard Select the desired cluster. The Nodes tab displays the Nodes and their status. To enable scheduling on the Node, perform the following steps: From the list, click the desired Node. From the Node Details, click Uncordon button. Unbound PersistentVolumeClaims Unbound PersistentVolumeClaims indicates that the Pod references a PersistentVolumeClaim that is not bound. This error might happen if your PersistentVolume failed to provision. You can verify that provisioning failed by getting the events for your PersistentVolumeClaim and examining them for failures. To get events, run: kubectl describe pvc [STATEFULSET_NAME]-[PVC_NAME]-0 This may also happen if there was a configuration error during your manual pre-provisioning of a PersistentVolume and its binding to a PersistentVolumeClaim. You can try to pre-provision the volume again. Connectivity issues As mentioned in the Network Overview discussion, it is important to understand how Pods are wired from their network namespaces to the root namespace on the node in order to troubleshoot effectively. For the following discussion, unless otherwise stated, assume that the cluster uses GKE's native CNI rather than Calico's. That is, no network policy has been applied. Pods on select nodes have no availability If Pods on select nodes have no network connectivity, ensure that the Linux bridge is up: ip address show cbr0 If it is down, raise it: sudo ip link set cbr0 up Ensure that the node is learning Pod MAC addresses attached to cbr0: arp -an Pods on select nodes have minimal connectivity If Pods on select nodes have minimal connectivity, you should first confirm whether there are any lost packets by running tcpdump in the toolbox container: sudo toolbox bash Install tcpdump in the toolbox if you have not done so already: apt install -y tcpdump Run tcpdump against cbr0: tcpdump -ni cbr0 host [HOSTNAME] and port [PORT_NUMBER] and [tcp|udp|icmp] Should it appear that large packets are being dropped downstream from the bridge (for example, the TCP handshake completes, but no SSL hellos are received), ensure that the Linux bridge MTU is correctly set to 1460 or below: ip address show cbr0 When overlays are used (for example, Weave or Flannel), this MTU must be further reduced to accommodate encapsulation overhead on the overlay. Intermittent failed connections Connections to and from the Pods are forwarded by iptables. Flows are tracked as entries in the conntrack table and, where there are many workloads per node, conntrack table exhaustion may manifest as a failure. These can be logged in the serial console of the node, for example: nf_conntrack: table full, dropping packet If you are able to determine that intermittent issues are driven by conntrack exhaustion, you may increase the size of the cluster (thus reducing the number of workloads and flows per node), or increase nf_conntrack_max: new_ct_max=$(awk '$1 == "MemTotal:" { printf "%d\n", $2/32; exit; }' /proc/meminfo) sysctl -w net.netfilter.> /etc/sysctl.conf "bind: Address already in use" reported for a container A container in a Pod is unable to start because according to the container logs, the port where the application is trying to bind to is already reserved. The container is crash looping. For example, in Stackdriver Logging: resource.type="container" textPayload:"bind: Address already in use" resource.labels.container_name="redis" 2018-10-16 07:06:47.000 CEST 16 Oct 05:06:47.533 # Creating Server TCP listening socket *:60250: bind: Address already in use 2018-10-16 07:07:35.000 CEST 16 Oct 05:07:35.753 # Creating Server TCP listening socket *:60250: bind: Address already in use When Docker crashes, sometimes a running container gets left behind and is stale. The process is still running in the network namespace allocated for the Pod, and listening on its port. Because Docker and the kubelet don't know about the stale container they try to start a new container with a new process, which is unable to bind on the port as it gets added to the network namespace already associated with the Pod. To diagnose this problem, you need the UUID of the Pod, field .metadata.uuid: kubectl get pod -o custom-columns="name:.metadata.name,UUID:.metadata.uid" ubuntu-6948dd5657-4gsgg name UUID ubuntu-6948dd5657-4gsgg db9ed086-edba-11e8-bdd6-42010a800164 Also get the output of the following commands from the node: docker ps -a ps -eo pid,ppid,stat,wchan:20,netns,comm,args:50,cgroup --cumulative -H | grep [Pod UUID] Check running processes from this Pod. Because the UUID of the cgroup namespaces contain the UUID of the Pod, you can grep for the Pod UUID in ps output. Grep also the line before, so you will have the docker-containerd-shim processes having the container id in the argument as well. Cut the rest of the cgroup column to get a simpler output: # ps -eo pid,ppid,stat,wchan:20,netns,comm,args:50,cgroup --cumulative -H | grep -B 1 db9ed086-edba-11e8-bdd6-42010a800164 | sed s/'blkio:.*'/''/ 1283089 959 Sl futex_wait_queue_me 4026531993 docker-co docker-containerd-shim 276e173b0846e24b704d4 12: 1283107 1283089 Ss sys_pause 4026532393 pause /pause 12: 1283150 959 Sl futex_wait_queue_me 4026531993 docker-co docker-containerd-shim ab4c7762f5abf40951770 12: 1283169 1283150 Ss do_wait 4026532393 sh /bin/sh -c echo hello && sleep 6000000 12: 1283185 1283169 S hrtimer_nanosleep 4026532393 sleep sleep 6000000 12: 1283244 959 Sl futex_wait_queue_me 4026531993 docker-co docker-containerd-shim 44e76e50e5ef4156fd5d3 12: 1283263 1283244 Ss sigsuspend 4026532393 nginx nginx: master process nginx -g daemon off; 12: 1283282 1283263 S ep_poll 4026532393 nginx nginx: worker process From this list, you can see the container ids, which should be visible in docker ps as well. In this case: - docker-containerd-shim 276e173b0846e24b704d4 for pause - docker-containerd-shim ab4c7762f5abf40951770 for sh with sleep (sleep-ctr) - docker-containerd-shim 44e76e50e5ef4156fd5d3 for nginx (echoserver-ctr) Check those in the docker ps output: # docker ps --no-trunc | egrep '276e173b0846e24b704d4|ab4c7762f5abf40951770|44e76e50e5ef4156fd5d3' 44e76e50e5ef4156fd5d383744fa6a5f14460582d0b16855177cbed89a3cbd1f gcr.io/google_containers/echoserver@sha256:3e7b182372b398d97b747bbe6cb7595e5ffaaae9a62506c725656966d36643cc "nginx -g 'daemon off;'" 14 hours ago Up 14 hours k8s_echoserver-cnt_ubuntu-6948dd5657-4gsgg_default_db9ed086-edba-11e8-bdd6-42010a800164_0 ab4c7762f5abf40951770d3e247fa2559a2d1f8c8834e5412bdcec7df37f8475 ubuntu@sha256:acd85db6e4b18aafa7fcde5480872909bd8e6d5fbd4e5e790ecc09acc06a8b78 "/bin/sh -c 'echo hello && sleep 6000000'" 14 hours ago Up 14 hours k8s_sleep-cnt_ubuntu-6948dd5657-4gsgg_default_db9ed086-edba-11e8-bdd6-42010a800164_0 276e173b0846e24b704d41cf4fbb950bfa5d0f59c304827349f4cf5091be3327 k8s.gcr.io/pause-amd64:3.1 In normal cases, you see all container ids from ps showing up in docker ps. If there is one you don't see, it's a stale container, and probably you will see a child process of the docker-containerd-shim process listening on the TCP port that is reporting as already in use. To verify this, execute netstat in the container's network namespace. Get the pid of any container process (so NOT docker-containerd-shim) for the Pod. From the above example: - 1283107 - pause - 1283169 - sh - 1283185 - sleep - 1283263 - nginx master - 1283282 - nginx worker # nsenter -t 1283107 - ~ # nsenter -t 1283169 - You can also execute netstat using ip netns, but you need to link the network namespace of the process manually, as Docker is not doing the link: # ln -s /proc/1283169/ns/net /var/run/netns/1283169 gke-zonal-110-default-pool-fe00befa-n2hx ~ # ip netns list 1283169 (id: 2) gke-zonal-110-default-pool-fe00befa-n2hx ~ # ip netns exec 1283169 ~ # rm /var/run/netns/1283169 Mitigation: The short term mitigation is to identify stale processes by the method outlined above, and kill them using kill [PID]. Long term mitigation involves identifying why Docker is crashing and fixing that. Possible reasons include: - Zombie processes piling up, so running out of PID namespaces - Bug in docker - Resource pressure / OOM
https://cloud.google.com/kubernetes-engine/docs/troubleshooting?hl=ar
CC-MAIN-2020-10
refinedweb
4,076
50.57
I will be using Microsoft Visual Studio 2005. The code is as following: First we will use the namespace "System.IO" as we will be viewing output from the text file. using System.IO; then the code will be in braces like this. { String line=Null; System.IO.Textreader readfile=New Streamreader("C:\\" + textbox1.Text); line=readfile.ReadToEnd(); textbox2.Text(line); readfile.close(); readfile=Null; } There may be some errors in this code as i am new to this particularly if readfile.close() gives error then remove the brackets.The name of the file you write in the text box1 must already exist the entire data of the file will be displayed in text box2.to create a file. { create.file("C:\\" + textbox1.Text); } You can also use combobox to display data of textfile. Edited by Roger, 07 July 2011 - 01:58 PM.
http://forum.codecall.net/topic/64644-c-how-to-read-data-from-a-text-file/
CC-MAIN-2019-09
refinedweb
143
69.58
random resultThanks a lot! Always got answers so quick here! random resulthow come without using rand(). My program still generate random result. I was trying to make a matr... checker program errorbut x=0, y=0 will mess up the game [output] 7 - b - b - b - b 6 b - b - b - b - 5 - b - b - b - b... checker program errorIf I choose some ok function like x=0, y=2, It is fine [output] 7 - b - b - b - b 6 b - b - b - b ... checker program errorI think the problem is in here: [code] #include <iostream> using namespace std; #ifndef GO_CXX #de... This user does not accept Private Messages
http://www.cplusplus.com/user/holywingz/
CC-MAIN-2014-15
refinedweb
109
76.52
Debugging DS-5 Jython Scripts Application Note 351 Non-Confidential Debugging DS-5 Jython Scripts Application Note 351 Release Information Change History Proprietary Notice Words and logos marked with or ® are registered trademarks or trademarks of ARM®. Confidentiality Status This document is Non-Confidential. This document may only be used and distributed in accordance with the terms of the agreement entered into by ARM and the party that ARM delivered this document to. Product Status The information in this document is final, that is for a developed product. Web Address This application note describes how to debug DS-5 Jython scripts using the PyDev debugger included in DS-5. This works by using the PyDev remote debugger. This consists of a debug server, which runs inside eclipse, and the debug client, which runs inside your scripts interpreter. Note that, while these instructions assume that you are using the PyDev debugger, it should be possible to use any other Python/Jython remote debugger. However, note that most debuggers are designed for Python, and may not work perfectly with Jython. It is also worth noting that the PyDev debugger is not limited to debugging DS-5 Jython scripts, and should also be able to debug other Python and Jython scripts. However, if a script is launched from outside DS-5, the PyDev debug client may not be in the python path by default. The PyDev debug client can be found at eclipse/plugins/org.python.pydev.debug_<version>/pysrc, inside your DS-5 installation directory. The PyDev debugger client uses the sys.settrace() function to set a tracing function which allows it to observe and pause code execution, so scripts should not use the sys.settrace() function for their own tracing purposes when the debugger is connected. The first task is to set up your development environment for using the PyDev remote debugger. This is done by firstly enabling the PyDev Debugger command group, which allows you to start and stop the debug server, and secondly opening the Debug perspective, if it is not already open. 1. Select Window → Customize Perspective 2. Switch to the Command Groups Availability tab 3. In the Available Command Groups box, enable the PyDev Debug option and click OK 4. Select Window → Open Perspective → Other 5. Select Debug (not DS-5 Debug), and click OK Once the Debug perspective has been opened, you can return to your previous perspective. Next you need to start the PyDev debug server. This should remain open until you close DS-5, even when you disconnect from all targets. The PyDev debug server shows up in the Console view, which shows its current state and allows it to be stopped if needed. 1. Select PyDev → Start Debug Server 2. The debug server should start in the Console view You now need to modify the python script to be debugged, importing the debug client and connecting it to the server. 1. Open your Jython script, and insert the following lines near the top of the file: import pydevd pydevd.settrace() 2. Optionally, the second line can be modified, to cause all output from the Jython script to be copied to the debug server console in the Console view: pydevd.settrace(stdoutToServer=True, stderrToServer=True) When the second line is executed, the debug client connects to the debug server and pauses execution of the Jython script. The script can now be started as normal, and when pydevd.settrace() is executed, the Python interpreter searches for Python debugger to connect to. Since you started a Python debugger earlier, execution of the script is halted and transferred to the Python debugger. Note that because execution is halted, any progress monitor dialog for the script should be backgrounded to ease switching to the Python debugger and interacting with it. Also, when debugging a DS-5 Jython script, the following error lines appear in the DS-5 console; those can be safely ignored. It is now possible to switch to the Debug perspective to debug the Jython script. In this perspective, the standard eclipse debugging views can be used to debug the Jython code. The Debug view has controls to resume, pause and step the code, as well as the ability to switch between threads and view the stack of each thread. The Variables view shows the values of all local and global variables, and allows them to be modified when the program is suspended. Note that modifying variables will currently only work in the outermost stack frame, due to a limitation in Python and Jython. Variables that were modified the last time the program stepped are shown highlighted in yellow. Breakpoints can be set by double-clicking in the left margin, and all current breakpoints are shown in the Breakpoints view. From the breakpoint view, you can remove or temporarily disable any breakpoint in your code. By right-clicking on a breakpoint in the left-hand margin (not in the Breakpoints view) and selecting Breakpoint Properties..., you can set a condition, so that the breakpoint is ignored unless the condition evaluates to true. The PyDev debugger can also be used to debug DTSL scripts, but some additional considerations must be taken into account. When a DTSL script is executed, it runs to completion, but only creates classes which are later instantiated by DS-5. Because of this, the PyDev debugger should not be connected at the top of the file, but instead to the beginning of the __init__ method. This means that the debugger will be connected when the DTSL object is created. Other than that, DTSL scripts can be debugged as usual. Debugging flash load scripts is similar to debugging DTSL scripts, in that the script is executed once to load a class, and this class is then later instantiated and its methods are called. Again, pydevd.settrace() must be called inside the methods of the class which inherits from FlashMethodv1, not at the top of the script. Typically these are getDefaultRegions(), getDefaultParameters(), setup(), teardown() and program(), as these are the methods that can be called by DS-5, though it is possible to connect the debugger at any point in the script.
http://infocenter.arm.com/help/topic/com.arm.doc.dai0351a/index.html
CC-MAIN-2017-17
refinedweb
1,027
61.26
# matrices.tcl -- # Simple demonstration of matrix-vector multiplications # # The idea: # In 3D space: # - A vector is represented as a list of 3 numbers # - A matrix is represented as a list of 3 lists of 3 numbers # - A series of vectors is also a list of lists # For instance: # The identity matrix is { {1 0 0} {0 1 0} {0 0 1}} # Rotation over X degrees around the z-axis is implemented # via: # { {C -S 0} # {S C 0} # {0 0 1}} # where C = cos X, S = sin X # # Rotating the vector {0 1 1} thus gives: # { [expr {C*0-S*1+0*1}] [expr {S*0+C*1+0*1}] [expr {0*0+0*1+1*1}] } # = {-S C 1} # namespace eval ::matrices { namespace export matmul } # matmul -- # Multiply a vector (or list of vectors) by a 3x3 matrix # # Arguments: # matrix Matrix to multiply with # vector Vector operand (or list of vectors) # Result: # Transformed vector (vector list) # Note: # A vector list of 3 vectors is identical to a 3x3 matrix, # hence this procedure can be used for matrix multiplications too # Transposition is implied by the implementation (just to remind # myself :) # proc ::matrices::matmul {matrix vector} { set n1 11 set n2 12 set n3 13 foreach row $matrix { foreach [list m$n1 m$n2 m$n3] $row { break } incr n1 10 incr n2 10 incr n3 10 } # # Add an extra level of list if there is only one vector # if { [llength [lindex $vector 0]] == 1 } { set vector [list $vector] } set r [list] foreach v $vector { foreach {x y z} $v { break } lappend r [list [expr {$m11*$x+$m12*$y+$m13*$z}] \ [expr {$m21*$x+$m22*$y+$m23*$z}] \ [expr {$m31*$x+$m32*$y+$m33*$z}] ] } return $r } # Test code # namespace import ::matrices::* set vectors { {1.0 0.0 0.0} {0.0 1.0 0.0} {0.0 0.0 1.0} } set matrix { {1.0 2.0 3.0} {4.0 5.0 6.0} {7.0 8.0 9.0} } set expected { {1.0 4.0 7.0} {2.0 5.0 8.0} {3.0 6.0 9.0} } puts "Per vector:" foreach vector $vectors exp $expected { set result [matmul $matrix $vector] puts "$result -- $exp" } puts "For a list of vectors:" set result [matmul $matrix $vectors] puts "$result -- $expected" puts "Matrix multiplication (matrix**2 is identity)" set matrix { {0.0 1.0 0.0} {1.0 0.0 0.0} {0.0 0.0 1.0} } set result [matmul $matrix $matrix] puts "$result" AMG: For my computer graphics class I developed some 3D routines and a nifty model display application. (I might post it here after the class is done.) Concerned about speed, and not wanting to depend on anything other than Tcl and Tk, I wrote the following. This unreadable hunk of metaprogramming produces matrix multipliers with fully unrolled loops. # Assemble a fast matrix multiply procedure. All matrices are 3x4 and are # treated as if they had a fourth row of [0 0 0 1]. set code "" for {set y 0} {$y < 3} {incr y} { set row "" for {set x 0} {$x < 4} {incr x} { set cell "" for {set i 0} {$i < 3} {incr i} { if {$i != 0} { append cell " + " } append cell "\[lindex \$m1 $y $i\] * \[lindex \$m2 $i $x\]" } if {$x == 3} { append cell " + \[lindex \$m1 $y $x\]" } if {$x != 0} { append row " " } append row "\[expr [list $cell]\]" } if {$y != 0} { append code " " } append code "\[list $row\]" } proc 3dmtx_compose {m args} [string map [list %CODE% $code] { if {[llength $args] == 0} { return $m } else { set m2 [lindex $args end] set matrices [concat [list $m] [lrange $args 0 end-1]] for {set i 0} {$i < [llength $matrices]} {incr i} { set m1 [lindex $matrices end-$i] set m2 [list %CODE%] } return $m2 } }] # Put together a fast matrix-vector multiply procedure. The matrix is 3x4 # and is combined with a fourth row of [0 0 0 1], and the vector is 1x3 and # is transposed and combined with a fourth row of [1]. set code "" for {set y 0} {$y < 3} {incr y} { set cell "" for {set i 0} {$i < 3} {incr i} { if {$i != 0} { append cell " + " } append cell "\[lindex \$m $y $i\] * \[lindex \$v $i\]" } append cell " + \[lindex \$m $y $i\]" if {$y != 0} { append code " " } append code "\[expr [list $cell]\]" } proc 3dmtx_apply {args} [string map [list %CODE% $code] { switch -- [llength $args] { 0 {error "wrong # args: should be \"3dmtx_apply ?matrix? ?...? vector\""} 1 {return [lindex $args 0]} 2 {set m [lindex $args 0]} default {set m [3dmtx_compose {*}[lrange $args 0 end-1]]} } set v [lindex $args end] return [list %CODE%] }][3dmtx_compose] multiplies any number of 4x4 affine transformation matrices*, each of which is stored as 3x4 list (three elements in the outer list; each element is itself a list containing four numbers). The fourth row is taken to be (0 0 0 1).[3dmtx_apply] multiplies (the composition of) any number of such matrices by a 3D column vector in homogeneous coordinates, represented by a list of three numbers. The fourth row is implicitly (1).* Affine transformation matrices can scale, shear, rotate, mirror, and translate. Parallel lines remain parallel after affine transformations. 3x3 matrices, as used by Arjen's code, cannot perform translation. 4x4 transformation matrices are constructed by adding an extra translation column (x y z) to the right of an Arjen-style 3x3 matrix, then adding a new row (0 0 0 1) for the sake of homogeneous coordinates.Hmm, I probably should have profiled the "loopy" version first. I plan to update this section to show a comparision between loopy multiplies and unrolled multiplies. Maybe there's no benefit. I don't know yet.So you can play around with my multipliers, here's code to generate useful transformation matrices. # Returns a matrix which translates by ($x,$y,$z). proc 3dmtx_trans {x y z} { return [list [list 1 0 0 $x]\ [list 0 1 0 $y]\ [list 0 0 1 $z]] } # Returns a matrix which rotates by $t radians about vector ($x,$y,$z). proc 3dmtx_rotate {x y z t} { if {$x == 0 && $y == 0 && $z == 0} { error "Cannot rotate around zero vector" } set l [expr {sqrt($x ** 2 + $y ** 2 + $z ** 2)}] foreach dim {x y z} { set $dim [expr {[set $dim] / $l}] } set result [list] foreach row_expr { {{$x * $x + (1 - $x ** 2) * cos($t)} {$x * $y * (1 - cos($t)) - $z * sin($t)} {$x * $z * (1 - cos($t)) + $y * sin($t)}} {{$y * $x * (1 - cos($t)) + $z * sin($t)} {$y * $y + (1 - $y ** 2) * cos($t)} {$y * $z * (1 - cos($t)) - $x * sin($t)}} {{$z * $x * (1 - cos($t)) - $y * sin($t)} {$z * $y * (1 - cos($t)) + $x * sin($t)} {$z * $z + (1 - $z ** 2) * cos($t)}} } { set row [list] foreach cell_expr [concat $row_expr [list 0]] { lappend row [expr $cell_expr] } lappend result $row } return $result } # Returns a matrix which scales by ($x,$y,$z). Negative scalars mirror. proc 3dmtx_scale {x y z} { return [list [list $x 0 0 0]\ [list 0 $y 0 0]\ [list 0 0 $z 0]] }And now an example. % set pi_2 [expr {acos(-1) / 2}] % 3dmtx_apply [3dmtx_trans -1 0 0] \ [3dmtx_rotate 1 0 0 $pi_2]\ [3dmtx_scale 2 2 2] \ {1 2 3} 1.0 -6.0 4.0Let's trace that. (1,2,3) scaled by 2 becomes (2,4,6) rotated by 90° about X becomes (2,-6,4) translated by -X becomes (1,-6,4). Nifty. And what's the matrix we used? % 3dmtx_compose [3dmtx_trans -1 0 0] \ [3dmtx_rotate 1 0 0 $pi_2]\ [3dmtx_scale 2 2 2] {{ 2.0 0.0 0.0 -1.0} { 0.0 0.0 -2.0 0.0} { 0.0 2.0 0.0 0.0}}I took the liberty of breaking the list into three lines and replacing 1.2246063538223773e-16 with 0.0 so you can more easily see what's going on. And remember, all matrices have an implicit fourth row of (0 0 0 1).On my 500MHz P3 laptop, the above composition takes 1097.3528 microseconds, and that includes time spent generating the inputs. Applying that matrix to a vector takes 48.9898 microseconds. Composing and applying together take 1149.24 microseconds.That's enough for now. It's time for me to go to class.
http://wiki.tcl.tk/10326
CC-MAIN-2017-17
refinedweb
1,365
64.14
Hello I have a pwa in the quasar 1.x branch and am trying to upgrade to quasar 2.x. I will comment on the problems I had: Following the update guide [1] I could never finish, in the end I had problems with workbox, so I discarded this option and went for the next one. I started an app from scratch and I was moving the code and modifies it according to the guide [1] and installing the dependencies. This worked fine, the app runs, but I have a problem with the storage. Below I comment what happens. - I use VuexPersistence and localForage for persistent storage. The problem I have is that the data is lost when refreshing or closing and re-entering. This worked fine before updating: import VuexPersistence from 'vuex-persist' import localForage from 'localforage' Vue.use(Vuex) const vuexLocal = new VuexPersistence({ storage: localForage, key: 'my_pwa_app' }) export default function () { const Store = new Vuex.Store({ plugins: [vuexLocal.plugin], modules: { ... but as I said, the data is lost. I thought it might be something relative to the localForage or VuexPersistence versions, because having created the project from scratch and installed the dependencies again, they were updated with respect to the original project, but it was not that - If I change the storage to window.localStorage it works fine: Vue.use(Vuex) const vuexLocal = new VuexPersistence({ storage: window.localStorage, key: 'my_pwa_app' }) Anyone have any idea what might be going on Thank you so much Jose [1] I have the same issue … any help plz ?
https://forum.quasar-framework.org/topic/6296/upgrading-to-v2-pwa-localforage
CC-MAIN-2021-39
refinedweb
254
56.15
So I *think* I've pieced together what caused the user crash that originated in the flair library. It turns out that pickle.load, via torch.load, is getting passed an mmap.mmap. Since mmap doesn't implement readinto, pickle.load objects as of Python 3.8. This is new behavior in Python3.8, it used to be possible to load a memory-mapped pickle file. Short repro script: import pickle import mmap data = "some data" with open('my_data.pkl', 'wb') as f: pickle.dump(data, f) with open("my_data.pkl", "r+b") as f_in: mm = mmap.mmap(f_in.fileno(), 0) print(pickle.load(mm)) On Python3.8, this script prints an error, on Python3.7 it prints "some data".
https://bugs.python.org/msg362291
CC-MAIN-2021-21
refinedweb
120
73.85
C and C++ CINT is a C/C++ interpreter. Although not wholly ANSI compliant CINT is hugely useful and generally intuitive. In case of difficulty consult the CINT documentation that has been reproduced here. For further online documentation and to access the support forum see the Links document page. Language Limitations CINT is a wonderful tool but it does have some limitations. Please read the included CINT Language limitations document for further details. Thus, to give a concrete example, it appears that CINT does not support snprintf(). Calling the Task Run Function Arguments are passed to CINT powered tasks as direct parameters rather than through a named entry point function. The task parameters will be forwarded to the task's main() function. Result Objects The CINT C and C++ tasks return results to the client by printing to stdout. To return structured data, including the contents of files, CINT powered tasks should format result data using YAML. KosmicTask supports both the YAML inline and block formats. #include <stdio.h> int main() { char *item1 = "item 1"; char *item2 = "item 2"; // return a YAML inline format array printf("--- [%s, %s]", item1, item2); return 0; } Result File Handling KosmicTask supports the returning of file contents within task results. KosmicTask automatically looks for a kosmicFile record containing file paths within a dictionary type result object. If found, KosmicTask will return the contents of the file or files to the client. For CINT shell powered tasks files are returned as results using the following YAML dictionary syntax: char *file = "capture.png"; printf("--- {kosmicFile: %s}", file); A common usage scenario is that a task creates a temporary file (or files) whose contents are then returned to the client. KosmicTask therefore supports automatic temporary file creation and deletion. Temporary files created through KosmicTask are automatically deleted once the parent task has completed. CINT powered tasks can create temporary files simply by creating files in the current working directory. #include <stdio.h> int main() { // capture screen image to file // files created in the current directory will be deleted when the task ends char *file = "capture.png"; char command[100]; sprintf(command, "screencapture -t png %s", file); // execute command system(command); // return a YAML inline format dictionary printf("--- {kosmicFile: %s, kosmicInfo: file returned}", file); return 0; } Logging and Debugging Diagnostic and logging information can be written to a task's error stream on stderr. // send log value to stderr fprintf(stderr, "Goodbye, kosmos!"); Sample Code For an extensive set of CINT samples download the CINT source. Sample code, including STL examples, can be found in the CINT demo folder. CINT CINT reference manual CINT support forum
http://mugginsoft.com/kosmictask/help/languages/c-and-c-plus-plus
CC-MAIN-2017-47
refinedweb
437
54.83
Red Hat Bugzilla – Bug 369941 Undefined symbol in wizardc.so Last modified: 2008-05-17 06:49:38 EDT Description of problem: Cannot start the GUI part of the software in URL. Version-Release number of selected component (if applicable): wxPython-2.8.4.0-1.fc7 How reproducible: Always. Steps to Reproduce: 1. Download the software and decompress the tarball 2. chmod +x pygrenouille.py in the directory 3. ./pygrenouille.py Actual results: Traceback (most recent call last): File "./pygrenouille.py", line 62, in <module> import wx.wizard Expected results: Having the GUI working. Additional info: Software URL : What happens if you run python interactively from the command line and type "import wx.wizard"? This work for me on both CentOS 5 and on Fedora rawhide. I don't have an F7 test box right now. I'm going to update to 2.8.6.x really soon; hopefully that will correct the problem. Same problem : [fraggle@morphee ~]$ python Python 2.5 (r25:51908, Oct 19 2007, 09:47:40) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx.wizard Traceback (most recent call last): File "<stdin>", line 1, in <module> Any chance to have this upgrade pushed any time soon in Fedora 8 and 7 ? By the way, compat-wxGTK26-2.6.4-0.8 upgrade have just broke the way the default translation is found in amule from livna but that's another story. bug can be closed ...
https://bugzilla.redhat.com/show_bug.cgi?id=369941
CC-MAIN-2016-44
refinedweb
256
70.8
Internet. Upon doing that and completing the installation, the configuration dialog will be presented to us where we can control various options of SoftICE. On the picture below we can see how SoftICE is started; by default, the Manual option is selected, which specifies that we must start SoftICE manually each time that we need it. There are also other options that we can select from. If we use the Boot option, SoftICE will be loaded before Windows loads, which will give us the chance to debug device drivers. There are also other options that can be seen on the picture below: The important thing we must do in the configuration settings is check the Video support. We must click on the Video option that can be seen on the picture above (on the left side) where “Universal Video Driver” is selected by default, which is ok. We can see the options presented on the picture below: We must click on the Detect button to detect our video adapter followed by clicking on the Test button to test if everything is ok. If all the tests succeed, the following pop-up button will be displayed: After that, we can save all the changes we’ve made, finish the installation and restart our computer (in our case the virtual machine running Windows XP SP3). After rebooting, let’s take a look at the configuration file that’s located under C:WINDOWSsystem32drivers directory: The default configuration is presented. PENTIUM=ON NMI=ON ECHOKEYS=OFF NOLEDS=OFF NOPAGE=OFF SIWVIDRANGE=ON THREADP=ON LOWERCASE=OFF SYM=512 HST=256 MACROS=32 DRAWSIZE=2048 INIT="wl; color f a 4f 1f e; code on; lines 60; wc 32; wd 4; wr; faults off; " INIT="ww 4;dex 1 ss:esp;altkey ctrl d;watch es:di;watch eax;watch *es:di;set mouse 3;cls;X;" F1="h;" F2="^wr;" F3="^src;" F4="^rs;" F5="^x;" F6="^ec;" F7="^here;" F8="^t;" F9="^bpx;" F10="^p;" F11="^G @SS:ESP;" F12="^p ret;" SF3="^format;" AF1="^wr;" AF2="^wd;" AF3="^wc;" AF4="^ww;" AF5="CLS;" AF11="^dd dataaddr->0;" AF12="^dd dataaddr->4;" CF1="altscr off; lines 60; wc 32; wd 8;" CF2="^wr;^wd;^wc;" MENU=Copy , NMPD_COPY , 0 MENU=Paste , NMPD_PASTE , 0 MENU=Copy&Paste , NMPD_COPYANDPASTE , 0 MENU=Display , NMPD_DISPLAY , 0 MENU=Un-Assemble , NMPD_UNASSEMBLE , 0 MENU=What , NMPD_WHAT , 0 MENU=Prev , NMPD_PREV , 0 MENU=Reip , r eip %cp% , 0 MENU=Add Watch , watch %cp% , 0 MENU=Break On Text , bpx %cp% , 0 NETSUPPORT=OFF ; WINICE.DAT ; (SystemRootSystem32DriversWINICE.DAT) ; for use with SoftICE for Windows NT (versions 3.0 and greater) ; ; ***** Examples of export symbols that can be included ***** ; Change the path to the appropriate drive and directory EXP=SystemRootSystem32hal.dll EXP=SystemRootSystem32ntoskrnl.exe EXP=SystemRootSystem32ntdll.dll EXP=SystemRootSystem32kernel32.dll EXP=SystemRootSystem32user32.dll EXP=SystemRootSystem32csrsrv.dll EXP=SystemRootSystem32basesrv.dll EXP=SystemRootSystem32winsrv.dll Upon rebooting the Windows system and pressing the Ctrl-D shortcut to start the SoftICE debugger, my system froze and the blue screen error message, like shown on the picture below, was presented. After downloading the full SoftICE package, the archive has enclosed instructions on how to install SoftICE. Basically, we have to do the same things as above, but once it’s installed, the configuration window has a little more options, as we can see below: Basically we must still click on the Video option and configure the video settings as already described. Additionally, we must disable DEP by editing the C:boot.ini configuration file and adding the ‘alwaysoff’ value option: /noexecute=alwaysoff We can do that by right-clicking on “My Computer” and selecting Preferences. Then we click on the “Advanced” tab and under “Startup and Recovery”, pressing on the Settings tab. Sometimes we must also configure the .vmx file and add the following configuration options: svga.maxFullscreenRefreshTick = 5 vmmouse.present = "FALSE" Now we’ve done everything needed for installing the SoftICE on Windows XP virtual machine. Starting the SoftICE Debugger To start SoftICE debugger we need to click on the “Start SoftICE” option that’s accessible under the All Programs options, as can seen on the picture below: We can immediately see that this is only a batch script (because of the icon). So if we right-click on that option and click on Edit, we’ll be presented with the script code that is run after clicking on it. We can see that on the picture below: When clicking on “Start SoftICE”, the “net start ntice” command is being run, so the SoftICE debugger was installed as a service that we must start whenever we want to start the SoftICE debugger. Since we’re only starting the service, let’s do it from the command prompt. Below we can see that the NTice service was started successfully: After that we can start interacting with SoftICE with its default shortcuts. If we would like to show the debugging screen, we need to press the Ctrl-D shortcut. If we press the Ctrl-D again, we’ll hide the SoftIce and get the control back; this means that SoftICE is running fine behind the scenes. When pressing the Ctrl-D, a SoftICE window should appear. as we can see on the picture below: SoftICE Commands If we enter the :help command into SoftICE, we should receive all the commands SoftICE supports. All the commands are presented on the four pictures below. This is being done because it’s rather hard to get all the commands out of the SoftICE quickly. Now you can just open up the tutorial and check out the command you’re interested in. If we input the command “help <command>”, we’ll get help about the specific command. This can be useful if we don’t know the exact command syntax and we would like to find out. We can use the proc command to display all processes that we can debug. We can also use the driver command to display all the drivers that we can debug. Let’s also present some other important commands: - addr: enters address space of some process, which is needed because the CPU doesn’t know anything about processes. - d: display the values at some virtual memory address. - e: edit the value at some virtual memory address. - u: disassemble instructions at some virtual memory address. - a: assemble instructions at some virtual memory address. - r: display/edit the contents of registers. - S: search for data in memory. - bpx: breakpoint on execution. - bpm: breapoint on memory access. - bpint: breakpoint on interrupt. - bmsg: breakpoint on Windows message. - bl: display current breakpoints. - bc: clear breakpoint. - bd: disable breakpoint. - be: enable breakpoint. - t: single step one instruction. - p: execute until return. - wmsg: display window messages. - hwnd: display window handle information. - exp: display export symbols. - wr: show/hide register window - wd: show/hide data window - wc: show/hide code window SoftICE Example Ok, so far we’ve presented the basic information about installing and configuring SoftICE and its basic commands, but what can we really do with it. We’ve already presented the SoftICE basic window when starting it, but let’s present it again: On the picture above, we can see multiple parts that constitute a window. At the top of the SoftICE window, we can see all the registers. Then we can see a disassembly listing and the command window. And in the line at the bottom of the window where is says “Enter a command”, we can see the current process being debugged. Currently it says Idle, because we’re not debugging any process. First, we can enter the command proc to check out the processes that we can debug. The picture below presents how we can enter the command into SoftICE just before executing it: Notice the :proc command at the bottom of the SoftICE window. After pressing enter, the command will be executed and all the processes will be shown, as seen below: We can see that there’s not much room for the data to be displayed. We can adjust that by entering the following command: width 90 lines 80 ww 2 wd 15 wc 50 If we execute the :proc command again, all the processes will be displayed as can be seen on the picture below: We can see all the processes displayed, which we can verify with opening the Task Manager and checking whether the same processes are displayed: What’s interesting is that when entering the :proc command all the processes are displayed, but with quite a lot of information. Each line displays the process name, process ID (PID), process threads, status, etc… Let’s start by entering the address space of the explorer process by executing the “addr explorer” command, as seen on the picture below: Notice that on the right side of the status line we can see the text explorer, which means that we’re currently debugging the explorer process. If we would like to display all the sections of the explorer process, we can do that with the maps32 command, as seen on the picture below: The explorer process has .text, .data, .rsrc and .reloc sections. We can also see their addresses, sizes, types and the access permissions on the picture above. Let’s now write a very simple program, which the source code can be seen below. The source code is written in C++ and compiled in Visual Studio: #include "stdafx.h" #include <stdio.h> int _tmain(int argc, _TCHAR* argv[]) { printf("Hello World!n"); /* wait */ getchar(); } Once the program is compiled and executed, it should print “Hello World!” to the console window, like it can be seen on the picture below: After the program runs, it prints the message to the console window and then waits for the key to be pressed. This happens because of the getchar() function that we’ve used so that the program doesn’t print the message and terminates but waits before termination. On the picture below we can see that we’ve already run the program hello and that we’re currently debugging it (notice the ‘*’ besides the program name and also the ‘hello’ string in the status bar): Let’s display all the segments the hello program has with the map32 command: If we execute the “:u eip” command, we’ll be displaying the assembly instruction of where the EIP points to. We can see that on the picture below; previously the command hlt was executed, which stops program execution and places the processor in a HALT state until the key is pressed. Let’s now search for the string “Hello World” in the executable. On the picture below, we can see that we first printed the help of the search command and later inputted the search command that searches for the “Hello World” string, which is found at address 0x0012C028. If we now execute the “d 0012C028″ command, we’ll dump the memory at that address, which can be seen on the picture below: Notice that the first string presented above is the “Hello World!” We’ve just successfully dumped the memory and confirmed that the string is actually located there. Now let’s add a breakpoint, which will be set on the memory location where our “Hello World!” string is saved. To do that, we must use the bpm command. On the picture below, we’re first presenting the help of the bpm command, then setting the breakpoint and listing all the breakpoints that are set for the current program. The breakpoint will not be hit whenever we will try to access or write to the location 0x0012C028. Conclusion We’ve seen the SoftICE installation, configuration and basic usage. We’ve also taken a look at the simple program and interacted with it with the SoftICE debugger. This was just a basic introduction and not a complete reference to SoftICE. SoftICE Commands/strong Do you realise that you just stole your copy of SoftICE, and included pictures to prove it? Hi, I’ve deleted those pictures from the post, but SoftICE hasn’t been actively developed for almost 10 years now, and there’s no support for it. I don’t thing it has a valid web page anymore. However, it remains copyrighted material. There is no such thing as “abandonware”. :-) Awesome stuff! Keep it up. Thank you, I will :)
http://resources.infosecinstitute.com/introduction-to-softice/
CC-MAIN-2014-42
refinedweb
2,061
60.35
Amazing Lookups Optimization Today’s article is about an unintuitive-yet-simple optimization you can use to hugely increase the speed of reading from Array, Vector, Dictionary, Object, and dynamic classes. Need I say more? Read on for this amazing speedup! I was recently reading an article on Mark Knol’s site about some of the loop optimizations I’ve discussed before (e.g. removing the length getter) when I saw something I’d never seen before, despite my nine articles on AS3 loops and years of reading other people’s AS3 code. Mark was casting the result of an Array read operation to the type of variable he was assigning it to: function test(items:Array, index:uint): void { var item:MyItem; item = items[index]; // normal version item = items[index] as MyItem; // Mark's version } To be sure, you do not need to type as MyItem because the result of indexing an Array is an untyped ( *) variable that can be assigned to anything. You don’t even get a compiler warning. If the type can’t be assigned, you’ll simply get null, 0, or some other default value. But, since this was an article on loop optimization and I was about to write a comment pointing out that casts can be expensive, I figured I should test my assumption. As it turns out, this cast wasn’t slowing down his version at all. In fact, it was yielding far superior performance to the version without a cast. Shocked, I developed a full performance test with Array, Vector, Dictionary, Object, and dynamic classes to see if this optimization applied elsewhere: package { import flash.display.*; import flash.utils.*; import flash.text.*; public class CastingLookups extends Sprite { private var __logger:TextField = new TextField(); private function row(...cols): void { __logger.appendText(cols.join(",") + "\n"); } public function CastingLookups() { __logger.autoSize = TextFieldAutoSize.LEFT; addChild(__logger); var beforeTime:int; var afterTime:int; var noCastTime:int; var castTime:int; var item:MyItem; var i:uint; var len:uint = 10000000; var itemsArray:Array = new Array(len); var itemsVector:Vector.<MyItem> = new Vector.<MyItem>(len); var itemsDictionary:Dictionary = new Dictionary(); var itemsObject:Object = new Object(); var itemsDynClass:Dynamic = new Dynamic(); for (i = 0; i < len; ++i) { itemsArray[i] = itemsVector[i] = itemsDictionary[i] = itemsObject[i] = itemsDynClass[i] = new MyItem(); } row("Type", "No Cast Time", "Cast Time"); beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsArray[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsArray[i] as MyItem; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("Array", noCastTime, castTime); beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsVector[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsVector[i] as MyItem; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("Vector", noCastTime, castTime); beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsDictionary[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsDictionary[i] as MyItem; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("Dictionary", noCastTime, castTime); beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsObject[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsObject[i] as MyItem; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("Object", noCastTime, castTime); beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsDynClass[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i) { item = itemsDynClass[i] as MyItem; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("Dynamic Class", noCastTime, castTime); } } } class MyItem{} dynamic class Dynamic{}: The point is not to compare the various container types (as in Map Performance or Accessing Objects), but the huge speedup when the cast is added. For Array and Vector, the cast nearly doubles the speed! For Object, Dictionary, and dynamic classes, the optimization is less drastic, but still about a 25% speedup. How is this possible? To see, let’s look at the bytecode generated for the “no cast” version of the Vector test: (with annotations by me) 221 pushbyte 0 // push 0 literal value 223 convert_u // convert 0 to an unsigned int 224 setlocal 4 // set 0 to i 226 jump L7 // go to block L7 L8: 230 label 231 getlocal 7 // get itemsVector 233 getlocal 4 // get i 235 getproperty null // index the vector 237 coerce private::MyItem // implicit cast the result to a MyItem 239 setlocal3 // set the result to item 240 getlocal 4 // get i 242 increment // i++ 243 convert_u // convert i to an unsigned int 244 setlocal 4 // set result to i L7: 246 getlocal 4 // get i 248 getlocal 5 // get len 250 iflt L8 // if i < len, go to block L8 Now let’s look at the version with the cast: 278 pushbyte 0 // push 0 literal value 280 convert_u // convert 0 to an unsigned int 281 setlocal 4 // set 0 to i 283 jump L9 // go to block L9 L10: 287 label 288 getlocal 7 // get itemsVector 290 getlocal 4 // get i 292 getproperty null // index the vector 294 getglobalscope // get the object at the top of the scope chain 295 getslot 2 // get the item at slot 2 in the global scope (i.e. MyItem) 297 astypelate // "as" cast to MyItem 298 coerce private::MyItem // implicit cast to MyItem (again) 300 setlocal3 // set the result to item 301 getlocal 4 // get i 303 increment // i++ 304 convert_u // convert i to an unsigned int 305 setlocal 4 // set result to i L9: 307 getlocal 4 // get i 309 getlocal 5 // get len 311 iflt L10 // if i < len, goto block L10 Notice that the only difference is that the cast version adds the as cast via these three lines: 294 getglobalscope // get the object at the top of the scope chain 295 getslot 2 // get the item at slot 2 in the global scope (i.e. MyItem) 297 astypelate // "as" cast to MyItem These three lines are the only difference between the “cast” and “no cast” versions of every tested type. How can adding instructions yield a 2x performance increase? I do not know. I’ve looked over the source code and bytecode at least a dozen times now and am positive that I haven’t switched the order or anything silly like that. If you spot an error, please comment below about it. Barring any mistake though, it looks like we have a way to hugely increase the speed at which we can access Array, Vector, Dictionary, Object, and dynamic classes! #1 by Matan Uberstein on July 18th, 2011 · | Quote Wow! This is an eye opener for me! My notion was the same as yours e.g. Casting = Slower. This is clearly not the case and come to think of it, it makes sense, I guess… Thanks for sharing, really love all your posts. :) #2 by makc on July 18th, 2011 · | Quote what about item = MyItem (items[index]); ? I always thought “as” brings additional overhead of safety, converting non-MyItem-s to null-s, where MyItem (…) will throw an RTE. #3 by skyboy on July 18th, 2011 · | Quote asis actually substantially faster than the function-style cast, if I recall earlier tests correctly. #4 by jackson on July 18th, 2011 · | Quote You do recall correctly. I converted the test to use function call-style casting (as suggested by makc) and the overhead made the cast version a little slower than the no-cast version. #5 by makc on July 18th, 2011 · | Quote people are checking this on wonderfl, and overall seem to have an agreement with your results, but not me :) <- here I have both "as" and f-style cast slower than untyped access (but "as" is still faster than f-style cast as you said). #6 by makc on July 18th, 2011 · | Quote wait a minute, there was copy-paste error in that code, now when I fixed it, “as” turns out to be slowest one #7 by makc on July 18th, 2011 · | Quote but for MovieClip-s “as” is clear winner seems to be in line with what focus reorted earlier #8 by intoxopox on August 12th, 2011 · | Quote With regard to the speed of as versus direct function-style casting, I have found that it really depends on the class. See my old post here: Those tests still stand up for me. #9 by skyboy on July 18th, 2011 · | Quote The speed up is definitely coming from the JIT here, possibly knowing the size of what’s being extracted allows for lookups to be directly inlined when generating machine code instead of passing through the native index function. What I’m curious about now, is whether or not saving MyItemto a variable will result in more of a speed gain, or remove it; as well as if an index into the multiname pool is faster (the class would need to be public and in its own package). The latter may offer no change, or it may speed it up. The former could do anything. One also has to wonder if a normal dot lookup to a non-dynamic property is sped up from this, or slowed down. While probably slowed down, apparently we can never know for certain without testing. #10 by jackson on July 18th, 2011 · | Quote I’m not sure what you mean by saving MyItemto a variable. I tried doing that and the result of the ascast becomes an Object, so I got this error: Changing the type of itemto Objectfixed the warning, but the speed was much slower. It was more on-par with the no-cast version. As for regular, non-dynamic dot access, I did try it but there was no speedup so I didn’t post the results. #11 by skyboy on July 18th, 2011 · | Quote Something like: If it still shows the same speedup, then this would also be a good test; Since flash can’t determine the type statically: While both are of limited use, generic code, such as what’s in a library, could benefit or suffer from any differences between this and an equivalent constant lookup. #12 by skyboy on July 18th, 2011 · | Quote I just ran a test similar to the second one by implementing it in my fastSort class for vector sorts, pre-sorted: So this advantage is definitely centered on load-time known types, and not on run-time determined types. A bit of a shame, this could have pushed my sort method to match or beat sortOn on all systems; not just the older systems where the main advantage is the in-place sorting. #13 by ben w on July 18th, 2011 · | Quote wow interesting find!! I used to have casting in my old 3d engine but took time stripping it all out as a number of tests showed it was definitely slower! This must be a newly added optimisation… do you have a way to test is across different flash versions! Also have you tried it with inbuilt classes i.e. Vector3D or something like that? ben #14 by jackson on July 18th, 2011 · | Quote I’ve tested back a few versions and found that it works in 10.2 and 10.1, but 10.0 wasn’t showing the speedup. Perhaps it was introduced in 10.1… And yes, it does work for Vector3D. However, the speedup seems to be much reduced on top-level classes like String. #15 by Mark on July 18th, 2011 · | Quote Wow, that’s a massive speed increase. I can kind of understand why this would be beneficial for an Array, as all of the elements are untyped, but I don’t understand the speed improvements for a Vector. Although, thinking about it, you don’t necessarily have to reference an element in a Vector to a variable of the same type (interfaces, subclasses, etc). So I guess there could be speed increases there too. Regardless, it’s an awesome spot! Mark #16 by pleclech on July 18th, 2011 · | Quote I think you should test something like that : You will be surprised but not on the right way. Best, Patrick. #17 by jackson on July 18th, 2011 · | Quote Hey Patrick, The code snippet in the link looks just like a regular loop over a Vector. Am I missing something? #18 by pleclech on July 18th, 2011 · | Quote Well in your test you didn’t use the Class after the as , what i added is a simple usage of the class for example read of a property or calling a method, and the result are terrible. #19 by jackson on July 18th, 2011 · | Quote Ah, I see now. I too see very poor results with the ascast when accessing a property or calling a method of item. However, there are other cases where I can insert some extra code into the loop and still see better performance with the ascast: Math.sqrt(64), item = item, item2 = item, or item = null. As skyboy correctly points out, these results are due to something going on in the JIT. I’ve looked at the bytecode for the property access and method call versions and nothing stands out. Anyone have any more ways that the item can be used once it’s been quickly accessed using the ascast? #20 by focus on July 18th, 2011 · | Quote Tested with top-level class (like String, Number, Object) typed variables in the array. Got the opposite results. #21 by jackson on July 18th, 2011 · | Quote Interesting find. I’ve just tried Stringand intand there was either a minor (~5%) speedup or no speedup at all. Built-in classes that are not on the top-level (e.g. Vector3D) do get the speedup though. #22 by Mark Knol on July 18th, 2011 · | Quote Cool to see there is room more performance boosts, even with some relative simple casting. Thanks for testing my blogpost + the link in your article :) #23 by Jonas on July 18th, 2011 · | Quote Different results with FP 10.1 standalone & 11plugin (flex_sdk_4.5.1.21328) WIN 10,1,52,14 StandAlone Type,No Cast Time,Cast Time Array,133,219 Vector,134,220 Dictionary,321,402 Object,333,433 Dynamic Class,338,427 WIN 11,0,0,58 PlugIn Type,No Cast Time,Cast Time Array,121,216 Vector,119,211 Dictionary,316,389 Object,292,396 Dynamic Class,299,397 #24 by jackson on July 18th, 2011 · | Quote Interesting. I am seeing the speedup on Windows with Flash 11 plugin, Flash 10.2 standalone, and Flash 10.1 standalone but not in Flash 10.0 standalone. All of this is with a 2.8 Ghz quad core Xeon W3530 on Windows 7. What system and OS did you run the tests on? #25 by Jonas on July 18th, 2011 · | Quote Hello, I run the test with a 2,67 GHz Core i5 on Win 7 64 bit. #26 by Daniel on July 18th, 2011 · | Quote I tried the test in 10.3 and 11.0 inside browser as well as 10 standalone and the results seem pretty consistent. I’ve also tried using int instead of MyItem, and there is little difference. I did however notice in the standalone DEBUG version my results were more in line with janas’ results. the project was compiled for release, not debug, but was ran inside the debug player. #27 by jackson on July 18th, 2011 · | Quote I’m not sure what you’re reporting here. Which versions are you seeing the cast speedup with and which are you not? Also, I try to never test under debug as end users do not run it. #28 by Daniel on July 18th, 2011 · | Quote I’ll summarize :) I see the speedup everywhere I tested except for standalone-debug. The reason I’m posting this is to give some perspective to others that are seeing these reverse results so that they test results in non-debug version of flash player. #29 by jackson on July 18th, 2011 · | Quote Thanks for clarifying. :) #30 by Lincoln on July 18th, 2011 · | Quote Great article. What are you using to view the compiled byte code? Are you doing it by hand or is there a tool you use? #31 by jackson on July 18th, 2011 · | Quote I used the nemo440 AIR app. It hasn’t been updated in a while, but it still works. :) #32 by Lincoln on July 19th, 2011 · | Quote Awesome, thanks a lot! #33 by Lincoln on July 19th, 2011 · | Quote Hmm, it works on basic asset swfs published from Flash, but our main project swf has the following error. Error: Error: Unknown format 0xb535743 It also seems to happen whenever I compile any swfs using Flash Builder 4.5. What are you using to compile your swfs and what sdk version are you using (if that matters)? #34 by skyboy on July 19th, 2011 · | Quote Nemo440 only works for certain target versions. Up to 10.1 I think. #35 by jackson on July 19th, 2011 · | Quote This is true. However, it’s easy to compile for an earlier version. I compiled the test app from the command line like so: #36 by Lincoln on July 20th, 2011 · | Quote Gotcha. Thanks again guys! #37 by Jonas on July 18th, 2011 · | Quote Oh… Same test on a non debug player (10.3) : WIN 10,3,162,28 ActiveXType, No Cast Time,Cast Time Array,103,49 Vector,96,45 Dictionary,263,209 Object,255,199 Dynamic Class,255,200 Vector + var access,104,159 Vector + method call,139,205 I added the pleclech “Vector + var access” and “Vector + method call” tests … In this case it seems that cast is less efficient. #38 by skyboy on July 18th, 2011 · | Quote While thinking about this, I realized the JIT might actually be removing operations, treating them as dead code. Jonas’s tests seem to verify this. A few simple and very quick operations seem to negate the DCE because it’s not complex enough. That code should be able to avoid any DCE, but the operations are all very fast and O(1) so do not impact the results in any significant way. Replacing short circuited boolean operators (&&, ||) with bitwise operations and int/boolean conversions where applicable (e.g., where the operations are not more expensive than the jumps themselves) could be an article itself, since it provides significant performance improvements. #39 by jackson on July 19th, 2011 · | Quote I don’t think it’s DCE because that would result in an empty loop. Commenting out the loop body and running on the same machine as in the article (2.4 Ghz Intel Core i5, Mac OS X 10.6), I still get about ~25ms for the empty loop and the same 68ms for the ascast version. As for your test code, it is indeed a way to take advantage of the ascast approach. I’m seeing ~244ms without the cast and ~225ms with the cast on the same machine. I’ll have to write that article on using bitwise operators instead of logical operators. :) #40 by Tommy Reilly on July 19th, 2011 · | Quote #41 by Nicolas on July 20th, 2011 · | Quote FYI, haXe () already does this optimization for you automatically. It also does fast array-index lookup, for instance in AS3 you have to convert arr[x+1] into arr[int(x+1)] in order to get decent speed. #42 by jackson on July 20th, 2011 · | Quote For this haXe code: I get this bytecode: I don’t see any astypelateinstruction in there, which seems to indicate that haXe isn’t doing this exact optimization. I do see a double coercethough, so perhaps that’s meant to do the same thing. As for performance, on my 2.8 Ghz Xeon I’m getting about 94ms for the “no-cast” version, 55 ms for the “as cast” version, and 94ms for the haXe version. This would also seem to indicate that the optimization hasn’t been done, since the haXe version is performing on-par with the unoptimized “no-cast” version. #43 by Ossi Rönnberg on July 20th, 2011 · | Quote Quite strange OSX 10.6 Core 2 Duo Chrome running 10.3.181.36 Type,No Cast Time,Cast Time Array,133,69 Vector,136,61 Dictionary,416,303 Object,415,292 Dynamic Class,413,297 Totally opposite results OSX 10.6 Core 2 Duo Safari running 11.0.1.60 Type,No Cast Time,Cast Time Array,229,388 Vector,223,427 Dictionary,543,711 Object,657,795 Dynamic Class,598,704 #44 by jackson on July 20th, 2011 · | Quote It seems like you’re using the debug version of Flash 11 and the release version of Flash 10. #45 by Deril on July 29th, 2011 · | Quote This is interesting find, it’s curious how it is slower in debug version… but not release. My best guess is that then op code is interpreted, virtual machine does not need to do some work on finding/setting objects type.., that is heavy if you don’t do this operator ‘as’ casting… … why it’s not automatically happen with Vectors is a mystery… #46 by Bram on August 3rd, 2011 · | Quote Mmm – 10 x slower on my machine ( MBP 5.2, 2.66 Intel Core Duo, 4GB memory ) after copy pasting your code. Flash Player 10,3,181,14 release build, Safari 5.1, OS X 10.6.8 Type No Cast Time Cast Time Array 1196 1356 Vector 1190 1322 Dictionary 1428 1573 Object 1412 1603 Dynamic Class 1399 1556 #47 by mani on September 1st, 2011 · | Quote Type,No Cast Time,Cast Time Array,1312,1481 Vector,1283,1427 Dictionary,1585,1724 Object,1553,1722 Dynamic Class,1591,1730 Flash Player 10,3,181,14 debug, Google Chrome, OS X 10.6.8 -_- #48 by jackson on September 1st, 2011 · | Quote I try to never test with the debug player. Not only are the results much slower than with the release player, but sometimes code that is faster in release will be slower in debug. #49 by Javier on February 9th, 2012 · | Quote First, sorry about my English. Jackson, this is very interesting and it´s going to help me a lot in some process consumer functions. One thing I notice, is that if I do the test with FP 10.1 debugger it get like double time casting but with FP 10.1 not debugger it get same result like yours. Another thing I don’t understand is way Vector casting is faster, if Vector is already casted. Thanks for all this tips. Have fun. #50 by jackson on February 9th, 2012 · | Quote No worries about your English; my Spanish is even worse. :) The debugger player is notoriously slow and inconsistent with the performance of the release player. For example, A may run faster than B in the debugger and then slower than B in the release player, even if both run much faster. Usually this is because the debugger punishes AS3 code heavily and native code (i.e. most of the Flash API) much less or not at all. For these reasons and that virtually no end users will ever run the debugger player, I’d recommend only performance testing with release players. This is the policy I’ve always had in this site’s articles. As to why Vectorcasting is faster, that is why the article has the word “amazing” in its title. You’re correct- It shouldn’t be faster at all as the Vectoris already typed. Actually, that’s the whole purpose of a Vector. The reason for the speedup remains a mystery to me. #51 by Javier on February 9th, 2012 · | Quote Thanks for the response :) #52 by caboosetp on March 19th, 2013 · | Quote Environment: FP 11.6.602.180 (Not Debug), Apache Flex 4.9 with Air 3.7, Intel I7-2600k @ 3.4ghz I was happy when I found this article as I thought I could get some code running faster. Since I’m using a different environment, I first ran your test code to make sure it worked the same and got similar results, aside from vector which seemed the same. This made sense since Vectors are type cast anyways and the newer libraries are supposed to be optimized. Type,No Cast Time,Cast Time Array,39,17 Vector,17,16 Dictionary,194,167 Object,184,161 Dynamic Class,184,165 Then I tried using the typecast in a Shellsort algorithm for the Number type and it exploded. Namely changing t = data[i];to t = data[i] as Number; and data[j] = data[ji];to data[j] = data[ji] as Number; and came out with AS3 Shell Sort: 3452 AS3 Shell Sort on ordered elements: 958 AS3 Shell Sort Typecast: 13013 AS3 Shell Sort Typecast on ordered elements: 5609 Which is almost 4 times as slow. This blew my mind, so I decided to run the same benchmark you had, but using Number instead of a user defined class. // .. rest of benchmark unchanged var num:Number; var itemsVectorN:Vector. = new Vector.(len); for (i = 0; i < len; ++i){ itemsVectorN[i] = 3.14; } beforeTime = getTimer(); for (i = 0; i < len; ++i){ num = itemsVectorN[i]; } afterTime = getTimer(); noCastTime = afterTime-beforeTime; beforeTime = getTimer(); for (i = 0; i < len; ++i){ num = itemsVectorN[i] as Number; } afterTime = getTimer(); castTime = afterTime-beforeTime; row("VectorN", noCastTime, castTime); and got the result VectorN,16,237as well as with nearly identical code for Array and got ArrayN,27,87 I know someone made a post earlier about top level elements being slower, and you had found int to have a similar speedup rather than a slowdown, so I tried out int just to be sure and found it to much slower with a result of VectorI,17,135 I’m wondering if I made a mistake in the code, or if it’s the new libraries. It seems the casting is still faster for user defined classes but much slower for primitive data types. I’m not currently using the ASC 2.0 compiler though, but I know it does a very good job at optimizing. I’m curious if, with the newer libraries and possibly ASC 2.0, you still get primitive data types to be faster and if so why I don’t see the same results. #53 by jackson on March 19th, 2013 · | Quote I happen to still have the original SWF (which I just uploaded for your testing) so I ran it in my new testing environment: And got these results: So with upgrades from Flash Player 10.3 to 11.6, OS X 10.6 to 10.8, and a Core i5 to a Core i7 it seems as though I’m still getting the same results on all but Vector, albeit faster due to the improvement in hardware. You’re seeing no improvement in Vectoreither, so our results match there. The rest of what you’re reporting in regards to Numberand intare showing huge performance losses where I found at the time a negligible change in performance compared to not casting. So I changed the test app to use Numberand got these results: ASC 1.0: ASC 2.0: And with intI got these results: ASC 1.0: ASC 2.0: Again I concur with your findings. This seems to be a huge change that has occurred since the article was originally written. I have a hard time believing that it’s due to my upgraded hardware, probably doesn’t have anything to do with upgrading my OS, and ASC 2.0 isn’t making much of a difference beyond the normal “noise” in testing. So it seems that somewhere between Flash Player 10.3 and 11.6 there was a change that dramatically reduced the performance of casting the result of a lookup to a top-level class. That’s a shame and possibly even a bug. Lastly, here are my results of the original test ( MyItem, not top-level classes) re-compiled with ASC 2.0: Vectoris now also worse off with the cast, but at least the optimization is still present with Array. #54 by skyboy on March 20th, 2013 · | Quote The dismal performance of Vector in the first test is probably because of the target version of flash in the SWF (and may impact casting for Number/int: different target versions occasionally use different code paths for compatibility’s sake). The effect of Number/int performing worse with the cast may be due to changes in the VM, causing a conversion to a boxed type then back? The same penalty may not exist for generic top-level classes; if it does, then the penalty is stemming from the way the core classes are included with the VM (rather than boxing/unboxing), effectively containing them in a separate SWF and limiting how much can be optimized due to the different context. #55 by Jeff Spicer on September 11th, 2013 · | Quote i’m no expert, but just thinking about how type casting might be done behind the scenes might explain why it’s faster to type cast items in a loop. if the type is not known, then perhaps Flash Player must iterate the unknown object, looking for properties and methods, and then attempting to match them to the defined type. But perhaps using “as” instead iterates the targeted type, matching it to the item’s vars/methods. a test might be to have MyItem be a complex class, but the item[i] is of a type extended from MyItem and has extra params in it. or perhaps MyItem is an interface or something. Maybe some tests like that will give a clue as to how type casting is done behind the scenes. If Flash Player does use different forms of type casting, then it would follow that the more base types like String and Number and the optimized Vector class would not benefit from type casting because the type is already known, and the extra step would slow it down.
https://jacksondunstan.com/articles/1305?replytocom=9027
CC-MAIN-2020-16
refinedweb
5,004
67.99
Reactive.Banana.Frameworks Synopsis - interpretAsHandler :: (Event a -> Moment - interpretFrameworks :: (Event a -> MomentIO (Event b)) -> [Maybe a] -> IO [Maybe b] - newEvent :: MomentIO (Event a, Handler a) - mapEventIO :: (a -> IO b) -> Event a -> MomentIO (Event b) - newBehavior :: a -> MomentIO (Behavior a, Handler a) - data EventNetwork - actuate :: EventNetwork -> IO () - pause :: EventNetwork -> IO () Synopsis Connect to the outside world by building EventNetworks and running them. Simple use interpretAsHandler :: (Event a -> Moment a)) Source # Output, return an Event that is adapted to the changes of a Behavior. Remember that semantically, a Behavior is a function Behavior a = Time -> a. This means that a Behavior does not have a notion of "changes" associated with it. For instance, the following Behaviors are equal: stepper 0 [] = stepper 0 [(time1, 0), (time2, 0)] = stepper 0 $ zip [time1,time2..] (repeat 0) In principle, to perform IO actions with the value of a Behavior, one has to sample it using an Event and the apply function. However, in practice, Behaviors are usually step functions. For reasons of efficiency, the library provides a way to obtain an Event that mostly coincides with the steps of a Behavior, so that sampling is only done at a few select points in time. The idea is that changes =<< stepper x e = return e Please use changes only in a ways that do not distinguish between the different expressions for the same Behavior above. Note that the value of the event is actually the new value, i.e. that value slightly after this point in time. (See the documentation of stepper). This is more convenient. However, the value will not become available until after event processing is complete; this is indicated by the type perform IO actions here, which is useful if you want to register additional event handlers dynamically. However, if two arguments to execute occur simultaneously, then the order in which the IO therein are executed is unspecified. For instance, in the following code example e = do e1 <- execute (liftIO (putStrLn "A") <$ e) e2 <- execute (liftIO (putStrLn "B") <$ e) return (e1,e2) it is unspecified whether A or B are printed first. Moreover, if the result Event of this function has been garbage collected, it may also happen that the actions are not executed at all. In the example above, if the events e1 and e2 are not used any further, then it can be that neither A nor B will be printed. If your main goal is to reliably turn events into IO actions, use the reactimate and reactimate' functions instead. liftIOLater :: IO () -> MomentIO () Source # module Control.Monad.IO.Class Utility functions This section collects a few convience functions built from the core functions. interpretFrameworks :: (Event a -> MomentIO (Event b)) -> [Maybe a] -> IO [Maybe b] Source # Interpret an event processing function by building an EventNetwork and running it. Useful for testing, but uses MomentIO. See interpret for a plain variant..
https://hackage.haskell.org/package/reactive-banana-1.2.2.0/docs/Reactive-Banana-Frameworks.html
CC-MAIN-2021-43
refinedweb
477
51.68
- Type: Bug - Status: Closed - Closed - links to - I investigated this issue and looks like it introduced by the Pipeline: Declarative plugin v1.3.5. The offending commit seems to be. Downgrading to v1.3.4.1 is the workaround for now. ^^ I can confirm, symptoms arise upgrading to 1.3.5. I updated an older Jenkins to 1.3.5 and it resulted in the same symptoms. Downgrading back to 1.3.4.1 resolved it. Lakshya Kapoor Yes, this is caused by PR 313, which was the fix for JENKINS-55459. In general, you cannot use currentBuild.result to accurately determine the current state of the build, because currentBuild.result does not take into account any in-flight exceptions that are propagating throughout the execution and will cause it to result in failure at the top-level. Post conditions in Declarative do account for these in-flight exceptions and should be triggered appropriately. Getting and/or setting the build result is somewhat messy in Scripted Pipeline as well and does not always do what you want because there is no step-level build result, only an overall build result. The changes made in PR 313 made Declarative match the behavior of Scripted. What is your actual use case? Can you use post conditions without actually inspecting the build result? Perhaps we could provide some other kind of API visible to scripts to expose the ephemeral result that will be used when deciding what POST steps to run, but if you are setting the build result intentionally to try and change the flow of execution then I am not sure what we could do to fix that use case. CC Andrew Bayer Devin Nusbaum Does all what you said also apply to currentBuild.currentResult ? It's also showing incorrectly on failed stages. Can you use POST conditions without actually inspecting the build result? I'd like to answer your question with another question: How do we get a build status when inspecting currentBuild if result and currentResult are both incorrect on a build failure? Wouldn't this also make resultIsBetterOrEqualTo and resultIsWorseOrEqualTo now moot since we can no longer rely on any build status checks? Does all what you said also apply to currentBuild.currentResult Yes, currentBuild.getCurrentResult() is identical to currentBuild.getResult() except for the fact that it defaults to SUCCESS instead of null if the build result has not yet been set, see the code here. How do we get a build status when inspecting `currentBuild` if `result` and `currentResult` are both incorrect on a build failure? As far as I am aware, there is no way in Declarative to get an accurate picture of the current build status using only currentBuild. In Scripted, I think you could use try/catch statements along with currentBuild to look at the current status and catch specific kinds of exceptions to handle status-conditional logic, essentially duplicating this logic in Declarative. In Declarative, you should be able to use post conditions to handle status-conditional logic without needing to use currentBuild directly. I asked about your exact use case because I am curious if there is a functionality gap we can address so that users would have no reason to use currentBuild given its confusing edge cases. I asked about your exact use case because I am curious if there is a functionality gap we can address so that users would have no reason to use currentBuild given its confusing edge cases. I use currentBuild extensively to get the build's information, following some examples from here: It's a notification prettier to send Slack messages about the build's status at the point of success, failure, etc. While they don't directly use result in the code, we used POST always { notifySlack(currentbuild.result) } as a catch-all for build statuses. currentBuild is, however, extensively used for grabbing test results and result details. Hi Devin Nusbaum, my use case is similar to Philip Zozobrado's. I am sending an email notification in my post step (always) and I am using currentBuild.currentResult to determine the font color for the build status and the subject line in the email: def statusColor = colorCodeByStatus(currentBuild.currentResult) // $BUILD_STATUS font color ... // Returns HEX code based on given build status def colorCodeByStatus(status) { if(status == 'SUCCESS') { '#28B463' // Green } else if(status == 'FAILURE') { '#DF0101' // Red } else { // Aborted or Unstable '#9E9E9E' // Gray } } I am not sure if this violates any sort of best practices, but this could be a workaround for such use cases: post { success { currentBuild.currentResult = 'SUCCESS' } unstable { currentBuild.currentResult = 'UNSTABLE' } failure { currentBuild.currentResult = 'FAILURE' } always { dir(path: 'report') { executePostSteps(JOB_NAME) } } } // post I haven't had a chance to test it yet, so please feel free to critique it. Lakshya Kapoor, unfortunately, always runs first. That won't work: The condition blocks are executed in the order shown below. always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, and cleanup. There's also some waterfalling not documented: fixed will also run success, for example. I've updated my pipeline to: post { cleanup { cleanWs() } failure { notifySlack([status : 'FAILURE', pipeline: this] as JenkinsStatus) } fixed { notifySlack([status : 'FIXED', pipeline: this] as JenkinsStatus) } unstable { notifySlack([status : 'UNSTABLE', pipeline: this] as JenkinsStatus) } success { notifySlack([status : 'SUCCESS', pipeline: this] as JenkinsStatus) } } However, I'm still looking for a way to kill the fixed waterfall into success. Lakshya Kapoor Your workaround won't work as Philip Zozobrado pointed out because always runs first, however cleanup has the same semantics as always other than running last, so you can probably use it for your workaround as they demonstrated. Philip Zozobrado Fall-through happens for changed, fixed, and regression, (and always, unsuccessful, and cleanup, but those are probably less interesting). The reason is that in Jenkins these conditions are not a first-class result, so Declarative computes them based on the current build status in comparison to the previous build's result, so one of aborted, failure, success, unstable, or notBuilt will always be executed if one of changed, fixed, or regression is executed. More than one of aborted, failure, success, unstable, and notBuilt will not be executed in the same post block. I think that it would be possible to support the use cases you both have mentioned by creating a new read-only variable that would only be set inside of post conditions in Declarative that would represent the current logical build status versus currentBuild.result which is just the literal value of Run.result. That way you would be able to access the current build status without Declarative needing to modify Run.result which is problematic in some cases. @Philip The condition blocks are executed in the order shown below. Yea, I had a feeling it was that way, but wasn't sure. Thanks for pointing it out! @Devin - I like your idea for the new read-only variable. P.S. JIRA is giving me a "Communications Breakdown" error when I @ your usernames . Was getting it since yesterday afternoon, but just figured it out it is related to tagging people. We run into this issue after last update of Jenkins core and plugins. It's highly critical because it results in wrong mails/notifications and changed behavior. Using currentBuild.result was a documented, working way of accessing the build result, also for declarative pipelines. It's not an option to change hundreds of pipelines in various branches and move code from always block to different post condition blocks. This would just duplicate a lot of code, like the call of emailext step. Moveover, the issue makes some plugins like claim-plugin unusable. This is called by step([$class: 'ClaimPublisher']) in the post section, and internally evaluates the build's status in order to decide whether to show claim functionality (build result is failure or unstalbe) or not; see ClaimPublisher.java: @Override public void perform(@Nonnull Run<?, ?> build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { Result runResult = build.getResult(); if (runResult != null && runResult.isWorseThan(Result.SUCCESS)) { ... } } Since the result is always SUCCESS now, claim UI elements are never shown. Same applies to some custom plugins developed here. Thus, please restore the previous functionality ASAP! After that, you might think about better ways to fix the edge cases or provide new variables... Hi Devin Nusbaum, I used currentBuild.currentResult in a good number of places and was affected by this issue. I think we should revert it or provide an alternative way. I used it with at least 4 different plugins: Slack, MS Teams, Email Ext and InfluxDB. For Slack is basically similar to what has being described already: String slackMessage() { "Build *${env.JOB_NAME}* finished with status *${currentBuild.currentResult}*" } String slackColor() { "${currentBuild.currentResult == 'SUCCESS' ? 'good' : 'danger'}" } I don't want to have to repeat the above for each type of result, instead, is easier on the pipeline library to just read the status as above. For MS teams I have got: pipeline.office365ConnectorSend message: 'Build completed', status: currentBuild.currentResult, webhookUrl: msTeamsWebhookUrl, color: currentBuild.currentResult == 'SUCCESS' ? '82C441' : 'C81423' Same use case as Slack. Another case with Slack and MS Teams is that we use a combination of lock and milestone plugins, so sometimes a build is skipped and the result is NOT_BUILT, so we have this: if (currentBuild.currentResult == 'NOT_BUILT') { //don't send Slack / MS Teams message in this case as this build has being skipped by lock/milestone } Now, the tricky cases are Email Ext (plugin id = email-ext) and InfluxDB (plugin id = influxdb). They need a value on currentBuild.result to function properly. So for both of them I have to do this before using the plugins: //to fix issue where mailer needs 'currentBuild.result' which is always null at this point - without this email does not report build result correctly currentBuild.result = currentBuild.currentResult step([$class: 'Mailer', recipients: emailList]) And InfluxDB: //to fix issue where InfluxDbPublisher needs 'currentBuild.result' which is always null at this point - without this build result is not reported to InfluxDB currentBuild.result = currentBuild.currentResult step([$class: 'InfluxDbPublisher', target: 'influxdb']) Both Email Ext (plugin id = email-ext) and InfluxDB (plugin id = influxdb) are a bit old (they don't seem to support Declarative Pipelines directly, and instead we need to use step). After this bug was introduced I don't have an easy way of "fixing" this two plugins and all of the above cases stopped working for me. Michel Zanini, for email-ext there is a Pipeline compatible step available, see and Yes Christoph Amshoff, thanks. At the time I did this there was an issue with it, I don't remind what exactly, but yes I can try migrate, but not sure the problem with build result will go away.... I agree with Christoph and Michael in that there's not just one, but several, plugins that break because of this change... and the change is often subtle. For instance, we didn't know about the false SUCCESS reports we were getting by email until we actually took a look at the log and found that the pipeline was actually failing. Granted, we're a small enough organization that uses just a few distributed pipelines and a standard jenkinsfile, so we were able to add a workaround, but for those like Cristoph who have to deal with hundreds of them, it's needless technical debt. For us, this issue is equally urgent as for Christoph Amshoff. I agree with Michel Zanini on the approach to "revert it or provide an alternative way." Right now, this change caused developers to be notified with a "Build Completed" Email in our infrastructure, even though the build actually failed. I just wish there would be something like an LTS release line for these deeply integrated plugins. This would greatly increase their reliability. +1. We have jobs that rely on this, e.g. compare previous build against current build, set slack message color, etc etc. As it stands, it seems there is no way to determine if the build is failing right now, even with the hudson API? I had to add a function to read the build log I understand that setting currentBuild.status for stage-level post conditions could potentially be problematic. But for the overall post conditions of the build there seems to be little reason not to set it if the build as a whole is failed. This is the point point where people are most likely to use various plugins originally designed for freestyle projects that expect a result to be set. Some of them have been upgraded to treat an unset status value as success, which means that they worked fine in an overall post-build step, prior to the recent change, but don't anymore. In the alternative, at the very minimum the read only value proposed would help. In practice people would just use it to initialize currentBuild.result though, in order to make various legacy plugins happy. I've just merged a potential fix () and am cutting 1.3.7-beta-1 now - see for how you can install the beta. It should be in the update center within an hour or so. We'd appreciate your feedback as to how this change works for you - if it turns out not to solve enough of the use cases, we'll switch to reverting the problematic change completely, but we'd really like to be able to keep it in if we can. Thanks, and we appreciate your patience and are very sorry for the inconvenience this change has caused. Thanks, Andrew Bayer and Devin Nusbaum! I'll test 1.3.7-beta-1 on Monday and report back. I've installed 1.3.7-beta-1 version of all four pipeline plugins (Pipeline: Declarative, Pipeline: Declarative Extension Points API, Pipeline: Model API and Pipeline: Stage Tags Metadata) and can confirm that it works! Status in post action is correcct now, mails are sent with proper status and Claims plugin's icon shows up again for unstable or failed builds. So, thanks for the fix! I really appreciate your efforts, and can imagine it's hard to fix this messy status implementation without breaking any functionality... Just wanted to remark that the currentBuild.resultIsBetterOrEqualTo / resultIsWorseOrEqualTo also does not work because of the same issue - assuming they use the same currentBuild.currentResult internally. 1.3.7-beta-1 also fixed the issue for our infrastructure: Andrew Bayer Devin Nusbaum thank you very much for the fast response and fix! 1.3.7-beta-1 is a very good improvement. Not just it works like before, it also works better. Now I won't need to do this anymore: currentBuild.result = currentBuild.currentResult To make it easy for everyone to see differences between the versions. I will post the result of executing the pipeline that is on the description of this issue below, on all different versions, so people can easily spot the differences. 1.3.4.1 and below: Init result: null Init currentResult: SUCCESS Post-Init result: null Post-Init currentResult: SUCCESS During Build result: null During Build currentResult: SUCCESS Post-Build result: FAILURE Post-Build currentResult: FAILURE Pipeline result: FAILURE Pipeline currentResult: FAILURE Note: problem with 1.3.6 is that it shows 'Post-Init result: null' where at that point it could be SUCCESS 1.3.6: Init result: null Init currentResult: SUCCESS Post-Init result: null Post-Init currentResult: SUCCESS During Build result: null During Build currentResult: SUCCESS Post-Build result: null Post-Build currentResult: SUCCESS Pipeline result: null Pipeline currentResult: SUCCESS Note: This is the worse version because result is always 'null' and currentResult always 'SUCCESS' 1.3.7-beta-1: Init result: null Init currentResult: SUCCESS Post-Init result: SUCCESS Post-Init currentResult: SUCCESS During Build result: null During Build currentResult: SUCCESS Post-Build result: FAILURE Post-Build currentResult: FAILURE Pipeline result: FAILURE Pipeline currentResult: FAILURE Note: this is the best version because both property are always correct on post blocks I am also glad to confirm that currentBuild.currentResult in v1.3.7-beta1 works as it did in v1.3.4.1. Thanks again!! With current version 1.5.0 of Pipeline: Declarative Plugin. I get the same issue. Artour Klevin If you reopen an old issue, please include a full reproduction case of the issue you are seeing, and describe the actual and expected behavior. In this case, since the issue has been fixed since March, it would be better to open a new ticket to track whatever issue you are seeing separately, so I am going to re-close this issue. For people who reported watched this issue its nice that the issue is reopened because it gets it on our radar. Forcing A new issue is a disservice to your hard core issue reporting users who wouldnt get notified But totally should have recreate steps chirs damour By all means, if you open a new issue that is related to an old issue, please comment on the old issue mentioning that you saw something similar, include a link to the new issue, and add a "relates to" issue link in Jira to the other issue. I think it is ok to reopen an issue if you do so very soon after it was originally resolved/closed, since the context is still the same, but given this issue was originally closed in March 2019, I think we need to reevaluate any related issue from scratch. For example, is the fix completely broken (hopefully not, we added some regression tests with the fix), is this a slightly different use case, does it only break when using matrix or parallel, etc. Sorry for just re-opening it without adding more information. It looked very similar to my problem, but after spending another day on it, I have no issues. I just set the curentBuild.result = 'FAILURE' in the catch when my step fails in the pipeline. Then everything works as I would like it to. Thanks for keeping the plugin alive! I'm experiencing the same. currentBuild.currentResult for all failed and aborted builds returns "SUCCESS". Same when using $BUILD_STATUS through the emailext plugin. Using Jenkins version 2.150.3 and Pipeline 2.6. All pipeline related plugins are at the latest version as well.
https://issues.jenkins-ci.org/browse/JENKINS-56402?focusedCommentId=363342&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2020-10
refinedweb
3,054
54.52
Who to get away from Bradford, and in most cases, the farther the better. But one thing I loathe is packing. I don’t know why, but I seriously struggle to even function as a human being when packing is on my to-do list. After managing to pack, the stress of the airport comes next, and that’s really everyone’s least favorite part, I think. Which is worse: waiting in line at security, waiting in line to board the plane, or waiting in your seat to take off? Trick question, they all suck. Even after you get off the plane, your stresses aren’t over yet, because then you either have to take a bus to the car rental place or get a taxi, and then check in to your hotel, blah blah blah, when does the fun part start?! So, yeah, I can understand why someone wouldn’t like traveling very much, but I believe the stress is beyond worth it. It’s worth it when you’re standing at the top of the Freedom Tower, looking out over New York as the sun sets, every window gleaming and golden. And it’s worth it when you’re parasailing over water clearer than crystals, or when you see a 2,000 foot tall waterfall. It’s worth it when you try foods you’ve never even heard of before; at least, that part is important to me, maybe not so much to someone who isn’t totally obsessed with food. The point is, there is so much to see in this world. There’s oceans and mountains and everything in between, and I intend to see as much of it as possible. In case you didn’t know, I’m in New York right now! Brooklyn, specifically. I’m so happy to be here, but it’s also super overwhelming. Does anyone else have the problem of everything looking the same? There’s a million different shops and buildings, but I feel like every deli or corner store looks the exact same, it’s very disorientating. I can’t figure out the subway, the traffic is terrible, and there’s a thousand people to move out of the way of on the sidewalk. But I’ll be darned if I don’t enjoy every minute of being here! Thank you to everyone who commented on my previous post about New York, your recommendations were super fun to read and I will definitely take some of them into consideration when planning what all I’m going to do while here. I will be sure to post about any amazing restaurants I try or spectacular things I see throughout the week. Where’s the best place you’ve ever traveled to? Do you hate flying or several day long car trips more? Anyways, hope you all have a great day! 45 thoughts on “The Love-Hate Relationship With Travel” It’s the stress leading up to traveling that gets me, not the traveling itself. I’m obsessive about having my flight info, rental car info, hotel info, etc., printed out and within easy reach at all times. Once I’m on the plane, though, I’m fine. Also, I don’t hate several days in the car at all. Some of the best vacations we’ve ever had have been road trips. I am 42 and in my life I’ve been all over the Continental U.S. on road trips with various members of my family. We’ve lived in Indiana, Oklahoma, Massachusetts, and now Maryland and we’ve taken trips from all of them. Coast to coast with the notable exception of everything north of Kansas and west of Illinois and Wisconsin. Which is a pretty big part of the country I’ve not visited. I have never left the country. I may not ever, as it would be very expensive and I loathe flying. I am an extremely big person, 6’6″ and built like a football player. I’ve never been anything but uncomfortable on planes. They just aren’t built for someone my size. The upgraded seating options would add even more prohibitive expense. That said I’d love to visit many places around the world, I have enjoyed exploring the history of the places I’ve visited here at home. There’s a million different shops and buildings, but I feel like every deli or corner store looks the exact same, it’s very disorientating. There’s a story by Connie Willis about that problem. I Met a Traveller in an Antique Land. Athena, I like how you’re honest about New York. I feel like I’m on Live Journal, anyways, here’s a different perspective: On road trips I like hotels, for air trips I like flying: I guess the novelty hasn’t worn off yet. Partly because I did neither until years after I was an adult. My family took no vacations, only “staycations.” Part of the reason I like hotels (besides being a science fiction fan who likes any half futuristic architecture) is that I can watch cable TV, and the science fiction channel. At home I only do DVD’s, not cable, nor even “peasant TV.” (Mainly to manage distractions, but also to save money) I grew up in the country, and so on long road trips, rather than hike on trails from the highway, I’d rather go into small town second hand book and used clothing stores. I’ve generally found packing easy. Count the days. Razors = days/2, shirts = days+1, socks = days*s, underclackers = days+1. Trousers = days/5. Air travel… just no. Not the 600mph in a tin can at 5 miles up thing. But the low-pressure, uncontrolled-lighting, small-seats, turn-up-3-hours-early, queue-for-security-theatre, 20-miles-out-of-the-way-each-end experience… no. I have the good fortune to live in Europe (at least, for the next 8 months. :( ), and there are still a few sleeper trains around. My best travel was one that didn’t quite go as planned, due to French train strikes: Home to London to Paris. Overnight stay opposite the Gare de Lyon, with some of the best seafood I’ve ever had in a randomly-chosen restaurant on the Rive Gauche. Paris to Zürich by TGV. Zürich to Milano, through some of the most spectacular scenery and impressive engineering I’ve met, via the Gotthard tunnel. Milano to Venezia Santa Lucia, with the Dolomites always on the horizon. Then a short walk (via the Ponte degli Scalzi, in a nod to our host) to the hotel for 7 days in Venice. Finally, return journey from Venice to Torino, through the Simplon tunnel, and down the Rhone valley, via even more spectacular scenery, through Montreux and Genève, back to Paris for another overnight before getting the train back home in the afternoon. Overall, a far more civilised and relaxing method of travel than tin cans with wings. I travel the best way possible: on my own sailboat. That way I can take my home with me and still see the wonders of the world. I love road trips, especially with my son. My favorite was when we spent a month driving coast to coast when he was 12 and had a wonderful time (it was my 3rd cross-country trip, his first). We’ve also done two day drives to vacation with friends in various places. Of course, it’s more fun when you aren’t racing to drive as far as possible in 10 hours – being able to stop and see the sights (and sites) is great. And at every stop, the first thing we looked for was a book store. I traveled solo to New York, last month. As disgusting as the humidity was, and how crowded Manhattan was, I just loved being there. The fact that I was able to go wherever I wanted and do what I wanted was liberating. In fact, I walked everywhere. Also, it was the first time in years since I’ve been on a plane. No matter, I was happy to be in a new city by myself. It was actually no joke that a week in NY isn’t long enough to see everything, but I still made the best of it. I loved the Water Taxi Tour, including the Flatiron District. Well, I definitely want to go back. Perhaps next year. :) Several years ago a relative in the midwest (I’m in CA) had a stroke and wasn’t expected to survive. I made emergency plane reservations, rushed home, and packed a suitcase. My wife was nice enough to set out clothes for me so I didn’t have to think about it. Flew out that night, rented a car, drove to the farm. Next morning, go to get dressed, only 1 shirt. No underwear. Did I mention my relatives live on a farm in the middle of nowhere? Nearest place to buy clothes was a 30 minute drive away, I was waiting by the door when they opened. Turned out my wife was putting away laundry, and that’s what I grabbed thinking she’d laid out clothes for 4-5 days. I think the best place I’ve ever visited was Prague, Czech Republic. We spent the whole time in Old Town and it was glorious. I don’t mind the packing, the airport, or the waiting to take off. It’s all part of the fun of traveling for me. I don’t like the packing again before leaving, but hopefully, the next time I have to go somewhere I’ll have fewer things to bring. Have a great trip! If you travel often by air, Precheck is worth every penny. Still air travel can be pretty awful. It’s worse for business, because you are already tense about getting there and doing whatever. Sometimes one just has to roll with the blows. I follow Joe Brancatelli who tells travelers to plan as well as they can and have a Plan B and a Plan C and so on, so when things go south, you have a clue as to your next move. He’s a guy who travels for a living, so I always love his 2003 Christmas column It captures his philosophy about life on the road so very well. Unless you were walking, travel has always been about waiting. waiting for a fresh mule, waiting for the coach, waiting at the border, waiting for the river to go down, waiting for the train, waiting for the ship to crawl across the Atlantic. I think of jet travel like anesthesia. Surgeons can heal you in many ways at the cost of damaging you. With anesthetics, they can hurt you even harder and longer, but this lets them cure more complicated things. Jet travel is awful, bit it’s all awful for maybe 24 hours, usually much less. In exchange for the concentrated wretchedness, one can travel to amazing places in surprisingly little time. TSA Precheck and Clear are worth every penny. No matter how busy the security lines, I’m through in less than 60 seconds. And you don’t have to go through the unregulated nuditron machines, or strip off you clothes and disassemble your gear. It’s the secret hiding in plain (plane? Ha!) sight. I enjoy vacations, but I loathe traveling. LOATHE it. I’m a control freak, and I’m a bit (ok, more than a bit) obsessive about planning for every possible eventuality, and I can never shake the feeling that despite all the planning, lists, contingencies and fallbacks that I am going to forget or miss something crucial. I know it’s something that I do to myself, but I can’t seem to stop it. Given the choice between driving and flying, I vastly prefer driving (that control freak thing), though I hate to spend days on the road. I live for the day when teleportation is possible, though I am sure that the TSA will do their level best to make that as unpleasant as boarding an airplane. The best place I’ve ever traveled to is unquestionably London. My spouse and I spent a couple weeks there several years ago, on what will undoubtedly be our first, last and only trip overseas, and it was an incredible experience. Hellaciously expensive, and being cooped up in a flying sardine can for eight hours each way was refined torture, but our time in London will always be a major highlight in my adult life. I kept a detailed travel journal, and I still go back and read it occasionally as a way of reliving an amazing fourteen days. I wish you safe and fun travels, Ms. Scalzi, and I look forward to reading about your experiences. I am very much a homebody, so I only travel to: 1. Visit family 2. Go see a show that isn’t coming near me So traveling, aside from the normal parts that suck, just puts me very out of sorts. So when I go to shows it has to be something that I feel I would regret if I didn’t go to it. And that leads to a net positive experience, but it also means that there are very few bands I would travel to see more than once. I don’t mind driving, but one-day trips (each way) are usually the most that I like to take; I drive about 600 miles each way a couple of times a year to see some friends. I prefer that to flying because I can leave on my own schedule, take whatever I want (as long as it fits in the car), stop when I feel like it, and not have to worry about wearing the right shoes or belt or packing a bunch of stupid tiny bottles or whatever. Flying itself doesn’t bother me at all – I can sleep pretty much anywhere, I’m small enough that I fit in pretty much any airplane, and I don’t get airsick. Back before security theater, it wasn’t as big of a deal to fly, but there’s still the scheduling part and the airport-to-destination part, although I’m fortunate enough these days that when I do fly, I can afford to rent a fun car every now and then. Plus I think it’s a lot easier to get around most cities with airports now than it was 20-30 years ago – there seems to be much more of an expectation that visitors need big signs and such, plus there’s nothing like having updated maps everywhere you go. I do not miss the days of relying on good old Rand McNally! Like Hugo, I’ve got a plan for packing, so I don’t have to think/stress out about it. If it’s for some place or event that needs unusual/lots of stuff, like an SF con or camping, I have a checklist that I update after I return (eg. burned pants, buy a new pair). Otherwise, I pack for a week. If I’ve packed for a week, I’ve packed for a month. Add something dressy, just in case, or buy it there. Only 3 colours, at least one of which is a neutral. Some clothes (and all underwear) should be washable in a sink or shower. Unless you just have to have full size toiletries, and are willing to pay luggage charges for them (does your shampoo really cost over $50?), this should all fit in a carry on duffle. I’ve done a lot of traveling, starting with a month-long trip to Europe in 1991. I loved it all, but Prague and Barcelona were my favorites. Prague at the time was incredibly inexpensive. Things like subway tickets cost literally pennies, and you could get a whole meal for a dollar. Not that I did a lot of eating. We were there as an afterthought, and the food I tried didn’t taste good to me. We jammed Prague into our itinerary after deciding we didn’t like Frankfurt, and we only got one day to see the city, from 7 am to midnight. We slept on trains to get there and to leave. Signs on the trains were in three languages, and none of them was English. Did I mention Prague was inexpensive? I changed a $20 travelers check when I arrived, and I wasn’t able to spend it all. I have never been back to Prague. I don’t think I’d find the same city again. I would not be the same person. I like New York also. I visited once in the 1990s, and then several times after 2001. I saw the ghostly silhouettes of the fallen towers and the echoes of the demolition equipment plus the burned concrete smell of the debris are etched in my mind forever. I watched the Freedom Tower rise, but I haven’t been inside it. I usually make it a point to visit Marie’s Crisis whenever I’m in NYC. It’s a nightclub, so over-21 only I think. It’s literally underground, only a block away from the Stonewall Inn. People stand around a piano singing show tunes. Occasionally you’ll spot a minor celebrity. Check out YouTube for Darren Criss playing piano while Lea Salonga sings. They also do a duet of A Whole New World from Aladdin. Lea of course did the singing voice in the Disney movie. Enjoy Brooklyn, Athena! It’s a very vital and fun place. And, if you have a chance, get together with some friends and walk over the Brooklyn Bridge to Manhattan. You’ll never regret it; it’s not the prettiest bridge in the world (he says, as a resident of the S.F. Bay Area), but it has great character and history, and you should not miss it. (You can come back via the Roosevelt Island Tramway to Roosevelt Island and then the subway back to Brooklyn after you’ve explored Roosevelt Island.) Since dinosaur days when I started international air travel (in, um, the Kennedy Administration) as an airline family brat, much has changed but the delight of strange places and unfamiliar cultures will never lose its freshness, so I encourage your way of thinking. When you have a chance, go outside your comfort zone, learn some of someone else’s language, hang out, and learn to view the world through other people’s eyes. It’ll expand your world. Places that delight? It differs between persons, but for me my home town (Victoria, Hong Kong) is always special and full of surprises, as is Barcelona, Catalunya, Spain. Also, Stockholm, the prettiest city in Scandinavia (which pains me as a Norwegian-American to admit, but it’s true). Also, Valparaiso, Chile, a place of great charm, especially if you like to walk and don’t mind hills. How to not be bothered by long trips? Bring an e-book reader; that simple. It’s magical. How on God’s green earth did we do without them? A 14-hour flight to Wellington, enn-zed, becomes just a cozy snuggle with several novels interrupted by somewhat terrible coffee. A few more tips: 1. For heaven’s sake, go to places out of season (after making sure they aren’t shut down to a problematic degree). Usually this means the rainy season just before or just after summer, when you aren’t broiled by the sun but (much more important) aren’t stuck in crowds everywhere and paying peak hotel rates. There’s no reason to be deterred by the chance of rain. Bring a brolly, and enjoy how fantastic (e.g.) Venice looks and feels in November, entirely without being clogged with tourists. Likewise, given a choice between the rainy side of an island where the real people live, and the desert side with most of the tourist resorts, make a beeline for the rainy side where it’s green, pleasant, and uncrowded. So, Hilo and never Kailua-Kona, for example; Hana and never Kahului. 2. Also, get the heck out of the usual hotels. Stay in a Hilton, and it’s almost like not bothering to leave home at all. Try a small place with some actual local character. 3. Research, research, research. Before you go to a strange place, spend a few days online learning what’s really cool about it, and not just the Tourism Top Ten, either. Find the places, the foods, the features, the people that are actually distinctive as opposed to just well advertised, and make time for them. And more walking rather than less is usually a win. 4. But, be prepared to change your plans. Some of the very best travel experiences involve serendipity (after careful planning wasn’t enough). And, hey, personally, if I’m in Brooklyn and have a chance to walk across the Brooklyn Bridge yet again, and keep walking through midtown Manhattan to Second Avenue Deli (which used to be on Second Avenue, but was forced by rent increases to relocate to E. 33rd Street between 3rd Ave. and 4th Ave. Why? For the pastrami sandwiches. I don’t know whether you get decent pastrami sandwiches in Ohio, but if you’re any doubt, try one at a really good NYC deli first, and then decide what a good one is. I hate travel from the moment I close the door of my house, until the moment I dump my stuff in the hotel/house/appartment/boat i’m going to be staying at. Only to hate every moment after going away again. I like being places, even if most of my experiences comes from only seeing the eyes of people fully covered in white suits as I travel the cleanrooms of the world. There’s something kinda sad – that you travel 12 hours to china to just on arrival, spend the next 20 hours of 48 in a cleanroom. But the food in all those places is great! I really dislike flying as a guy that’s 6 feet 3, you’re just not always getting upgrades if you’re economical about your travelling, its always a struggle to even get a seat with enough breathing room to not feel like your knees are getting destroyed. You find yourself praying – to the person in front of you, please don’t lower your seat, please don’t lower your seat. Which never, ever works unless you’re an asshole, and you just block them. I wasn’t the biggest fan of new-york, although I really liked central park, and the museums i went to, I found the city itself kinda depressing – how manhattan is these giant perfectly upkeeped skyscrapers and everything around it is in a state of disrepair. My favourite vacation was in schotland, when me and a couple of friends hiked from coast to coast, along the canal. seeing the nature and the sights, and staying in quaint B&Bs with a variety of colourful hosts, and a bar that was in a houseboat. Or the time we went kayaking in sweden across the lakes for 10 days. There is one good thing about flying across oceans, that’s a lot of time to read a lot of fun books. I like being places, just don’t like the process of getting there so rarely do. I suspect this goes back to me suffering really badly from travel-sickness as a child, I had a 50-50 radius of about 10 miles which some medications could extend to a reasonable distance, but a lot of the various travel sickness ‘cures’ have tranquilising effects so it could be well after arrival (long day-trips were pointless) before I was in a state to enjoy myself. These days I’m fine on trains or driving myself, other people driving cars depends very much on their style, long distance coaches and aircraft I’ve not done enough journeys to tell. I am 53 and don’t fly very often. I still get the rush and excitement every time I fly. Getting jammed back into your seat by the crazy acceleration on the runway, the feeling of semi-weightlessness as the wheels leave the ground and having the view of a bird as the plane ascends is awesome! I’ve read that the food scene in Brooklyn is crazy delicious right now. Have a super fun vacation! I fly to Japan every other year so that’s always my most stressful trip. It was awful coming back this past time in May. I had to transfer through O’Hare, and let me tell you, I am NEVER doing that again. NEVER. Traveling is awesome, but I absolutely loathe airports. Even flying is not a problem for me. But to be trapped in the terminal where the food is overpriced is ridiculous. And my first flight after 9/11, about 13 years ago, the car rental place gave me the wrong day. The agent asked why I only wanted the car for half an hour. “Um… I was supposed to pick up today, not yesterday.” Damn you, Orbitz! I don’t miss CVG being a hub. Delta’s service in Cincinnati was horrible back then. Now I can pretty much fly anywhere more cheaply without having to drive for two hours. But the sooner I’m in my rental car or on the hotel shuttle, the better. I HATE airports. I’ve been to 49 of the 50 states, eastern and western Canada, parts of Mexico, the Caribbean, The Republic of Ireland and the UK, Europe, the Middle East, Australia and New Zealand. My favorite places, and the ones I keep going back to are Yosemite and Ireland. I travel every other week for my job, so I’ve learned a few things that make air travel a lot less stressful: 1. Schedule PLENTY of time for the actual traveling. If you need to make connections, make sure you’ve got at least 90 minutes between flights so that you don’t have to race from one gate to another. Arrive at the airport at least two hours early for domestic flights; three for international. Don’t plan to DO anything the same day you arrive. Yes, you will wind up spending a lot more time sitting around or walking around an airport with nothing to do but read, buy overpriced bad food or shop for stuff you don’t want or need, but it also means that when there’s an unexpectedly lengthy line or two, or a delay of some kind, you’re still going to make your flight. 2. When you travel frequently, Global Entry, TSA pre-check and CLEAR are worth every penny. So is the ability to wait in the airline’s frequent flier lounge vs. sitting with the general population. Hanging around with stressed-out strangers is rarely relaxing. 3. If you have fun reading material, the waiting time for travel is no big deal. Losing myself in a fun, well-written world makes my own journey far more pleasant. 4. When things don’t work out exactly according to plan, try to roll with it rather than fight against it. When you interact with other people, be NICE. Whatever it is that’s pissing you off and stressing you out is probably not their fault, and even when it is, hollering at them is not going to help you, them or anyone around you. Always take a moment to breathe, unclench and then find the humor in whatever situation you’re in. 5. Even if you make lists, chances are there will be something vital you forget to pack. Figure out how to do without it or replace it and move on with your trip: there’s nothing to be gained by beating yourself up for making a mistake. I’ve always liked traveling, and even the TSA hasn’t managed to wreck it for me. I will add one more vote for getting PreCheck, though. You wouldn’t think the first flight of the day out of a regional airport would be busy, but if I hadn’t had PreCheck I would have been standing in a very long line at 5 AM. I prefer driving if I’ve got a lot to take with me (say, it’s a convention trip). I did fly to a convention earlier this year, but 1) Southwest still lets you check two suitcases for free and 2) I didn’t have to change planes, which reduces the chance of one’s luggage taking the scenic route. Someday I’d like to take a train trip, but the only Amtrak trains that come through here do so late at night. If I’m driving 3 hours to get to a train station that has daytime arrivals/departures, and paying to park my car while I’m gone, it’s more cost-effective to just fly or drive instead. If you do any overseas traveling, then the State Department has Global Entry. It costs about the same amount as PreCheck but is run by folks who are much nicer than the TSA. And, as an added bonus, it includes PreCheck certification. So go with Global Entry! For me, the absolute worst part of traveling is dealing with airline seats. I upgrade when I can, but I’m not wealthy, so sometimes I just have to deal. I’m a large person and I have joint issues. A two-hour flight isn’t so bad, but overseas travel is torture. But if I don’t get in a plane, I can’t get overseas in any reasonable time, can I? So I suffer it as the price of going somewhere very different. Security lines bother me because they’re just time-wasting theater. I don’t typically have issues with them otherwise (the privilege of being white and middle-aged). Waiting to board doesn’t bother me either, because I don’t usually bring a carry-on other than a backpack, which can squish as needed. I just stay in a seat at the waiting area and board later. (Or if my arthritis is acting up, I have my cane and get priority boarding.) Sitting on the plane, eh, it’s all torture to me, so what’s another fifteen minutes of it. I love takeoff. LOVE IT. It’s like an amusement park ride. My favorite vacation…tough call between Ireland, Iceland, and Malta. I did not expect to love Malta as much as I did. The food in all three places was amazing! I had the same problem with the subway at first, but it turns out that Google Maps will give you subway directions in NYC and tell you which trains to take to get somewhere. It’s amazingly useful! It’s hard to pick a favorite trip, but Tahiti may still be it. Two weeks on three islands, no rental car, just relaxation and diving. Food was great and everyone we met was too. And I was traveling with friends, not family. To reduce travel stress, I have a trello board that I use for packing. I have cards for things like underwear, camera, chargers and columns like to pack, packed, not this trip. I also have columns for to do and done, for things like empty the trash and laundry. When I start packing, everything gets moved to the to pack and to do columns, respectively. Then as I pack things I move them to the packed column, or if I decide I don’t need it, I move it to the not this trip column. When there are no cards left in the to pack column, I know I have just about everything I’m likely to need. If I get to my destination, and realize I forgot something, I create a card for it right then so it will not be forgotten next time. I’ve been really happy with this system for both work and personal travel for the last couple of years. It has pretty much stopped the whole “OMG I hope I didn’t forget something” merry go round in my head the night before I’m supposed to leave. Some trips I do have to remind myself that the security crud we go through is jut a tiny bit of pain for a really good payoff. I’ve flown quite a few places now and as much as I dread the flight the destination usually makes it worth it. Also helps for longer flights that I splurge a bit for an aisle or emergency row seat for the extra leg room. Best trip I ever did was head over to Japan (10 hr flight) for 6 weeks. Had so much fun and got to try so many new foods and activities on top of exploring. Huzzah for backpacking and hostels! New York is pretty cool and the subway was easy to figure out once I associated Uptown with North and Downtown with South. Was just a matter of memorizing stops which is easy peasy after a few loops. Brooklyn and Broadway were my 2 favorite places to visit when I was in NYC. Driving, for cons and things has so many perks too! You see the coolest most random stuff in unexpected places or smaller cities/towns. Utah particularly comes to mind… one trip from Saskatchewan Canada to San Diego we come across a legit petting zoo in the middle of the desert… nothing for 3 hrs in either direction but this petting zoo/gas station. It had Zebras, Ostrich, Alpacas, Horses, Goats, Ducks, Buffalo…. so unexpected lol. The minute I get on an airplane my legs begin to ache. By the end of the flight, I can barely sit still they bother me so much. I’m sure the people sitting next to me wish they weren’t as I’m constantly rubbing my legs trying to get them to stop bothering me. Sometimes I try to find a space to stand in for a while, but there isn’t much space on an airplane for an extra human to hang around in. So, flying, not my favorite. But I do love seeing new places. Right now Scotland and Ireland are my favorite places. Galway is the best little city ever and Edinburgh is my second favorite city. But mostly, I love the small places in the middle of nowhere, and all the nowhere it takes to get there. If that makes sense. Traveling is *great.* I go as far as I can, whenever I can. We have 12 & 14-year-old kids, so were relatively grounded for a decade or so, but it’s been so fun to start traveling with them, too– their first trip out of the US was two weeks in Mexico to start immersion Spanish. Travel days are pretty much lost days, unless you luck into great food somewhere. Waiting is easier if you can pick up some kind of handwork– I always have a sock-in-progress in my purse, and if we’re traveling internationally I bring some kind of fiddly lacework knitting project in case there’s no power. Travel as much as you can now, and eat everything that looks interesting. I’ve never regretted either. Flying? I’m over it. I know that if I want to go certain places, flying is the only option. But there are other options for those of us who enjoy the journey as much (or more) than the destination. You sound like a “destination” person – if a teleporter existed, you’d do that. The actual traveling is an inconvenience and never over fast enough. (I wonder if you drive fast, not because of the thrill, but because you’re impatient to get where you’re going.) In recent years, I’ve slowed down. I’ve taken buses and trains so I could look out the window and see what lay BETWEEN the destinations. I’ve driven nearly a thousand miles to visit family rather than fly, because there were things along the way I wanted to see, and for the enjoyment of the drive. My bucket-list trip is a trip around the world on the surface of the planet: by train and by ship. Did you know container ships often have cabins for passengers? That you can travel across the ocean ON the ocean? A week at sea with nothing to do except chat with other passengers (if there are any), play games with the crew in the off hours, or read, or watch videos saved on a laptop. And look out the window at the sea. For some of us, THAT is traveling. Thinking about air travel makes me want to quote Douglas Adams in Long Dark Teatime of the Soul: “Airports are ugly.” (and great descriptors of why that you should read or listen to if you haven’t already). I absolutely detest flying. I don’t like the lines, the security theater, the overpriced food, uncomfortable seats, etc. If it is at all feasible, I will gladly drive all day to get somewhere (between travel time, wait time, delays, and lines it takes all day to fly somewhere that is only a 3 hour flight on the schedule anyway.) I would say that if you get the opportunity, you should travel by train. I’m partial to the train from San Diego to Santa Barbara because of the gorgeous ocean views along the way. Less freedom than a car, where you can control the temperature, music, stops, and food choices, but more leg room, you can get up and wander if you need to stretch, and still great views of places you’re passing. Lindy’s (the restaurant from Guys and Dolls) has a good breakfast and lunch and is decently priced. I also found the Russian Samovar to have decent food as well. Bring cash though as they’re not keen on plastic. And, of course the Met is always totally worthwhile. I stopped worrying about packing a few dozen trips back. I have a ‘go-bag’ of essentials (shampoo, toothbrush, makeup, etc.) that lives in a cabinet, ready to be tucked into my suitcase. Clothes are easy – multitaskers – every top must go with every bottom, so I have an array of outfits that fit easily into my rolling bag. Once I figured it out, it was easy. Best place I ever traveled; that’s a tough one. I love each of the places I have been for different reasons. I think as long as you travel with an open mind, you find things to love about pretty much everywhere. That said, it is a toss-up at the moment between Prague and Copenhagen. Such gorgeous cities, lovely people, history and culture and fun all packed into these wonderful packages. I have not been on a plane in 25 years. The last Amtrak I took was 10 years ago. And I don’t drive. I’ve had stretches of up to five years when I have not been outside my local tri-county area. Every vacation, I stay at home and use the time. Pure bliss. When it comes to traveling, I consider Wendell Urth to be my role model!. What I dislike most is the time between landing & disembarking. We tend to fly to Europe from the US West coast so by the time we land I’ve most likely been more or less on my feet for the better part of 24 hours. Having a Global Entry Card helps a lot with TSA and US customs/immigration hassles. It gets you TSA pre on domestic flights & some int’l flights and greatly expedites clearing customs/immigration upon one’s return. Kathryne, four entries above, reminds me of what a joy it has been to fork out for a “go bag” that just sits in my car. Needless duplication? No, worth every penny, for the peace of mind. The bag sits in an easy-carry eco box that includes an artist’s (from an art store) flat office tower-like bright spectrum desk lamp that I can even use in an easy chair: so many expensive hotel rooms in America don’t have a proper overhead light. The folding bag includes a plastic crock-kettle and all the makings, for those cheaper hotel rooms that lack a coffee machine, or lack enough coffee mate. No kindle, because even on an Atlantic flight from the Rocky Mountains I only read one book, and it’s fun to browse the native second hand bookstores. Oxfam runs one in London’s bloomsbury district. Dear Athena, I’d much rather drive than fly, but I’m self-employed like John. A multi-day drive to anywhere is going to eat up a week of time that I usually can’t afford. So, it’s flying. I will add my vote for TSA PreCheck. Ohmigod it’s soooo worth it. It’ll save you so much time and hassle and, in a pinch, can make the difference between making your flight or missing it. If you plan on traveling out of the country, I would spring for Global Entry; it’s not a lot more expensive. It’ll save you a lot of time dealing with customs, and it will also move you faster through many international airports — PreCheck is strictly a US thing. Here’s another thing — fly First Class. No I’m not kidding, and no I don’t think you’re made of money. (I know nothing about intrafamilial finances in ScalziLand and I’m not asking — none of my business.) With careful shopping, a first-class ticket will cost you about twice what a coach ticket will cost. For domestic travel. Fly overseas, and they’ll charge you a fortune for anything above economy. Add up how much you spend on air travel each year. It’s probably less than you think. That’s the premium you will pay for traveling First Class, and it makes a huge difference in the quality of the experience. Much more comfortable accommodations, much better service, priority clearance through TSA checkpoints at airports that don’t have PreCheck, and the airline personnel will be a lot more accommodating if you arrive a little late for check-in or your luggage is a bit overweight. A final tip … this one won’t cost you an arm and a leg. Or even an arm. It’ll make packing a whole lot less stressful. Those personal items you take on every single trip? Buy duplicates that live in your suitcase 24-7. A lightweight bathrobe and slippers, a good hairbrush, chargers for your never-without electronic devices, everyday medicines and toiletries, whatever’s on your always-travel list. Then you never have to think about that stuff again. – pax \ Ctein [ Please excuse any word-salad. Dragon Dictate in training! ] ====================================== — Ctein’s Online Gallery. — Digital Restorations. ====================================== I hate to fly, but all the best places require at least two flights. Long flights. My favorite place to travel is sub-Saharan Africa. I love the wildlife, the landscapes, and the mix of cultures. It’s great. I highly recommend it. Traveled a ton, visited many places, loved them all. Like you, I hate to pack. Cool thing though, my wife love to pack. So I avoid the whole thing by asking her to do it. I fight with the rental car companies, hotels and deal with the general travel hassles and she does all of the planning. Great division of labor. Works well for life also. Dave
https://whatever.scalzi.com/2018/07/25/the-love-hate-relationship-with-travel/
CC-MAIN-2019-30
refinedweb
7,348
80.51
tomcat the following links: i downloaded and installed taomcat server but my servlet TOMCAT TOMCAT When i am deploy the servlet class file in tomcat server i get the following errors pe Exception report description The server... in the Apache Tomcat/6.0.32 logs. Apache Tomcat/6.0.32 my servlet code How Run JSP in Apache TomCat Server? - JSP-Servlet How Run JSP in Apache TomCat Server? How to Run JSP in Apache Tomcat Server? I have getting Jasper Exception which says class not found i have...:// Thanks apache tomcat server - Java Server Faces Questions apache tomcat server i dont know how to install apache tomcat... procedure. Hi Friend, To install the tomcat server,please visit the following link: why we got the error like HTTP Status 500 - type Exception report description The server encountered an internal error () that prevented it from fulfilling this request. exception tomcat web server the Tomcat Server Tomcat is an open source web server developed by Apache Group. Apache Tomcat is the servlet container that is used in the official...Tomcat Web Server   Tomcat Configuration For Eclipse Server Tomcat Server? I am using Tomcat 6.0v Thanks In Advance Install tomcat... on the add button. 4)Now select Apache as a server type and expend and select...)Again select Apache and then tomcat 6.0 and clicks on the next button. 14 Download Tomcat to install tomcat etc. What is Apache Tomcat ? Apache Tomcat is a Web Server... Releases Apache Software Foundation release tomcat web server time to time.... This section will describe you about Apache Tomcat. This page will describe you Running and deploying Tomcat Server for servlet is like this Apache Software Foundation/Tomcat 5.0/webapps/ i created...Running and deploying Tomcat Server HI Somebody has given... directory Now i started Tomcat . Next i opened Browser and i typed Tomcat Manager How to Configure Tomcat Apache in Netbeans IDE How to Configure Tomcat Apache in Netbeans IDE Can any one tell me how to add tomcat server in Netbeans IDE? With its steps ?? Thnx Apache Tomcat Training Apache Tomcat Training Description of Apache Tomcat Server Tomcat is an open source web server developed by Apache Group. Apache Tomcat is the web container that is used Working with Tomcat Server 1) Installation and Configuration- Apache... and execute your servlet- To run the server Go to C:\apache tomcat... Working with Tomcat Server   Tomcat Server Tomcat Server Why my tomcat server installation stop at using:jvm c:\program files\java\jdk 1.6.0\bin\client\jvm.dll. Even though i trying to install several times. please help me.... Installing Tomcat Server an Introduction ; Apache Tomcat: Apache Tomcat server is one of the most popular open source... server provided by Apache Software Foundation. Tomcat adds tools of its... in XML format. Apache Tomcat is intended to be a collaboration of the best developers Introduction to Tomcat Server server developed by Apache Group. Apache Tomcat is the servlet container...Introduction to Tomcat Server  ... are developed by Sun under the Java Community Process. Web Servers like Apache Tomcat apache tomcat start error - Java Server Faces Questions apache tomcat start error Hi sir,While starting tomcat services i am... operating system ERROR:- Windows could not start the Apache Tomcat 6 on Local...; Please check port for tomcat Tomcat Web Server Tomcat Web Server Introduction to the Tomcat web server Tomcat is an open source web server developed by Apache Group. Apache Tomcat is the servlet Java Memory of Apache Tomcat - Java Beginners Java Memory of Apache Tomcat Dear All, Please help me to fetch the Java memory occupied by Apache tomcat server using Java Codes. I have three applications installed on Application server, if i start using all Introduction to the Tomcat web server Introduction to the Tomcat web server Tomcat is an open source web server developed by Apache Group. Apache Tomcat is the servlet container that is used in the official problem regarding tomcat server 6.0 problem regarding tomcat server 6.0 Jul 27, 2012 10:39:19 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performanc e in production environments installation - Java Beginners tomcat installation How to install the apache-tomact server on my..., To install the tomcat server,please visit the following link: Then set Web Server ecclipse_tomcat - JSP-Servlet runtime click on add button on the right side panel choose Apache Tomcat... have java also installed.. How can I configure Tomcat for ecclipse...For running a small applcation.. Procedure to configure Tomcat in eclipse Go tomcat server - Java Server Faces Questions tomcat server Hi, friends /* the given given below is the tomcat server error */ Jul 28, 2008 10:42:07 PM... org.apache.catalina.core.StandardEngine start INFO: Starting Servlet Engine: Apache change Books will learn how to integrate Tomcat with the Apache HTTP server (and the situations... alone. The Apache Tomcat Training The Apache Tomcat server... as a deployment server or integrating Tomcat as a plugin within the regular Apache Environment Setup - Java Beginners -server/tomcat/install-configure.shtml Thanks...Tomcat Environment Setup Kindly explain how to set path in tomcat.., i have install tomcat 6 version. Hi Friend, Set the following installation problem - JSP-Servlet :\apache-tomcat-6.0.16; 2) Put the servlet-api.jar into lib folder of apache tomcat...:// Thanks...Tomcat installation problem Hello I have installed Tomcat Tomcat 6. Tomcat 6. hi......I have problem like windows could not start the Apache Tomcat 6 on Local Computer. for more information ,review theSystem Event Log. If this is a non-Microsoft service,contact the service vendor, and refer server/any application server Tomcat server/any application server how the server understands request is coming from client and how can it give response within very short span of time Tomcat Tomcat.... - WebSevices ;Suggession: Restart tomcat server and then try again. Before that check...Tomcat.... Hi i am using tomcat5.0 & jdk1.5.The installation... with the name: classes (small cases only.) Restart your server and make connect jsp with tomcat - JSP-Servlet ://... in making connection between tomcat 6.0.18 and jsp pages.my system configuration... already set) ->tomcat 6.0.18 (c:/tomcat/tomcat6.0/) I have my site folder urgent-Exception in Tomcat - Java Beginners urgent-Exception in Tomcat I am using eclipse ee and tomcat server... Exception report description The server encountered... The full stack trace of the root cause is available in the Apache Tomcat/6.0.10 logs path setting for tomcat to java for Desktop PC - JDBC or configuration about the Tomcat Server in Java. Kindly visit them . We hope...:// TOMCAT INSTALLATION ERROR - Design concepts & design patterns TOMCAT INSTALLATION ERROR I HAD INSTALL APACHE TOMCAT 5.5...ALSO SET...:// Hope...:\apache-tomcat-5.5.28\common\lib\servlet-api.jar.. WHILE RUNNING Tomcat server - Servlet Interview Questions Tomcat server Hello, I am Executing the Servlet application at the time am getting the message like HTTP STSTUS 404 plz tell me wht's this problem and show me the solution to me Error 404 on localhost:8080 Tomcat Apache 6.0.32 with Elipse IDE and IE/Other Browsers Error 404 on localhost:8080 Tomcat Apache 6.0.32 with Elipse IDE and IE/Other... this: Several ports (8005, 8080, 8009) required by Tomcat v 6.0 Server at localhost are already in use. The server may be running in another procerss, or a system When i click on Monitor Tomcat, it shows ://localhost/ then i get the Apache tomcat page, but when i finally want to see my... folder of apache tomcat. 1)create a servlet. import java.io.*; import...;"); } } 2)Go to the webapps folder of your apache tomcat and create a web JSF using Tomcat 6.0 - Java Server Faces Questions JSF using Tomcat 6.0 Hai i have a problem during deployement time...: Starting Servlet Engine: Apache Tomcat/6.0.14 Mar 3, 2010 12:09:42 PM..., 2010 12:09:43 PM org.apache.catalina.startup.Catalina start INFO: Server startup Tomcat - Development process Tomcat connection pooling What is Tomcat connection pooling configuration? And how can i configure it? Hi,You can configure the Apache DBCP for connection pooling in tomcat.Please check tomcat - Java Beginners tomcat can any body help me for installing apache tomcat and running the servlet program Just go to the website in this website help mention regarding your problem tomcat - JSP-Interview Questions the tomcat, create a folder 'application' into C:\apache-tomcat-6.0.16... the tomcat, go to C:\apache-tomcat-6.0.16\bin and double click the startup.bat....tomcat how to run a program of jsp using tomcat server.please give Apache Tomcat6.0 Apache Tomcat6.0 Starting Tomcat process... Waiting for Tomcat... Starting of Tomcat failed. E:\Project\Medisoft\nbproject\build-impl.xml:590: Deployment error: Starting of Tomcat failed. See the server log for details. BUILD tomcat problem - JSP-Servlet tomcat problem Hi! Rose India Team, I am unable to install the tomcat server. It stops at this stage during installation .......c:\program files... found your problem.. Tomcat - Java Beginners :-jdk1.5_0_06-windows-i586-p 2:-apache-tomcat-5.5.15 please send... You just follow the Steps for jdk as well as tomcat 1)Run the exe file 2)see...:\Tomcat 4)Click Next Button 5)finally finish Thanks Rajanikant installation - Java Beginners :// installation i am unable to run tomcat6.0 , can you give me a step by step procedure to instal it , the error shown is :the specified Guide to download and install Tomcat 6 -) Configuring from toolbar Panel To Configure Apache Tomcat web server from the toolbar... fast. First of all learn the steps of 'How to download Apache Tomcat... and follow the steps according to your requirement to achieve Tomcat server Apache Axis2 - Apache Axis2 Tutorial . Apache Axis2 on Tomcat The Apache Tomcat server can be used to run the Axis2 engine and deploy the Web... on tomcat server. Apache Axis2 Hello World Example... file path is Tomcat-folder\conf\server.xml a tag is available Apache Server Running But project not deploying on server? Apache Server Running But project not deploying on server? May 27... based Apache Tomcat Native library which allows optimal performance...)\Apache Software Foundation\Tomcat 5.5\bin;.;C:\Windows\sys tem32;C:\Windows
http://www.roseindia.net/tutorialhelp/comment/86649
CC-MAIN-2013-48
refinedweb
1,729
59.4
Up to [cvs.NetBSD.org] / pkgsrc / math / libmatheval Request diff between arbitrary revisions Default branch: MAIN Revision 1.13 / (download) - annotate - [select for diffs], Wed Mar 9 08:25:13 2016 UTC (6 years, 5 months ago) by tnn Changes since 1.12: +1 -2 lines Diff to previous 1.12 (colored) USE_TOOLS+= flex, no need for flex/buildlink3.mk Revision 1.12 / (download) - annotate - [select for diffs], Tue Dec 15 23:27:17 2009 UTC (12 years, 7 months ago) by drochner.11: +1 -2 lines Diff to previous 1.11 (colored) don't propagate guile dependency, it is only used at build time Revision 1.11 / (download) - annotate - [select for diffs], Tue Dec 15 21:55:05 2009 UTC (12 years, 7 months ago) by joerg Branch: MAIN Changes since 1.10: +2 -2 lines Diff to previous 1.10 (colored) Recursive bump for libltdl Revision 1.10 / (download) - annotate - [select for diffs], Wed May 20 00:58:22 2009 UTC (13 years, 2 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2009Q3-base, pkgsrc-2009Q3, pkgsrc-2009Q2-base, pkgsrc-2009Q2 Changes since 1.9: +2 -2 lines Diff to previous 1.9 (colored) Recursive ABI depends update and PKGREVISION bump for readline-6.0 shlib major change. Reported by Robert Elz in PR 41345. Revision 1.9 / (download) - annotate - [select for diffs], Fri Mar 20 19:24:57 2009 UTC (13 years, 4 months ago) by joerg Branch: MAIN CVS Tags:], Sat Jul 8 23:10:59 2006 UTC (16 years, 1 month.7: +2 -2 lines Diff to previous 1.7 / (download) - annotate - [select for diffs], Sat Jul 8 22:39:28 2006 UTC (16 years, 1 month:26 2006 UTC (16 years, 4 months:22:20 2006 UTC (16 years, 4 months ago) by reed Branch: MAIN Changes since 1.4: +3 -3 lines Diff to previous 1.4 .4 / (download) - annotate - [select for diffs], Sun Feb 5 23:10:02 2006 UTC (16 years,], Fri Oct 15 14:50:07 2004 UTC (17 years, 9 months ago) by tv.2: +1 -11 lines Diff to previous 1.2 (colored) Update linkage to libltdl (via guile{,14}), which is now its own package. Unfortunately, guile{,14}/buildlink3.mk directly includes it, and I don't know which dependencies actually need libltdl, so it was a recursive bump. Hopefully this recursive inclusion can be ripped out of guile{,14}/buildlink3.mk at some point and bubble down to dependencies that actually use libltdl, avoiding this headache in the future.... Revision 1.2 / (download) - annotate - [select for diffs], Sun Oct 3 00:12:56 2004 UTC (17 years, 10 months ago) by tv Branch: MAIN Changes since 1.1: +2 -1 lines Diff to previous 1.1 .1.1.1 / (download) - annotate - [select for diffs] (vendor branch), Tue Aug 24 12:36:29 2004 UTC (17 years, 11 months ago) by drochner Branch: TNF CVS Tags: pkgsrc-base, pkgsrc-2004Q3-base, pkgsrc-2004Q3 Changes since 1.1: +0 -0 lines Diff to previous 1.1 (colored) import libmatheval-1.1.1, a Library for evaluating mathematical expressions Revision 1.1 / (download) - annotate - [select for diffs], Tue Aug 24 12:36:29 2004 UTC (17 years, 11.
http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/math/libmatheval/buildlink3.mk?sortby=log
CC-MAIN-2022-33
refinedweb
540
74.69
Casio PV-S660 Here you can find all about Casio PV-S660 like manual and other informations. For example: review. Casio PV-S660 manual (user guide) is ready to download for free. On the bottom of page users can write a review. If you own a Casio PV-S660 please write about it to help other people. [ Report abuse or wrong photo | Share your Casio PV-S660 photo ] Manual Preview of first few manual pages (at low quality). Check before download. Click to enlarge. Casio PV-S660 User reviews and opinions No opinions have been provided. Be the first and add a new opinion/review. Documents To view memo data.... 63 To display an item in the full-screen view... 64 Moving a Memo within a List Screen... 65 Renaming Memo Categories.... 65 Chapter 5 Expense Manager.. 66 Entering the Expense Manager Mode... 66 Inputting a New Transaction... 66 Recalling Expense Manager Data... 68 Calculating Periodic Totals... 69 Managing Payment and Expense Types... 70 To change a payment type or expense type name.. 70 Chapter 6 Currency Converter.. 71 Entering the Currency Converter Mode... 71 General Currency Conversion... 71 Performing a Conversion.... 71 Changing the Currency Name and Rate... 72 Displaying the Current General Rates.... 73 Euro Conversion... 73 Performing a Conversion.... Changing the Displayed National Currencies... Displaying the Current Euro Rates.... Changing the Currency Name and Rate... 75 75 Specifying the Rounding Method... 76 Chapter 7 Quick-Memo... 78 Entering the Quick-Memo Mode.. 78 Quick-Memo Categories... 78 To select a Quick-Memo category... 78 Using the Quick-Memo Drawing Tools.. 79 Creating a New Quick-Memo... 80 To input a new Quick-Memo... 80 To draw a line or rectangle.... 80 Recalling a Quick-Memo... 81 Screen Copy.... 82 To record a screen copy.... 82 Chapter 8 Pocket Sheet.. 83 Entering the Pocket Sheet Mode... 83 Pocket Sheet Basics.... 83 Creating a New Sheet from Scratch... Making a Cell the Active Cell... Selecting a Range of Cells.... Jumping to a Specific Cell in a Sheet... General Input Rules.... Cell References.... Relative Cell References... Absolute Cell References.... Mixed Cell References.... Using the On-screen Keyboards.... Inputting Mathematical Expressions... Inputting Text.... 89 91 Inputting Data Into a Cell... 86 Input Example.... 92 Example Data.... 92 Controlling the Appearance of a Cell... 93 Changing the Format Settings of a Cell... 93 Specifying Cell Border Lines... 96 Row and Column Operations... 97 Changing the Width of a Column... 97 Scroll Freezing Rows and Columns... 98 Inserting Rows.... 100 Inserting Columns.... 101 Deleting Rows and Columns... 101 Sheet Operations.... 102 Opening a Sheet.... Displaying the Input Screen... Saving a New Sheet.... Saving an Existing Sheet Under a New Name... Exiting a Sheet.... Renaming a Sheet.... Cutting and Copying Cell Data... Pasting Cell Data... Copying a Relative Cell Reference... Copying an Absolute or Mixed Cell Reference... Clearing Cell Data.... 105 Cut, Copy, Paste, Clear... 103 Searching for Data in a Sheet... 106 To search for data in a sheet... 106 Setting Sheet Calculation, Gridline, and Protect Options.. 107 Date and Size Information... 107 Displaying Date and Size Information... 107 Pocket Sheet Sync... 108 Computer System Requirements... 108 Pocket Sheet Errors... 108 Chapter 9 Secret Function.. 109 Creating a New Secret Memory Area.. 109 Using the Secret Memory Area... 110 To enter an existing secret memory area.. To exit the secret memory area... To change your password.... To transfer data from the open memory area to the secret memory area.. To transfer data from the secret memory area to the open memory area.. 111 Chapter 10 Pop Up Tools... 112 Displaying the Pop Up Tool Screen... 112 Using the Clock Screen... 112 To display the clock screen.... To make one of the clocks the main clock... To select a time zone city.... To switch between standard time and daylight saving time (DST).. To display the calculator... Calculator Keys.... To perform calculations... To perform constant calculations... To correct entries during calculations... About calculation errors.... To clear an error.... 118 Using the Calculator Screen... 114 Next Appointment Screen... 118 To display the next appointment screen... 118 Chapter 11 Data Communication.. 119 Using the Cable.... 119 To connect the cable to the PV Unit... 119 To disconnect the cable from the PV Unit... 120 Data Communications Between Two PV Units.. 121 To connect two PV Units.... 121 To send data from the host unit to the terminal unit.. 121 To receive data from the terminal unit on the host unit.. 123 Data Communications Between a PV Unit and a BN Unit.. 124 To connect a PV Unit to a BN Unit... 124 To send data from the PV Unit to the BN Unit.. 125 To receive data from the BN Unit on the PV Unit.. 127 Receiving Data From an SF/CSF/NX Series Unit.. 128 To connect a PV Unit and an SF/CSF/NX Series Unit.. 128 To make communication parameter settings... 129 To receive data from an SF/CSF/NX Series Unit... 129 Chapter 12 PV Applications.. 131 Obtaining PV Applications... 131 Installing a PV Application to your PV Unit.. 132 To download a PV Application to your PV Unit.. 132 Deleting PV Application Data... 133 Updating Your PV Unit Operating System.. 134 Chapter 13 Game... 135 Entering the Game Mode and Selecting a Game.. 135 Game-1.... 135 How to play.... 136 To move a card or stack of cards... 136 Game Levels.... 137 Game-2.... 137 How to play.... 137 Game Levels.... 138 Now you can maneuver around the Scheduler Mode to input and recall data. Inputting New Scheduler Data This section describes how to input Schedule, To Do, and Reminder data. Note that a Schedule item can be input as a single-date item (an appointment that starts and ends on the same day) or a multiple-date item (an appointment that spans more than one day). You can input a new multiple-date item with the New button or with the calendar screen. Chapter 2 To input a single-date Schedule item 1. While any Scheduler Mode data screen is on the display, tap New. 2. On the menu that appears, tap Schedule. 1 Data input tool bar 2 Date 3 Time bar 3. If you want to change the date of the appointment, tap the displayed date and then use the date keyboard that appears to make the changes you want. Tap NEXT to advance to the appointment time. 4. Use the time keyboard that appears to input the start time and end time if you want, and then tap NEXT to advance to the alarm time. 5. Use the time keyboard to input the Schedule alarm time if you want, and then tap NEXT to advance to description text input. 6. Use the text keyboard to type text that describes the item. 7. After the item is the way you want, tap Save to store it. In addition to a date, you must input description text or a start time. The PV Unit will refuse to store the item if it does not contain a date plus description text or a start time. To input a multiple-date Schedule item with the New button 1. While any Scheduler Mode data screen is on the display, tap New. 2. On the menu that appears, tap Multi-date item. If you drag the stylus across a range of dates on the 1-Month Calendar screen (page 38), a multiple-date item is created with the corresponding range of dates. 3. Tap the date you want to change and then input the year, month, and day. 4. Tap NEXT to advance to the description text input screen. 5. Input text that describes the item. 6. After the item is the way you want it, tap Save to store it. Note that you must input a start date, end date, and description text. The PV Unit will refuse to store the item if it does not contain a start date, end date, and description text. To input a To Do item 1. While any Scheduler Mode data screen is on the display, tap New. 2. On the menu that appears, tap To Do. Priority Data input tool bar Category Due date Date keyboard 3. Change the priority if you want. A new To Do item is automatically assigned a priority of B. Tap the priority you want to change to. 4. If you want to change the category, tap on current category setting. 5. On the tab that appears, tap the category you want to assign (Business, Personal, or Free), and then tap NEXT to advance to the due date. 6. Use the date keyboard that appears to input the due date if you want, and then tap NEXT to advance to the alarm date. The initial due date setting is the date that was selected (flashing) when you tapped New. To change the contents of a categorys input screen 1. Display the Contacts list of the category whose input screens contents you want to change. 2. Tap Menu Bar to display the menu bar, and then tap Option Prompt edit to display a list of entries (fields) that can be displayed in categorys input screen. Check boxes The above is the entry selection screen for the Business category. 3. Tap the check box next to an entry to toggle it between checked (display entry) and unchecked (do not display entry). You can check or uncheck any of the displayed entries shown on the screen. 4. After making the settings you want, tap Yes to save them and close the entry selection screen. Managing Untitled Categories and Free Entries You can use the procedures described here to change the names of each of the five Untitled categories, and the names of the 13 entries (fields) under each of the Untitled categories. Contacts Categories There are seven categories in the Contacts Mode: the two preset categories named Business and Personal, and five undefined categories named Untitled 1 through Untitled 5. The Business and Personal categories contain identical entries (fields). The difference between them is the sequence the fields appear on the display, and how data is sorted. The Untitled categories contain entries that can be configured by you. Contacts Field Names Business Name* Company* Phone (B) Fax (B) Address (B) E-mail Position Department Phone (H) Fax (H) Mobile Address (H) Note Personal Name* Phone (H) Fax (H) Mobile Address (H) E-mail Company Phone (B) Fax (B) Position Department Address (B) Note Untitled 1 - 5 Free 1* Free 2 Free 3 Free 4 Free 5 Free 6 Free 7 Free 8 Free 9 Free 10 Free 11 Free 12 Free 13 * Indicates entries on which data items are sorted. (B): Business (H): Home To edit Contacts Untitled category and Free entry names 1. In the Contacts Mode, display the list screen of the Untitled category you want to edit. 2. Tap Menu Bar to display the menu bar, and then tap Option Name edit. 3. On the screen that appears, tap the category name or one of the entry names, and make any changes you want. Repeat this step for as many names as you want to change. You can assign category names up to 14 characters long, and entry names up to 10 characters long. 4. After everything is the way you want, tap Save to store the data. Memo Currency Converter Pocket Sheet To record a screen copy 1. Display the data for which you want to record a screen copy. 2. Tap Menu Bar to display the menu bar, and then tap Option Screen copy. The PV Unit switches to the Quick-Memo Mode, with the new screen copy on the display. Make any additions or changes if you want, and then store the image by tapping Save. Pocket Sheet Pocket Sheet gives you access to basic spreadsheet capabilities while on the go. You can build your own spreadsheets from scratch, and even synchronize with Microsoft Excel data on your computer. Entering the Pocket Sheet Mode 1. Tap the Menu icon to display the Mode Menu, and then tap Pocket Sheet. 1 Sheet titles 2 Scroll bar This is the Pocket Sheet list screen, which appears first when you enter the Pocket Sheet Mode. Pocket Sheet Basics With Pocket Sheet, you can open up a blank sheet and build the sheet you want from scratch. The following sections describe how to open a new sheet, and how to perform some of the most basic sheet operations. Chapter 8 Pocket Sheet Creating a New Sheet from Scratch 1. Display the Pocket Sheet list screen. 2. Tap the New button. Row numbers Keyboard Input field Current cell Column names Cells Columns are named using the letters of the alphabet from A to Z, while rows are numbered sequentially from 1 to 999. The maximum capacity for a single sheet is about 32KB (about 1,900 cells when each cell contains one character, without any format settings or borderlines). The message Sheet is too big! appears on the display whenever the contents of a file exceeds this limit. If a sheet being received by the unit during a Pocket Sheet Sync operation exceeds the maximum limit (about 32KB), the excess cell data is automatically cut off. In this case, the sync operation ends normally, with no indication that the data was cut off. This means you should always check sheet contents visually after a sync operation is complete. A cell is referred to using its cell reference, which is made up of the cells column name and row number. This means that the cell reference of the upper left cell in the above sheet is A1, and the cell reference of the lower right cell is D5. The active cell is the one that is currently selected for input. The active cell is highlighted. The numeric keyboard appears first whenever you open a new sheet. Chapter 8 Pocket Sheet Making a Cell the Active Cell You can make a cell active by tapping it with the stylus so it becomes highlighted. You can also move the highlighting around the display using the scroll bar. Tapping the gray areas of the scroll bar scrolls the entire screen with the highlighted active cursor in the same relative position in the newly displayed screen. Examples The following are some examples of mathematical expressions you can input into sheet cells. Cell Contents =1+2-3 =(1+2)*(3+4) =(A1+B5)*2 Displayed Result Result of expression using contents of cells A1 and B5 =$A$1+B2 Contents of cell A1 + Contents of cell B2 =2^(Raises left value to power specified by right value.) =ABS(A1) Absolute value of value in A1 =AVERAGE(A1:D5) Average of values in cells A1 through D5 =COUNT(A1:D5) Number of values in cells A1 through D5 =COUNTA(A1:A7) Number of non blank cells in cells A1 through A7 =EVEN(3) 4 (Rounds up to the nearest even number.) =INT(8.9) 8 (Rounds down to the nearest integer.) =MAX(A1:D5) Greatest value of those in cells A1 through D5 =MIN(A1:D5) Least value of those in cells A1 through D5 =MOD(3,2) 1 (Integer result when left value is divided by right value.) =ODD(2) 3 (Rounds up to the nearest odd number.) =ROUND(2.15,1) 2.2 (Rounds left value to decimal places specified by right value.) =SQRT(A1*5) Square root of value in cell A1 multiplied by 5 =SUM(A1:D5) Sum of contents of cells A1 through D5 Chapter 8 Pocket Sheet Inputting Text Text (letters and numbers) can be input into the active cell using the onscreen text input keyboard. Input make up entirely of numbers (including decimal point) is treated as a numeric value. Inclusion of even a single non-numeric character (alpha-character or symbol) causes the input to be treated as text. Text is normally aligned in the cell flush left, while numbers are aligned flush right. If a text string is longer than the cell, the extra text is allowed to extend into the next cell to the right in the sheet display, as long as the neighboring cell does not contain any data. If it does, the extra characters are cut off in the sheet display. If an input value is longer than the cell that contains it, the contents of the cell are replaced by a string of # marks. This is to let you know that the cell contains a value, but the value cannot be displayed. If this happens, try making the cell wider (page 97). If the first character in a cell is an equals sign (=), the text is considered to be part of a mathematical expression. Input Example This section contains an example that illustrates a number of Pocket Sheet input techniques. Example Data All of the operations in this section are performed using the data shown below. Example: To input the function below into cell C5. =SUM(A2:B5)*C2 This calculates the total of the values from cell A2 through cell B5, and then multiplies it by the value in cell C2 (4). 1. Open a sheet and then tap cell C5. 2. Perform the following keys operations to input characters into the input field. 3. Next, use the stylus to drag from cell A2 to cell B5, so all the required cells become highlighted. 4. Remove the stylus from the screen to input the range of selected cells into the input field. 5. Tap in the input bar to the right of the close parenthesis to move the cursor there. Current width (number of screen dots) 3. Tap K to increase the value or L to decrease it. You can set the width value in the range of 3 to 130. 4. When the setting you want is displayed, tap Set to apply it. Scroll Freezing Rows and Columns Scroll freeze is a technique you can use to stop rows, and columns from scrolling when you tap the scroll bars on the screen. This is helpful when you want to leave row and column titles frozen on the screen as you scroll the data only. You can freeze rows only or columns, or you can freeze rows and columns at the same time. To freeze columns only Example: The following procedure describes how to freeze column A. 1. In the top row of the displayed sheet, tap cell in the column to the right of the column you want to freeze. To freeze column A, for example, you would tap cell B in the top row. To freeze both column A and column B, tap cell C. 2. Tap Menu Bar to display the menu bar, and then tap Option Freeze. Solid line indicates column to the left is frozen. To freeze a row only 1. In the far left column of the displayed sheet, tap the cell in the row below the row you want to freeze. To freeze row 1, for example, you would tap cell 2 in the far left column. To freeze both rows 1 and 2, tap cell 3. 2. Tap Menu Bar to display the menu bar, and then tap Option Freeze. Solid line indicates row above is frozen. To freeze a row and column at the same time 1. Tap the cell below the row and to the right of the column you want to freeze. To freeze column A and row 1, for example, you would tap cell B2. To unfreeze rows and columns If a row and/or column is frozen on the current sheet, tap Menu Bar to display the menu bar, and then tap Option Freeze to unfreeze them. Inserting Rows 1. Select the location in the sheet where you want to input the rows. The number of cells you select determines the number of rows that are inserted. Selecting C1 inserts a single row at row 1. Selecting C1 and C2 inserts two rows at rows 1 and 2. Existing rows will be shifted downwards to make room for the newly inserted rows. 2. Tap Menu Bar to display the menu bar, and then tap Option Insert. 3. On the dialog box that appears, tap Rows to perform the row insert operation in accordance with the cells you selected in step 1. Pocket Sheet Errors The message #ERR appears inside of a cell any time one of the following operations is attempted with the cell. Division by zero Any mathematical operation that produces a value that exceeds the calculation limit Any mathematical operation in which a cell references itself Deletion of a row or column that contains a cell referenced by the cell A copy operation that causes the referenced cell to be outside the sheet Any copy operation, or row or column insert operation that causes the length of a function to exceed 256 characters Mathematical error Adding a large number of mathematical expressions to a sheet for which Auto Calculation is turned off can cause the #ERR message to appear. Parentheses can be nested up to 10 times inside a single calculation. Referencing of other cells within the same sheet is limited to 256 levels per calculation. Important! Referencing a cell that contains a calculation that has not yet been performed may cause the referencing calculation to take a long time. Secret Function Your PV Unit lets you set up a secret memory area that keeps your data safe and secure under a password you specify. After you enter the secret memory area, you can use the Scheduler, Contacts, Memo, and Expense Manager modes to store data. Important! You can have only one secret memory area at any one time. All secret data for all modes is stored in the same secret memory area, regardless of what mode you were in when you created the secret memory area. Make sure you do not forget your password! There is no way to look up a password if you forget it. You will have to reset the PV Unit and clear all its memory contents in order to clear a forgotten password and create a new secret memory area. Creating a New Secret Memory Area Use the following procedure to create a new secret memory area. Note that this operation can be performed only if there is no secret memory area already in memory. 1. Tap the Menu icon to display the Mode Menu, and then tap Secret. 2. Use the text keyboard to type up to 12 characters for the password you want to use. 3. Tap Set to register your password and create a secret memory area. 4. In response to the confirmation message that appears, tap Yes. Registering a password creates and immediately enters the secret memory icon. area, which is indicated by the Using the Secret Memory Area The following describes the operations you can perform after you create a secret memory area. To enter an existing secret memory area 1. 2. Tap the Menu icon to display the Mode Menu, and then tap Secret. Use the text keyboard to type the correct password, and then tap Set. If the password is correct, the PV Unit enters the secret memory area. Once you enter the secret memory area, you can move between it and the open (non-secret) memory area without having to input the password again until you turn power off and then back on again. To correct entries during calculations If you enter a wrong value, tap C to clear the value and then input the correct one. If you tap the wrong arithmetic key (+, , #, $), simply tap the correct arithmetic key before inputting anything else. About calculation errors An error indicator appears on the display and further calculation becomes impossible whenever an error occurs. Error indicator Chapter 10 Pop Up Tools Any of the following conditions produces an error. Whenever the number of digits in the mantissa of an intermediate or final result exceeds 12 Whenever the number of digits in the mantissa of a value in calculator memory exceeds 12 digits. In this case, the PV Unit automatically retains the last value stored that did not exceed 12 digits. Division by zero Attempting to calculate the square root of a negative value To clear an error Tap C to clear an error and continue with the same calculation from the point immediately before the error occurred. To clear the entire calculation and start again, tap AC. Next Appointment Screen This screen shows a display of the current month, along with details about the next appointment scheduled from the current time and date, as kept by the main clock (if any). To display the next appointment screen 1 Current month 2 Date for which appointment is scheduled 3 Next appointment details 4 Next appointment The current month is determined in accordance with the time and date as kept by the main clock. The next appointment details area shows the next Schedule item or Reminder item that includes time data. It does not show any Schedule or Reminder items that do not include time data. The next appointment details area is blank when there is no future appointment scheduled. You can close the next appointment screen by tapping. Data Communication Data communications capabilities let you transfer data between two CASIO PV Units, between a PV Unit and a BN-10/BN-20 Unit, or between a PV Unit and a BN-10A/BN-20A/BN-40A Unit. You can also receive data from a CASIO SF, CSF, or NX Series Unit, and communicate with a personal computer using PC sync for Windows. See the manual that comes with PC sync for Windows for details on connecting to a computer and setting up for communication. Data Communications Between a PV Unit and a BN Unit This section describes how to set up and communicate between a PV Unit and a BN Unit (BN-10/BN-20 or BN-10A/BN-20A/BN-40A). You must purchase a separately available SB-90 in order to connect a PV Unit to a BN Unit. To connect a PV Unit to a BN Unit 1. Make sure that the power of both units is turned off. 2. Open the cover of the Mini Cradle port of the BN Unit, and connect its Mini Cradle to the port. 3. Plug the cable that comes with the PV Unit into its cable connector. 4. Use an optional SB-90 9-9 pin connector to connect the PV Unit cable to the BN Unit Mini Cradle. Host unit (PV Unit) Terminal unit (BN Unit) Mini Cradle START button SB-90 9-9 pin connector All data communication settings must be made on the PV Unit, which is the host unit. The BN Unit is the terminal unit. To send data from the PV Unit to the BN Unit 1. After connecting the two units, turn on the PV Unit. BN Unit power should still be off at this time. 2. Display the list view in a mode whose data can be sent with this setup. This configuration supports transfer of Contacts (Business, Personal), Memo, Schedule, To Do, and Reminder data. Calendar and Expense Manager data cannot be transferred. Contacts Untitled 1-5 data is transferred as Personal data. Memo Untitled 1-5 data is transferred as Memo data (no category). 3. Tap Menu Bar to display the menu bar, and then tap System Data communication. 4. On the screen that appears, tap the button next to BUSINESS NAVIGATOR to specify the data communication configuration. 5. Tap the button next to Send. 6. Tap Set. 7. Tap the check boxes to specify the data you want to send (checked) and the data you do not want to send (unchecked). 8. After everything is the way you want it, tap Set. 9. Turn on the power of the BN Unit and then press the START button on its cradle to start the data transfer operation. The following shows the relationship between data when sent from the PV Unit to a BN Unit. Mode Contacts PV Unit Untitled 1-5 BN Unit PERSONAL Check Contacts (1-5) as the data type to send this data. Not transferred Not transferred Not transferred Due date MEMO Check Memo (1-5) as the data type to send this data. 1. Tap Menu Bar at the beneath of the PV Unit screen to display the menu bar. 2. Tap the name of the menu that contains the command you want to execute. 3. Tap the command you want to execute, or use Action control up/down scrolling to move the highlighting to the command you want, and then click the Action control to execute the command. Data Input and Editing Use the procedures in this section to input and edit data. These procedures apply for all input and editing screens. Chapter 14 Moving Between Entries (Fields) When inputting and editing data, you can move between entries (fields) either by tapping on the entry you want with the stylus, or by tapping the on-screen NEXT button to advance to the next sequential entry. Note that the NEXT button may not appear on some input or editing screen. On-screen Keyboards This section describes the keyboards that appear when data input is required. Note To close a keyboard screen without registering the data you input with it, tap Esc. Text Keyboard Description Deletes the character at the current cursor location. Shifts letter keys between upper-case and lower-case for the input of one character only. Shifts to the Code Keyboard. Shift-locks letter keys between upper-case and lower-case. Shifts to the Symbol Keyboard. Inputs a carriage return (newline) operation. Advances to the next entry (field). Symbol Keyboard Description Displays other symbols. Returns to the Text Keyboard. Code Keyboard Date Keyboard Specify a date by tapping it in the calendar, or by tapping the number keys. Key Description Scrolls the month shown on the input screen. Jumps to the month that contains todays date as kept by the main clock. Moves the input point between the month, day, and year. Deletes the character at the current cursor location. Advances to the next field. Calculator Keyboard See Using the Calculator Screen on page 114 for details on mathematical operations. Deleting Data The following describes the general procedure for deleting data. 1. Enter the mode that contains the data you want to delete. 2. If you want to delete a particular data item, select the item. 3. Tap Menu Bar to display the menu bar, and then tap Edit Delete to display the data delete screen. Note that the contents of the data delete screen differ from mode to mode. 4. On the data delete screen, tap the delete operation you want to perform. See the Delete Operations Table below for details on available delete operations in each mode. Some modes allow delete operation that delete data within a range of dates. Selecting such an option displays a screen for input of a start date and end date. Specify the dates you want and then tap the Exe button before advancing to the next step. 5. On the confirmation message that appears, tap Yes to perform the delete operation you selected or No to close the dialog box without doing anything. Delete Operations Table Delete Operation Single data item Schedule data items Done data items To Do data items Reminder data items Specified data items Deletes Data item that is selected when Edit Delete is tapped All Schedule data All done To Do data items All To Do data All Reminder data All Scheduler Mode data up to a specific date. Tapping this option displays a screen that you must use to specify the date up to which you want to delete Scheduler Mode data. All Scheduler data All data items in the mode you are in when you tap Edit Delete All data items in the selected category when Edit Delete is tapped All Scheduler data items All data items Category data items Searching for Data You can use either initial character search or all search to look for specific data in the Scheduler (Schedule, To Do, Reminder), Contacts, and Memo Modes. Note that both search operations check the data only in specific entries (fields) of each data item. The following table shows which entries (fields) are checked in each mode for each type of search. Mode Schedule To Do Reminder Contacts - Personal Contacts - Business Contacts - Untitled Contacts - All Memo Fields Checked Initial Character Search All Search Description Description Description Name Company Free 1 Name (Free 1) Memo contents Description Description Description All All All All Memo contents To perform memory management 1. Tap Menu Bar to display the menu bar, and then tap System Memory management. 2. In response to the message that appears, tap Yes to start memory management or No to close the dialog box without doing anything. The message shown below appears after you tap Yes to start memory management. You can tap Esc at any time to interrupt the memory management procedure. Technical Reference This section contains technical information about the PV Unit. Date Formats The following describes the date formats that can be set for the system (page 159). Format M/D/Y D/M/Y Y/M/D Description Month/Day/Year. Example: Jan/31/2002 Day/Month/Year. Example: 31/Jan/2002 Year/Month/Day. Example: 2002/1/31 Time Formats The following describes the time formats that can be set for the system (page 159). Format 12-hour 24-hour Description Represents time in two blocks, from midnight to 11:59am, and from noon to 11:59pm. Represents time as a single block, from 0:00 to 23:59. This format is often referred to as military time. Chapter 16 Technical Reference Tool Bars The PV Unit uses standard tool bars for data input and display. The following shows typical examples of these toolbars, and describes the items that can appear in each. Data Input Tool Bar Mode icon Button Mode icon Description Indicates the mode you are currently in. Clears all characters in the entry (field) where the cursor is located. In the Contacts Mode, pressing this button clears the data from all the input fields for the data item (record) you are inputting. Pastes the current date and time as being kept by the main clock at the current cursor location. Displays a calculator. Advances to the next screen. Returns to the previous screen. Saves input data and closes the input screen. In the Quick-Memo Mode, tapping this button changes to the list view. Displays the pop up tool screen. The above table shows all the buttons that can possibly appear in a data input tool bar. Depending on mode and other factors, some of the tools shown above may not be included in a data input tool bar. Data Display Tool Bar Description Indicates the mode you are currently in. Displays a menu of other views that can be used to display data. In the Scheduler and Expense Manager modes, jumps to todays date as kept by the PV Units built-in clock. Advances to the next item. Returns to the previous item. Displays the new data input screen. Returns to the list screen from a Contacts, Memo, Expense Manager, and Quick-Memo mode data screen. Changes to the data editing screen for the current data item. Displays the pop up tool screen. Review IC-706mkiig 1604-VLZ3 SGH-X680 VWM-950 Electramac 235 GP-1650WF NN-T687SA FT2500 Mana 850 Fishfinder 250C CH1HR-2ABP RD-6105 PRO ESC Stylus D92 MN-740 GPS 2L SA-8800 Program RPD555 CP510 Sportback CFC544M2 A1100 IS Sentra-1999 Explorer HO-FCS-51 XS350-XS250 Scales AEG-electrolux Z55 Control RC5200 B193W Rule Book BH-105 21FE3RGE-TY LN32R71BD ESC 340 VGN-Z31xn B MP-FUB31 Wolfenstein SD-200 Cuisinart GR-4 M-512G 26PF3320-10 Gpsmap 2106 Confidence 7463 E-100 RS 6-30 MM Xe5V 4201 Siemens M50 NVE-K200 Streetfighter S 27907 LE19B450c4W HBH-DS980 BCO70 HVR-HD1000E Dista T500 R-363 Pinguino L30 Mustang-1998 EL-1750V 42PX3RVA Andreas DS-10 DSC-T5 FZS600-2002 2243NW Korg M3 AM1450 Series 07-THE Show CQ-DFX751N PPD01 SA-67 Philips 755 MC-85 FT-900 Rcs-77h Olympus E500 MT880 L1530TM KX-TES824 Avxl 109 MX-600 M-512 SGH-E310 IC-W2a-E Kdsh1000E-KD-sh1000 U5-111 Defender D845gerg2 DES-3010G MV-MV830I El52250 Digimax A7 DVD-1920 SPY WEB Nokia N82
http://www.ps2netdrivers.net/manual/casio.pv-s660/
crawl-003
refinedweb
6,115
74.59
The Problem Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s = "a" Output: "a" Example 4: Input: s = "ac" Output: "a" Constraints: 1 <= s.length <= 1000 sconsist of only digits and English letters (lower-case and/or upper-case) Tests import pytest from .Day19_LongestPalindromicSubstring import Solution s = Solution() @pytest.mark.parametrize( "string,expected", [("babad", "bab"), ("cbbd", "bb"), ("a", "a"), ("ac", "a"), ("bb", "bb")], ) def test_longest_palindrome(string, expected): assert s.longestPalindrome(string) == expected Solution class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) # If we have a string with all single letters this will actually be the answer ans = s[0] for i in range(n): # We need to scan i and i+1 to account for palindromes with multiple letters from the middle e.g. bb or abba dist = max(self.scan(s, n, i, i), self.scan(s, n, i, i + 1)) # If we discovered a palindrome longer than the current answer if dist > len(ans): # set our answer to a substring using dist to calculate the appropriate indices ans = s[i - (dist - 1) // 2 : (i + dist // 2) + 1] return ans def scan(self, s: str, n: int, l: int, r: int) -> int: while l >= 0 and r < n and s[l] == s[r]: l -= 1 r += 1 return r - l - 1 Analysis Commentary Hopefully the comments in the code explain the solution well enough. I felt there were 2 ways to possibly do it. One is to check palindromes outside in. The other is inside out. Inside out was more intuitive to me. It was also easier to code and seems to perform well. One bit that caught me for a while which might be worth talking about. dist = max(self.scan(s, n, i, i), self.scan(s, n, i, i + 1)) Initially I had dist = self.scan(s, n, i, i). I struggled for a while trying to figure out why it worked in some cases and not in others. I turned out to fail when there were 2 letters together in the middle of a palindrome. For example, take 'bb'. Calling scan('bb', 2, 0, 0). Let's replace the variables with the values to see what it looks like: while 0 >= 0 and 0 < 2 and 'b' == 'b': 0 -= 1 0 += 1 return 1 - (-1) - 1 # The result is 1 We get 1 back but obviously it should be 2 since 'bb' is a palindrome. If we push the right pointer up 1 we can fix that. Calling scan('bb', 2, 0, 1). while 0 >= 0 and 1 < 2 and 'b' == 'b': 0 -= 1 1 += 1 return 2 - (-1) - 1 # The result is 2 (minus + a minus is a plus) Given those 2 example for 'bb', we are looking at max(1, 2) which gives us 2 and is correct in this case. Why not always just call scan(s, n, i, i + 1)? That won't work for the case where letters are 1 letter in the middle of matching letters like aba. Discussion (0)
https://dev.to/ruarfff/day-19-longest-palindromic-substring-1ci9
CC-MAIN-2022-33
refinedweb
531
71.14
prompt% javac Hello.javaThe compiler produces files with the extension .class, which is the object code for each of the classes defined within the file. If you've written an application, you can run it using java; as in: prompt% java Hello Hello World!for the classic first program. If you've written an applet to be run through a browser, you can run it using a viewer, appletviewer as in: prompt% appletviewer Hello.htmlwhich will bring up a separate window. // standard first program // runs via terminal i/o class Hello { public static void main (String[] args) { System.out.println("Hello World!"); } } // standard first program // run as an applet import java.applet.Applet; import java.awt.*; public class HelloWorld extends Applet { public void paint (Graphics g) { g.drawString("Hello World!", 25, 25); } }In this case, we need to inherit the Applet class for our class definition. Additionally, we overwrite a method from the class, paint, to print what we want. We also need the companion html file, as shown in your notes to define the size of the window to open and designates the java code to be run within it.
http://www.cs.colostate.edu/helpdocs/JavaHowe.html
crawl-001
refinedweb
191
67.15
<?xml version="1.0" encoding="UTF-8"?> <Test label="test" name="test" xmlns:xsi="" xmlns:aa="" xmlns="" xsi: [Updated on: Mon, 29 August 2011 01:44] Report message to a moderator Are you getting any other messages about that file? As it is, it's invalid because there's no end tag for the Test start tag. That could cause the XML Validator to not be able to finish parsing (it's more strict about that than the editor) and think it never saw your attributes. Hi Marco, the syntax of your schemaLocation attribute is invalid. It should map a "xmlns" value to a URL, e.g. xsi:schemaLocation="" This would map the namespace "aa" to a specific location. Hope this helps
http://www.eclipse.org/forums/index.php/t/237289/
CC-MAIN-2014-15
refinedweb
122
72.76
mongooplog-alt 0.1.1-dev Improved alternative to official mongooplog utility. ============== About ----- **mongooplog-alt** exclude one or more namespaces (i.e. dbs or collections) from being synced. * works on mongodb 1.8.x, 2.0.x, and 2.2.x. Official utility supports 2.2.x only. * at the time of writing (2.2.0), official ``mongooplog`` suffers from bug that limits its usage with replica sets .. _official mongooplog utility: Installation ------------ Using pip (preferred):: pip install --upgrade mongooplog-alt Using easy_install:: easy_install -U mongooplog-alt Command-line options -------------------- Options common to original ``mongooplog``: .. option:: --host <hostname><:port>, -h Hostname of the mongod server to which oplog operations are going to be applied. Default is "localhost" .. option:: --port <number> Port of the mongod server to which oplog operations are going to be applied, if not specified in ``--host``. Default is 27017. .. option:: --seconds <number> Number of seconds of latest operations to pull from the remote host. Default is 86400, or 24 hours. Options specific to ``mongooplog-alt``: .. option:: --follow, -f Wait for new data in oplog. Makes the utility polling oplog forever (until interrupted). New data is going to be applied immideately with at most one second delay. .. option:: --exclude, -x List of space separated namespaces which should be ignored. Can be in form of ``dname`` or ``dbname.collection``. Usage ----- Consider the following sample usage:: mongooplog-alt --from prod.example.com:28000 --host. - Downloads (All Versions): - 18 downloads in the last day - 137 downloads in the last week - 567 downloads in the last month - Author: Aleksey Sivokon - Keywords: mongodb,mongo,oplog,mongooplog - License: - Platform: any - Categories - Package Index Owner: Aleksey.Sivokon - DOAP record: mongooplog-alt-0.1.1-dev.xml
https://pypi.python.org/pypi/mongooplog-alt/0.1.1-dev
CC-MAIN-2015-27
refinedweb
280
52.66
Hi, I am making a simple game which involves moving a character around the screen. In my main class I have declared a member class which extends Canvas as follows: In my main class constructor I then create an instance of myCanvas as follows:In my main class constructor I then create an instance of myCanvas as follows:Code:public class myCanvas extends Canvas { public void paint (Graphics g) { // Paint stuff } // end paint method } // end member class myCanvas keyCanvas = new myCanvas(); This works fine and I can issue the command keyCanvas.repaint(); to repaint the screen. My question is this.. Is it possible to access my keyCanvas device from a subclass? For example I have created a subclass called food, which extends Thread. When this thread is started it generates a random number. When this random number is a certain value I would like to paint a food sprite to the main display for the games hero to collect! Is it possible to access my keyCanvas directly from the food class? Or would it be better to create a method in my food class which returns the random value to the main class and then have my main class draw the food sprite when the required random number is received? Thanks in advance for any help, Phil
http://developer.nokia.com/community/discussion/showthread.php/199012-Accessing-Canvas-Class-from-Subclass
CC-MAIN-2014-35
refinedweb
217
68.7
This article demonstrates how to download the contents of most HTML tables to a csv file. To accomplish this, we use a simple index.html page that utilizes jQuery with the jQuery.post method to request data from the Northwind source tables. An IFrame is added to the index.html page using jQuery.append(). The IFrame src is SaveCSV.aspx plus a query string containing the FileName of the downloaded output file to produce. SaveCSV.aspx.cs contains all of the server-side code that does the Response.Write to produce the data that your browser will handle as content type "text/csv". Another header tag "Content-Disposition" is added to the Response data to tell your browser that this text coming back is an "attachment" that should be download to a file. FileName Response.Write "text/csv". "Content-Disposition" My main inspiration for this article comes from Chris Pels' asp.net video that can be found here: [How Do I:] Export Data to a Comma Delimited (CSV) The difference from Pels' video is that I dislike using ASP.NET grid view controls and wanted to explore ways to enable downloading data from regular html files using AJAX technology. I work on GIS-based map-viewer pages that derive data from many sources. Since the presentation is generally done in html tables using AJAX to collect the data from various web services, the easiest way to add an option for clients to save the data is by adding an anchor tag on a table that is already rendered. I also want to avoid post-backs of the map viewer page because it can be slow to render the map images. The sweet spot of the code for this article is the jQuery map method that maps the table contents to JSON objects. I found good instructions on how to use the map method here: jQuery map map Use jQuery to extract data from HTML lists and tables by Dave Ward The project is set up as a "Web application" project type. I'm a desktop developer too, and I hate the "Web site" project type. I find it very confusing and hard to manage. The "Web application" project is the right way to manage your projects. The Web.config file contains the path to NWind1.mdb under App_Data. If you copy the project source to "C:\inetpub\wwwroot\TableViewer", you will not have to do anything to the connectionStrings setting. Otherwise, change the path to where you copied the project. "C:\inetpub\wwwroot\TableViewer" The project is set up for .NET 3.5 in Windows 7. You should be able to get it to run on older versions if you create a new Web-application project and manually add the source files. Two required references for this project that are not added by default are:System.Configuration - for ConfigurationManager.ConnectionStrings in SelectionHandler.ashx.csSystem.Web.Extensions - for System.Web.Script.Serialization in SaveCSV.aspx.cs System.Configuration ConfigurationManager.ConnectionStrings System.Web.Extensions System.Web.Script.Serialization The web application starts with selecting a table to view. SelectionHandler.ashx.cs is used to get the data from the sample database and Response.Write it back to the client. Then jQuery methods are used to build html tables with the AJAX result. Most people use "$" in place of "jQuery", but I prefer to use "jQuery" spelled out for readability. Javascript is already full of enough special symbols for me. Response.Write I'm not going into detail about the first step here because the article is really about the second phase which involves adding the IFrame link to the table header in order to be able to save the contents of the table to a file. The first part is really just part of my test driver for demonstration. I may write another article about this if there is enough interest. The special part about building the result table is shown here: var jsonResult = jQuery.parseJSON(result); var cols = jsonResult.Columns; var tableName = jQuery("#TableDD option:selected").text(); var queryStr = "FileName=csvFile.csv"; jQuery("#NwindTable thead").append('<tr><th class="header1" colspan="' + cols.length + '"><div>' + tableName + '<iframe id="PostFrame" src="SaveCSV.aspx?' + queryStr '" /></div></th></tr>'); Specifically, this IFrame is appended to the first header row in the table: '<iframe id="PostFrame" src="SaveCSV.aspx?'+ queryStr + '" />... The PostFrame id is css styled with float: right; width: 100px so that it will stay on the right of the table header row. PostFrame id float: right; width: 100px As soon as the IFrame src is added to the html page, the server-side-cs code is executed to handle the initial Page_Load event. The "onclick" attribute is added to the lnkExport asp:LinkButton and is set to run the Javascript function DownloadTable() which is located in the index.html page. So, because the asp:LinkButton has a runat="server" attribute, the javascript function will be excuted on the client when the control is clicked, and then the whole SaveCSV.aspx page will post back to be handled in the normal asp.net server-side processing. Page_Load "onclick" lnkExport asp:LinkButton DownloadTable() runat="server" The DownloadTable() Javascript function is designed to be a reusable function that should be generic enough to use with most any html table to extract data. jQuery has a map method that does a nice job of mapping the contents of the thead/tbody rows to JSON objects. See the link referenced in the Background section above for an article about how the map method works. thead/tbody Here is the code that maps the table data rows to the Rows object: Rows //assemble comma separated rows in a JSON map var Rows = jQuery("#NwindTable tbody tr").map(function() { var cells = ""; jQuery(this).find('td').each(function() { var celValue = jQuery(this).text(); if (cells.length > 0) { cells += ',' + celValue.replace(/,/g, ';'); } else { cells += celValue.replace(/,/g, ';'); } }); return { row: cells }; }).get(); The code here examines each td cell for a row (tr) and extracts the text.Then the commas are replaced within the text string with ';' and all the values for the row are appended to the cells var with commas between each value. Finally cells is added as a row object to the Rows JSON object. tr ';' cells var cells row Rows The Columns object is populated in a similar manner and supports multiple thead rows. Since none of my column names contain commas, I don't need the Javascript replace method for the th cells. Columns thead th The final bit of Javascript code combines Columns and Rows into the tableCSV object. Then the hidden <input> tag with id="TableData" that is located in the src page (SaveCSV.aspx) of the IFrame (labeled with id="PostFrame" in the index.html page) gets the value of the JSON.stringify()version of the tableCSV object. tableCSV <input> id="TableData" id="PostFrame" JSON.stringify() Here are the two lines to do all this: var tableCSV = { "Columns": Columns, "Rows": Rows }; //Save data to Iframe page SaveCSV.aspx before postback to page is done. //The runat='server' in asp:LinkButton does the postback needed for download jQuery("#PostFrame").contents().find("#TableData")[0].value = JSON.stringify(tableCSV); The client-side rendering and Javascript has finished so the last thing that happens at the client is the asp.net postback of the SaveSCV.aspx page. The sData is extracted from the TableData form object. Then ExportCSV method is called to send the csv data back to the client browser with a header that tells the browser to save or open the data in an external application instead of displaying the data in the browser. sData TableData ExportCSV Note that the "FileName" property was saved on the initial page load in a Page.Session object. Take a look at the code: "FileName" Page.Session protected void Page_Load(object sender, EventArgs e) { Session["_bExportCSVCalled"] = "false"; if (!IsPostBack) { lnkExport.Attributes.Add( "onclick", "window.top.DownloadTable();"); Session["_FileName"] = Context.Request.QueryString["FileName"]; } else { string sData = Context.Request.Form["TableData"]; if (String.IsNullOrEmpty(sData)) { return; } ExportCSV(sData); } } To turn the string data back into a deserialized object, the JavaScriptSerializer Deserialize method is utilized. Here is the code snippet from ExportCSV: JavaScriptSerializer Deserialize JavaScriptSerializer serializer = new JavaScriptSerializer(); TableData data = serializer.Deserialize<TableData>(sData); This looks simple enough except that this set of classes has to be crafted first in order for it to work: public class columns { public string ColumnNames; } public class rows { public string row; } [Serializable] public class TableData { public columns[] Columns; public rows[] Rows; } Back in ExportCSV, the cs TableData object can be used to Response.Write all of the rows in two simple for loops. for The last thing to do is to override the Page Render method to prevent the other usual form data from being posted back with your csv data. The article I referenced just does this with a Response.End (kills off all the rest of the Page processing), but Microsoft recommends against this. They recommend the Context.ApplicationInstance.CompleteRequest()instead. Response.End Context.ApplicationInstance.CompleteRequest() Thus, the following bit of code completes the server-side "file" download: protected override void Render(HtmlTextWriter writer) { bool bExportCSVCalled = Convert.ToBoolean(Session["_bExportCSVCalled"]); if (bExportCSVCalled) { Context.Response.Flush(); return; //stop the rest of the output from being written } base.Render(writer); } Note that I do a Context.Response.Flush() here since I previously set Context.Response.BufferOutput = true. Context.Response.BufferOutput = true. This causes all of the Response.Write data to be held in memory until Response.Flush() is called. If you don't want this, you can remove the line that sets BufferOutput = true. Then you must also remove the Response.Flush() call. Response.Flush() BufferOutput = true Response.Flush() In the Render method I revert to the usual Render base method if ExportCSV was not called first. Render Now if everything worked correctly, the client browser will pop up a message that asks the user if they want to open or save the file. If the open option is chosen, the application that is set up to handle files with the ".csv" extension (e.g. Excel) will open with the data in it. It can be very hard to work with DOM elements from the parent page that are contained within an IFrame. I used to spend a lot of time figuring out how to find the references to these elements when using standard Javascript. jQuery makes this pretty easy to do. I first thought I could use the generic ashx handler to send the response back for the file download, but the browser would not start the download dialog this way. I found the IFrame solution to be a pretty clean workaround for this problem. The IFrame page performs the post back instead of the parent page. First Published January 29,.
http://www.codeproject.com/Articles/321088/Export-HTML-Table-Data-to-CSV-File-Using-ASP-NET-a?PageFlow=FixedWidth
CC-MAIN-2015-48
refinedweb
1,803
66.54
Fisheye distortion correction using Omnidir namespace - change of perspective I have been able to correctly calibrate a 180 degrees FOV camera (fisheye), i.e. I have been able to extract the distortion and camera matrices using the omnidirectional model, so I used the omnidir::calibrate() function to extract the matrices and used the omnidir::undistortImage() function for undistorting the images. Everything works well, but I would like to change the angle at which the undistort is done, i.e. the angle at which the camera is viewing when the image is undistorted. To get a better idea of what I am after please check this link: paulbourke.net/dome/fish2/ (4th image down - looking right by 40 degrees) something similar to that. I have tried changing the cx value in the Knew matrix but that doesn't have the desired effect. Any help would be greatly appreciated. @JackGold1 Were you able to figure out how to change perspective ? I need to do it for my application as well. Thanks !
https://answers.opencv.org/question/143514/fisheye-distortion-correction-using-omnidir-namespace-change-of-perspective/
CC-MAIN-2021-25
refinedweb
169
63.59
And a Pinch of Python Next semester I am a lab TA for an introductory programming course, and it’s taught in Python. My Python experience has a number of gaps in it, so we’ll have the opportunity for a few more Python primers, and small exercises to go along with it. This time, we’ll be investigating the basics of objects and classes, and have some fun with image construction using the Python Imaging Library. Disappointingly, the folks who maintain the PIL are slow to update it for any relatively recent version of Python (it’s been a few years since 3.x, honestly!), so this post requires one use Python 2.x (we’re using 2.7). As usual, the full source code for this post is available on this blog’s Github page, and we encourage the reader to follow along and create his own randomized pieces of art! Finally, we include a gallery of generated pictures at the end of this post. Enjoy! How to Construct the Images An image is a two-dimensional grid of pixels, and each pixel is a tiny dot of color displayed on the screen. In a computer, one represents each pixel as a triple of numbers , where represents the red content, the green content, and the blue content. Each of these is a nonnegative integer between 0 and 255. Note that this gives us a total of distinct colors, which is nearly 17 million. Some estimates of how much color the eye can see range as high as 10 million (depending on the definition of color) but usually stick around 2.4 million, so it’s generally agreed that we don’t need more. The general idea behind our random psychedelic art is that we will generate three randomized functions each with domain and codomain , and at each pixel we will determine the color at that pixel by the triple . This will require some translation between pixel coordinates, but we’ll get to that soon enough. As an example, if our colors are defined by the functions , then the resulting image is: We use the extra factor of because without it the oscillation is just too slow, and the resulting picture is decidedly boring. Of course, the goal is to randomly generate such functions, so we should pick a few functions on and nest them appropriately. The first which come to mind are and simple multiplication. With these, we can create such convoluted functions like We could randomly generate these functions two ways, but both require randomness, so let’s familiarize ourselves with the capabilities of Python’s random library. Random Numbers Pseudorandom number generators are a fascinating topic in number theory, and one of these days we plan to cover it on this blog. Until then, we will simply note the basics. First, contemporary computers can not generate random numbers. Everything on a computer is deterministic, meaning that if one completely determines a situation in a computer, the following action will always be the same. With the complexity of modern operating systems (and the aggravating nuances of individual systems), some might facetiously disagree. For an entire computer the “determined situation” can be as drastic as choosing every single bit in memory and the hard drive. In a pseudorandom number generator the “determined situation” is a single number called a seed. This initializes the random number generator, which then proceeds to compute a sequence of bits via some complicated arithmetic. The point is that one may choose the seed, and choosing the same seed twice will result in the same sequence of “randomly” generated numbers. The default seed (which is what one uses when one is not testing for correctness) is usually some sort of time-stamp which is guaranteed to never repeat. Flaws in random number generator design (hubris, off-by-one errors, and even using time-stamps!) has allowed humans to take advantage of people who try to rely on random number generators. The interested reader will find a detailed account of how a group of software engineers wrote a program to cheat at online poker, simply by reverse-engineering the random number generator used to shuffle the deck. In any event, Python makes generating random numbers quite easy: import random random.seed() print(random.random()) print(random.choice(["clubs", "hearts", "diamonds", "spades"])) We import the random library, we seed it with the default seed, we print out a random number in , and then we randomly pick one element from a list. For a full list of the functions in Python’s random library, see the documentation. As it turns out, we will only need the choice() function. Representing Mathematical Expressions One neat way to represent a mathematical function is via…a function! In other words, just like Racket and Mathematica and a whole host of other languages, Python functions are first-class objects, meaning they can be passed around like variables. (Indeed, they are objects in another sense, but we will get to that later). Further, Python has support for anonymous functions, or lambda expressions, which work as follows: >>> print((lambda x: x + 1)(4)) 5 So one might conceivably randomly construct a mathematical expression by nesting lambdas: import math def makeExpr(): if random.random() < 0.5: return lambda x: math.sin(math.pi * makeExpr()(x)) else: return lambda x: x Note that we need to import the math library, which has support for all of the necessary mathematical functions and constants. One could easily extend this to support two variables, cosines, etc., but there is one flaw with the approach: once we’ve constructed the function, we have no idea what it is. Here’s what happens: >>> x = lambda y: y + 1 >>> str(x) '<function <lambda> at 0xb782b144>' There’s no way for Python to know the textual contents of a lambda expression at runtime! In order to remedy this, we turn to classes. The inquisitive reader may have noticed by now that lots of things in Python have “associated things,” which roughly correspond to what you can type after suffixing an expression with a dot. Lists have methods like “[1,2,3,4].append(5)”, dictionaries have associated lists of keys and values, and even numbers have some secretive methods: >>> 45.7.is_integer() False In many languages like C, this would be rubbish. Many languages distinguish between primitive types and objects, and numbers usually fall into the former category. However, in Python everything is an object. This means the dot operator may be used after any type, and as we see above this includes literals. A class, then, is just a more transparent way of creating an object with certain associated pieces of data (the fancy word is encapsulation). For instance, if I wanted to have a type that represents a dog, I might write the following Python program: class Dog: age = 0 name = "" def bark(self): print("Ruff ruff! (I'm %s)" % self.name) Then to use the new Dog class, I could create it and set its attributes appropriately: fido = Dog() fido.age = 4 fido.name = "Fido" fido.weight = 100 fido.bark() The details of the class construction requires a bit of explanation. First, we note that the indented block of code is arbitrary, and one need not “initialize” the member variables. Indeed, they simply pop into existence once they are referenced, as in the creation of the weight attribute. To make it more clear, Python provides a special function called “__init__()” (with two underscores on each side of “init”; heaven knows why they decided it should be so ugly), which is called upon the creation of a new object, in this case the expression “Dog()”. For instance, one could by default name their dogs “Fido” as follows: class Dog: def __init__(self): self.name = "Fido" d = Dog() d.name # contains "Fido" This brings up another point: all methods of a class that wish to access the attributes of the class require an additional argument. The first argument passed to any method is always the object which represents the owning instance of the object. In Java, this is usually hidden from view, but available by the keyword “this”. In Python, one must explicitly represent it, and it is standard to name the variable “self”. If we wanted to give the user a choice when instantiating their dog, we could include an extra argument for the name like this: class Dog: def __init__(self, name = 'Fido'): self.name = name d = Dog() d.name # contains "Fido" e = Dog("Manfred") e.name # contains "Manfred" Here we made it so the “name” argument is not required, and if it is excluded we default to “Fido.” To get back to representing mathematical functions, we might represent the identity function on by the following class: class X: def eval(self, x, y): return x expr = X() expr.eval(3,4) # returns 3 That’s simple enough. But we still have the problem of not being able to print anything sensibly. Trying gives the following output: >>> str(X) '__main__.X' In other words, all it does is print the name of the class, which is not enough if we want to have complicated nested expressions. It turns out that the “str” function is quite special. When one calls “str()” of something, Python first checks to see if the object being called has a method called “__str__()”, and if so, calls that. The awkward “__main__.X” is a default behavior. So if we soup up our class by adding a definition for “__str__()”, we can define the behavior of string conversion. For the X class this is simple enough: class X: def eval(self, x, y): return x def __str__(self): return "x" For nested functions we could recursively convert the argument, as in the following definition for a SinPi class: class SinPi: def __str__(self): return "sin(pi*" + str(self.arg) + ")" def eval(self, x, y): return math.sin(math.pi * self.arg.eval(x,y)) Of course, this requires we set the “arg” attribute before calling these functions, and since we will only use these classes for random generation, we could include that sort of logic in the “__init__()” function. To randomly construct expressions, we create the function “buildExpr”, which randomly picks to terminate or continue nesting things: def buildExpr(prob = 0.99): if random.random() < prob: return random.choice([SinPi, CosPi, Times])(prob) else: return random.choice([X, Y])() Here we have classes for cosine, sine, and multiplication, and the two variables. The reason for the interesting syntax (picking the class name from a list and then instantiating it, noting that these classes are objects even before instantiation and may be passed around as well!), is so that we can do the following trick, and avoid unnecessary recursion: class SinPi: def __init__(self, prob): self.arg = buildExpr(prob * prob) ... In words, each time we nest further, we exponentially decrease the probability that we will continue nesting in the future, and all the nesting logic is contained in the initialization of the object. We’re building an expression tree, and then when we evaluate an expression we have to walk down the tree and recursively evaluate the branches appropriately. Implementing the remaining classes is a quick exercise, and we remind the reader that the entire source code is available from this blog’s Github page. Printing out such expressions results in some nice long trees, but also some short ones: >>> str(buildExpr()) 'cos(pi*y)*sin(pi*y)' >>> str(buildExpr()) 'cos(pi*cos(pi*y*y*x)*cos(pi*sin(pi*x))*cos(pi*sin(pi*sin(pi*x)))*sin(pi*x))' >>> str(buildExpr()) 'cos(pi*cos(pi*y))*sin(pi*sin(pi*x*x))*cos(pi*y*cos(pi*sin(pi*sin(pi*x))))*sin(pi*cos(pi*sin(pi*x*x*cos(pi*y)))*cos(pi*y))' >>> str(buildExpr()) 'cos(pi*cos(pi*sin(pi*cos(pi*y)))*cos(pi*cos(pi*x)*y)*sin(pi*sin(pi*x)))' >>> str(buildExpr()) 'sin(pi*cos(pi*sin(pi*cos(pi*cos(pi*y)*x))*sin(pi*y)))' >>> str(buildExpr()) 'cos(pi*sin(pi*cos(pi*x)))*y*cos(pi*cos(pi*y)*y)*cos(pi*x)*sin(pi*sin(pi*y*y*x)*y*cos(pi*x))*sin(pi*sin(pi*x*y))' This should work well for our goals. The rest is constructing the images. Images in Python, and the Python Imaging Library The Python imaging library is part of the standard Python installation, and so we can access the part we need by adding the following line to our header: from PIL import Image Now we can construct a new canvas, and start setting some pixels. canvas = Image.new("L", (300,300)) canvas.putpixel((150,150), 255) canvas.save("test.png", "PNG") This gives us a nice black square with a single white pixel in the center. The “L” argument to Image.new() says we’re working in grayscale, so that each pixel is a single 0-255 integer representing intensity. We can do this for three images, and merge them into a single color image using the following: finalImage = Image.merge("RGB", (redCanvas, greenCanvas, blueCanvas)) Where we construct “redCanvas”, “greenCanvas”, and “blueCanvas” in the same way above, but with the appropriate intensities. The rest of the details in the Python code are left for the reader to explore, but we dare say it is just bookkeeping and converting between image coordinate representations. At the end of this post, we provide a gallery of the randomly generated images, and a text file containing the corresponding expression trees is packaged with the source code on this blog’s Github page. Extending the Program With New Functions! There is decidedly little mathematics in this project, but there are some things we can discuss. First, we note that there are many many many functions on the interval that we could include in our random trees. A few examples are: the average of two numbers in that range, the absolute value, certain exponentials, and reciprocals of interesting sequences of numbers. We leave it as an exercise to the reader to add new functions to our existing code, and to further describe which functions achieve coherent effects. Indeed, the designs are all rather psychedelic, and the layers of color are completely unrelated. It would be an interesting venture to write a program which, given an image of something (pretend it’s a simple image containing some shapes), constructs expression trees that are consistent with the curves and lines in the image. This follows suit with our goal of constructing low-complexity pictures from a while back, and indeed, these pictures have rather low Kolmogorov complexity. This method is another framework in which to describe their complexity, in that smaller expression trees correspond to simpler pictures. We leave this for future work. Until then, enjoy these pictures! Gallery - The picture generated by (sin(pi*x), cos(pi*x*y), sin(pi*y)) Brilliant colors wish you luck for 2012 🙂 LikeLiked by 1 person Funny that this idea shows up on planet scheme. It had already three years ago (can’t find the original link, though), and I had given it a try as well: (with ugly code). P! LikeLiked by 1 person That program gives the wrong filename extension; it should be “.ppm” and not “.pgm” (not that anyone actually cares; any program that reads the file is likely to work even if the extension is “.pgm”). LikeLiked by 1 person OK I included the random library…. Available are: ‘Random’,’WichmannHill’, ‘betavariate’, ‘choice’, ‘division’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘jumpahead’,’, ‘SystemRandom’ Awesome images btw! LikeLiked by 1 person I can’t access your server. Did you set up a thing for users to create python images online? For the random library all you need is random.choice() LikeLiked by 1 person Sorry about that, some dev going on here! Python image server is up again, however we are porting it (have a 95% working version!) to client-side JavaScript. Although I do prefer Python, it’s just too much load on the server… If you want to go ahead anyway, any images you submit to the Python server will still appear with source in the next version, people just won’t be able to reuse the code. LikeLiked by 1 person If you haven’t read this yet, you’d probably enjoy it LikeLiked by 1 person Thanks for posting this, I’ve just begun to scratch the surface of what Python can do. It’s a wonderful language. I’m working on a program to turn images into sound. I enjoyed your examples, they are very useful. LikeLiked by 1 person Can’t believe I’ve been having so much fun with this piece of code since yesterday !! Just added a Plus class, coded in the same fashion as the Times class, that adds its arguments and trims the result to be in [-1,1]. Results are breathtaking (much more so than averaging) ! Thank you for these genuinely pythonic ideas about expression nesting by the way. LikeLiked by 1 person What a cool project… working on something for school now, and im going to try to implementn this 🙂 regards LikeLiked by 1 person ‘buildExpr()’ uses CosPi function that is not defined!!! Please see the complete code at Cool. It’s similar to the plasma effect used in many oldskool demo’s. See
https://jeremykun.com/2012/01/01/random-psychedelic-art/?like_comment=75116&_wpnonce=d46c576acd
CC-MAIN-2021-04
refinedweb
2,912
61.67
How about we come up with a new interface called ExceptionHandler or something that can be registered with the ExecutorMethodInterceptor? We could come up with a NullExceptionHandler which basically does nothing. We use a similar concept in HiveMind (ErrorHandler). I would like to be able to plug in error handling code for stuff like when we find a final method in a superclass. Right now, we merely ignore the method and it doesn't get proxied. But, I can see a case where you'd want to throw an exception instead. You'd almost have to invent an ExceptionHandler interface which contains a method for each error scenario or have different ExceptionHandler references for each scenario... public class JavassistProxyFactory implements ProxyFactory { private ExceptionHandler finalMethodInSuperclassHandler; // Setter/Getter } I don't know how it should look, but it would be nice to be able to customize these scenarios on a case-by-case basis. I would hate to have to use a scenario id (or simply a message key) to decide which scenario we're dealing with. -----Original Message----- From: Jörg Schaible [mailto:Joerg.Schaible@Elsag-Solutions.com] Sent: Monday, September 12, 2005 3:17 AM To: Jakarta Commons Developers List Subject: RE: [proxy] Commons-Lang Dependency... Hi James, James Carman wrote on Friday, September 09, 2005 1:33 PM: > What good would a runtime exception do me at that point? The > method interceptor which contains that code is executing the > method invocation in another thread using an Executor (JDK5). > So, the runtime exception wouldn't get back to the caller. > At best it would probably just get printed to standard error > or something. That's why I chose to actually log the error in the > first place. this is the typical use case for monitors (see for background). Just invent a monitor for the proxy package, that is called for different events. Then it's up to a user, to register a monitor that will act on such an event. - J
http://mail-archives.apache.org/mod_mbox/commons-dev/200509.mbox/%3C200509121025.j8CAPpM1003520@carmanconsulting.com%3E
CC-MAIN-2015-27
refinedweb
330
54.83
NAME mmap - allocate memory, or map files or devices into memory LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <sys/mman.h> void * mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset); DESCRIPTION The mmap() system call argument argument is ignored. MAP_FIXED Do not permit the system to select a different address than the one specified. If the specified address cannot be used, mmap() will fail. If MAP_FIXED is specified, addr must be a multiple of the pagesize. If a MAP_FIXED request is successful, the mapping established by mmap() replaces any previous mappings for the process’ pages in the range from addr to addr + len. Use of this option is discouraged. MAP_HASSEMAPHORE Notify the kernel that the region may contain semaphores and that special handling may be necessary. MAP_INHERIT This flag never operated as advertised and is no longer supported. Please refer to minherit(2) for further information./file system) system call close(2) system call The mmap() system call will fail if: [EACCES] The flag PROT_READ was specified as part of the prot argument and fd was not open for reading. The flags MAP_SHARED and PROT_WRITE were specified as part of the flags and prot argument and fd was not open for writing. [EBADF] The fd argument is not a valid open file descriptor. [EINVAL]. The offset argument was not page-aligned. (See BUGS below.) [ENODEV] MAP_ANON has not been specified and fd did not reference a regular or character special file. . Note that an attempt to mmap() zero bytes has no effect and succeeds, while an attempt to munmap() zero bytes will return [EINVAL].
http://manpages.ubuntu.com/manpages/jaunty/man2/mmap.2freebsd.html
CC-MAIN-2014-41
refinedweb
270
64.2
Hi, I accidentally cleaned a solution that has 10 projects and now I faced many errors, some of the errors are like these: Error 186 Type 'websearch.svcProfile.Profile' is not defined. D:\DOM VS2010\890624\DOM\33UI\Controls\ctlCatalogue.ascx.vb 502 44 UI witch svcProfile is a webservice reference. all of my webreferences are not working anymore. other errors are like these: Error 185 Type 'websearch.Class.CommonText' is not defined. D:\DOM VS2010\890624\DOM\33UI\Controls\ctlBasicSearch.ascx.vb 45 29 UI Error 1 The type or namespace name 'UI' could not be found (are you missing a using directive or an assembly reference?) D:\DOM VS2010\890624\DOM\33websearch\BasicSearchControl.ascx.cs 12 11 websearch and: Error 174 'Could not load file or assembly 'ComponentArt.Web.UI, Version=2009.1.1819.3, Culture=neutral, PublicKeyToken=9bc9f846553156bb' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))' D:\DOM VS2010\890624\DOM\33UI\LC UI What do I do? I don't want to go through the process of restoring the backup solution because I did many changes to project.
http://www.dotnetspark.com/links/37364-clean-solution-causes-many-errors.aspx
CC-MAIN-2017-13
refinedweb
186
58.08
csStringReader Class ReferenceThis is a convenience class that reads an input buffer line by line. More... #include <csutil/stringreader.h> Detailed DescriptionThis is a convenience class that reads an input buffer line by line. It takes care of OS specific line endings (CR or CR/LF). Definition at line 32 of file stringreader.h. Constructor & Destructor Documentation Create an empty string reader. Open a new string reader on the given input. 'input' must point to a null terminated character buffer. Member Function Documentation Get the next line from the input and put it in the string argument. Returns true on success or false if there are no more lines left (the string will be made empty in that case). Note that the returned string will not contain a newline at the end. Returns true if there are more lines. Reset the reading offset at the start of the input. Set input buffer. 'input' must point to a null terminated character buffer. The documentation for this class was generated from the following file: - csutil/stringreader.h Generated for Crystal Space 1.0.2 by doxygen 1.4.7
http://www.crystalspace3d.org/docs/online/api-1.0/classcsStringReader.html
CC-MAIN-2017-17
refinedweb
187
69.38
Call Java Methods with DataWeave From a DataWeave statement, you can call Java Methods from any Java class that’s in your Mule project. Note that you can only call Static methods via DataWeave (methods that belong to a Java class, not methods that belong to a specific instance of a class). Call a Java Method Before you can call a method, you must first import the class it belongs to into your DataWeave code. You can import Java classes just as you import DataWeave modules by including java! into the statement. For example, below is a simple Java class with a single method that appends a random number at the end of a string. Assume that you created this class as part of a Java package named "utils" in your Mule project’s src/main/java folder.: MyUtils:. package utils; public class MyClass { private String foo; public MyClass(String foo) { this.foo = foo; } public String getFoo() { return foo; } } The DataWeave example below first imports the "MyClass" class, then creates a new instance of it and calls its instance variable "foo". Note that even though the object has a method "getFoo()", it can’t be called via DataWeave. %dw 2.0 import java!utils::MyClass output application/json --- { a: MyClass::new("myString").foo } This should output the following: { "a":"myString" }
https://docs.mulesoft.com/mule-runtime/4.1/dataweave-cookbook-java-methods
CC-MAIN-2020-05
refinedweb
220
72.36
CVE-2017-16653: CSRF protection does not use different tokens for HTTP and HTTPS implementation of CSRF protection did not use different tokens for HTTP and HTTPS, therefore the token was subject to MITM attacks on HTTP and could then be used in HTTPS context to do CSRF attacks. Resolution The tokens are now namespaced by default to differentiate HTTP from HTTPS. Note that this patch introduces a small BC break (the token ID can change, and isn't the one specified by the user in some cases) but has the benefit of fixing all use cases: - Form component; - Login and logout security listeners; - Direct usage of the security.csrf.token_managerservice; - Direct usage of the CsrfTokenManager(component without the full stack framework) even if not used with HttpFoundation. The previous behavior can be restored by using '' as namespace. The patch for this issue is available here. Credits I would like to thank Oliver Hoff for reporting this security issue, Kevin Dunglas for providing a fix, and the Symfony Core Team for reviewing the patch. To ensure that comments stay relevant, they are closed for old posts. Kousuke Ebihara said on Nov 17, 2017 at 07:24 #1 Is it really that this vuln is of Intl component?
https://symfony.com/blog/cve-2017-16653-csrf-protection-does-not-use-different-tokens-for-http-and-https
CC-MAIN-2018-43
refinedweb
207
57.4
Zen Charts This chapter explains how to place a chart on a Zen page. Every chart is an SVG component as described in the chapter “Zen and SVG” and is derived from the class %ZEN.SVGComponent.svgComponent. Charts follow the layout and style conventions for SVG components, but add specific behaviors of their own. Zen reports callback charts use the same syntax as Zen pages to display charts. Callback charts are defined in the package %ZEN.Report.Display.COSChart, and all of the chart element names begin with the letter “c”, for example, <cbarChart>. See “Using Callback Charts in Zen Reports”. Syntax described in sections “Types of Chart,” “Chart Layout, Style, and Behavior” and “Chart Axes” applies equally well to charts in Zen pages and callback charts in Zen reports. XPath charts is an older implementation of charting in Zen reports which uses syntax different from Zen pages. See “Using XPath Charts in Zen Reports”. Techniques for providing data for charts in Zen pages are different from both callback charts and XPath charts in Zen reports. See “Providing Data for Zen Page Charts” in this book and “Providing Data for Zen Report Charts” in the book Using Zen Reports. The base chart class %ZEN.SVGComponent.chart defines the data, grid (axes and scales), styles, and legend used by charts. You can think of charts as occupying a virtual coordinate space that measures 100 units by 100 units. Internally, charts are plotted in terms of pixels, which allows you to specify size and positioning parameters in pixels as well as in terms of the virtual coordinate space. See “Specifying Size and Position.” Within the total space occupied by the chart, there is a smaller plot area where the chart plots the data. Margins define the space around the plot area. Generally you use these margins as space in which to display the labels and legend for the chart. This chapter begins by introducing the various types of chart, so that you can look at some visual examples and think about the items you want to display on the Zen page, before reading the exact details of how to use a specific type of chart. Chapter topics appear in this order: “Types of Chart” “Providing Data for Zen Page Charts” “Chart Layout, Style, and Behavior” “Chart Axes” Types of Chart This topic describes and illustrates the types of chart that you can place on the Zen page. Each description includes the unique attributes that define that type of chart. For attributes that all charts share in common, see the sections “Providing Data for Zen Page Charts” and “Chart Layout, Style, and Behavior.” Zen offers the following built-in chart types: “Bar Charts” “Bubble Charts” “Bullseye Charts” “Combo Charts” “Difference Charts” “High/Low Charts” “Line Charts” “Percent Bar Charts” “Pie Charts” “Scatter Charts” “Tree Map Charts” Bar Charts A <barChart> displays one or more data series as a set of vertical or horizontal bars. The following figure shows a Zen bar chart displaying data from three data series. <barChart> has the following attributes: Bubble Charts A <bubbleChart> displays data as circles or “bubbles” positioned at x and y coordinates. It requires a minimum of two data series. The first series supplies x values and the second supplies y values. When used to chart only two data series, <bubbleChart> is effectively an <xyChart>. <bubbleChart> does not support chartPivot If you supply a third series, the chart uses that data to draw the radius of each bubble. Values in the radius series are scaled and multiplied by the value of the radius property. The following figure shows a chart with x, y and radius data series. Note how the default partial transparency of the bubbles lets you see the shapes even when they overlap. The property opacity controls this characteristic. Note also that in this example, the value of showQuadrant is true, so the chart area is divided into quadrants. You can supply up to two additional data series. The fourth series determines how colors are applied to the data bubbles, and the fifth controls opacity of bubbles. Values in the fourth, or color data series can be any arbitrary data. The chart establishes color categories for each new value encountered in the series, and assigns the colors to corresponding bubbles on the chart. The chart uses the colors that are currently in effect, see seriesColors and seriesColorScheme. The following code fragment shows the part of an ongetData handler that sets up a color data series. /// Callback to provide data for bubble chart. ClientMethod getBubbleChartData(series) [ Language = javascript ] { var chart = zenPage.getComponentById('chart'); var data = new Array(chart.seriesSize); // ...code omitted... if (series == 3) // color { for (var i = 0; i < chart.seriesSize; i++) { data[i] = (i%3)?"group 1":"group 2" } } return data; } The following figure shows the resulting chart, with colors applied to randomly generated data. Note that in this chart, the value of showRegression is true, so the chart contains a computed linear regression line, and showQuadrant is false, so the chart does not show quadrants. The property lineStyle provides a style specification for the regression line. Values in the fifth, or opacity data series can be any arbitrary data. Values in the opacity series are scaled and multiplied by the value of the opacity property. Values are not normalized, so a large range in values can result in the smallest values being driven to 0 and becoming invisible. /// Callback to provide data for bubble chart. ClientMethod getBubbleChartData(series) [ Language = javascript ] { var chart = zenPage.getComponentById('chart'); var data = new Array(chart.seriesSize); // ...code omitted... if (series == 4) // opacity { data[1] = 1; data[2] = 4; data[3] = 1; data[4] = 1; data[5] = 4; data[6] = 1; data[7] = 4; data[8] = 4; data[9] = 4; } return data; } The following figure shows the resulting chart, with opacity applied to random generated data. Note also that the quadrants have been modified by setting the property xCenterValue, and the properties upperRightStyle and lowerLeftStyle have been used to modify the quadrant colors. <bubbleChart> has the following attributes: Bullseye Charts A <bullseyeChart> displays data items as concentric circles. Bullseye charts are often used in situations where the largest circle shows the entire data set, the next circle shows data items that meet some relevant set of criteria, and the next circle shows data items that meet additional criteria. For example, if the largest circle shows the total number of patients in a study, the next circle might show patients with diabetes, and the smallest diabetic patients undergoing a specific treatment. Combo Charts A <comboChart> displays multiple data series in a single chart, using area, bar and line charts. The following figure illustrates all three chart types. You can use other chart elements to plot multiple data series using a single type of chart, but <comboChart> sometimes offers advantages. For example, you can chart multiple filled line charts using <lineChart>, but <comboChart> may be a better choice, because it renders area charts with partial transparency, so all of the chart areas are visible, even when they overlap. You can also use the attribute seriesTypes to display one of the data series as target lines. The following figure shows a chart where the fourth data series supplies target lines. <comboChart> supports the following attributes: Difference Charts A <diffChart> is a specialized type of line chart that highlights the difference between two data series: The first series provides a set of reference data values. The second data series provides values that you want to compare to the reference data set. The <diffChart> shades the area between the two series using the color of the second data series. To further distinguish between the series, the chart draws a line representing the reference series across the shaded area of the chart. This line uses the color of the first, or reference data series, and can take additional styling from the refLineStyle attribute. <diffChart> does not support chartPivot. The following figure shows a difference chart: For comparison, the following figure shows the same data plotted as a filled line (area) chart: <diffChart> has the following attributes: High/Low Charts A <hilowChart> can be used to show stock market high-low-close values, or to trace a measured value along with its high and low ranges to indicate possible error margins. The chart displays a set of bars as established by three data series: A series of high values sets the top (right) limit of each bar. A series of low values sets the bottom (left) limit of each bar. (Optional) The “closing” values. The chart places a marker on each bar at these values. Each low value is assumed to be smaller than its corresponding high value. Each closing value is assumed to be between its corresponding high and low values. The chart uses its first seriesColors value to plot all bars and marker. It ignores the colors provided for the other series. <hilowChart> has the following attributes: Line Charts A <lineChart> displays one or more data series as a set of lines. The following figure shows a simple line chart. <lineChart> has the following attributes: Percent Bar Charts A <percentbarChart> displays each data series as a bar in the chart. All the bars are the same height, and represent 100% of the values in the series. Bands in the bar represent items in the series, and are sized proportional to that items contribution to the total. This method of handling data series is similar to a <pieChart> when plotBy="both", except that the pie chart also shows the relative contribution of each series. See “Pie Charts by Items.” You can use ongetLabelX to provide labels for the bars, and seriesNames to provide labels for the legend, matching names to colors by order in the series. <percentbarChart> has the following attributes: Pie Charts Pie charts can plot single or multiple data series, and can show the series, the items in the series, or both. <pieChart> does not support axes or grids in the plot area, as do line charts or bar charts. A <pieChart> that plots the items in a single data series displays a circle with radial slices representing items in the series. The chart adjusts the size of each slice to be proportional to the contribution of that item to the total. Note that the end user can rotate the pie chart with click and drag gestures in the browser. <pieChart> has the following attributes: plotBy The <pieChart> plotBy attribute controls how Zen generates a pie chart from the data provided. You may actually provide multiple series to the <pieChart>. The chart processes all the data series to create one series, and then displays that series as slices in the chart. plotBy options are as follows. "items" – plot a slice for every item in this chart's data. "series" – plot a slice for every data series in this chart's data. "both" – plot a slice for each item within each data series, which means that the chart contains seriesCount * seriesSize slices. "auto" – automatically select the appropriate way to display data based on how many data series and items are present. Pie Charts by Items When the value of plotBy is "items", a <pieChart> plots one slice for every item within the data series. If you provide multiple data series to an "items" pie chart, each slice of the pie represents the total of a particular item, summed across all of the data series in the chart. The following conceptual figure shows how three data series, each containing six items, would generate an six-slice pie chart. Each slice represents the sum of the values for that item provided by the three series. When the value of plotBy is "items", labels for the slices are treated as <yAxis> labels. This means you cannot specify them directly using a chart attribute such as seriesNames. Labels are provided by a %ZEN.Auxiliary.dataController, if present, or you can provide an onGetLabelY event handler to get the label values. Pie Charts by Series When the value of plotBy is "series", multiple series are in use. The <pieChart> plots one slice for every data series, so the number of slices in the pie chart is seriesCount. Each slice represents the sum of all the items within one of the series. The seriesNames attribute provides the labels for the slices, and for the legend. The following conceptual figure shows how three data series, each containing six items, generate a three-slice pie chart. Each slice represents the sum of the eight items in that series. Pie Charts by Both Items and Series When the value of plotBy is "both", multiple series are in use. The <pieChart> plots one slice for every item in every data series, so there are seriesCount times seriesSize slices. The base color for each slice is the associated series color. Alternating slices use dark and normal shades of this color. The chart legend displays series names; the seriesNames attribute provides these labels. The slices display item names; the labels are provided by an onGetLabelY event handler, or a data controller. The following pie chart example compares three series (Products, Services, and Training), each of which has data items in four categories (America, Asia, Europe, and Africa). The chart has twelve slices. Scatter Diagrams An <xyChart> plots two or more data series as (x,y) points. This type of chart is sometimes called a scatter diagram; it is intended to show the raw data distribution for the series. The <xyChart> represents its data series as follows: The first data series provides the x values The second data series provides correlated y values Any additional data series are plotted as y values correlated to the x values provided by the first series. The result is that an <xyChart> always displays one less plot than its number of data series. <xyChart> has no unique attributes. <xyChart> has the same general-purpose attributes as any Zen chart. For descriptions, see the sections “Providing Data for Zen Page Charts” and “Chart Layout, Style, and Behavior.” An <xyChart> always has markersVisible and plotToEdge set to true. Generally you need to manipulate some of the other chart attributes to produce the desired results. For example: The seriesCount value must always be one more than the number of plots you want to display. This leaves room for the first, x-value series. The first data series is not plotted, so the <xyChart> applies series settings beginning with the second series, not the first. For example: The seriesColors list applies to the second, third, and successive series. The seriesNames list applies to the second, third, and successive series. The markerShapes list applies to the second, third, and successive series. A scatter diagram does not appear “scattered” unless you hide the lines between the markers. To do this, set the plotStyle for an <xyChart> as follows: plotStyle="stroke:none;". This is a better approach than setting plotStyle="stroke-width: 0;", because some SVG implementations render a very thin line, even when stroke-width is set to 0. <xyChart> has the following attributes: Tree Map Charts A <treeMapChart> plots the items in a single data series and displays each item in the series as a rectangle and arranges them in a larger rectangle. The chart adjusts the size of each smaller rectangle to be proportional to the contribution of that item to the total. You can display more than one data series by setting the attribute showMultiples to true. Each of the multiple charts displays a different data series. Providing Data for Zen Page Charts The data for a chart consists of one or more data series. Each data series that you use for a chart is a simple array of numeric values. You can provide the data for a Zen page chart in one of two ways: “Using a JavaScript Method” in the page class, by setting the chart’s ongetData attribute. “Using a Data Controller”, by setting the chart’s controllerId attribute. Regardless of which technique your chart uses to retrieve data, you can limit the data returned by either technique to the desired number and size of series. Zen reports callback charts and Zen pages use identical syntax to display charts. Callback charts are defined in the package %ZEN.Report.Display.COSChart When it comes to displaying charts, Zen pages and Zen reports use identical syntax. Syntax described in the previous section, “Types of Chart,” and in the later sections “Chart Layout, Style, and Behavior” and “Chart Axes” applies equally well to Zen pages and Zen reports. However, the techniques for providing data for charts in Zen reports are different from the techniques for Zen pages. For details, see the section “Providing Data for a Zen Report Chart” in the book Using Zen Reports. To provide data for charts on Zen pages, use the topics in this section. Using a JavaScript Method All charts support the ongetData attribute for generating chart data. The ongetData expression invokes a client-side JavaScript method defined in the page class. This method becomes the ongetData event handler for the chart. The chart calls the ongetData event handler once for each of the data series specified by seriesCount. The event handler accepts a single argument, series, which specifies the data series currently being processed. The value of series is the 0-based ordinal number of the current data series; possible values range from 0 to seriesCount - 1. The event handler also needs to know how many values to supply for the data series. This value is provided by the seriesSize attribute of the chart. In the example code that follows this explanation, this line gets the value of seriesSize from the chart: var data = new Array(chart.seriesSize); The method puts seriesSize - 1 items into an array and returns that array. It can use whatever approach is appropriate to provide data for the chart. For instance, it may use a switch statement based on the value of the series input argument. The following is a sample ongetData event handler that provides random values as a test. You can see this event handler in the SAMPLES namespace in the template page class ZENTest.SVGChartTest. It provides the data for charts drawn by page classes that extend the ZENTest.SVGChartTest template, such as SVGLineChartTest and SVGBarChartTest: ClientMethod getChartData(series) [ Language = javascript ] { var chart = zen('chart'); var data = new Array(chart.seriesSize); var value = 50; for (var i = 0; i < chart.seriesSize; i++) { if (Math.random() > 0.9) { value += (Math.random() * 50) - 35; } else { value += (Math.random() * 20) - 9; } data[i] = value; } return data; } The previous example creates a chart with random data. Normally, you want to create charts using real data from the server. In the typical case, your server-side method returns a list. On the client side, this list is consumed by the chart component that displays the data. One way to make this work is shown in the following example: When our example page is first displayed, its %OnAfterCreatePage method calls a server-side method PopulateData() to place values into a page property called Population for later use by client-side code. In our example, this happens only once, when %OnAfterCreatePage is called. Later user actions may change how this data is viewed, but in this example, we only get data from the server once. Method %OnAfterCreatePage() As %Status { // Get the data while we're on the server Set sc = ..PopulateData() // Set the initial series size programmatically Set chart = %page.%GetComponentById("chartPop") Set chart.seriesSize = $Length(..States,",") Quit sc }Copy code to clipboard The Population property is defined in our page class as follows: Property Population As %ZEN.Datatype.list(DELIMITER = ",");Copy code to clipboard And our server-side method PopulateData() places values and comma delimiters into the Population list as follows. Step 3 describes the Internals of the GetCountByState() class query referenced here: Method PopulateData() As %Status { Try { Set sc = $System.Status.OK() // Get a resultset containing population by state Set sc = ##class(SimpleZenChart.Person).GetCountByState(.rs) Quit:$System.Status.IsError(sc) // Populate the page properties with comma delimited values While (rs.%Next()) { Set ..Population = ..Population _ rs.%Get("PersonCount") _ "," Set ..States = ..States _ rs.%Get("HomeState") _ "," } // Remove trailing delimiter Set ..Population = $Extract(..Population,1,*-1) Set ..States = $Extract(..States,1,*-1) } Catch(ex) { Set sc = ex.AsStatus() } Quit sc }Copy code to clipboard As seen in the above excerpt, PopulateData() invokes a class query defined in SimpleZenChart.Person to retrieve the results that it uses in constructing the Population list. The GetCountByState() method looks like this: ClassMethod GetCountByState(Output Results As %SQL.StatementResult) As %Status { Try { Set sc = $System.Status.OK() // Make a new SQL statement // Use an array to create the query text (this is not required) // Pass in schema search list into statement constructor Set statement = ##class(%SQL.Statement).%New(,"SimpleZenChart") Set query = 4 Set query(1) = "SELECT HomeState, COUNT(ID) As PersonCount" Set query(2) = "FROM Person" Set query(3) = "GROUP BY HomeState" Set query(4) = "ORDER BY HomeState" // Prepare query Set sc = statement.%Prepare(.query) Quit:$System.Status.IsError(sc) // Execute query Set Results = statement.%Execute() // Check %SQLCODE for an error If (Results.%SQLCODE < 0) { Set sc = $System.Status.Error($$$GeneralError, "Error in %Execute. %SQLCODE = " _Results.%SQLCODE_" Error message = "_Results.%Message) Quit } } Catch (ex) { Set sc = ex.AsStatus() } Quit sc }Copy code to clipboard Each time a chart on our example page is refreshed, including the first time the page is displayed, the chart consults its ongetData expression to see which client-side method it should invoke to populate itself with data. In the following excerpt, the chart is a <barChart> and the client-side method is called getData(): <barChart id="chartPop" width="100%" height="100%" selectedItemStyle="fill:rgb(255,0,255);" seriesCount="1" appearance="2D" title="Population By State" ongetData="return zenPage.getData(series);" ongetLabelX="return zenPage.getXLabels(value);" onelementClick="zenPage.onSelectElement(zenThis);"> <xAxis title="States"/> </barChart>Copy code to clipboard Our sample client-side method getData() consults the Population property of the client-side page object to get the list of values stored in that property. Because Population was defined as type %ZEN.Datatype.list in the page class, getData() automatically understands Population as a JavaScript array; no conversion is necessary. getData() returns this array as its return value. ClientMethod getData(series) [ Language = javascript ] { try { var data = zenPage.Population; return data; } catch (ex) { zenExceptionHandler(ex,arguments); } }Copy code to clipboard The <barChart> updates its display using the values in the JavaScript array returned by getData(). This example offers other interesting features. For example, when you click on a bar in the bar chart, Zen fires the client-side method identified by the <barChart> onelementClick attribute. In our example, this client-side method is called onSelectElement(). It uses the JavaScript utility function zenSetProp() to find some of the other components on the page then change their contents using data acquired from client-side methods, including getData(). ClientMethod onSelectElement(chart) [ Language = javascript ] { try { var selected = chart.getProperty('selectedItem') // Set the population and count for the item zenSetProp('htmlState','content',this.getXLabels(selected)); zenSetProp('htmlCount','content',(this.getData())[selected]); } catch (ex) { zenExceptionHandler(ex,arguments); } }Copy code to clipboard In the excerpt above, the client-side method onSelectElement() uses the number of the currently selected bar in the bar chart as an index into the array returned by getData(). getXLabels() also uses an index into a JavaScript array, but in this case the array is the page property States, which contains a list of states whose population statistics are being stored in the example. Because the States property was defined as type %ZEN.Datatype.list in the page class, getXLabels() automatically understands States as a JavaScript array; no conversion is necessary. ClientMethod getXLabels(value) [ Language = javascript ] { try { var data = zenPage.States return data[value]; } catch (ex) { zenExceptionHandler(ex,arguments); } }Copy code to clipboard A final item of note in this example is one that changes the series size for the chart without modifying or resending any data. The client-side method changeSeriesSize() is invoked when the user selects one of the choices in a list box on the same page with the bar chart. The list box is defined as follows: <listBox id="lbSeriesSize" label="Select Series Size" value="5" onchange="zenPage.changeSeriesSize(zenThis);"> <option text="10"/> <option text="20"/> <option text="30"/> <option text="40"/> <option text="50"/> </listBox>Copy code to clipboard The client-side method changeSeriesSize() uses the text value from the selected <option> and uses it to reset the seriesSize value for the <barChart> whose id is chartPop. This is our example <barChart> as shown in step 4. When the seriesSize is reset, the chart redisplays. ClientMethod changeSeriesSize(listbox) [ Language = javascript ] { try { // Get selected index and compute value var selected = listbox.getProperty('selectedIndex'); var value = listbox.getOptionText(selected); // Set the series size in the chart zenSetProp('chartPop','seriesSize',value); } catch (ex) { zenExceptionHandler(ex,arguments); } }Copy code to clipboard Using a Data Controller All charts support the following attributes, which associate the chart with a view on a data controller as described in the chapter “Model View Controller. ” If your XData Contents block contains a <dataController> reference that looks like this: <dataController id="source" modelClass="myPackage.MyModel" modelId="1"/> Then your XData Contents block may also contain a chart definition that looks like this: <pieChart id="myChart" controllerId="source" height="300" width="300" title="Pie Chart" titleStyle="fill: black;" backgroundStyle="fill: #c5d6d6;" plotAreaStyle="fill: white;" labelStyle="fill: black;" legendVisible="true" legendX="83" legendY="8" legendHeight="" legendWidth="15" > </pieChart> The chart’s controllerId value must match the <dataController> id value. The chart takes its seriesSize from the number of properties in the <dataController> modelClass. Limiting the Data Set The following attributes from the base class %ZEN.SVGComponent.chart tell the chart how many series to use, and how many of the items in each data series to use, when constructing the chart. All types of chart support these attributes. If you do not use a dataController to provide the data set, you must specify both seriesCount and seriesSize. If you use a dataController, Zen determines the number of series and items from the data. Chart Layout, Style, and Behavior The following diagram shows the major components of a Zen chart. The chart properties described in the following sections control the positioning, style, and behavior of these components. Chart properties include those from the SVG component class %ZEN.SVGComponent.svgComponent, such as width andheight, and those from the base chart class %ZEN.SVGComponent.chart, such as marginTop and borderOffset. The base class %ZEN.SVGComponent.chart offers a large number of attributes that you can apply to a Zen chart to control details such as: “Layout and style” — The relative size and characteristics of the background “Plot area” — The part of the chart that displays the data “Markers” — Shapes that highlight the exact data points on a continuous plot “Legends” — A key to the meaning of each plot on the chart “Titles” — Text that labels the chart, and the items on the chart “User Selections” — How the chart should respond to user actions, such as mouse clicks “Chart Axes” — Characteristics of the two axes that define most charts Specifying Size and Position Unless the specific description of a property states otherwise, you can give values for properties that specify sizes and positions in one of the following ways: Do not specify a value, and let Zen calculate the value automatically. Use a value from 0 to 100 that is interpreted as a percentage of the current chart size. Specify a length value with units, such as "10px", to indicate that you want a margin of 10 pixels, independent of chart size Layout and Style The following attributes from the base class %ZEN.SVGComponent.chart determine the background style and the position of the plot area within the chart. Plot Area The following attributes from the base class %ZEN.SVGComponent.chart determine display conventions for graphs within the plot area and for the coordinate axes that border the plot area. Also see the section “Chart Axes.” A number of attributes are supported by several chart types. These attributes are listed in the table of attributes for the relevant charts, and described in more detail in the following sections. chartPivot If the attribute chartPivot is true, rotate the chart so that the x-axis is vertical and the y-axis horizontal. If false, display the chart in typical fashion, with x-axis horizontal and the y-axis vertical. This attribute has the underlying data type %ZEN.Datatype.boolean. See “Zen Attribute Data Types.” The following figure shows a pivoted bar chart. chartStacked The attribute chartStacked comes into play if there are multiple data series. If true, the data series are drawn stacked on top of one another (values are additive). If false, the bars appear side by side (the values are independent). This attribute has the underlying data type %ZEN.Datatype.boolean. See “Zen Attribute Data Types.” If you set the property chartStacked to true, the result is a chart with values at each data point from all the data series in the chart stacked into a single bar. The following figure illustrates a stacked bar chart: And the next figure shows the same data presented as a stacked line chart: showMultiples If the attribute showMultiples is true, charts that support small multiples display the data as a set of small charts, one for each data series. The chart method hasMultiples lets you determine whether the chart supports multiples. This attribute has the underlying data type %ZEN.Datatype.boolean. See “Zen Attribute Data Types.” The following figure shows a line chart with four data series and showMultiples="true". timeBased The attribute timeBased specifies that the x-axis is a time line. It is valid only for line and combo chart types. In order to plot a time based chart, you must use the ongetLabelX callback method to provide time values in the format YYYY-MM-DD or YYYY-MM-DD HH:MM:SS. These values are placed in their proper position on the x-axis timeline. Because the logic that positions values on the timeline depends on the returned date values, you cannot set the property maxLabelLen to a value less than ten. The chart properties startTime and endTime set the start and end dates for the time line. If you do not supply values for startTime and endTime, the chart uses the earliest and latest values returned by the ongetLabelX callback method. The following figure illustrates the effect of a timeBased x-axis. The top chart uses a time based x-axis, while the lower chart plots the same x values on a category axis. Markers Markers are shapes that are placed at each data point along the chart. If the chart has multiple series, each series in the chart can use a different shape for its marker. Marker attributes apply only to types of chart that support markers (that is, line charts). The base class %ZEN.SVGComponent.chart offers the following marker attributes. Legends The following attributes from the base class %ZEN.SVGComponent.chart determine the style of the chart legend and whether or not it should display. Titles The following attributes from the base class %ZEN.SVGComponent.chart determine the style and contents of the chart title. User Selections The following attributes control user interactions with the chart. Zen reports does not support any of the properties in this section, because reports are not interactive. Chart Axes Zen displays all charts except pie charts with x and y axes. Axes determine how chart data is displayed. You can use <xAxis> or <yAxis> elements to specify the range of axis values (minValue to maxValue), or Zen can determine these values automatically based on the range of data values. <xAxis> can be a category axis or a value axis, depending in the type of chart. A category axis names the data categories. A value axis indicates the values of plotted data. <yAxis> is a value axis. You can supply more than one y-axis to a chart, which enables you to plot data series with different ranges of values on the same chart in a meaningful way. The following example plots six months of data on heating degree days (HDD), and electricity use in kilowatt hours (kWh) for a residential building in the Boston MA area. A heating degree day is a measure of the energy demand for heating buildings. In this example, data values for HDD range from 11 to 34, and data values for kWh range from 841 to 1148. The following code fragment creates a line chart that plots these two data series using two different axes, one for values from 10 to 40, the other for values from 700 to 1200: <lineChart id="chart" ongetData="return zenPage.getLineChartData(series);" onelementClick="zenPage.chartElementClick(chart);" ongetLabelX="return zenPage.getXLabels(value);" seriesNames="HDD,kWh" backgroundStyle="fill: #cccccc;" plotAreaStyle="fill: #eeeeee;" title="Line Chart: Two Y Axes" currYAxis="1" seriesCount="2" seriesSize="6" seriesColorScheme="solid" plotStyle="stroke-width: 1px;" labelsVisible="true" seriesYAxes="1,0" width="300" height="300"> <xAxis id="xAxis" /> <yAxis minorGridLines="true" minValue="700" maxValue="1200" labelUnits="100" minorUnits="10" majorUnits="50" majorGridLines="true" /> <yAxis minorGridLines="true" minValue="10" maxValue="40" labelUnits="10" baseValue="0"/> </lineChart> The property seriesYAxes associates data series with axes. The property currYAxis specifies the axis that is active when you first display the chart. See “Plot Area”. The following figure shows the resulting chart. The first image shows the chart as it is initially displayed, with the HDD axis visible. The HDD item in the legend is highlighted to show that it is the relevant data series for the axis currently in use. If you click on kWh in legend, the chart displays the appropriate y-axis. All data series associated with an axis are all highlighted when that axis is active. Compare these charts with the following chart, which attempts to plot both HDD and kWh on a single axis. Note that <xyChart>, <diffChart> and <bubbleChart> do not support alternate yAxes. The following attributes from the class %ZEN.Auxiliary.axis are available as attributes of either <xAxis> or <yAxis> within a chart definition. All of these attributes are optional; Zen provides reasonable defaults for each of them based on the data supplied to the chart. When you work with %ZEN.SVGComponent.chart subclasses programmatically, you work with axes as the xAxis and yAxis properties of the chart object. Each of these properties is a %ZEN.Auxiliary.axis object with properties corresponding to the attributes listed above.
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GZCP_CHARTS_AND_GRAPHS
CC-MAIN-2021-04
refinedweb
5,773
54.63
Hi ALL, Can any one help us regarding How to fecth the Date column(or month column) from the file name specified in the path in a generalized way . For example : file name is :subscribers (Cost) Sep13.csv is specified in the below path E:\Accounting\documents\subscribers (Cost) Sep13.csv here I need to fetch the "Sep13" as a Date column in the ODI 11g in the generalized way. Can any one help us in this case as early as possible. I would suggest using a piece of Jython code for this. Something like this... import os import os.path filelist = os.listdir(E:\Accounting\documents\) for file in filelist: datestr = file[19:-4] You'd need to work out what to do with datestr next... perhaps write it to a table or update an ODI variable with it. Hope this is of some help.
https://community.oracle.com/message/11224062
CC-MAIN-2016-07
refinedweb
146
85.69
How to specify file on local disk with external schema Discussion in 'XML' started by pohmart@yahoo,057 - Jas Shultz - Dec 3, 2003 - Replies: - 1 - Views: - 1,768 - Markus - Nov 23, 2005 How to specify a local (!) Schema file in the same (!) directory as the xml file ?Till Soerensen, Jun 9, 2004, in forum: XML - Replies: - 1 - Views: - 1,385 - Henry S. Thompson - Jun 9, 2004 [XML Schema] Including a schema document with absent target namespace to a schema with specified tarStanimir Stamenkov, Apr 22, 2005, in forum: XML - Replies: - 3 - Views: - 1,409 - Stanimir Stamenkov - Apr 25, 2005 Large data array (operations) via disk disk files, Nov 13, 2006, in forum: C Programming - Replies: - 12 - Views: - 592 - santosh - Nov 15, 2006
http://www.thecodingforums.com/threads/how-to-specify-file-on-local-disk-with-external-schema.168959/
CC-MAIN-2015-22
refinedweb
122
64.64
Haskell is a pure language. Every Haskell expression is referentially transparent, meaning that you can substitute that expression with its evaluated result without changing the program. Or, put into code: -- this program f expr expr -- apply function f to arguments expr, expr -- is equivalent to this one, which factors out `expr` let x = expr -- introduce a new variable `x` with the value of `expr` in f x x And this is true for all expressions e, and all functions f. These could be complex expressions which describe ways of manipulating network channels or window buffers, or something trivial like a numeric literal. You can always substitute the expression with its value. This is not true in Scala, simply because Scala allows unrestricted side-effects. Unlike Haskell, Scala puts no limitations on where and when we can use things like mutable state ( vars) or evaluated external effects like println or launchTheMissiles. Since there are no restrictions on where and when we can do evil, the Scala equivalent to the above just doesn’t work: f(e, e) // isn't really equivalent to! val x = e f(x, x) The reason it isn’t equivalent comes from the different sorts of expressions that we could find in e. For example, what if e is println("hi!"). If we make that substitution, our snippet looks like the following: f(println("hi"), println("hi")) // isn't really equivalent to! val x = println("hi") f(x, x) Clearly these are not the same two programs. The first prints "hi" twice, while the second only prints it once. This is a violation of referential transparency, and it’s why we sometimes say that Scala is an impure language. Any expression which is not referentially transparent must contain side-effects, by definition. Now of course, we found this problem by using a side-effecting function: namely, println. Haskell clearly has the ability to print to standard output, so how does it avoid this issue? If we build the same program in Haskell, can we violate referential transparency? f (putStrLn "hi") (putStrLn "hi") -- is equivalent to let x = putStrLn "hi" in f x x As it turns out, this is still referentially transparent! These two programs still have the same meaning. This is possible only because neither program actually prints anything! In Haskell, effects are treated as first-class values. The putStrLn function doesn’t print to standard out, it returns a value (of type IO ()) which describes how to print to standard out, but stops short of actually doing it. These sorts of values can be composed using the monadic operators (in Scala, flatMap and pure), allowing Haskell programmers to build up expressions composed of sequences of dependent effects, all of which are merely descriptions of the side-effects which will eventually be performed by the runtime. Ultimately, the description which comprises your whole program is the return result from the main function. The Haskell runtime runs the main function to get this description of all your effects, and then runs the effects per your instructions. This is kind of a clever trick. It allows Haskell to simultaneously be pure and still have excellent support for manipulating effects and interacting with the “real world”. But why is it relevant to Scala? After all, Scala is an impure language. We don’t need to go through this complex rigmarole of describing our effects and composing those descriptions; the language lets us just do it! So why wouldn’t we just, you know, evaluate the effects that we need evaluated? The answer is that we want to reason about where and when our effects are evaluated. And of course, we want to be able to leverage laws and abstractions which assume equational semantics for expressions (i.e. referential transparency). Cats is full of these sorts of abstractions, and cats-laws provides a vast set of laws which describe them. But all of these abstractions and all of these laws break down the moment you introduce some sort of side-effecting expression. Because, much like our referential transparency example from earlier, these abstractions assume that you can substitute expressions with their evaluated results, and that’s just not true in the presence of side-effects. What we need is a data type which allows us to encapsulate Scala-style side-effects in the form of a pure value, on which referential transparency holds and which we can compose using other well-defined abstractions, such as Monad. Scalaz defines two such data types which meet these criteria: scalaz.effect.IO and scalaz.concurrent.Task. But in practice, nearly everyone uses Task instead of IO because of its support for asynchronous effects. Cats does not define any such abstraction, and what’s worse is the cats ecosystem also doesn’t really provide any such abstraction. There are two Task implementations that are relatively commonly used with cats – namely, monix.eval.Task and fs2.Task – but these are not part of cats per se, nor are they deeply integrated into its abstraction hierarchy. Additionally, the proliferation of broadly equivalent options has led to confusion in the ecosystem, with middleware authors often forced to choose a solution for their end-users, and end-users uncertain as to which choice is “right”. The cats-effect project aims to change all of that. The goal of cats-effect is to provide an “easy default” IO type for the cats ecosystem, deeply integrated with cats-core, with all of the features and performance that are required for real world production use. Additionally, cats-effect defines a set of abstractions in the form of several typeclasses which describe what it means to be a pure effect type. These abstractions are extremely useful both in enabling MTL-style program composition and to ensure that other pre-existing Task implementations remain first-class citizens of the ecosystem. IO does not overshadow monix.eval.Task or fs2.Task; it complements them by providing a set of abstractions and laws which allow users to write safe, parametric code which supports each of them equally. One important sidebar here: cats-effect does not provide any concurrency primitives. scalaz.concurrent.Task and monix.eval.Task are both notable for providing functions such as both, which takes two Tasks and runs them in parallel, returning a Task of a tuple of the results. The cats.effect.IO type does not provide any such function, and while it would be possible to define such a function (and others like it!), we strongly encourage users to instead consider full-on streaming frameworks such as fs2 or Monix for their concurrency needs, as these frameworks are able to provide a much sounder foundation for such functions. See here for a rough outline of why this is. Also note that some Task implementations, such as Monix’s, can and do provide parallelism on a sound foundation by enriching their internal algebraic structures. Thus, monix.eval.Task is actually quite different from cats.effect.IO, despite having a similar core set of operations. What does this look like in practice? Well, ideally, as convenient as possible! Let’s look at our println example: def putStrLn(line: String): IO[Unit] = IO { println(line) } f(putStrLn("hi!"), putStrLn("hi!")) // is equivalent to val x = putStrLn("hi!") f(x, x) Great! We can write Haskell fanfic in Scala. 😛 The notable element here is the use of the IO.apply constructor to wrap the println effect in a pure IO value. This pattern can be applied to any side-effect. You can think of this sort of like an FFI that converts impure code (like println) into pure code (like putStrLn). The goal of this API was to be as simple and straightforward as possible. If you have a curly brace block of impure side-effecting code, you can wrap it in a composable and pure abstraction by just adding two characters: IO. You can wrap arbitrarily large or small blocks of code, potentially involving complex allocations, JNI calls, resource semantics, etc; but it is generally considered a best practice to wrap side-effects into the smallest composable units that make sense and do all of your sequentialization using flatMap and for-comprehensions. For example, here’s a program that performs some simple user interaction in the shell: import cats.effect.IO val program = for { _ <- IO { println("Welcome to Scala! What's your name?") } name <- IO { Console.readLine } _ <- IO { println(s"Well hello, $name!") } } yield () We could have just as easily written this program in the following way: val program = IO { println("Welcome to Scala! What's your name?") val name = Console.readLine println(s"Well hello, $name!") } But this gives us less flexibility for composition. Remember that even though program is a pure and referentially transparent value, its definition is not, which is to say that IO { expr } is not the same as val x = expr; IO { x }. Anything inside the IO { … } block is not referentially transparent, and so should be treated with extreme care and suspicion. The less of our program we have inside these blocks, the better! As a sidebar that is actually kinda cool, we can implement a readString IO action that wraps Console.readLine as a val! val readString = IO { Console.readLine } This is totally valid! We don’t need to worry about the difference between def and val anymore, because IO is referentially transparent. So you use def when you need parameters, and you use val when you don’t, and you don’t have to think about evaluation semantics. No more subtle bugs caused by accidentally memoizing your effects! Of course, if program is referentially transparent, then clearly repeated values of program cannot possibly run the effects it represents multiple times. For example: program program program // must be the same as! program If this weren’t the case, then we would be in trouble when trying to construct examples like the Haskell one from earlier. But there is an implication here that is quite profound: IO cannot eagerly evaluate its effects, and similarly cannot memoize its results! If IO were to eagerly evaluate or to memoize, then we could no longer replace references to the expression with the expression itself, since that would result in a different IO instance to be evaluated separately. This is precisely why scala.concurrent.Future is not a suitable type for encapsulating effects in this way: constructing a Future that will eventually side-effect is itself a side-effect! Future evaluates eagerly (sort of, see below) and memoizes its results, meaning that a println inside of a given Future will only evaluate once, even if the Future is sequenced multiple times. This in turn means that val x = Future(...); f(x, x) is not the same program as f(Future(...), Future(...)), which is the very definition of a violation of referential transparency. Coming back to IO… If program does not evaluate eagerly, then clearly there must be some mechanism for asking it to evaluate. After all, Scala is not like Haskell: we don’t return a value of type IO[Unit] from our main function. IO provides an FFI of sorts for wrapping side-effecting code into pure IO values, so it must also provide an FFI for going in the opposite direction: taking a pure IO value and evaluating its constituent actions as side-effects. program.unsafeRunSync() // uh oh! This function is called unsafeRunSync(). Given an IO[A], the unsafeRunSync() function will give you a value of type A. You should only call this function once, ideally at the very end of your program! (i.e. in your main function) Just as with IO.apply, any expression involving unsafeRunSync() is not referentially transparent. For example: program.unsafeRunSync() program.unsafeRunSync() The above will run program twice. So clearly, referential transparency is out the window whenever we do this, and we cannot expect the normal laws and abstractions to remain sound in the presence of this function. Future’s eager evaluation As Viktor Klang is fond of pointing out, Future doesn’t need to evaluate eagerly. It is possible to define an ExecutionContext in which Future defers its evaluation until some indefinitely later point. However, this is not the default mode of operation for 99% of all Futures ever constructed; most people just use ExecutionContext.global and leave it at that. Additionally, if someone hands me an arbitrary Future, perhaps as a return value from a function, I really have no idea whether or not that Future is secretly running without my consent. In other words, the referential transparency (or lack thereof) of functions that I write using Future is dependent on the runtime configuration of some other function which is hidden from me. That’s not referential transparency anymore. Because we cannot be certain that Future is deferring its evaluation, we must defensively assume that it is not. This, in a nutshell, is precisely why Future is not appropriate for functional programming. IO provides a pair of functions ( fromFuture and unsafeToFuture) for interacting with Future-using APIs, but in general, you should try to stick with IO as much as possible when manipulating effects. Scala runs on three platforms: the JVM, JavaScript and LLVM. For the moment, we’ll just focus on the first two. The JVM has support for multiple threads, but those threads are native (i.e. kernel) threads, meaning that they are relatively expensive to create and maintain in the runtime. They are a very limited resource, sort of like file handles or heap space, and you can’t just write programs which require an unbounded number of them. The exact upper bound on the JVM varies from platform to platform, and varies considerably depending on your GC configuration, but a general rule of thumb is “a few thousand”, where “few” is a small number. In practice, you’re going to want far less threads than that if you want to avoid thrashing your GC, and most applications will divide themselves into a bounded “main” thread pool (usually bounded to exactly the number of CPUs) on which all CPU-bound tasks are performed and most of the program runs, as well as a set of unbounded “blocking” thread pools on which blocking IO actions (such as anything in java.io) are run. When you add NIO worker pools into the mix, the final number of threads in a practical production service is usually around 30-40 on an 8 CPU machine, growing roughly linearly as you add CPUs. Clearly, this is not a very large number. On JavaScript runtimes (such as node or in the browser), the situation is even worse: you have exactly one thread! JavaScript simply doesn’t have multi-threading in any (real) form, and so it’s like the JVM situation, but 30-40x more constraining. For this reason, we need to be very careful when writing Scala to treat threads as an extremely scarce resource. Blocking threads (using mechanisms such as wait, join or CountDownLatch) should be considered absolutely anathema, since it selfishly wastes a very finite and very critical resource, leading to thread starvation and deadlocks. This is very different from how things are in Haskell though! The Haskell runtime is implemented around the concept of green threads, which is to say, emulated concurrency by means of a runtime dispatch lock. Haskell basically creates a global bounded thread pool in the runtime with the same number of threads as your machine has CPUs. On top of that pool, it runs dispatch trampolines that schedule and evict expression evaluation, effectively emulating an arbitrarily large number of “fake” threads atop a small fixed set of “real” threads. So when you write code in Haskell, you generally just assume that threads are extremely cheap and you can have as many of them as you want. Under these circumstances, blocking a thread is not really a big deal (as long as you don’t do it in FFI native code), so there’s no reason to go out of your way to avoid it in abstractions like IO. This presents a bit of a dilemma for cats-effect: we want to provide a practical pure abstraction for encapsulating effects, but we need to run on the JVM and on JavaScript which means we need to provide a way to avoid thread blocking. So, the IO implementation in cats-effect is going to necessarily end up looking very, very different from the one in Haskell, providing a very different set of operations. Specifically, cats.effect.IO provides an additional constructor, async, which allows the construction of IO instances from callback-driven APIs. This is generally referred to as “asynchronous” control flow, as opposed to “synchronous” control flow (represented by the apply constructor). To see how this works, we’re going to need a bit of setup. Consider the following somewhat-realistic NIO API (translated to Scala): trait Response[T] { def onError(t: Throwable): Unit def onSuccess(t: T): Unit } // defined trait Response trait Channel { def sendBytes(chunk: Array[Byte], handler: Response[Unit]): Unit def receiveBytes(handler: Response[Array[Byte]]): Unit } // defined trait Channel This is an asynchronous API. Neither of the functions sendBytes or receiveBytes attempt to block on completion. Instead, they schedule their operations via some underlying mechanism. This interface could be implemented on top of java.io (which is a synchronous API) through the use of an internal thread pool, but most NIO implementations are actually going to delegate their scheduling all the way down to the kernel layer, avoiding the consumption of a precious thread while waiting for the underlying IO – which, in the case of network sockets, may be a very long wait indeed! Wrapping this sort of API in a referentially transparent and uniform fashion is a very important feature of IO, precisely because of Scala’s underlying platform constraints. Clearly, sendBytes and receiveBytes both represent side-effects, but they’re different than println and readLine in that they don’t produce their results in a sequentially returned value. Instead, they take a callback, Response, which will eventually be notified (likely on some other thread!) when the result is available. The IO.async constructor is designed for precisely these situations: def send(c: Channel, chunk: Array[Byte]): IO[Unit] = { IO async { cb => c.sendBytes(chunk, new Response[Unit] { def onError(t: Throwable) = cb(Left(t)) def onSuccess(v: Unit) = cb(Right(())) }) } } // send: (c: Channel, chunk: Array[Byte])cats.effect.IO[Unit] def receive(c: Channel): IO[Array[Byte]] = { IO async { cb => c.receiveBytes(new Response[Array[Byte]] { def onError(t: Throwable) = cb(Left(t)) def onSuccess(chunk: Array[Byte]) = cb(Right(chunk)) }) } } // receive: (c: Channel)cats.effect.IO[Array[Byte]] Obviously, this is a little more daunting than the println examples from earlier, but that’s mostly the fault of the anonymous inner class syntactic ceremony. The IO interaction is actually quite simple! The async constructor takes a function which is handed a callback (represented above by cb in both cases). This callback is itself a function of type Either[Throwable, A] => Unit, where A is the type produced by the IO. So when our Response comes back as onSuccess in the send example, we invoke the callback with a Right(()) since we’re trying to produce an IO[Unit]. When the Response comes back as onSuccess in the receive example, we invoke the callback with Right(chunk), since the IO produces an Array[Byte]. Now remember, IO is still a monad, and IO values constructed with async are perfectly capable of all of the things that “normal”, synchronous IO values are, which means that you can use these values inside for-comprehensions and other conventional composition! This is incredibly, unbelievably nice in practice, because it takes your complex, nested, callback-driven code and flattens it into simple, easy-to-read sequential composition. For example: val c: Channel = null // pretend this is an actual channel for { _ <- send(c, "SYN".getBytes) response <- receive(c) _ <- if (response == "ACK".getBytes) // pretend == works on Array[Byte] IO { println("found the guy!") } else IO { println("no idea what happened, but it wasn't good") } } yield () This is kind of amazing. There’s no thread blocking at all in the above (other than the println blocking on standard output). The receive could take quite a long time to come back to us, and our thread is free to do other things in the interim. Everything is driven by callbacks under the surface, and asynchronous actions can be manipulated just as easily as synchronous ones. Of course, this is an even bigger win on JavaScript, where nearly everything is callback-based, and gigantic, deeply nested chunks of code are not unusual. IO allows you to flatten those deeply nested chunks of code into a nice, clean, linear and sequential formulation. Now there is a caveat here. When our Response handler is invoked by Channel, it is very likely that the callback will be run on a thread which is part of a different thread pool than our main program. Remember from earlier where I described how most well-designed Java services are organized: We definitely want to run nearly everything on that first pool (which is probably ExecutionContext.global), but we’re probably going to receive the Response callback on one of the third pools. So how can we force the rest of our program (including those printlns) back onto the main pool? The answer is the shift function. import scala.concurrent._ implicit val ec = ExecutionContext.global for { _ <- send(c, "SYN".getBytes) response <- receive(c).shift // there's no place like home! _ <- if (response == "ACK".getBytes) // pretend == works on Array[Byte] IO { println("found the guy!") } else IO { println("no idea what happened, but it wasn't good") } } yield () shift’s functionality is a little complicated, but generally speaking, you should think of it as a “force this IO onto this other thread pool” function. Of course, when receive executes, most of its work isn’t done on any thread at all (since it is simply registering a hook with the kernel), and so that work isn’t thread shifted to any pool, main or otherwise. But when receive gets back to us with the network response, the callback will be handled and then immediately thread-shifted back onto the main pool, which is passed implicitly as a parameter to shift (you can also pass this explicitly if you like). This thread-shifting means that all of the subsequent actions within the for-comprehension – which is to say, the continuation of receive(c) – will be run on the ec thread pool, rather than whatever worker pool is used internally by Channel. This is an extremely common use-case in practice, and IO attempts to make it as straightforward as possible. Another possible application of thread shifting is ensuring that a blocking IO action is relocated from the main, CPU-bound thread pool onto one of the pools designated for blocking IO. An example of this would be any interaction with java.io: import java.io.{BufferedReader, FileReader} // import java.io.{BufferedReader, FileReader} def readLines(name: String): IO[Vector[String]] = IO { val reader = new BufferedReader(new FileReader(name)) var back: Vector[String] = Vector.empty try { var line: String = null do { line = reader.readLine() back :+ line } while (line != null) } finally { reader.close() } back } // readLines: (name: String)cats.effect.IO[Vector[String]] for { _ <- IO { println("Name, pls.") } name <- IO { Console.readLine } lines <- readLines("names.txt") _ <- if (lines.contains(name)) IO { println("You're on the list, boss.") } else IO { println("Get outa here!") } } yield () Clearly, readLines is blocking the underlying thread while it waits for the disk to return the file contents to us, and for a large file, we might be blocking the thread for quite a long time! Now if we’re treating our thread pools with respect (as described above), then we probably have a pair of ExecutionContext(s) sitting around in our code somewhere: import java.util.concurrent.Executors implicit val Main = ExecutionContext.global val BlockingFileIO = ExecutionContext.fromExecutor(Executors.newCachedThreadPool()) We want to ensure that readLines runs on the BlockingFileIO pool, while everything else in the for-comprehension runs on Main. How can we achieve this? With shift! for { _ <- IO { println("Name, pls.") } name <- IO { Console.readLine } lines <- readLines("names.txt").shift(BlockingFileIO).shift(Main) _ <- if (lines.contains(name)) IO { println("You're on the list, boss.") } else IO { println("Get outa here!") } } yield () Now we’re definitely in bizarro land. Two calls to shift, one after the other? Let’s break this apart: readLines("names.txt").shift(BlockingFileIO) One of the functions of shift is to take the IO action it is given and relocate that action onto the given thread pool. In the case of receive, this component of shift was meaningless since receive didn’t use a thread under the surface (it was asynchronous!). However, readLines does use a thread under the surface (hint: it was constructed with IO.apply rather than IO.async), and so that work will be relocated onto the BlockingFileIO pool by the above expression. Additionally, the continuation of this work will also be relocated onto the BlockingFileIO pool, and that’s definitely not what we want. The evaluation of the contains function is definitely CPU-bound, and should be run on the Main pool. So we need to shift a second time, but only the continuation of the readLines action, not readLines itself. As it turns out, we can achieve this just by adding the second shift call: readLines("names.txt").shift(BlockingFileIO).shift(Main) Now, readLines will be run on the BlockingFileIO pool, but the continuation of readLines (namely, everything that follows it in the for-comprehension) will be run on Main. This works because shift creates an asynchronous IO that schedules the target action on the given thread pool and invokes its continuation from a callback. The ExecutionContext#execute function should give you an idea of how this works. This means that the result of the first shift is an IO constructed with async, and cannot itself be thread-shifted (unlike an IO constructed with apply), but its continuation can be thread-shifted, which is exactly what happens. This sort of double- shift idiom is very common in production service code that makes use of legacy blocking IO libraries such as java.io. Speaking of asynchrony, readers who have been looking ahead in the class syllabus probably realized that the type signature of unsafeRunSync() is more than a little suspicious. Specifically, it promises to give us an A immediately given an IO[A]; but if that IO[A] is an asynchronous action invoked with a callback, how can it achieve this promise? The answer is that it blocks a thread. (gasp!!!) Under the surface, a CountDownLatch is used to block the calling thread whenever an IO is encountered that was constructed with IO.async. Functionally, this is very similar to the Await.result function in scala.concurrent, and it is just as dangerous. Additionally, it clearly cannot possibly work on JavaScript, since you only have one thread to block! If you try to call unsafeRunSync() on JavaScript with an underlying IO.async, it will just throw an exception rather than deadlock your application. This is not such a great state of affairs. I mean, it works if unsafeRunSync() is being run in test code, or as the last line of your main function, but sometimes we need to interact with legacy code or with Java APIs that weren’t designed for purity. Sometimes, we just have to evaluate our IO actions before “the end of the world”, and when we do that, we don’t want to block any of our precious threads. So IO provides an additional function: unsafeRunAsync. This function takes a callback (of type Either[Throwable, A] => Unit) which it will run when (and if) the IO[A] completes its execution. As the name implies, this function is also not referentially transparent, but unlike unsafeRunSync(), it will not block a thread. As a sidebar that will be important in a few paragraphs, IO also defines a safe function called runAsync which has a very similar signature to unsafeRunAsync, except it returns an IO[Unit]. The IO[Unit] which is returned from this function will not block if you call unsafeRunAsync(). In other words, it is always safe to call unsafeRunSync() on the results of runAsync, even on JavaScript. Another way to look at this is in terms of unsafeRunAsync. You can define unsafeRunAsync in terms of runAsync and unsafeRunSync(): def unsafeRunAsync[A](ioa: IO[A])(cb: Either[Throwable, A] => Unit): Unit = ioa.runAsync(e => IO { cb(e) }).unsafeRunSync() // unsafeRunAsync: [A](ioa: cats.effect.IO[A])(cb: Either[Throwable,A] => Unit)Unit This isn’t the actual definition, but it would be a valid one, and it would run correctly on every platform. As mentioned earlier (about 10000 words ago…), the cats-effect project not only provides a concrete IO type with a lot of nice features, it also provides a set of abstractions characterized by typeclasses and associated laws. These abstractions collectively define what it means to be a type which encapsulates side-effects in a pure fashion, and they are implemented by IO as well as several other types (including fs2.Task and monix.eval.Task). The hierarchy looks like this: Monad and MonadError are of course a part of cats-core, while everything else is in cats-effect. MonadError is functionally equivalent to the familiar scalaz.Catchable typeclass, which was commonly used in conjunction with scalaz.concurrent.Task. It literally means “a monad with error-handling capabilities”. IO certainly fits that description, as any exceptions thrown within its apply method (or within async) will be caught and may be handled in pure code by means of the attempt function. Sync, Async, LiftIO and Effect are the new typeclasses. Sync simply describes the IO.apply function (in the typeclasses, this function is called delay). Which is to say, any type constructor F[_] which has a Sync[F] has the capability to suspend synchronous side-effecting code. Async is very similar to this in that it describes the async function. So any type constructor F[_] which has an Async[F] can suspend asynchronous side-effecting code. LiftIO should be familiar to Haskell veterans, and is broadly useful for defining parametric signatures and composing monad transformer stacks. Effect is where everything is brought together. In addition to being able to suspend synchronous and asynchronous side-effecting code, anything that has an Effect instance may also be asynchronously interpreted into an IO. The way this is specified is using the runAsync function: import cats.effect.{Async, LiftIO, Sync} trait Effect[F[_]] extends Sync[F] with Async[F] with LiftIO[F] { def runAsync[A](fa: F[A])(cb: Either[Throwable, A] => IO[Unit]): IO[Unit] } What this is saying is that any Effect must define the ability to evaluate as a side-effect, but of course, we don’t want to have side-effects in our pure and reasonable code. So how are side-effects purely represented? With IO! From a parametric reasoning standpoint, IO means “here be effects”, and so any type signature which involves IO thus also involves side-effects (well, effects anyway), and any type signature which requires side-effects must also involve IO. This bit of trickery allows us to reason about Effect in a way that would have been much harder if we had defined unsafeRunAsync as a member, and it ensures that downstream projects which write code abstracting over Effect types can do so without using any unsafe functions if they so choose (especially when taken together with the liftIO function). The lack of a production-ready Task-like type fully integrated into the cats ecosystem has been a sticking point for a lot of people considering adopting cats. With the introduction of cats-effect, this should no longer be a problem! As of right now, the only releases are snapshots with hash-based versions, the latest of which can be found in the maven badge at the top of the readme. These snapshots are stable versions (in the repeatable-build sense), but they should not be considered stable, production-ready, future-proof software. We are quickly moving towards a final 0.1 release, which will depend on cats-core and will represent the stable, finalized API. Once cats releases a final 1.0 version, cats-effect will also release version 1.0 which will depend on the corresponding version of cats-core. Changes to cats-effect are expected to be extremely rare, and thus the dependency should be considered quite stable for the purposes of upstream compatibility. Nevertheless, the release and versioning cycle is decoupled from cats-core to account for the possibility that breaking changes may need to be made independent of the cats-core release cycle. Check out the sources! Check out the documentation. Play around with the snapshots, and let us know what you think! Now is the time to make your opinion heard. If IO in its current form doesn’t meet your needs, we want to hear about it! Unless otherwise noted, all content is licensed under a Creative Commons Attribution 3.0 Unported License.Back to blog
https://typelevel.org/blog/2017/05/02/io-monad-for-cats.html
CC-MAIN-2018-39
refinedweb
5,565
54.52
Generating objects from extensions If you need an extension to generate an object in Inkscape, there are many tools that already exist to help you. inkex.py is the most notable, as this provides the routines to insert the SVG element into the XML tree of the SVG document, for more info on these is available at Python modules for extensions. There is currently no universal set of tools to allow a single function to be called, because different extension have different attibutes for thir objects. For example, the barcode extension merely needs a black rectangle with no stroke, but another may need a way to set the stroke width, dashes and opacity. Thus, it is often best to write your own subroutine for generating your objects. A simple example Let's look at a simple Python function for drawing a black rectangle: #SVG element generation routine def draw_SVG_square((w,h), (x,y), parent): style = { 'stroke' : 'none', 'stroke-width' : '1', 'fill' : '#000000' } attribs = { 'style' : simplestyle.formatStyle(style), 'height' : str(h), 'width' : str(w), 'x' : str(x), 'y' : str(y) } circ = inkex.etree.SubElement(parent, inkex.addNS('rect','svg'), attribs ) The first thing to notice is that all the attributes of the object are stored in a dictionary format, with everything being a string. This means you have to convert all your parameters to strings if appropriate (like the height and width attributes). Next, all the style attributes (colours, widths, fonts, etc) are put together in SVG under style. To generate this string, there exists a helper function simplestyle.formatStyle(). You simply feed this function a dictionary of the styles you want, just like the attributes. You can then use this directly as the style attribute. The next thing to see is how to add the element to the XML tree. inkex.py has the function to do this using the LXML parser. This needs to be given the "parent" of the object (we'll come back to this), the "type" of the object, and the attributes of the object. The type of the object is in the svg namespace, which means it begins svg: (for a rectangle, it is svg:rect). LXML cannot parse colons, so we use the inkex.addNS to prepend the namespace. The attributes of the object just needs to be passed the dictionary attribs we made earlier. The "parent" of the object is the containing element. This is usually a group or a layer. This will be passed in by the calling function, and we will see it in action later. When this function is run with the right parameters, the rectangle will be added to the SVG document. Getting the parent Finding the parent is easy: you can just pass in the current layer from the self object if you like: parent = self.current_layer draw_SVG_square((1,1), (0,0), parent) This will just plonk the rectangle into the document, centred on the origin. Alternatively, you can create a group much like any other object: centre = self.view_center #Put in in the centre of the current view grp_transform = 'translate' + str( centre ) grp_name = 'Group Name' grp_attribs = {inkex.addNS('label','inkscape'):grp_name, 'transform':grp_transform } grp = inkex.etree.SubElement(self.current_layer, 'g', grp_attribs)#the group to put everything in By the way, any object can be assigned a name as we did there, which is often helpful when generating many objects: inkex.addNS('label','inkscape') : name By setting the transform as self.view_center, we made sure the origin of the group is in the centre of the current view of the document. We will come back to transforms later. The grp object can now be used as a parent for the rectangle: draw_SVG_square((1,1), (0,0), grp) This will draw a 1×1 black square in the center of the view. Transforms It is easy to transform an object: just supply a string like the folllowing as the transform attribute of the element: - trans = 'translate(10,10)' - trans = 'translate(10,10) rotate(10)' - trans = 'skewX(-1)' Available commands: translate, scale, rotate, skewX, skewY, matrix. The transforms are composed in left-right order (i.e. the translate comes first in the second example). More Examples Ellipses Ellipses are actually path elements, but Inkscape generates the nodes automatically if you feed it the correct attributes in the Sodipodi namespace. The vital ones are rx, ry, cx, cy. Ellipses require some attributes in the sodipodi: namespace, so we also use the addNS() function in the attribute dictionary: def draw_SVG_ellipse((rx, ry), (cx, cy), parent, start_end=0,2*pi),transform='' ): style = { 'stroke' : '#000000', 'stroke-width' : '1', 'fill' : 'none' } ell_attribs = {'style':simplestyle.formatStyle(style), inkex.addNS('cx','sodipodi') :str(cx), inkex.addNS('cy','sodipodi') :str(cy), inkex.addNS('rx','sodipodi') :str(rx), inkex.addNS('ry','sodipodi') :str(ry), inkex.addNS('start','sodipodi') :str(start_end[0]), inkex.addNS('end','sodipodi') :str(start_end[1]), inkex.addNS('open','sodipodi') :'true', #all ellipse sectors we will draw are open inkex.addNS('type','sodipodi') :'arc', 'transform' :transform } ell = inkex.etree.SubElement(parent, inkex.addNS('path','svg'), ell_attribs ) This will draw an open arc, with a black stroke of width 1 and no fill. The transform here can be passed in from outside. If in doubt about the right attribute name and format, just check a similar object in the XML viewer in Inkscape. Line Segment Paths can be quite tricky to get the hang of if you don't know the meaning of the letters. Read the SVG specification for a full list. Here, the style information has been passed in from outside the function. #draw an SVG line segment between the given (raw) points def draw_SVG_line( (x1, y1), (x2, y2), style, name, parent): line_style = { 'stroke': style.l_col, 'stroke-width':str(style.l_th), 'fill': style.l_fill } line_attribs = {'style' : simplestyle.formatStyle(line_style), inkex.addNS('label','inkscape') : name, 'd' : 'M '+str(x1)+','+str(y1)+' L '+str(x2)+','+str(y2)} line = inkex.etree.SubElement(parent, inkex.addNS('path','svg'), line_attribs )
https://wiki.inkscape.org/wiki/Generating_objects_from_extensions
CC-MAIN-2021-39
refinedweb
989
64.81
ztv - astronomical image viewerztv - astronomical image viewer ztv is an astronomical image viewer designed to be used from a python command line for display and analysis. ztv is useful as-is for display and simple analysis of images already loaded in to numpy arrays, as well as FITS files. It can display the most recently acquired image by watching a directory for new FITS files to appear or watching a single FITS file for when it changes. It can also receive new images via an ActiveMQ message stream. ztv is intended for real-time display and analysis. ztv is not intended to produce publication quality figures. ztv comes with a number of built-in control panels, for: - selecting input source (FITS file, auto-reload from FITS file, etc) - selecting a frame to subtract (e.g. sky or dark) and a flat field frame to divide by - setting colormap, stretch, and lower/upper limits - doing basic slice plots, statistics, and aperture photometry. Additional panels can be written and added, for e.g. controlling a camera. (One example add-on panel is included that generates faked images in the FITS format.) If proper FITS header keywords are available, ztv will display the ra/dec of the cursor point. Examples of usageExamples of usage To launch: import ztv z = ztv.ZTV() To load an image in a numpy array: import numpy as np im = np.random.normal(size=[10, 256, 256]) # create a 3-d image stack z.load(im) You can now look at your data, manipulate display parameters, etc all using the gui elements. All of these elements are accessible through the tabbed control panels. You can also switch amongst the control panel tabs by cmd-alt-# where # is the number of the panel, starting from 1. Or, by cmd-[ and cmd-] to move left/right amongst the tabs. You can even switch tabs from the command line api, e.g.: z.control_panel('Color') To change cursor mode, press cmd-# where # is the number shown in the pop-up menu that's available by right-clicking in the primary image area: To manipulate display parameters: z.cmap('gist_heat') z.minmax(0., 4.) z.scaling('Sqrt') z.xy_center(100, 100) z.zoom(5.) To set up a statistics box and see the GUI output (note that output is also returned to your command line as a dict): z.stats_box(xrange=[80, 100], yrange=[100,120], show_overplot=True) z.control_panel('Stats') There's a lot more you can do from the command line if you play with ztv, especially in an exploration-friendly environment like ipython. And, anything you can do from the command line can be done from the GUI. Download an iconic FITS image from the web and display it: from urllib import urlopen from zipfile import ZipFile from StringIO import StringIO remote_url = '' local_filename = '/tmp/hst-eagle-nebula-656nmos.fits' zip = ZipFile(StringIO(urlopen(remote_url).read())) zip_filename = zip.filelist[0].filename open(local_filename, 'w').write(zip.open(zip_filename).read()) z.load(local_filename) z.scaling('Log') z.minmax(0, 500) We can even do a little aperture photometry while we're here: z.cmap('gray') z.xy_center(624, 524) z.zoom(4) z.minmax(0, 1000) z.scaling('Asinh') z.control_panel('phot') z.aperture_phot(xclick=614, yclick=516, show_overplot=True) And, of course, you can adjust the window size to suit your needs, either smaller: or larger: Example of an Add-on Control PanelExample of an Add-on Control Panel One of the motivating use cases for ztv was real-time quick-look of incoming images and the ability to extend the basic installation, including instrumentat control. An example of this is that ztv will be used to both control and inspect the images from a slit viewing camera on a spectrograph of mine. To demonstrate this extensibility, there's a simple example in ztv_examples/fits_faker_panel/: from ztv_examples.fits_faker_panel.launch_ztv import launch_ztv z = launch_ztv() z.start_fits_faker() Our fake example data looks a lot better when we subtract the sky and divide the flat field (someone needs to blow the dust off that fake dewar window...): z.control_panel('Source') z.sky_frame(True) z.flat_frame(True) Installation and DependenciesInstallation and Dependencies ztv uses several packages, including wxPython, astropy. These should be automatically installed if you install ztv from pypi with: pip install ztv You can also grab source code from github. Note that ztv was developed and tested on OS X. Example of installation using Mac OS X's included PythonExample of installation using Mac OS X's included Python The following steps worked on a fresh install of OS X Yosemite 10.10.5 on 2015-09-06: - Install Xcode from the App Store - Launch Xcode one time to accept licenses - Install pip and other necessary python packages Run following command lines in a terminal: curl -o ~/Downloads/get-pip.py sudo -H python ~/Downloads/get-pip.py sudo -H pip install matplotlib sudo -H pip install astropy sudo -H pip install astropy-helpers - Install wxPython version 3 - Download OS X cocoa version of wxPython version 3 from here (was wxPython3.0-osx-docs-demos-3.0.2.0-cocoa-py2.7.dmg at time of writing) - Open disk image and install with the following command line command: (This is necessary because package isn't properly signed & is an old-style package, see here. Obviously may need to update exact file path to the pkg.) sudo installer -pkg /Volumes/wxPython3.0-osx-3.0.2.0-cocoa-py2.7/wxPython3.0-osx-cocoa-py2.7.pkg -target / Finally, install ztv: sudo -H pip install ztv Example of installation into anaconda python distributionExample of installation into anaconda python distribution The following was tested on a fresh install of OS X 10.10.5 on 2015-09-08. Install Xcode from the App Store and launch Xcode one time to accept its licenses. Download Anaconda-2.3.0-MacOSX-x86_64.sh from here. bash Anaconda-2.3.0-MacOSX-x86_64.sh source ~/.bash_profile conda create --name ztv-test wxpython matplotlib source activate ztv-test pip install ztv Example of installation into a Homebrew python distributionExample of installation into a Homebrew python distribution The following was tested on a fresh install of OS X 10.10.5 on 2015-09-07. Install Xcode from the App Store and launch Xcode one time to accept its licenses. Install Homebrew with the one-line ruby command on Homebrew's home page Install python & other necessary bits with the following commands. brew install python brew install wxpython pip install numpy pip install ztv Note that numpy is explicitly installed first using pip install numpy before ztv is installed. During testing on OS X 10.10.5 on 2015-09-07 allowing the numpy dependency to be automatically filled by pip install ztv resulted in an installation error that does not occur if you follow the above sequence. Linux/UbuntuLinux/Ubuntu I tested briefly on Ubuntu 14.04. ztv basically works, although the pulldown colormap menus will not have bitmaps of the colormaps. Also, (at least on my testing virtual machine) the performance of ztv was much laggier than on my main OS X laptop. For the colormaps you could try looking at this link, but it didn't work on my test system. BackgroundBackground In graduate school in the late 1990's I learned IDL and used Aaron Barth's ATV extensively. I even contributed a little to a now-outdated version of ATV, adding 3-d image stack capability. ATV was and is incredibly useful for quick-looks at image data, analysis, and all the things you want when working with typical astronomical image data. After graduate school I began migrating toward python and away from IDL. I've written about this choice elsewhere, but some of the basic reasons were to avoid IDL licensing issues and being beholden to one company. (To be fair, how much I pay every year to keep my IDL license current has always been reasonable. It helps that my license has some obscure history to it that makes the maintenance fees moderate. But, at any time they could raise the prices on me massively. And, I wanted to use a language that could effectively be on every machine I touch, from my main laptop to an embedded server.) In python there are already a multitude of possible image viewers. Many of which are great and can do much of what I needed. (See next section for some links.) But, inevitably as I've played with them I've found they each doesn't scratch my itch in some way. I wanted something that worked exactly the way I wanted, with the right (for me) mix of complexity and simplicity. I need day-to-day image quicklook from the python command-line, e.g. while I'm developing some new image processing algorithm or to check on last night's data. But, I also need to be able to easily adapt my viewer to other situations, including real-time use on a slit-viewing camera, quick-reduction of incoming data, etc.. So, I wrote ztv. The name ztv is an obvious play off of ATV. And, "z" is my daughter's middle initial. Other Image Viewers You Should Check OutOther Image Viewers You Should Check Out - If you're using IDL, check out ATV of course! - SAOImage DS9 - Aladin Desktop Sky Atlas (not primarily an image viewer, but can open FITS files and overlay catalogs and other images nicely) - ginga - Toyz (If your favorite isn't on this list, please email hroe@hroe.me to get it added.) AcknowledgementsAcknowledgements Thank you to Aaron Barth for his original ATV. Thank you to all the numerous people who have put so much effort in to all the packages that make my work not only easier but possible. I especially thank the developers of astropy and its associated packages. e.g. It's an amazing thing to do correct FITS coordinate conversions in one line of code. AuthorAuthor Henry Roe (hroe@hroe.me) LicenseLicense ztv is licensed under the MIT License, see LICENSE.txt. Basically, feel free to use any or all of this code in any way. But, no warranties, guarantees, etc etc..
https://libraries.io/pypi/ztv
CC-MAIN-2022-40
refinedweb
1,708
55.24
Feeling the closing action of human body, within the measurable scope with distance measurement sensor, the collected infrared intensity will affect its own resistance and to change the output voltage value. The processor decides whether to open the garbage can or not and the direction to open to accept the rubbish through judging the output voltage. Sharp 2y0a21 model measurement sensor is a distance measurement sensor based on PSD. Through changing the resistance according to the temperature of the outside environment by its thermal resistance in the circuit, change the voltage of both ends of the sensor. But the there is a certain scope that the thermal resistance measures the distance according the change of the temperature, and the measuring scope of sharp 2y0a21 is 10~80cm. Within the scope of around 0~8cm, the temperature is proportional nonlinear relationship with the distance, and within the scope of around 10~80cm, it is proportional inverse nonlinear relation with the distance, and the mean consumption is around 30mA, and the reaction time is around 5ms, and it has a strong adaptability to the background and the temperature. The effective measurement angle is bigger than 40 degrees, and the output signal is analog voltage. The steering engine is a kind of deck machinery on ship. The size of the steering gear depends on the outfitting according to the standard of classification society. When select the shape, you should mainly consider the torque size. The steering gear is widely used in aerospace. In the field of space, the pitching, yawing, and rolling motions of missile attitude transformation are done with the cooperation of the steering gear. Steering gear is used in many engineering applications, not just limited in the ship. Steering gear is mainly composed of the shell, circuit board, no-core motor, gears and position detector. Its work principle is that the receiver sends signal to the steering gear, and through the judgment of rotation of the IC on the circuit board, drive the no-core motor to start turning, and transmit the power to the swing arm through the reduction gear, at the same time, the position detector returns signal to judge whether it has reached the position. The maximum rotation angle of MG996R is 180 degrees. When programming, the rotating angle range is(0~180 degrees). The distance measurement sensor induces the infrared intensity on both sides, and send the value to the core chip. The core chip determines the rotating angle of the steering gear through dueling with this data, to determine whether the garbage should open the door, and which door to open. Because the rotating angle of the steering gear is 0~180 degree, you'd better place the equilibrium position in the center of the rotating angle of the steering gear. The principle diagram of the installation of the garbage can Distance measurement sensor The characteristics of the distance measurement sensor MG996R steering gear The circuit description of the MG996R steering gear, as shown in the picture. The characteristics of(MG996R). The attachment pin of Microduino servo-cin. In this program, define the pins of the steering gear, corresponding to one pin in one Microduino-Sensorhub slot (there are two pins in one slot), and the farer end away from the board is the pin with smaller number. Stack Microduino Core and Microduino USBTTLtogether, and use USB cable to upload the completed program to Microduino Core through Microduino USBTTL. Open the program, and click the program to compile. After the success of the compilation, choose【port】, 【board】 and 【processor】in 【Tool】. After choosing【board】 and 【processor】, click to upload. The choice of the board The choice of the processor The choice of the port Fix Microduino-Duo-v with screws on the garbage can. Stack modules, and stack Microduino-Core, Microduino-USBTTL, Microduino-BM, Microduino-Duo-v, and Microduino-Sensorhub together(no order). Install the measurement sensor Place the measurement sensors on both sides of the garbage can. When fixing, there should be a certain angle between it and the wall. ( around 45 degrees). Fix the word arm on the door of the garbage can. Connect the circuit The instruction of the pins of the slot that the Microduino-Sensorhub needs to connect to. Connect the measurement sensor on the left of the module to A0, and the right to A2. After connecting the steering gear and Microduino servo-cin, connect the connecting line to D4 slot of Microduino-Sensorhub. Install the steering gear Make the rotating axis of the steering gear rotate to the medium(avoiding it rotating only to a direction after being installed). The door of the garbage can is a rotary switch. Place the steering gear and fix it on the rotating axis, to make the rotation of the steering gear spins the door of the garbage can. System testing Connect the computer and the USB interface of the USB board with USB cable, and test the measurement sensors on both sides. Modify the rotating angle of the steering gear in the program, adjust the rotating angle and direction of the steering gear to make it can control the opening direction of the steering gear through the human body induction. The function of debugging the direction of the steering gear is myservo.write(). Just set the rotating angle of the steering gear in the brackets of the function. Note: In the program, the angle can/t be written into negative. #define sensor_vol 300 //sensor_vol core input (the sensor inputs)bigger that this value:hand approaching;smaller that this value:no hand near #define servo_vol 93 //The angle that the steering gear rotates to. /*Why is it 300? The output value of the infrared distance sensor is an analog quantity between 0~5V. The closer the measurement is, the higher the voltage is. This analog is (0~5V)input into A0 and A2 ports of the core module(two analog input ports). Make it convert into the quantity that the compute is able to identify, through the AD converter(ADC), which is called as digital quantity. The digital quantity is 0~1023(5V<-->1023, different ADC has different measurement range). Conversion relation: Input voltage | The quantity of the numbers used in the computer. V | V*1023/5. According to the measurement, when there is no hand approaching, the output voltage of the infrared sensor is 0.3V, and the corresponding number quantity is 0.3*1023/5=61.38 . When there is hand approaching, the output voltage is 1.6V, and the corresponding number quantity is 1.6*1023/5=61.38=327.36. Choose one between the two as the standard to judge whether there is a hand approaching. Think about that can it be changed into 200? Have a try. */ int potpin[2] = { A0, A2 }; //Define the input pins of the sensor. #include "key.h" #include <Servo.h> //Since the steering gear is used, we should load the library file for it. This library file contains various operating instruction for the steering gear, such as myservo.write(). Servo myservo; // create servo object to control a servo int val[2] = {0, 0}; // variable to read the value from the analog pin //The array, is used to store the input values in the two analog input ports(it has been converted to the number between 0~1023). boolean sta[2] = { false, false };//Status flag. False represents the lid is closed, and true represents the lid is open. //Two elements are used because the lid can be open on both side. void setup() { Serial.begin(9600);//Set up the serial port rate to be used to communicate with the computer by serial ports. pinMode(potpin[0], INPUT); pinMode(potpin[1], INPUT); myservo.attach(4); //Set the steering gear's pin as D4 . myservo.write(servo_vol); // //When the steering gear rotates to the angle the servo_vol shows, the garbage can closes the lid. key_init(); } void loop() { //------0--------------------------------------------------------------- val[0] = analogRead(potpin[0]); //The output voltage that is read into the sensor 0 reads the value of the potentiometer (value between 0 and 1023) if((val[0] > sensor_vol) && (sta[0] == false)) //When this voltage > threshold value(there is hand approaching the garbage can) and at this time the lid is closed, open the lid positively. { Serial.println("sta[0]!"); Serial.println("UP"); myservo.write(180); // sets the servo position according to the scaled value sta[0] = true; delay(1000); } if((val[0] < sensor_vol) && (sta[0] == true)) //When this voltage < threshold value(there is no hand approaching) and at this time the lid is open, close the lid. { Serial.println("DOWN"); myservo.write(servo_vol); sta[0] = false; delay(1000); } /*Why need to add sta? The loop function is implemented in cycle. If it is only "rotating when the senor is covered by hand", when the sensor is covered all the time, the lid will constantly reverse. So our logic must be when"the hand cover the sensor" and "at this time the lid is closed",it reverses. */ //------------------------------------ val[1] = analogRead(potpin[1]); // reads the value of the potentiometer (value between 0 and 1023) if((val[1] > sensor_vol) && (sta[1] == false)) { Serial.println("sta[1]!"); Serial.println("UP"); myservo.write(0); // sets the servo position according to the scaled value sta[1] = true; delay(1000); } if((val[1] < sensor_vol) && (sta[1] == true)) { Serial.println("DOWN"); myservo.write(servo_vol); sta[1] = false; delay(1000); } } #include "arduino.h" boolean key_status[NUM_DIGITAL_PINS]; //The keys boolean key_cache[NUM_DIGITAL_PINS]; //Detect the button is released and cache. void key_init() { for(int a = 0; a < NUM_DIGITAL_PINS; a++) { key_status[a] = LOW; key_cache[a] = HIGH; } } boolean key_get(int _key_pin, boolean _key_type) { key_cache[_key_pin] = key_status[_key_pin]; //The cache for judgment key_status[_key_pin] = analogRead(_key_pin) > sensor_vol; //When the trigger switch(_key_type) { case 0: if(!key_status[_key_pin] && key_cache[_key_pin]) // After the press releases return true; else return false; break; case 1: if(key_status[_key_pin] && !key_cache[_key_pin]) //After the press releases return true; else return false; break; } }
http://wiki.microduinoinc.com/Smart_Garbage_Can
CC-MAIN-2019-09
refinedweb
1,656
61.67
DLL hell? Posted at 04:35PM Jun 09, 2009 by nico in General | Comments[5] Automated Porting Difficulties: Run-time failures in roboported FOSS. Posted at 03:23PM Dec 12, 2008 by nico in General | Massively] Technology Underlying the Sun Storage 7000 Series. Posted at 12:54PM Nov 10, 2008 by nico in sunstorage7000 | If | Observing ID mapping with DTrace Want to see how idmapd maps some Windows SID to a Unix UID/GID? The idmap(1M) command does provide some degree of observability via the -v option to the show sub-command, but not nearly enough. Try this DTrace script. The script is not complete, and, most importantly, is not remotely stable, as it uses pid provider probes on internal functions and encodes knowledge of private structures, all of which can change without notice. But it does help a lot! Not only does it help understand operational aspects of ID mapping, but also idmapd's internals. And, happily, it points the way towards a proper, stable USDT provider for idmapd. Folks who've seen the RPE TOI for ID mapping will probably wish that I'd written this months ago, and used it in the TOI presentation :) Running the stress tests on idmapd with this script running produces an enormous amount of output, clearly showing how the asynchronous Active Directory LDAP searches and search results are handled. Posted at 12:28PM Sep 19, 2008 by nico in General | The compromise on abortion that the Republican mavericks should offer. Posted at 03:36PM Sep 04, 2008 by nico in General | Comments[1] Conclusions from the Georgia war Georgia was simply not a defensible route for Europe to energy independence from Russia. Nor could it have been for years more, and because of its remoteness, and unless Turkey wished to have a very active role in NATO (which seems unlikely) then it was bound to stay indefensible for as long as Russia manages to keep up its military (i.e., for the foreseeable future). Therefore Europe has two choices: become a satellite of Russia, or pursue alternatives to natural gas and oil from Russia. To save Europe from subservience to Russia will require the development of new energy sources. Geopolitical plays can only work if backed by willingness to use superior military firepower. Europe clearly lacks the necessary military superiority and will-power, therefore only new nuclear power plants, and new non-Russian/non-OPEC oil and gas sources qualify in the short- to medium-term. So, ramp up nuclear power production (as that's the only alternative fuel with a realistic chance of producing enough additional power in in the short- to medium-term). And, of course, build more terminals to receive oil and LNG tankers would help. But any oil/gas to be received by tanker terminals have got to come from somewhere (and Russia's has got to have an outlet other than Europe). It would help enormously if new oil sources outside OPEC and Russia could be developed, as new friendly supplies would reduce the leverage that Russia has on Europe. That can only be Brazilian, American and Canadian oil. Does Europe have the fortitude to try? Does the U.S. have the leverage to get Europe to try? The big loser here is Europe. Europe now has to choose whether to surrender or struggle for independence. The U.S. probably can't force them. A European surrender to Russia will be slow, and subtle, but real. If Europe surrenders then NATO is over. Funny, that Russia is poised to achieve what the Soviet Union could not. But it isn't funny. And I suspect few citizens of Europe understand, and few that do object; anti-Americanism may have won. The only thing Europe has going for it is that there is much less NIMBYist resistance to nuclear power there than in the U.S. Also, awareness that a power crunch is at hand, and a much more severe one probably coming is starting to sink in around the world (drilling for oil everywhere is now very popular in the U.S., for example, with very large majorities in favor; support for new nuclear power plants is bound to follow as well). As for the environment, I don't for a second believe in anthropogenic global warming, but ocean acidification is much easier to prove, and appears to be real, and is much, much more of an immediate and dire threat to humans than global warming. Regardless of which threat is real, and regardless of how dire, there's only one way to fight global warming/ocean acidification: increase the wealth of Earth's nations, which in the short-term means producing more energy. American rivers were an environmental mess four decades ago, but today the U.S. is one of the cleanest places on Earth. The U.S. cleaned up when its citizens were rich enough that they could manage to care and to set aside wealth for cleaning things up. It follows that the same is true for the rest of the world, and if that's not enough, consider what would happen if the reverse approach is followed instead: miserable human populations that will burn what they have to to survive, the environment be damned. Let us set on a crash course to develop new energy sources, realistic and practical ones, and let us set on a course to promote and develop international commerce like never before. Posted at 01:00PM Aug 12, 2008 by nico in General | Comments[21] Can we map IDs between Unix domains? (e.g, for NFSv4) Today (onnv build 92), no. But there's no reason we couldn't add support for it. Here's how I would do it: - First, map all UIDs and GIDs in foreign Unix domains to S-1-22-3-<domain-RIDs>-<UID> and S-1-22-4-<domain-RIDs>-<UID>. Whence the domain RIDs? Preferably we'd provide a way for each domain to advertise a domain SID. Otherwise we could allow each domain's SID to be configured locally. Or else derive it from the domain's name, e.g., octet_string_to_RIDs(SHA_256(domain_name)). - Second, map all user and group names in foreign Unix to <name>@<domain-name> - Third, use libldap to talk to foreign Unix domains with RFC2307+ schemas. Possibly also add support for using NIS. (Yes, the NIS client allows binding to multiple domains, though, of course, the NIS name service backend uses only one; the yp_match(3NSL) and related functions take an optional NIS domain name argument.) This would require changes to idmapd(1M). I think the code to talk to foreign Unix domains and cast their IDs into our local form should be easy to compartmentalize. idmapd would have to learn how to determine the type of any given domain, and how to find how to talk to it -- this is going to be what most of the surgery on idmapd would be about. I don't know when we might get to this. Maybe an enterprising member of the community could look into implementing this if they are in a hurry. Posted at 02:37PM Jun 13, 2008 by nico in General | Comments[1] (destructuring-bind) for XML Plus ça change... Posted at 01:55PM Jan 11, 2008 by nico in General | More on the design and implementation of Solaris' ID mapping facility, part 1: kernel-land. Posted at 04:05PM Nov 13, 2007 by nico in General | Comments[1] Another CIFS server topic to blog about: Filesystem I18N? Posted at 05:47PM Nov 07, 2007 by nico in General | Dealing with Windows SIDs in Solaris, part 2 As described in my first post on this subject, Solaris can now map SIDs to POSIX UIDs/GIDs and back, and it can store SIDs in ZFS. The identity models of Windows and Solaris are now unified, and the ACL model of ZFS has been extended. And we have a unified administration of SMB and NFS shares. Wow. I find this exciting, and not just because I've worked on parts of this story. In this post I want to walk through the identity mapping facility's design. Next I'll talk about implementation, and then about how to use the facility. Design of the Solaris ID mapping facility The salient points of the design of the ID mapping facility are: /var/idmap/idmap.db-- contains persistent name-based ID mapping rules /var/run/idmap/idmap.db-- caches Windows name<->SID lookups, ID mappings and ephemeral ID allocations - ephemeral ID mapping, where we dynamically allocate the next available UID or GID from the erstwhile negative uid_t/gid_t namespace (uid_t and gid_t are now unsigned), but we forget these mappings on reboot (see part 1 for more) - name-based ID mapping, where the sysadmin provides rules for mapping Windows users and groups to Solaris users and groups; these rules use names and wildcards, not SIDs and UIDs/GIDs. - idmap_reg() to register idmapd's door; besides a door fd argument there's a boolean that tells the kernel whether idmapd was unable to open/recover /var/run/idmap/idmap.db(see below) - idmap_unreg(), which is called when idmapd exits cleanly - allocids(), which allocates a number of ephemeral UIDs and GIDs for idmapd to use for dynamic ID allocation I've run out of time. I'll cover implementation details next. Posted at 04:17PM Nov 07, 2007 by nico in General |: - proper interaction of SMB share modes, file locks and oplocks with NFSv4equivalents - proper integration with Solaris administration utilities (e.g., sharemgr(1M)) - support for case- and Unicode normalization-insensitive but case- and normalization preserving filesystems (yes, we now have Unicode normalization code in the kernel!) - integration of the Solaris and Windows identity models - filesystem support for the integrated identity model, as well as extended ACLs to support Windows ACL features - etcetera That is a very significant list! A lot of work went into this project and related sub-projects. I'll be blogging about the integration of the Solaris and Windows identity models, both in this post and subsequent ones. Solaris has distinct, small, flat user and group identity namespaces (POSIX UIDs and GIDs). Windows has a unified, practically unlimited, and non-flat namespace for user and group identities (SIDs). There's a very high impedance mismatch there! We knew we'd need to map between these two models, so we started a project to do that. We needed to be able to map any valid SID in an AD forest to a Unix UID and/or GID, as needed. And we needed such a system to be low-configuration, easy to use, and safe. Mapping between these models isn't hard, it's the other requirements that were challenging to tackle. Initially we pursued a notion of persistent dynamic mappings within each Unix (NIS/NIS+/native LDAP) domain, but Mike Shapiro helped us simplify things greatly with an outside-the-box idea: use the heretofore unused "negative" UID/GID namespaces for ephemeral dynamic ID mapping, thus removing two big problems with our earlier design (the need to configure a pool of IDs and the reliability issues associated with having to persistently store important mappings). "Negative UID/GID namespaces", you ask? Until now uid_t and gid_t have been signed 32-bit integers in Solaris, but the relevant standards (POSIX, SUS) require UIDs and GIDs to be positive integers, which means that we wasted almost half of the uid_t/gid_t namespace. Mike's insight was that we could use that wasted ID namespace as a pool of IDs that we can dynamically allocate IDs from, resetting the pool at boot time, and that this wouldn't be too expensive in terms of incompatibility (more on that below). So we changed the uid_t and gid_t types, and we reserved the 2^31..2^32-2 ID namespace for Solaris-driven allocation (i.e., customers cannot assign these IDs directly). ID mapping then works as follows: - there is an ID mapping service, svc:/system/idmap:default - the idmap service is accessed via RPC over doors only (i.e., it's a local service) - by default the idmap service validates SIDs and maps them to the next available 'ephemeral' UID or GID, and this mapping persists until the system reboots (more on this below) - the mapping service also offers name-based ID mapping, where you can map Windows domain users and groups to Unix users and groups by name - the consumers are: the SMB server in the kernel and in user-land utilities, the NFSv4 user-land nfsmapid daemon, the kernel ksid*() functions (which are called from cr*() kernel functions that deal with cred_t), and the idmap(1M) utility Now, using ephemeral IDs in the erstwhile negative ID space has some implications. First and foremost: ephemeral IDs must not be persistently stored anywhere, including in filesystem objects. Because that is far too restrictive the Solaris VFS and one filesystem, ZFS, have been modified to support storing SIDs instead of ephemeral IDs (the other filesystems simply reject any attempt to store an ephemeral ID). You read that right: ZFS can now use SIDs in ACL entries! Most applications will already do the Right Thing -- either reject or pass through ephemeral IDs -- and those core Solaris apps that needed modification have been modified. C++ mangled symbols for methods that take uid_t or gid_t arguments will change on recompile (this was deemed acceptable). For more information you should see the ARC case that covers ephemeral IDs (which will be available soon, as I understand it). By the way, I think Solaris may now be the first non-Windows implementation of NFSv4 that supports the use of user/group names from many domains on the wire! Next up: current limitations of ID mapping, ongoing sub-projects, and a guided tour of the source. The impatient can start by looking at: - the local door RPC protocol used between the kernel/utilities/nfsmapid and idmapd - the idmap kernel module - the idmap daemon - the idmap(1M) utility - kernel code related to SIDs and cred_t - and related header files in $SRC/uts/common/sys Posted at 04:19PM Nov 06, 2007 by nico in General | Comments[4] Phishing as a man-in-the-middle kind of attack I gave a presentation to the Liberty Staff yesterday about Phishing as an MITM attack, and what can be done about it. I think it went very well, and I'm very excited that I'll be meeting people I didn't know who are working in this space, and that we could have a significant impact on the future of web authentication and in ridding us of phishers. I don't have enough time to give this topic a complete treatment in this blog entry, so I'll stick to a very short summary. The Internet-Drafts and links to them that are relevant here are linked to in earlier blog entries of mine. Rest assured though, I will be writing more link-rich blog entries about this topic soon enough, and I'll post my presentation once I add a few more slides (mostly to include relevant links and to give credit where it's due -- I had to limit myself to two slides for the presentation itself!). The gist of this presentation was: phishing is not about stealing passwords, it is about stealing our money -- passwords are gravy to a phisher. If we replace cleartext passwords in HTML forms POSTed over https as our predominant method of web authentication, but aren't careful enough to defeat MITM attacks then phishers will still be in business, and they'll still steal our money. Note that there are practical MITM attacks that phishers can and do mount that are not on-path attacks (i.e., the phisher need not be in the route path from the client to the server) -- think of URLS like "". It's crucial that we understand that neither DNS registrars nor certificate authorities care to help, nor are they in a position to help us defeat phishing. Here's where Project Liberty comes in: federations, by dint of being much smaller than the Internet as a whole, Besides the message that federated mutual authentication provides a mechanism to keep phishers out, there's also the issue of ensuring that there are no practical MITM attacks left to phishers. This is where channel binding comes in. If authentication happens about the HTTP/TLS layer, then we need to make sure that the server we think we're talking to at that layer is the same as the one at the HTTP/TLS layer, or we have to make sure that all messages to the server are additionally proteted about the HTTP/TLS layer (this last is never going to happen). So either we push authentication down the stack, to the HTTP/TLS layer, or we need to provide some way to bind web authentication to the HTTP/TLS "channel." I described several ways to do the channel binding and mutual authentication. Credit for these ideas, by the way, goes to Sam Hartman, Leif Johansson, and the IETF usual suspects who helped refine them (Jeff Hutzelman, Jeff Altman, Love Hörnquist, RL "Bob" Morgan, and Lisa Dusseault, Chris Newman, and many others). Posted at 11:51AM Oct 11, 2007 by nico in General | Comments[1]
http://blogs.sun.com/nico/
crawl-002
refinedweb
2,901
57.1
When a web site gets more requests than it can handle it can become slow and unresponsive. In the worst case too many requests to a web site can cause the server to completely overload, stop handling requests and possibly even crash. This can be a problem for any kind of server application, not just Zope. The obvious solution to this problem is to use more than one computer, so in case one computer fails, another computer can continue to serve up your web site. Using multiple computers has obvious benefits, but it also has some drawbacks. For example, if you had five computers running Zope then you must ensure that all five Zope installations have the same information on them. This is not a very hard task if you're the only user and you have only a few static objects, but for large organizations with thousands of rapidly changing objects, keeping five separate Zope installations synchronized manually would be a nightmare. To solve this problem, Zope Corporation created. ZEO is a system that allows you to run your site on more than one computer. This is often called clustering and load balancing. By running Zope on multiple computers, you can spread the requests evenly around and add more computers as the number of requests grows. Further, if one computer fails or crashes, other computers can still service requests while you fix the broken one. ZEO runs Zope on multiple computers and takes care of making sure all the Zope installations share the exact same database at all times. ZEO uses a client/server architecture. The Zope installations on multiple computers are the ZEO Clients. All of the clients connect to one, central ZEO Storage Server, as shown in Figure 11-1. Figure 11-1 Simple ZEO illustration The terminology can be a bit confusing, because normally you think of Zope as a server, not a client. When using ZEO, your Zope processes act as both servers (for web requests) and clients (for data from the ZEO server). ZEO clients and servers communicate using standard Internet protocols, so they can be in the same room or in different countries. ZEO, in fact, can distribute a Zope site all over the world. In this chapter we'll explore some interesting ways you can distribute your ZEO clients. ZEO serves many hits in a fail-safe way. If your site does not get millions of hits, then you probably don't need ZEO. There is no hard-and-fast rule about when you should and should not use ZEO, but for the most part you should not need to run ZEO unless: All of these cases are fairly advanced, high-end uses of Zope. Installing, configuring, and maintaining systems like these requires advanced system administration knowledge and resources.. The most common ZEO setup is one ZEO server and multiple ZEO clients. Before installing and configuring ZEO though, consider the following issues: ZEO is not distributed with Zope, you must download it from the Products Section of Zope.org. Installing ZEO requires a little bit of manual preparation. To install ZEO, download the ZEO-1.0.tgz from the Zope.org web site and place it in your Zope installation directory. Now, unpack the tarball. On Unix, this can be done with the following command: $ tar -zxf ZEO-1.0.tgz On Windows, you can unpack the archive with WinZip. Before installing ZEO, make sure you back up your Zope system first. Now you should have a ZEO-1.0 directory. Next, you have to copy some files into your Zope top level lib/python directory. This can be done on UNIX with: $ cp -R ZEO-1.0/ZEO lib/python If you're running windows, you can use the following DOS commands to copy your ZEO files: C:\...Zope\>xcopy ZEO-1.0\* lib\python /S Now, you have to create a special file in your Zope root directory called custom_zodb.py. In that file, put the following python code: import ZEO.ClientStorage Storage=ZEO.ClientStorage.ClientStorage(('localhost',7700)) This will configure your Zope to run as a ZEO client. If you pass ClientStorage a tuple, as this code does, the tuple must have two elements, a string which contains the address to the server, and the port that the server is listening on. In this example, we're going to show you how to run both the clients and the servers on the same machine, so the machine name is set to localhost. Now, you have ZEO properly configured to run on one computer. Try it out by first starting the server. Go to your Zope top level directory in a terminal window or DOS box and type: python lib/python/ZEO/start.py -p 7700 This will start the ZEO server listening on click on Database Managment. Here, you see that Zope is connected to a ZEO Storage and that its state is connected. Running ZEO on one computer is a great way to familiarize yourself with ZEO and how it works. Running ZEO on one computer does not, however, improve the speed of your site, and in fact, it may slow it down just a little. To really get the speed benefits that ZEO provides, you need to run ZEO on several computers, which is explained in the next section. Setting up ZEO to run on multiple computers is very similar to running ZEO on one computer. There are generally two steps, the first step is to start the ZEO server, and the second step is to start one or more ZEO clients. For example, let's say you have four computers. One computer named zooserver will be your ZEO server, and the other three computers, named zeoclient1, zeoclient2 and zeoclient3, will be your ZEO clients. The first step is to run the server on zooserver. To tell your ZEO server to listen on the tcp socket at port 9999 on the zooserver interface, run the server with the start.py script like this: $ python lib/python/ZEO/start.py -p 9999 -h zooserver.zopezoo.org This will start the ZEO server. Now, you can start up your clients by going to each client and configuring each of them with the following custom_zodb.py: import ZEO.ClientStorage Storage=ZEO.ClientStorage.ClientStorage(('zooserver.zopezoo.org',9999)) elaboration in your system. The next section describes why, and how, you distribute the load of your visitors among many computers. In the previous example you have a ZEO server named zooServer and three ZEO clients named zeoclient1, zeoclient2, and zeoclient3. The three ZEO clients are connected to the ZEO server and each client is verified to work properly. Now you have three computers that serve content to your users. The next problem is how to actually spread the incoming web requests evenly among the three ZEO clients. Your users only know about, not zeoclient1, zeoclient2 or zeoclient3. It would be a hassle to tell only some users to use zeoclient1, and others to use zeoclient3, and it wouldn't be very good use of your computing resources. You want to automate, or at least make very easy, the process of evenly distributing requests to your various ZEO clients. There are a number of solutions to this problem, some easy, some advanced, and some expensive. The next section goes over the more common ways of spreading web requests around various computers using different kinds of technology, some of them based on freely-available or commercial software, and some of them based on special hardware. The easiest way to distribute requests across many web servers is to pick from a list of mirrored sites, each of which is a ZEO client. Using this method requires no extra software or hardware, it just requires the maintenance of a list of mirror servers. By presenting your users with a menu of mirrors, they can use to choose which server to use. Note that this method of distributing requests is passive (you have no active control over which clients are used) and voluntary (your users need to make a voluntary choice to use another ZEO client). If your users do not use a mirror, then the requests will go to your ZEO client that serves. If you do not have any administrative control over your mirrors, then this can be a pretty easy solution. If your mirrors go off-line, your users can always choose to come back to the master site which you do have administrative control over and choose a different mirror. On a global level, this method improves performance. Your users can choose to use a server that is geographically closer to them, which probably results in faster access. For example, if your main server was in Portland, Oregon on the west coast of the USA and you had users in London, England, they could choose your London mirror and their request would not have to go half-way across the world and back. To use this method, create a property in your root folder of type lines named "mirror_servers". On each line of this property, put the URL to your various ZEO clients, as shown in Figure 11-2. Figure 11-2 Figure of property with URLs to mirrors Now, add some simple DTML to your site to display a list of your mirrors: <h2>Please choose from the following mirrors: <ul> <dtml-in mirror_servers> <li><a href="&dtml-sequence-item;"><dtml-var sequence-item></a></li> </dtml-in> </ul> This DTML displays a list of all mirrors your users can choose from. When using this model, it is good to name your computers in ways that assist your users in their choice of mirror. For example, if you spread the load geographically, then choose names of countries for your computer names. Alternatively, if you do not want users voluntarily choosing a mirror, you can have the index_html method of your site issue HTTP redirects. For example, use the following code in your site's index_html method: Figure 11-3. Figure 11-3 Load balancing with round-robin DNS. When gets resolved, BIND answers with the address of either zeoclient1, zeoclient2, or zeoclient3 - but in a rotated order every time. For example, one user may resolve and get the address for zeoclient1, and another user may resolve and get the address for zeoclient2. This way your users are spread over the various ZEO clients. This not a perfect load balancing scheme, because DNS resolve information gets cached by the other nameservers on the net. Once a user has resolved to a particular ZEO client, all subsequent requests for that user also go to the same ZEO client. The final result is generally alright, because the total sum of the requests are really spread over your various ZEO clients. One down-side to this solution is that it can take from hours to days for name servers to refresh their cached copy of what they think the address of is. If you are not responsible for the maintenance of your ZEO clients and one fails, then 1/Nth of your users (where N is the number of ZEO clients) will not be able to reach your site until their name server cache refreshes. Configuring your DNS server to do round-robin name resolution is a pretty advanced technique that is not covered in this book. A good reference on how to do this can be found in the Apache Documentation. Distributing the load with round-robin DNS is useful, and cheap, but not 100% effective. DNS servers can have strange caching policies, and you are relying on a particular quirk in the way DNS works to distribute the load. The next section describes a more complex, but much more powerful way of distributing load called Layer 4 Switching. Layer 4 switching lets one computer transparently hand requests to a farm of computers. This is a pretty advanced technique that is beyond the scope of this book, but it is worth pointing out several products that do Layer 4 switching for you. Layer 4 switching involves a switch that, according to your preferences, chooses from a group of ZEO clients whenever a request comes in, as shown in Figure 11-4. Figure 11-4 Illustration of Layer 4 switching There are hardware and software Layer 4 switches. There are a number of software solutions, but one in general that stands out is the Linux Virtual Server (LVS). This is an extension to the free Linux operating system that lets you turn a Linux computer into a Layer 4 switch. More information on the LVS can be found on its. Without ZEO, your entire Zope system is a single point of failure. ZEO allows you to spread that point of failure around to many different computers. If one of your ZEO clients fails, other clients can answer requests on the failed clients behalf. Note that as of this writing, the single point of failure can't be entirely eliminated, because there is still one central storage server. The methods described in this section, however, do minimize the risks of failure by spreading most of Zope across many computers. What this means is that, while this does remove a lot of risk away from your web servers as a single point of failure, it does not eliminate all risk because now the ZEO server is a single point of failure. There are several ways of dealing with this issue. One popular method is to accept the single point of failure risk and mitigate that risk as much as possible by using very high-end, reliable equipment for your ZEO server, frequently backing up your data, and using inexpensive, off-the-shelf hardware for your ZEO clients. By investing the bulk of your infrastructure budget on making your ZEO server rock solid (redundant power supplies, RAID, and other fail-safe methods) you can be pretty well assured that your ZEO server will remain up, even if a handful of your inexpensive ZEO clients fail. Some applications, however, require absolute 100% up-time. There is still a chance, with the solution described above, that your ZEO server will fail. If this happens, you want a backup ZEO server to jump in and take over for the failed server right away. Like Layer 4 switching, there are a number of products, software and hardware, that help you mitigate this kind of risk. One popular software solution for linux is called fake. Fake is a Linux based utility that can make a backup computer take over for a failed primary computer by "faking out" network addresses. When used in conjunction with monitoring utilities like mon or heartbeat, fake can guarantee almost 100% up-time of your ZEO server and Layer 4 switches. Using fake in this way is beyond the scope of this book. So far, we've explained these techniques for mitigating a single point of failure: The final piece of the puzzle is the ZEO server itself, and where it stores its information. If your primary ZEO server fails, how can your backup ZEO server ensure it has the most recent information that was contained in the primary server? As usual, there are several ways to solve this problem, and they are covered in the next section. Before explaining the details of how the ZEO server works, it is worth understanding some details about how Zope storages work in general. Zope does not save any of its object or information directly to disk. Instead, Zope uses a storage component that takes care of all the details of where objects should be saved. This is a very flexible model, because Zope no longer needs to be concerned about opening files, or reading and writing from databases, or sending data across a network (in the case of ZEO). Each particular storage takes care of that task on Zope's behalf. For example, a plain, stand-alone Zope system can be illustrated in Figure 11-5. Figure 11-5 Zope connected to a filestorage You can see there is one Zope application which plugs into a FileStorage. This storage, as its name implies, saves all of its information to a file on the computer's filesystem. When using ZEO, you simple replace the FileStorage with a ClientStorage, as illustrated in Figure 11-6. Figure 11-6 Zope with a Client Storage and Storage server Instead of saving objects to a file, a ClientStorage sends objects over a network connection to a Storage Server. As you can see in the illustration, the Storage Server uses a FileStorage to save that information to a file on the ZEO server's filesystem. Storages are interchangeable and easy to implement. Because of their interchangeable nature, ZEO Storage Servers can use ZEO ClientStorages to pass on object data to yet another ZEO Storage Server. This is illustrated in Figure 11-7. Figure 11-7 Multi-tiered ZEO system Here, you can see a number of ZEO clients funnel down through three ZEO servers, which in turn act as ZEO clients themselves and funnel down into the final, central ZEO server than saves its information in a FileStorage. Now, that central ZEO server is the single point of failure in the system. If any of your other clients, or intermediate servers fail, the system will still continue to work, but if the central server fails, then you need an alternative. Using fake you can have a back-up storage server strategy, but this method is not very well proven and hasn't been explored by the authors. In the future, ZEO will have a "multiple-server" feature, that allows a group of storage servers to act as a quorum, so if one or more storage servers fail, the remaining servers in the quorum can continue to serve objects. There are a number of advantages to an approaches like these, especially if you are interested in creating a massively distributed network object database. Of course, with any system of advantages, there are some drawbacks as well, which are discussed in the next section. For the most part, running ZEO is exactly like running Zope by itself, but there are a few issues to keep in mind. First, it takes longer for information to be written to the Zope object database. This does not slow down your ability to use Zope (because Zope does not block you during this write operation) but it does increase your chances of getting a ConflictError. Conflict errors happen when two ZEO clients try to write to the same object at the same time. One of the ZEO clients wins the conflict and continues on normally. The other ZEO client looses the conflict and has to try again. Conflict errors should be as infrequent as possible because they could slow down your system. While it's normal to have a few conflict errors (due to the concurrent nature of Zope) it is abnormal to have a lot of conflict errors. The pathological case is when more than one ZEO client tries to write to the same object over and over again very quickly. In this case, there will be lots of conflict errors, and therefore lots of retries. If a ZEO client tries to write to the database three times and gets three conflict errors in a row, then the request is aborted and the data is not written. Because ZEO takes longer to write this information, the chances of getting a ConflictError are higher than if you are not running ZEO. Because of this, ZEO is more write sensitive than running Zope without ZEO. You may have to keep this in mind when you are designing your network or application. As a rule of thumb, more and more frequent writes to the database increase your chances of getting a ConflictError. On the flip side, faster and more reliable network connections and computers lower your chances of getting a ConflictError. By taking these two factors into account, conflict errors can be mostly avoided., and that can be bad news. the capacity of your website. In addition to running ZEO on one computer to get familiarized, we looked at running ZEO on many computers, and various techniques for spreading the load of your visitors among those many computers. ZEO is not a magic bullet solution, and like other system designed to work with many computers, it adds another level of complexity to your web site. This complexity pays off however when you need to serve up lots of dynamic content to your audience.
http://www.faqs.org/docs/ZopeBook/ZEO.html
CC-MAIN-2017-04
refinedweb
3,437
69.11
Your search did not match any results. We suggest you try the following to help find what you're looking for: The Oracle Cloud Infrastructure Tagging enables you to tag resources in any organizational scheme that you choose, so you can better organize, control, manage, and report on cloud resources. Administrators can find, control access, and perform bulk actions on a set of resources identified by tags. Tagging is a platform service and available to all tenants. There is no setup required to enable tagging for a tenancy - you can use it today.. There is no charge for Oracle Cloud Infrastructure Tagging.. A tag key definition defines the schema of a tag, and includes a tag namespace and tag key. There are two types of tags: free-form tags and defined tags. You can tag resources by using the Oracle Cloud Infrastructure console, CLI, or SDK. Tags can also be applied when creating resources. For example, your organization could apply a "cost center" tag when launching new compute instances. Yes. Tagging allows you to easily write scripts that target batches of machines with tags. For example, you could write a script to create backups for only those compute instances that have a tag of Backup=priority.. Yes, you can set tag defaults that require tag keys and specified values to be applied to your resources. For example, you can establish tag defaults to specify that a tag key and its value is Finance.CostCenter=1234. Yes, you can ensure that resources are properly and automatically tagged with a range of searchable metadata. For example, you can automatically tag all resources with the username that created them. You can then search for resources by user, and track costs and usage on a per-user basis. Yes, administrators can specify a list of allowed values for any given tag key. When an end-user attempts to apply a tag to a resource, they select a tag key (e.g. "Environment") and then must enter in a valid entry from a list of values (e.g. "Dev", "Test", "Production"). Applying any other value including an empty string will fail with a validation error and present the user with a list of the valid enumerated values to correct the error. Yes, if you have use permission to the resource and the tag definition, you can modify or remove a tag that has been applied to it. Yes, you can move tag namespaces between compartments. No, if you retire a tag key definition, the tag key definition may not be used on new resources. However, if you have current resources with that tags, they will continue to have the retired tag associated with the resource. You will have to remove the tags individually. Yes. When you start the delete operation, the state of the tag changes to deleting, and tag removal from resources begins. This removal can take up to 48 hours, depending on the number of resources that were tagged and the regions in which those resources reside. Note that you can't restore a deleted tag. After the state of the deleted tag changes to deleted, you can use the same tag name again. Yes. You can use our command line interface to apply tags to resources. You can also use our SDK to automate the management of tags.. Tagging integrates with our Authorization System giving you policy controls to enable restrictions of tag manipulation. Tagging integrates with our Authorization System giving you policy controls to enable restrictions of tag manipulation. The maximum size of a Tag on a resource is 5KB. 10 defined tags maximum per resource can be used for cost tracking. You can tag costs by user, group, project, department or any other metadata that you choose. It varies but it may take up to 4 hours for the cost tracking tag data to show up in MyServices. Go to the MyServices portal and select Account Management from the Dashboard. Then click on the filter link and you should see cost tracking tags in the filter drop down box. The following resources support cost-tracking tags: Oracle Cloud Infrastructure Compute, Web Application Firewall, Database, Autonomous Data Warehouse, Autonomous Transaction Processing, Object Storage, and Block Volumes.
https://www.oracle.com/za/cloud/systems-management/tagging-faq.html
CC-MAIN-2020-45
refinedweb
705
63.59
Next article: Friday Q&A 2012-12-28: What Happens When You Load a Byte of Memory Previous article: Friday Q&A 2012-11-30: Let's Build A Mach-O Executable Tags: cocoa fridayqna objectivec. Introduction I'll use the same definition as Horstmann: a pitfall is code that compiles, links, runs, but doesn't do what you might expect it to. He provides this example, which is just as problematic in Objective-C as it is in C++: if (-0.5 <= x <= 0.5) return 0; A naive reading of this code would be that it checks to see whether x is in the range [-0.5, 0.5]. However, that's not the case. Instead, the comparison gets evaluated like this: if ((-0.5 <= x) <= 0.5) In C, the value of a comparison expression is an int, either 0 or 1, a legacy from when C had no built-in boolean type. It is that 0 or 1, not the value of x, that is compared with 0.5. In effect, the second comparison works as an extremely weirdly phrased negation operator, such that the if statement's body will execute if and only if x is less than -0.5. Nil Comparison Objective-C is highly unusual in that sending messages to nil does nothing and simply returns 0. In nearly every other language you're likely to encounter, the equivalent is either prohibited by the type system or produces a runtime error. This can be both good and bad. Given the subject of the article, we'll concentrate on the bad. First, let's look at equality testing: [nil isEqual: @"string"] Messaging nil returns 0, which in this case is equivalent to NO. That happens to be the correct answer here, so we're off to a good start! However, consider this: [nil isEqual: nil] This also returns NO. It doesn't matter that the argument is the exact same value. The argument's value doesn't matter at all, because messages to nil always return 0 no matter what. So going by isEqual:, nil never equals anything, including itself. Mostly right, but not always. Finally, consider one more permutation with nil: [@"string" isEqual: nil] What does this do? Well, we can't be sure. It may return NO. It may throw an exception. It may simply crash. Passing nil to a method that doesn't explicitly say it's allowed is a bad idea, and isEqual: doesn't say that it accepts nil. Many Cocoa classes also include a compare: method. This takes another object of the same class and returns either NSOrderedAscending, NSOrderedSame, or NSOrderedDescending, to indicate less than, equal, or greater than. What happens if we compare with nil? [nil compare: nil] This returns 0, which happens to be equal to NSOrderedSame. Unlike isEqual:, compare: thinks nil equals nil. Handy! However: [nil compare: @"string"] This also returns NSOrderedSame, which is definitely the wrong answer. compare: will consider nil to be equal to anything and everything. Finally, just like isEqual:, passing nil as the parameter is a bad idea: [@"string" compare: nil] In short, be careful with nil and comparisons. It really just doesn't work right. If there's any chance your code will encounter nil, you must check for and handle it separately before you start doing isEqual: or compare:. Hashing You write a little class to contain some data. You have multiple equivalent instances of this class, so you implement isEqual: so that those instances will be treated as equal. Then you start adding your objects to an NSSet and things start behaving strangely. The set claims to hold multiple objects after you just added one. It can't find stuff you just added. It may even crash or corrupt memory. This can happen if you implement isEqual: but don't implement hash. A lot of Cocoa code requires that if two objects compare as equal, they will also have the same hash. If you only override isEqual:, you violate that requirement. Any time you override isEqual:, always override hash at the same time. For more information, see my article on Implementing Equality and Hashing. Macros Imagine you're writing some unit tests. You have a method that's supposed to return an array containing a single object, so you write a test to verify that: STAssertEqualObjects([obj method], @[ @"expected" ], @"Didn't get the expected array"); This uses the new literals syntax to keep things short. Nice, right? Now we have another method that returns two objects, so we write a test for that: STAssertEqualObjects([obj methodTwo], @[ @"expected1", @"expected2" ], @"Didn't get the expected array"); Suddenly, the code fails to compile and produces completely bizarre errors. What's going on? What's going on is that STAssertEqualObjects is a macro. Macros are expanded by the preprocessor, and the preprocessor is an ancient and fairly dumb program that doesn't know anything about modern Objective-C syntax, or for that matter modern C syntax. The preprocessor splits macro arguments on commas. It's smart enough to know that parentheses can nest, so this is seen as three arguments: Macro(a, (b, c), d) Where the first argument is a, the second is (b, c), and the third is d. However, the preprocessor has no idea that it should do the same thing for [] and {}. With the above macro, the preprocessor sees four arguments: [obj methodTwo] @[ @"expected1" @"expected2 ] @"Didn't get the expected array" This results in completely mangled code that not only doesn't compile, but confuses the compiler beyond the ability to provide understandable diagnostics. The solution is easy, once you know what the problem is. Just parenthesize the literal so the preprocessor treats it as one argument: STAssertEqualObjects([obj methodTwo], (@[ @"expected1", @"expected2" ]), @"Didn't get the expected array"); Unit tests are where I've run into this most frequently, but it can pop up any time there's a macro. Objective-C literals will fall victim, as will C compound literals. Blocks can also be problematic if you use the comma operator within them, which is rare but legal. You can see that Apple thought about this problem with their Block_copy and Block_release macros in /usr/include/Block.h: #define Block_copy(...) ((__typeof(__VA_ARGS__))_Block_copy((const void *)(__VA_ARGS__))) #define Block_release(...) _Block_release((const void *)(__VA_ARGS__)). Property Synthesis Take the following class: @interface MyClass : NSObject { NSString *_myIvar; } @property (copy) NSString *myIvar; @end @implementation MyClass @synthesize myIvar; @end Nothing wrong with this, right? The ivar declaration and @synthesize are a little redundant in this modern age, but do no harm. Unfortunately, this code will silently ignore _myIvar and synthesize a new variable called myIvar, without the leading underscore. If you have code that uses the ivar directly, it will see a different value from code that uses the property. Confusion! The rules for @synthesize variable names are a little weird. If you specify a variable name with @synthesize myIvar = _myIvar;, then of course it uses whatever you specify. If you leave out the variable name, then it synthesizes a variable with the same name as the property. If you leave out @synthesize altogether, then it synthesizes a variable with the same name as the property, but with a leading underscore. Unless you need to support 32-bit Mac, your best bet these days is to just avoid explicitly declaring backing ivars for properties. Let @synthesize create the variable, and if you get the name wrong, you'll get a nice compiler error instead of mysterious behavior. Interrupted System Calls Cocoa code usually sticks to higher level constructs, but sometimes it's useful to drop down a bit and do some POSIX. For example, this code will write some data to a file descriptor: int fd; NSData *data = ...; const char *cursor = [data bytes]; NSUInteger remaining = [data length]; while(remaining > 0) { ssize_t result = write(fd, cursor, remaining); if(result < 0) { NSLog(@"Failed to write data: %s (%d)", strerror(errno), errno); return; } remaining -= result; cursor += result; } However, this can fail, and it will fail strangely and intermittently. POSIX calls like this can be interrupted by signals. Even harmless signals handled elsewhere in the app like SIGCHLD or SIGINFO can cause this. SIGCHLD can occur if you're using NSTask or are otherwise working with subprocesses. When write is interrupted by a signal, it returns -1 and sets errno to EINTR to indicate that the call was interrupted. The above code treats all errors as fatal and will bail out, even though the call just needs to be tried again. The correct code checks for that separately and just retries the call: while(remaining > 0) { ssize_t result = write(fd, cursor, remaining); if(result < 0 && errno == EINTR) { continue; } else if(result < 0) { NSLog(@"Failed to write data: %s (%d)", strerror(errno), errno); return; } remaining -= result; cursor += result; } String Lengths The same string, represented differently, can have different lengths. This is a relatively common but incorrect pattern: write(fd, [string UTF8String], [string length]); The problem is that NSString computes length in terms of UTF-16 code units, while write wants a count of bytes. While the two numbers are equal when the string only contains ASCII (which is why people so frequently get away with writing this incorrect code), they're no longer equal once the string contains non-ASCII characters such as accented characters. Always compute the length of the same representation you're manipulating: const char *cStr = [string UTF8String]; write(fd, cStr, strlen(cStr)); Casting to BOOL Take this bit of code that just checks to see whether an object pointer is nil: - (BOOL)hasObject { return (BOOL)_object; } This works... usually. However, roughly 6% of the time, it will return NO even though _object is not nil. What gives? The BOOL type is, unfortunately, not a boolean. Here's how it's defined: typedef signed char BOOL; This is another bit of unfortunate legacy from the days when C had no boolean type. Cocoa predates C99's _Bool, so it defines its "boolean" type as a signed char, which is just an 8-bit integer. When you cast a pointer to an integer, you just get the numeric value of that pointer. When you cast a pointer to a small integer, you just get the numeric value of the lower bits of that pointer. When the pointer looks like this: ....110011001110000 The BOOL gets this: 01110000 This is not 0, meaning that it evaluates as true, so what's the problem? The problem is when the pointer looks like this: ....110011000000000 Then the BOOL gets this: 00000000 This is 0, also known as NO, even though the pointer wasn't nil. Oops! How often does this happen? There are 256 possible values in the BOOL, only one of which is NO, so we'd naively expect it to happen about 1/256 of the time. However, Objective-C objects are allocated aligned, normally to 16 bytes. This means that the bottom four bits of the pointer are always zero (something that tagged pointers takes advantage of) and there are only four bits of freedom in the resulting BOOL. The odds of getting all zeroes there are about 1/16, or about 6%. To safely implement this method, perform an explicit comparison against nil: - (BOOL)hasObject { return _object != nil; } If you want to get clever and unreadable, you can also use the ! operator twice. This !! construct is sometimes referred to as C's "convert to boolean" operator, although it's just built from parts: - (BOOL)hasObject { return !!_object; } The first ! produces 1 or 0 depending on whether _object is nil, but backwards. The second ! then puts it right, resulting in 1 if _object is not nil, and 0 if it is. You should probably stick to the != nil version. Missing Method Argument Let's say you're implementing a table view data source. You add this to your class's methods: - (id)tableView:(NSTableView *) objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex { return [dataArray objectAtIndex: rowIndex]; } Then you run your app and NSTableView complains that you haven't implemented this method. But it's right there! As usual, the computer is correct. The computer is your friend. Look closer. The first parameter is missing. Why does this even compile? It turns out that Objective-C allows empty selector segments. The above does not declare a method named tableView:objectValueForTableColumn:row: with a missing argument name. It declares a method named tableView::row:, and the first argument is named objectValueForTableColumn. This is a particularly nasty way to typo the name of a method, and if you do it in a context where the compiler can't warn you about the missing method, you may be trying to debug it for a long time. Conclusion Objective-C and Cocoa have plenty of pitfalls ready to trap the unwary programmer. The above is just a sampling. However, it's a good list of things to be careful of. That's it for today! Check back next time for more wacky advice. Friday Q&A is driven by user ideas, in case you didn't already know, so until next time, please send in your ideas for articles! - (const char *)UTF8Stringmethod of NSStringis that it needs to calculate the number of bytes that the string will take in UTF-8 but there is no way to get that information out of there so you need to call strlen, which calculates the same information again, again taking a time of O(n). A method like - (const char *)UTF8String returnedBytes:(* int)byteCountwould be very helpful. You could then rewrite your example as follows: int byteCount; const char *cStr = [string UTF8String returnedBytes:&byteCount]; write(fd, cStr, byteCount); NSMutableArray * result; [result addObject:someObject]; //... add a bunch of objects return [NSArray arrayWithArray:result]; Which returns an empty array. :( -dataUsingEncoding:method is for. It gives you a NSDataobject which encapsulates both the bytes and the length. bealex: The problem only happens if you write i >= 0, and any decent C compiler will warn you that the comparison is always true if you have warnings turned up to decent levels. E.G. If you are in a loop reading/writing gigs of data your app could stay alive well past the intended short cleanup delay. You'd have to watch a flag set by the signal handler to exit the I/O loop for a complete solution. -dataUsingEncodingas well. How much overhead is there to using the NSData wrapper? Also, regarding the “casting objects to BOOL” issue: does this pitfall still hold true when doing something like if(object) {…? I gather C uses int for the comparison happening in the if. What if pointers were longer than the standard int type, would that be a problem then? Are there any platforms where this is the case? error: cast from pointer to smaller type 'BOOL' (aka 'signed char') loses information BOOL x = (BOOL)object; - (NSString *)newString { __block NSString *returnString = nil; dispatch_async(dispatch_get_main_queue(), ^{ returnString = [[NSString alloc] initWithFormat:@"Expensive String"]; }); return returnString; } - When does -newString return? Almost immediately. - When does returnString get initialized? Um, whenever. - When does returnString get released? WAT BOOL foo = ComputeSomething() if (foo == YES) ... Hopefully clang will warn on this one day: <>;. Until then, at least searching your codebase for "== YES" is not so hard. NSMutableArray *result;would give a pointer filled with garbage instead of a valid mutable array object, so adding objects to it and the returning an autoreleased object would fail and most likely crash the app. Is in fact exactly what I would expect, equating nil with an SQL-like concept of no/null value, and that a null value cannot equal anything, not even another null value. It might be the case that result pointer will be garbage, but it might also be nil depending on how it is defined, luck, what type of build, etc. This is the problem with pseudocode, there can be a number of "issues" that aren't really issues at all depending on if we have all the context or not. So we are all simultaneously correct and incorrect :) Add your thoughts, post a comment: Spam and off-topic posts will be deleted without notice. Culprits may be publicly humiliated at my sole discretion.
https://www.mikeash.com/pyblog/friday-qa-2012-12-14-objective-c-pitfalls.html
CC-MAIN-2017-34
refinedweb
2,704
63.09
Re: freebsd and multiprocessing - From: Tim Arnold <a_jtim@xxxxxxxxxxxxx> - Date: Tue, 2 Mar 2010 10:31:50 -0800 (PST) On Mar 2, 12:59 pm, Tim Arnold <a_j...@xxxxxxxxxxxxx> wrote: On Mar 2, 11:52 am, Philip Semanchuk <phi...@xxxxxxxxxxxxx> wrote: On Mar 2, 2010, at 11:31 AM, Tim Arnold wrote:? Hi Tim, I don't use multiprocessing but I've written two low-level IPC packages, one for SysV IPC and the other for POSIX IPC. I think that multiprocessing prefers POSIX IPC (which is where sem_open() comes from). I don't know what it uses if that's not available, but SysV IPC seems a likely alternative. I must emphasize, however, that that's a guess on my part. FreeBSD didn't have POSIX IPC support until 7.0, and that was sort of broken until 7.2. As it happens, I was testing my POSIX IPC code against 7.2 last night and it works just fine. SysV IPC works under FreeBSD 6 (and perhaps earlier versions; 6 is the oldest I've tested). ISTR that by default each message queue is limited to 2048 bytes in total size. 'sysctl kern.ipc' can probably tell you that and may even let you change it. Other than that I can't think of any SysV limitations that might bite you. HTH Philip Hi Philip, Thanks for that information. I wish I could upgrade the machine to 7.2! alas, out of my power. I get the following results from sysctl: % sysctl kern.ipc | grep msg kern.ipc.msgseg: 2048 kern.ipc.msgssz: 8 kern.ipc.msgtql: 40 kern.ipc.msgmnb: 2048 kern.ipc.msgmni: 40 kern.ipc.msgmax: 16384 I'll write some test programs using multiprocessing and see how they go before committing to rewrite my current code. I've also been looking at 'parallel python' although it may have the same issues. thanks again, --Tim Well that didn't work out well. I can't import either Queue or Pool from multiprocessing, so I'm back to the drawing board. I'll see now how parallel python does on freebsd. --Tim . - Follow-Ups: - Re: freebsd and multiprocessing - From: Philip Semanchuk - References: - freebsd and multiprocessing - From: Tim Arnold - Re: freebsd and multiprocessing - From: Philip Semanchuk - Re: freebsd and multiprocessing - From: Tim Arnold - Prev by Date: Re: conditional import into global namespace - Next by Date: Re: Email Script - Previous by thread: Re: freebsd and multiprocessing - Next by thread: Re: freebsd and multiprocessing - Index(es):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2010-03/msg00168.html
CC-MAIN-2013-20
refinedweb
417
76.11
- Code: Select all #!/usr/bin/python import time from Adafruit_I2C import Adafruit_I2C class TMP102 : i2c = None # Constructor def __init__(self, address=0x48, mode=1, debug=False): self.i2c = Adafruit_I2C(address) self.address = address self.debug = debug # Make sure the specified mode is in the appropriate range if ((mode < 0) | (mode > 3)): if (self.debug): print "Invalid Mode: Using STANDARD by default" self.mode = self.__BMP085_STANDARD else: self.mode = mode def readRawTemp(self): "Reads the raw (uncompensated) temperature from the sensor" raw = self.i2c.readU16(0x48) #The TMP102 returns 12-bits, I think if (self.debug): print "DBG: Raw Temp: 0x%04X (%d)" % (raw & 0xFFFF, raw) return raw def readTemperature(self): "Gets the compensated temperature in degrees celcius" RawBytes = self.readRawTemp() #get the temp from readRawTemp (above) temp =float(RawBytes) * (float(0.0625) / 16.0) # dividing by 16 accomplishes the bit-shift if (self.debug): print "DBG: Calibrated temperature = %f C" % temp return temp You can see that it is still based off of the code for the BMP085. I don't know if we have anyone that is really good at stylistic issues. I'm probably going to stick with one way and just consistently write that way, but: Stylistically, should I create a 12-bit read entry in the I2C library, or stick with my current work which creates a new class to handle the behind the scenes math? Is there a way that is more expected? My goal is to have some hardware and software that anyone can use easily. I know that I'm stuck too far into the weeds to see what is easy to use.
http://adafruit.com/forums/viewtopic.php?f=8&t=34626&start=15
CC-MAIN-2013-20
refinedweb
270
66.54
MEF or Managed Extensibility Framework is cool. Firstly, it allows you to decouple your components pretty easily. Secondly, it supports various component discovery scenarios, and enables you to write better frameworks. In this post, I’ll cover few basic aspects of MEF. MEF classes reside in the assembly System.ComponentModel.Composition.dll – Creating plug-in frameworks is quite easy with MEF. The main application can Import plug-ins, marked with an Export attribute. MEF terminology is pretty simple. To start with, you can Export and Import your Parts. A Part is anything you export or import - be it a class, method, or property. Any such composable Part should be attributed with either the Export or Import attributes (You can find those attributes in System.ComponentModel.Composition namespace). For simple scenarios, you may use the Export attribute along with a Contract to mark your part as exportable. Also, you may use the Import attribute to specify where you want to import the available exported parts. MEF will do the back ground work of dynamically discovering information about parts, to resolve and import them where ever you specify, based on the Contracts. This step is called Composing the Parts. MEF discovers information about these parts from various sources, i.e Catalogs, or you may add them directly to the container. For example - you may use an assembly catalog to point MEF to a specific assembly to grab the exported parts from there, a directory catalog to point to a set of assemblies in a folder etc. To make things straight, let us create a simple Zoo example with MEF, and we’ll cover MEF terminologies on the go. Visiting the MEF Zoo Alright, so to start with, assume that you are creating a Zoo application, where Animals can be ‘plugged-in’. I.e, if you are creating a new Animal, you don’t really need to rebuild your zoo. Needless to say – that means, your Animals will be loosely coupled with your Zoo. We have the following projects in our MefZoo solution. - MefZoo.Lib – A simple library for keeping our contracts, to identify parts while exporting and importing them. - MefZoo.Animals – A couple of concrete animals for our Zoo. - MefZoo – Here is where most of the work happens – like grabbing parts from Catalogs, composing them etc. In our MefZoo.Lib project, we’ve a simple IAnimal class. If any one need to create an Animal for your Zoo, IAnimal is the interface or contract they should use, to create their concrete Animal. The IAnimal interface is pretty simple. public interface IAnimal { string Name { get; } } In MefZoo.Animals project, we have a reference to MefZoo.Lib. There we’ve a couple of ‘concrete’ animals. For now, let us have a Lion and Rabbit in our Zoo. If you are curios, here is the Lion and Rabit classes. [Export(typeof(IAnimal))] public class Lion : IAnimal { public string Name { get { return "Lion1"; } } } [Export(typeof(IAnimal))] public class Rabbit : IAnimal { public string Name { get { return "Rabbit1"; } } } If you’ve observed, we are using the Export attribute to ‘export’ our animals, so that they can be ‘imported’ to our Zoo later. Time to visit our MefZoo project. We have a simple Zoo class there – and as you'd expect we’ve a collection of Animals there. public class Zoo { [ImportMany(typeof(IAnimal))] public IEnumerable<IAnimal> Animals { get; set; } } And before we actually discuss about loading animals to the Zoo, you might want to note that we have the build path of MefZoo as ..\bin and that of MefZoo.Lib as ..\bin\Extensions. Essentially, you need to make sure MefZoo.Lib.dll will be under the Extensions folder in MefZoo.exe's path Alright, now it’s time for the main action. Here is the Main method in Program.cs.The Main method simply creates the Zoo object, and pass the same to LoadAnimals. static void Main(string[] args) { Zoo z=new Zoo(); LoadAnimals(z); foreach (var animal in z.Animals) Console.WriteLine(animal.Name); Console.ReadLine(); } As explained earlier, to compose all these parts together, we need to - Specify the catalogs from where these parts are coming. If you have a look at the below code, you’ll find that we are pointing MEF to all libraries under the Extension folder of the main application, and also to the current assembly, for discovering the parts (Remember, anything that is marked with either Export or Import is a Composable Part). - Create a container, and compose the parts static void LoadAnimals(Zoo zoo) { try { //A catalog that can aggregate other catalogs var aggrCatalog = new AggregateCatalog(); //A directory catalog, to load parts from dlls in the Extensions folder var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location) + "\\Extensions", "*.dll"); //An assembly catalog to load information about part from this assembly var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); aggrCatalog.Catalogs.Add(dirCatalog); aggrCatalog.Catalogs.Add(asmCatalog); //Create a container var container = new CompositionContainer(aggrCatalog); //Composing the parts container.ComposeParts(zoo); } catch (Exception ex) { Console.WriteLine(ex.Message); } }At this point, if you run the application, you'll find the following output. Lion1 Rabbit1 Feeding your MEF Animals Now you have the Zoo, obviously the next problem is feeding your animals. For this, we’ll need our animals to make some grumble sound (a call back), to call the attention of zoo keepers. (If you are tired with story telling, this section will show you how to inject a call back mechanism to the loaded Animals). First of all, let us define a GiveFood method in our Zoo class. It is self explanatory. Only thing you might notice is, we are exporting GiveFood method as a part. How ever, we are using "AnimalFood" as the contract name, instead of a type. This is allowed, and valid in MEF – You can either use a string or a type, or both together, as a contract. public class Zoo { [ImportMany(typeof(IAnimal))] public IEnumerable<IAnimal> Animals { get; set; } [Export("AnimalFood")] public string GiveFood(string animalType) { switch (animalType.ToLower()) { case "herbivores": return "GreenGrass"; case "carnivores": return "Readmeat"; default: return "Waste"; } } }Now, we have the facility in our Zoo to give food to Animals. To enable our Animals to consume food, let us extend our IAnimal class a bit. Here is the new IAnimal class - We just added a delegate property, synonymous to the GiveFood method, so that MEF can hook up the GiveFood method later, when importing the exported GiveFood. public interface IAnimal { string Name { get; } Func<string ,string> GiveMeFood { get; set; } } And well, let us re-wire the Lion class a bit, so that the Lion can periodically call back the zoo keeper to request some food. [Export(typeof(IAnimal))] public class Lion : IAnimal { Timer t; //MEF will inject the call back here [Import("AnimalFood")] public Func<string , string> GiveMeFood { get; set; } public string Name { get { return "Lion1"; } } //Let us use a timer to get food and eat it regularly public Lion() { t = new Timer(1000); t.Elapsed += (sender, args) => { string food = GiveMeFood("carnivores"); Console.WriteLine("Lion eating " + food); }; t.Start(); } }Nothing fancy there, we just have a timer there to make the Lion hungry. And let me do the same modifications for rabbit as well. Run the application, and you'll see Rabbit and Lion eating their food (The timer interval for rabbit is lesser than the lion). Also, I just want to point that we havn’t made any modifications to the part composition code, for exporting a call back method for our Animals. One interesting aspect here is, the Zoo can decide what food to supply for each animal (probably based on available stock). And this is an example of how you can use MEF to achieve decoupling even in fine-grained systems. You may also need to visit the official MEF site,
http://www.amazedsaint.com/2009/11/mef-or-managed-extension-framework.html
CC-MAIN-2015-27
refinedweb
1,300
55.34
Creates or opens a job object. HANDLE WINAPI CreateJobObject( __in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCTSTR lpName ); HANDLE WINAPI CreateJobObject( __in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCTSTR lpName ); name space. The object can be created in a private namespace. For more information, see Object Namespaces. Terminal Services: The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces. Windows 2000: If Terminal Services is not running, the "Global\" and "Local\" prefixes are ignored. The remainder of the name can contain any character except the backslash character./2000:. Send comments about this topic to Microsoft Build date: 7/2/2009
http://msdn.microsoft.com/en-us/library/ms682409(VS.85).aspx
crawl-002
refinedweb
125
50.63
This functionality provided by this module is now part of mechanize. I don't intend to make further standalone releases of ClientCookie. Please read this note explaining the relationship between ClientCookie, cookielib and urllib2, and which to use when. Client, automatic observance of robots.txt and lazily- seek()able responses. These extras are implemented using an extension that makes it easier to add new functionality to urllib2. It has developed from a port of Gisle Aas' Perl module HTTP::Cookies, from the libwww-perl library. import ClientCookie response = ClientCookie.urlopen("") This function behaves identically to urllib2.urlopen, except that it deals with cookies automatically. That's probably all you need to know. Python 2.0 or above is required, and urllib2 is recommended. If you have 2.1 or above, you've already got a recent enough version of urllib2. For Python 2.0, you need the newer versions from Python 2.1 (available from the source distribution or Python CVS: urllib2.py). Note that you don't need to replace the original urllib2 / urllib - you can just make sure they're in sys.path ahead of the copies from 2.0's standard library. For full documentation, see here and the docstrings in the module source code. Other than Gisle, particular thanks to Johnny Lee (MSIE Perl code) and Ronald Tschalar (advice on Netscape cookies). urllib2and cookielib Even if you're not using Python 2.4, please note the last of these points. cookieliband extensions to module urllib2. urllib2and cookielibinstead of ClientCookie. I recommend turning on RFC 2965 support to work around a bug in cookielibin Python 2.4.0. urllib2(eg. HTTPRefreshProcessor) may be used with 2.4's urllib2(however, note the paragraph below). With any version of Python, parts of urllib2that are missing from ClientCookie (eg. ProxyHandler) may be used with ClientCookie, and urllib2.Requestobjects may be used with ClientCookie. IMPORTANT: For all other code, use ClientCookie exclusively: do NOT mix use of ClientCookie and urllib2! Finally, note that, if you want to use ClientCookie.RefreshProcessor with Python 2.4's urllib2, you must also use ClientCookie.HTTPRedirectHandler. All documentation (including these web pages) is included in the distribution. To port your code from 0.4.x to 1.0.x, see here. Stable release. Old release. For installation instructions, see the INSTALL file included in the distribution. The Subversion (SVN) trunk is, so to check out the source: svn co ClientCookie Cookie, do this? No: Cookie.py does the server end of the job. It doesn't know when to accept cookies from a server or when to pass them back. 2.0 or above. No. You probably want it, though. You don't, but if you want to use the extended urllib2 callables from ClientCookie, and you have Python 2.0, you need to upgrade to the version from Python 2.1. Otherwise, you're OK. ClientCookie is dual-licensed: you may pick either the BSD license, or the ZPL 2.1 (both are included in the distribution). ClientCookie knows about that, too. I prefer questions and comments to be sent to the mailing list rather than direct to me. John J. Lee, May 2006.
http://wwwsearch.sourceforge.net/old/ClientCookie/
CC-MAIN-2017-04
refinedweb
531
70.8
Follow large sets of icon assets. We needed a technique that works on our supported browsers, looks crisp on HiDPI displays and is easily maintainable. The solution I eventually came to was to create an icon font containing all these icons. Key reasons for using an icon font at Atlassian: - A single source of truth so we never have two versions of the same icon - It can be included in the Atlassian User Interface (AUI), the UI library for all Atlassian product, for easy consumption for all our product teams - It works all the way back to IE7 - Scales up and down so you don’t have to manage normal resolution and @2x resolution assets - Image sprites can be removed for your code base - Less resources to load and a lighter page weight Our new icons Part of the icon font roll out was to overhaul their visual style. The old icons were starting to look a little tired, and with the ADG moving into our products we needed an icon style that would match our design principles. Designing icons is not an easy task. You have 16 pixels to convey a clear metaphor which can be quite challenging. There’s one main topic around icon design that I want to discuss. The conceptual metaphors around icons is a huge topic but for this post I will be focusing on the craft and production side of icon design for an icon font (optimized for 16px) step-by-step. Step 1: Make your icons sharp Before we get into this I wanted to point out the tools I will be using along the way. I’ve got Photoshop and Illustrator CS6 installed along with Glyphs for Mac and for the coding part you can us whatever IDE you prefer. I’ve been using the TextMate 2 alpha version and is my IDE of choice right now. The first and most important thing is to make sure that your anchors snap to a pixel grid. Sometimes, snapping to pixels is not good but generally speaking, your icons will look much sharper if they do. In Photoshop (or Illustrator) this is easy to do: go to the Preferences and turn pixel snapping on/off. I ended up recording an action for it to make the switching a simple click of the mouse. You might consider taking one of the existing icon sets out there like Pictos or Glyphicons instead of creating your own icons. Just be careful when you resize them down to 16px. Designing icons can be very time consuming. The best results will only come from being obsessive with the details. That’s what makes the difference between good icons and great icons. Step 2: Moving from Photoshop/Illustrator to Glyphs I like to make my icons in Photoshop as vector shapes because I feel it gives me more control in a tool I’m familiar with but it’s just a personal preference. Once an icon is created in Photoshop, I then open up the PSD in Illustrator and then copy the shape over to a new Illustrator document that is 1024pts x 1024pts. I’ve left Illustrator to render values at points and not pixels, changing it didn’t make a difference. In Illustrator, your 16px icon is going to look amazing at any size. Make sure you change your viewing mode in Illustrator by going to View > Pixel Preview. This will make Illustrator view your vector like a rasterised image even though it isn’t. Resize the icon up to fill the 1024pts x 1024pts and centre it on the canvas with the x,y co-ordinates at 512pts (assuming you have a 16×16 icon). This shape is what you’ll be copying into Glyphs so make sure that it looks awesome and all your paths are still behaving. If they aren’t, Glyphs will render exactly what you have on screen at 1024pts. Once you’re happy with how the icon looks, copy the shape and head over to Glyphs. Step 3: Setting up Glyphs If you haven’t installed Glyphs yet, you can grab it from the Mac App Store or get a trial from the Glyphs website. Unfortunately it’s only for Mac, but I’m sure there is a Windows equivalent out there. First, create a new font file and then remove all the alphabet characters they pre-fill the font with. We don’t need alphanumeric characters because this is a symbol font. We’ll be using the private use unicode character ranges. If you have a small set of icons that can fit into a normal alphabet then you can use that instead of the unicode ranges. The major advantage of the unicode ranges is that it holds 6,400 possible icons in the private use range which is more than enough for all our products combined. Secondly, make sure the settings under the hood are correct. Go to File > Font Info and you’ll see the settings for the font. Make note of the keyboard short-cut (cmd + i), you’ll be coming back to this settings pane a lot. On the font screen, make sure you fill out: - Font family name - Designer - Date - Set the ‘units per Em’ to 1024 (default is 1000) I hadn’t worked with type design before so I had to research a little and play with the values in Glyphs to get the icons to sit on the right baseline. The values that I have used in Glyphs don’t match the diagram exactly, I think this may just be because of the way Glyphs is calculating it. It doesn’t seem to matter though, the icons render correctly anyway. - Ascender: 832 - Cap height: 768 - X-height: 576 - Descender: -192 We’re using the 1024pts as the direct representation of 16px in the browser. Think of 1px in the browser as 64pts in Glyphs. I found it handy to write out the corresponding pixel amounts for easy math when pushing lots of these icons into the font. In the settings pane is the ‘Other Settings’ tab which has the important grid spacing field. That should be set to 1 to start with. Later on you’ll want to change this value to 64 so you can see the grid that will represent the 16px displayed in the browser. Remember, 1px in the browser is 64pts in Glyphs. Keep using the keyboard shortcut to get back to this window (cmd + i), it saves a lot of time clicking around. The last thing to do in the settings pane is to make sure you’ve checked the checkbox ‘Don’t use nice names’. You won’t be able to enter unicode values for your icons without having this confusing label checked. Step 4: Creating icons in Glyphs Once you’ve followed these steps you can start turning your lovely vectors from Photoshop/Illustrator into unicode mapped icons. Move back to your 1024pt icon in Illustrator that we first resized and copy the whole shape. Move over to Glyphs and add your first character by clicking the ‘+’ button at the bottom of the app. Once the new glyph is selected, change the value of the width in the sidebar from 600 to 1024 and make sure the padding on both sides is set to 0. Now double-click on the new glyph to edit it. Paste (cmd + v) in your copied icon shape from Illustrator. Glyphs will probably prompt you to reset the bounding box, accept the changes. Your icon should now be in Glyphs but not in the position you want. Make sure the whole icon is selected (cmd + a) and then change the x,y coordinates accordingly. This is where that 64pts = 1px post-it note comes in handy. The majority of the time I set the anchor to be in the middle, the Y axis to be 320 and the X axis to be 512. For icons that are 16px x 14px or some other shape, you will need to use the 64pts increments to make it sit where you want. Keep in mind that the whole 16px box will be displayed in the browser. For example, if you have a 12px high icon and position it at the top of the 16px container, it will be 2px off centre when displayed in the browser. If you need to nudge the icon into position, make sure you change the grid spacing back to 1 (cmd + i to view settings). If you leave it at 64 to see the overlay grid and then nudge your icon into position, Glyphs will grab hold of the anchors and your icon will look like the one below. Unfortunately, Glyphs has some pretty bad undo (cmd + z) capabilities so this disaster will not be recoverable with a simple undo. To fix your icon, you’ll have to re-paste the shape in but before you do, set the grid spacing back to 1. Step 5: Maintaining and organising your font Atlassian has several products that have specific icons and we needed a way to organise the font accordingly. The easy way to do it was to namespace the icons and set up filters in the sidebar. The convention I’m using is to separate global, Confluence, JIRA and Dev Tools (Stash, Bitbucket, FishEye, Crucible and Bamboo) icons. For example, the help icon is named ‘aui-global-help’. With the filters set up in the sidebar, viewing a specific set of icons is easy. Unicode ranges Private use unicode ranges from UTF+E001 – U+F8FF which is 6,400 characters so I don’t think we’re going to run out of characters any time soon. The unicode ranges are hexadecimal. The sequence always starts with numbers ‘1’ through ‘9’ and then the letters ‘a’ through ‘f’ (e000, e001, e002, … e009, e00a, e00b, … e00f, e010, e011, etc). In Glyphs you’ll need to specify the unicode values for every icon you add. Do this by selecting the icon and then changing its value in the sidebar. You don’t need to specify the ‘UTF+’ part in Glyphs, only the hexadecimal part. Now that you’ve completed one icon, you can repeat these same steps for all your remaining icons. Step 6: Exporting When you’re happy with your icons in Glyphs you’ll need to export the saved file (cmd + e). Choose OTF from the menu pane, select a location to export to and click ‘Next…’. Glyphs tends to crash every now and then when it runs exports so make sure you’ve saved all your progress. Once the export is successful, navigate to the folder Glyphs has export the font into to convert this OTF file into a web font to use in your application. Making the web font Font Squirrel is a great free service for turning OTF files into web fonts. Go to the web font generator and add your font file. The configuration I used is below: Mode: Expert Formats: ttf, woff, eot, svg Truetype Hinting: Keep existing Subsetting: Custom Unicode ranges: E000-E3FF, EC00-EFFF Make sure you adjust your unicode range to the unicodes you actually use and tick the ‘Remember my settings’ checkbox. Convert the font and then download it to your desktop and you’re ready to put the final touches on it to make your icon font perfect. Step 7: Subpixel rendering of icons The last bit of tuning comes in the browser to make the new icons extra crisp. Using -webkit-font-smoothing: antialiased; on the font makes a big difference. You might not be able to tell on standard screens when you’re entering this in the CSS but have a closer look on an Apple screen to see the difference in Safari and Chrome. The CSS The basic CSS for the small and large icon sizes we have: [cc lang=’css’ ] @font-face { font-family: “Atlassian Icons”; src: url(atlassian-icons.eot); src: url(atlassian-icons.eot?#iefix) format(“embedded-opentype”), url(atlassian-icons.woff) format(“woff”), url(atlassian-icons.ttf) format(“truetype”), url(atlassian-icons.svg#atlassian-icons) format(“svg”); font-weight: normal; font-style: normal; } .aui-icon-small, .aui-icon-large { line-height: 0; position: relative; vertical-align: text-top; } .aui-icon-small { height: 16px; width: 16px; } .aui-icon-large { height: 32px; width: 32px; } .aui-icon-small:before, .aui-icon-large:before { color: inherit; font-family: “Atlassian Icons”; font-weight: normal; -webkit-font-smoothing: antialiased; /* Improves the rendering of icons */ font-style: normal; left: 0; line-height: 1; position: absolute; text-indent: 0; speak: none; /* This prevents screen readers from pronouncing the pseudo element text content used to trigger the icon font */ top: 50%; } .aui-icon-small:before { font-size: 16px; margin-top: -8px; /* (font-size/2) */ } .aui-icon-large:before { font-size: 32px; margin-top: -16px; /* (font-size/2) */ }[/cc] When coding up the classes for the individual icons you’ll need to remember those unicodes from Glyphs that you entered earlier and put the values in as the content. [cc lang=’css’ ] .aui-iconfont-configure:before { content: “\e001”; }[/cc] The HTML markup is specific to Atlassian so feel free to use your own pattern. The text inside of the span is inserted for screen readers but is not displayed on the page. [cc lang=’css’ ] [/cc] You’re all done It may have seemed like a lot of work but after doing a couple of icons it gets much faster. The real time-saver will be in the developer speed when the icons are reused. I’ve already seen big improvements for the Stash team from using the icon font everywhere in our UI. We’ll be adding more icons to the Atlassian icon font as we convert the old icons over for all our products.
https://www.atlassian.com/blog/archives/how-to-make-an-icon-font-the-8-step-guide
CC-MAIN-2017-17
refinedweb
2,312
68.91
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got pretty darn close! I'm impressed with how the community managed to pull together and face the enormous challenge of picking a single alternative (from more than two dozen on the Wiki!) and arguing consistently. I expect to see more proposals like this in the future, and I'm sure that some of them will be good enough to make it into the language. I've also (again) learned a lesson: dramatic changes must be discussed with the community at large. In a large enough group there are no uncontroversial proposals, so this will take time, but it's worth it -- one of the main issues with the @decorator syntax was not technical but socio-political, in the sense that it hadn't been properly discussed outside a *very* small circle. I take the full blame for that, and I don't want to hide behind my current lack of time which, realistically, won't change until either my ESI stock options earn me an early retirement, or the PSF strikes it rich and can pay me full time :-). So let me explain why I'm not choosing J2, and what's next. There are two major issues and one minor that made me decide against J2. Major issue one:. To me, this is a more serious problem than the namespace questions brought up in the proposal (unfortunately that particular section of the proposal is its most confused part; but even if the text had been crystal clear, the problem remains). The best counter-argument to this I've heard is "you'll get used to it", which is also what I'm saying of @decorators; and many people have already testified that they indeed got used to it and even liked it. Major issue a function definition carries one or more decorators, the most important information is not the fact that it has decorators, but the specific decorators used. A classmethod or staticmethod decorator adds a completely different flavor than a decorator that provides an external linkage hint for ObjC, or one that adds synchronization, or one that declares deprecation. I expect that at least 80% of the use of decorators will have a single decorator per function, and it's a pain for that decorator to be hiding behind a content-free keyword. (This is *not* a number-of-keystrokes argument. You know I don't care much about that.) Minor issue: "using" is a poor choice of keyword. It resembles C#'s "using" and perhaps Perl's "use", both of which have completely different meanings. But there don't seem to be any better alternatives (the best I could come up with was "transmogrify" :-). So, what's. In the coming years I hope that as a community we'll gain enough experience with decorators to decide whether we need to adopt a different syntax for Python 3000 or not. One of the difficulties with choosing a decorator syntax has definitely been that nobody can predict how they are going to be used predominantly. Different alternatives look better depending on whether there are many or few decorators per function, whether they have long argument lists or not, and perhaps also whether their use is for transformation or for annotation. Despite the novelty of using the @ character, I personally feel that prefix decorators are a huge improvement over the "f = staticmethod(f)" style of decorating. A warning: some people have shown examples of extreme uses of decorators. I've seen decorators proposed for argument and return type annotations, and even one that used a decorator to create an object that did a regular expression substitution. Those uses are cute, but I recommend being conservative when deciding between using a decorator or some other approach, especially in code that will see a large audience (like 3rd party library packages). Using decorators for type annotations in particular looks tedious, and this particular application is so important that I expect Python 3000 will have optional type declarations integrated into the argument list. Thanks to everyone who read until the end of this message! -- --Guido van Rossum (home page:)
http://mail.python.org/pipermail/python-dev/2004-September/048518.html
crawl-002
refinedweb
753
57
Possible Duplicate: What is the best way to deal with DBNull's What is the most efficient syntax in .NET to set a variable that has a value of DBNull (aka SQL null value being returned)? I remember reading something that was put into .NET 3.0 for this sort of thing. Lets assume the variable I'm setting has a type of DateTime. Common error: Conversion from type 'DBNull' to type 'Date' is not valid. DateTime is a value type, and can only contain valid date/times. Typically the way this is handled is to check your value returned from teh database to see if it's DBNull.Value, and if so set the DateTime to a special value like DateTime.MinValue which represents Null. Alternatively you can use DateTime? which is a nullable DateTime datatype and you can actually assign it null (regular .Net null, not DBNull). DateTime foo; if (row["SomeField"] == DBNull.Value) { foo = DateTime.MinValue; } else { foo = (DateTime)row["SomeField"]; } You can make this syntax a little bit nicer by creating an extension method on a DataRow like so: public static void ToDateTime(this DataRow row, string columnName) { if (row[columnName] == DBNull.Value) { return DateTime.MinValue; } else { return (DateTime)row[columnName]; } } then you can rewrite the original code like this: DateTime foo = row.ToDateTime("SomeField"); I usually get around this by making the property in my class a NULLABLE type. This is especially relevant to the bool type, since by default, it has no value (neither true nor false). public class MyDbTable { public int MyId { get; set; } public DateTime? Date { get; set; } public bool? IsDirty { get; set; } } Similar Questions
http://ebanshi.cc/questions/4060595/most-efficient-way-of-dealing-with-dbnull-in-net
CC-MAIN-2017-22
refinedweb
273
68.77
Igor wrote: > #ifndef __x86_64___ > /* some comment > #else /* __x86_64__ */ > /* some DIFFERENT comment > #endif /* __x86_64__ */ > */ > ... > I don't know if this is a bug or if stuff was made simple since diff is > not a C parser, however, reported. As you say, stuff was made simple. The diff program doesn't parse the C code. It simply creates a diff based upon the differences in the file. If you had used diff -u you would have seen a more normal diff output and the differences would have shown: -/* some comment +/* some DIFFERENT comment */ int somefunc(); The -D option wraps the diff in cpp ifdef constructs. It is a textual convenience. But it isn't going to perfectly handle pathological constructs. Thanks for the report just the same! Bob
http://lists.gnu.org/archive/html/bug-gnu-utils/2010-04/msg00016.html
CC-MAIN-2018-05
refinedweb
126
74.49
The travelling salesman problem, or TSP, must be one of the most popular problems amongst computer science students. It is extremely simple to state; what is the shortest route by which one can tour n cities and return to one's starting point? Figure 1 shows random and optimal tours of a 9-city TSP. On first inspection, it seems to be fairly simple. The 9-city tour in figure 1 can be solved by eye in just a few seconds. However, the general case is fiendishly difficult. So much so that finding a fast algorithm to generate the optimal tour, or even proving that no such algorithm exists, will net you $1,000,000 from the Clay Mathematics Institute [Clay]. This is because it is an example of an NP-complete (nondeterministic polynomial complexity) problem. This is the class of problems for which the answer can be checked in polynomial time, but for which finding it has unknown complexity. The question of whether an NP-complete problem can be solved in polynomial time is succinctly expressed as 'is P equal to NP?' and answering it is one of the Millennium Prize Problems, hence the substantial cash reward. The answer to this question is so valuable because it has been proven that if you can solve one NP-complete problem in polynomial time, you can solve them all in polynomial time. And NP-complete problems turn up all over the place. For example, secure communication on the internet relies upon P≠NP.The cryptographic algorithms used to make communication secure depend on functions that are easy to compute, but hard to invert. If P=NP then no such functions exist and secure communication on an insecure medium is impossible. Since every financial institution relies upon such communication for transferring funds, I suspect that you could raise far more than $1,000,000 if you were able to prove that P=NP. Fortunately for the integrity of our bank accounts the evidence seems to indicate that if the question is ever answered it will be in the negative. So, given that some of the keenest minds on the planet have failed to solve this problem, what possible insights could an amateur modeller provide? Not many, I'm afraid. Well, not for this problem exactly. I'd like to introduce a variant of the TSP that I'll call the regular travelling salesman problem. This is a TSP in which the cities are located at the vertices of a regular polygon. Figure 2 shows the first four regular TSPs. The question of which is the shortest tour is rather uninteresting for the regular TSP as it's simply the circumference of the polygon. Assuming that the cities are located at unit distance from the centre of the polygons (i.e. the polygons have unit radius), the length of the optimal tour can be found with a little trigonometry. Figure 3 shows the length of a side. For a tour of n cities, the length, l, of the optimal tour is given by: 2π θ = —— n θ h sin — = — 2 2 π l = n × h = 2 n sin — n As n gets large, so θ gets small, and for small θ , sinθ is well approximated by θ itself. We can conclude, therefore, that for large n, the length of the optimal tour is approximately equal to 2θ . This shouldn't come as much of a surprise since for large n a polygon is a good approximation for a circle. In fact, it was this observation that Archimedes [Archimedes] used to prove that The ratio of the circumference of any circle to its diameter is less than 31/7 but greater than 310/71. It's also fairly easy to find the length of the most sub-optimal tour. The key is to note that for odd n the furthest two cities from any given city are those connecting the opposite side of the polygon. Figure 4 shows the longest single steps and tour in a 5-city regular TSP. For odd regular TSPs, we can take a step of this length for every city, giving us a star shaped tour. We can calculate the length of this tour in a similar way to that we used to calculate the shortest tour length. Figure 5 shows the length of the longest single step. So for a tour of odd n cities, the length, l', of the worst tour is given by: 2π n-1 π θ = —— × ——— = π - — n 2 n θ h sin — = — 2 2 ⌈ π π ⌉ π l' = n × h = 2 n sin | — - —— | = 2 n cos —— ⌊ 2 2n ⌋ 2n This time for sufficiently large n, is small enough that cos θ is well approximated by 1. For large odd n, therefore, the length of the worst tour is approximately equal to 2n. Once again, we could have equally well concluded this from the fact that for large n the polygon is a good approximation for a circle for which the largest step is across the diameter. For an even number of cities the worst single step is to the city on the opposite side of the polygon with a distance of 2. Unfortunately each time we take such a step we rule it out for the city we visit, which will have to take a shorter step. So we can have ½n steps of length 2 and ½n steps of length strictly less than 2, giving a total length strictly less than 2n. This doesn't show that for an even number of cities the limit is 2n, just that it cannot exceed 2n. However, we can follow the longest step with the second longest to one of the first city's neighbours. We can repeat this for all but the last pair of cities for which we can take the longest step followed by the shortest. Figure 6 shows a 2n-2 limit tour for 6 cities. Whilst I haven't shown that this is the worst strategy, it does have a limit close to 2n for large n. It takes ½n steps with length 2, ½n-1 steps with length approximately equal to 2 and one step with length approximately equal to 0 giving a total of 2n-2. So are there any remotely interesting questions we can ask about the regular TSP? How about what the average length of a tour is? Or, more generally, how are the lengths of random regular TSP tours distributed? This is where the maths gets a little bit tricky, so we'll need to write a program to enumerate the tours directly. The simplest way to do this is to assign each city a number from 0 to n-1 so we can represent a tour as a sequence of integers. Figure 7 shows labels for a 5-city regular TSP. A tour can be defined as: #include <vector> namespace tsp { typedef std::vector<size_t> tour; } We'll need some code to calculate the distance between the cities. We can save ourselves some work if we calculate the distances in advance rather than on the fly. We can exploit the fact that our cities are located at the vertices of regular polygons by noting that due to rotational symmetry the distance between two cities depends only on how may steps round the circumference separate them. Listing 1 shows a class to calculate distances between cities. The constructor does most of the work, calculating the distances between cities 0 to n-1 steps apart. Listing 2 calculates the distances between cities. Of course we could have also exploited the reflectional symmetry that means the distance between cities separated by i and n-i steps are also the same, but I'm not keen to make the code more complex for the relatively small improvement that results. The code to retrieve the distance between two cities is relatively simple and is shown in Listing 3. To calculate the length of a tour we need only iterate over it and sum the distances of each step (Listing 4, overleaf). The final thing we'll need before we start generating tours is some code to keep track of the distribution of tour lengths. Listing 5 shows a class to maintain a histogram of tour lengths. Most of the member functions of our histogram class are pretty trivial, so we'll just look at the interesting ones. Firstly, the constructors. Listing 6 shows how the tour histograms are constructed. As you can see, unless we specify otherwise, we'll use twice as many buckets as we have vertices. This is because we've already proven that the maximum tour length is bounded above by 2n, so it makes sense to restrict our histogram to values between 0 and 2n and dividing this into unit length ranges is a natural choice. The init member function simply initialises the ranges for each of the buckets and sets their counts to 0. Note that, for our default histogram, the bucket identified with length l records tours of length greater than or equal to l-1 and less than l. Listing 6 shows initialising the tour histogram. We can exploit the fact that our histogram buckets are distributed evenly over the range 0 to 2n when recording tour lengths. To identify the correct bucket we need only take the integer part of the tour length multiplied by the number of buckets and divided by 2n. Listing 7 shows adding a tour to the histogram Now we have all of the scaffolding we need to start measuring the properties of random tours of the regular TSP. Before we start, however, we should be mindful of the enormity of the task we have set ourselves. The problem is that the number of tours grows extremely rapidly with the number of cities. For a TSP with n cities, we have a total of n! tours which are going to take a lot of time to enumerate. Table 1 shows the growth of n! with n. We can improve matters slightly by considering symmetries again. Firstly we have a rotational symmetry, in that we can start at any of the cities in a given tour and generate a new tour. By fixing the first city, we improve matters by a factor of n. Secondly we have a reflectional symmetry in that we can follow any given tour backwards and get a new tour. By fixing which direction we take around the polygon, we reduce the complexity of the problem by a further factor of 2. Whilst exploiting the rotational symmetry is relatively straightforward, the reflectional symmetry once again requires quite a bit of house-keeping. Hence I shall only attempt to exploit the former for the time being. The first thing we're going to need is a way to generate the initial tour. void tsp::generate_tour(tour::iterator first, tour::iterator last) { size_t i = 0; while(first!=last) *first++ = i++; } Once we can do that it is a simple matter of iterating through each of the remaining tours and adding their lengths to our histogram. Fortunately there's a standard function we can use to iterate through them for us; std::next_permutation. This takes a pair of iterators and transforms the values to the lexicographically next largest permutation, returning false if there are no more permutations. Using this function to calculate the histogram of tour lengths is relatively straightforward, as shown in Listing 8. Note that exploiting the rotational symmetry of the starting city is achieved by simply leaving out the first city in our call to std::next_permutation. Now we are ready to start looking at the results for some tours, albeit only those for which the computational burden is not too great. Figure 8 shows the tour histograms for 8, 10, 12 and 14 city regular TSPs. We can also use the histograms to calculate an approximate value for the average length of the tours. We do this by assuming that every tour that is added to a bucket has length equal to the mid-point of the range for that bucket. For our default number of buckets, this introduces an error of at most 0.5, which for large n shouldn't be significant. If you're not comfortable with this error it would not be a particularly difficult task to adjust the add member function to also record the sum of the tour lengths with which you could more accurately calculate the average length. I'm not going to bother though. The approximate average lengths of the above tours, as both absolute length and in proportion to the number of cities, are given in Table 2. The distributions shown by the histograms and the average tour lengths both hint at a common limit for large n, but unless we can analyse longer tours we have no way of confirming this. Unfortunately, the computational expense is getting a little burdensome as Table 3 illustrates. So can we reduce the computational expense of generating the tour histograms? Well that, I'm afraid, is a question that shall have to wait until next time Acknowledgements With thanks to Larisa Khodarinova for a lively discussion on group theory that lead to the correct count of distinct tours and to Astrid Osborn and John Paul Barjaktarevic for proof reading this article. References & Further Reading [Clay] Clay Mathematics Institute Millennium Problems,. [Archimedes] Archimedes, On the Measurement of the Circle, c. 250-212BC. . [Agnihothri98] Agnihothri, A Mean Value Analysis of the Travelling Repairman Problem, IEE Transactions, vol. 20, pp. 223-229, 1998. [Basel01] Basel and Willemain, Random Tours in the Travelling Salesman Problem: Analysis and Application, Computational Optimization and Applications, vol. 20, pp. 211-217, 2001. [Hoffman96] Hoffman and Padberg, Travelling Salesman Problem, Encyclopedia of Operations Research and Management Science, Gass and Harris (Eds.), Kluwer Academic, Norwell, MA, 1996.
https://accu.org/index.php/journals/1433
CC-MAIN-2018-34
refinedweb
2,320
68.7
01 August 2012 11:19 [Source: ICIS news] SINGAPORE (ICIS)--Prices of Group I base oils in the ?xml:namespace> Prices of SN150 cargoes fell by $75-95/tonne (€61-77/tonne) CFR (cost & freight) UAE (United Arab Emirates) to $955-1,015/tonne CFR UAE, while prices of SN500 cargoes fell by $55-65/tonne CFR UAE to $995-1035.tonne CFR UAE during the week ended 26 July, according to data from ICIS. Iranian major Iranol was heard to have concluded a deal for 21,000 tonnes of Group 1 base oils for prompt loading to buyers in the UAE, according to market players. The deal includes 6,600 tonnes of SN600 at $925/tonne FOB (free on board) BIK (Bandar Imam Khomeini), 5,800 tonnes of SN500 at $950/tonne FOB BIK, 4,900 tonnes of SN 150 at $920/tonne FOB BIK, and 3,500 tonnes of SN650 at $925/tonne FOB BIK, they said. Meanwhile, Russia-origin Group 1 cargoes were offered at $980/tonne CFR UAE, but there was no buying interest because there is a preference for cargoes from “European product is of high quality, but there are some colour differences from what blenders in the UAE are used to, so interest is weak,” a trader said. “Some blenders who are able to accept the specifications of the European cargoes may consider buying them in a week or two, if there are offers. This may cause the prices to fall further,” another trader said. Iranian major Sepahan has not lowered its selling ideas of SN500 to the buyers’ levels at the low-to-mid $900s/tonne FOB “We don’t see a real need to lower our prices now. We prefer to wait for prices to stabilise before we make a decision to do so,” a source from Sepahan
http://www.icis.com/Articles/2012/08/01/9582721/mideast-base-oil-prices-fall-on-lower-discussions-european.html
CC-MAIN-2015-22
refinedweb
306
60.28
A holiday farewell, and some thoughts about Coffee HouseFraser Nelson 1:12pm Many smokers I know say they aren’t addicted, they just choose not to stop. By the same token, I’m seeing if I can give up Coffee House for a fortnight as I take my summer holidays in Sweden. I was asked by a media reporter for the Sunday Herald newspaper last week if I mind when anonymous people attack my pieces online. On the contrary, I replied, it’s why I blog. When James Forsyth got Coffee House going for last year’s May elections, I had no idea I’d end up writing far more as a Coffee House barista than for the magazine. The comments are the pull. There’s something gratifying (and, I admit, addictive) about writing an idea at 2pm and having CoffeeHousers – a strikingly smart, diverse, eloquent and well-informed group of people - comment by 2.15pm. And if I’m trashed, it’s normally for a good reason. In newspapers, writers normally get only two forms of feedback: promotion or a P45. Your friends and parents normally praise what you do, it’s the devil’s own job finding an honest assessment. And this is what the web offers. Up to a point - those thinking “this Nelson drivel is beyond derision” won’t comment, of course. But more often than not in Coffee House, I find the flabbier points in my arguments are noticed and skewered. Many writers would pay good money for that kind of feedback. On the internet, arguments stand and fall by their strengths - no matter who makes them. The web flattens hierarchies, producing a level arena where eBay sellers compete with John Lewis, but where professional pundits like me must compete with – and, often, be spectacularly outshone by - amateurs. The primary voter opinion, contempt for the whole system, is given a proper venting. Guido, who (as far as I know) is an ordinary bloke who took an interest in stirring things up in politics, has become the guy who David Cameron and Ed Balls privately admit they read regularly. Iain Dale didn’t get elected in 2005 but through his blog wields more influence than any backbencher could. Robert Fisk is knocked off his pedestal and – how you say? - Fisked. ConservativeHome now has such stature that Jonathan Isaby has quit The Telegraph to work as Tim Montgomerie’s co-editor. Like The Spectator magazine, Coffee House is not a mass market product and doesn’t attempt to be. Guido can put up a post saying just “hungover” and get 51 comments. We don’t. But what we get is, for my money, the best comment thread on the web. When we first started getting comments, James and I wondered if Matt d’Ancona (a novelist, as well as our editor) was adopting different personas such as Tiberius and TGF UKIP, and leaving comments just to make us feel better about the blog thing. The comments being left were suspiciously pithy and knowledgeable. But unless Matt really has been working overtime, the commentators are real and you can often learn more reading the thread than the original post. To my mind, this is what’s best about Coffee House. My wife says she can tell when I’m blogging, because I smile when I type. But for the next fortnight, my laptop will be closed as the three of us (we called him Alex in the end) head to the archipelago. So if you see my name on Coffee House before 18 August, please trash me and say no one cares what I think. And if you don’t, my wife certainly will. Bruce. UKAugust 4th, 2008 1:25pm Give it a rest, why don't you? fulcanelliAugust 4th, 2008 1:35pm Enjoy your holiday! Scandinavia seems particularly popular this year. I know a number of friends who have also chosen that area. The people are so friendly. daniel1979August 4th, 2008 1:43pm Frasier, you are an addict. I suspect you will be posting again in uder 4 days Faceless BureaucratAugust 4th, 2008 1:51pm Why Fraser, I’m (we’re) touched… Enjoy your break – you have earned it. Meanwhile, just think of all the potential material that will be waiting for you upon your return (let’s hope Brown doesn’t go while you are languishing on a beach somewhere – that really would be lousy timing!). Philip WrightAugust 4th, 2008 2:23pm Fraser, will you really be able to keep your itchy fingers off the keyboard of your laptop if Team Brown and the Milipede start to get it on over the next two weeks, I wonder? Anyway have a great break! TiberiusAugust 4th, 2008 2:51pm Enjoy your hols, Fraser, but I'm disappointed you won't be in your home country for the next week when I'm on holiday there - I was anticipating a chance encounter in the Galloway Forest, but c'est la vie. It's been an enjoyable year observing the unravelling of New Labour. It's overthrow (if that's not too strong a word) is my motivation for posting on here. I want to see a start to putting Britain back on track. Finally, make sure you relax with Alex - these times away with him will be so precious. RayAugust 4th, 2008 2:57pm I too enjoy the Speccie website and comments. However, I must hire myself a proper proof-reader because my most irritating fault is changing words or sentences here and there and then forgetting to reread my whole comment through again to make sure everything is still in context. Take care, Fraser. William NortonAugust 4th, 2008 3:17pm Hmmm. I'm sure I read somewhere or other that the only holiday Kruschev took was the week that Brezhnev decided to oust him.... Ian CAugust 4th, 2008 3:22pm I reckon you'll be coming back to one of the more interesting Septembers - and the proper kickoff of the US elections as a pure bonus. VerityAugust 4th, 2008 3:31pm Where did David Cameron get his photo taken on the ice floe with those two handsome huskies? Was it Sweden? If so, you might be able to contact their agent and have your and your family's photo taken. ("I 'ad that Fraser Nelson and 'is family in the back of my sled once, Lars.") Happy hols! Marian CAugust 4th, 2008 3:49pm Fraser, hope you and your family have a great holiday; we will all miss you I'm sure. Chuck UnsworthAugust 4th, 2008 3:54pm Bon Voyage! billAugust 4th, 2008 4:23pm Fraser Enjoy your holiday in Greece (?). I have been going for almost thirty years and still love it. I think the Coffee House is great: both posts and comments thereon. Changing computers recently caused me to cull a wide swathe of blogs which I read. The Coffer House remains a must read along with Guido. PS If you have not read it before, I recommend an englishmans castle to you. Max KayeAugust 4th, 2008 4:37pm Enjoy your break, Fraser. DMAugust 4th, 2008 4:39pm You'll be taking David Cameron's reading list along though, won't you? ..or just Thomas the Tank Engine. Enjoy the break! D ShortAugust 4th, 2008 4:42pm How much dumber can this place get? Why ever did the Barclays give a blank cheque to you know who, and his henchmen? We mourn this once-wonderful magazine. Why are some people created simply to be destructors? And why do we allow it? KeithAugust 4th, 2008 5:27pm Missing you already!!!!!!!!!! Jack RAugust 4th, 2008 5:52pm Of course, the fall of New Labour, and the rise of 'Spectator'/Coffee House/Blogs is no coincidence. Coffee House, etc. should remain wider than being pro-Conservative Party; Coffee House should be a continuing critique of the political correct, multicultural tendency of the liberal/left. Paul BAugust 4th, 2008 7:27pm Fraser, happy hols. Not too much binge drinking now, we know what you Fleet Streets hacks are like :-) Pity I do not take my own advice. TGF UKIPAugust 4th, 2008 8:17pm Fraser,I'm disappointed, I've been patiently waiting for you to comment on the windfall tax. Or are you escaping to avoid the possible embarrassment? Is Dave in his best headbanging green, social democrat persona going to promise to double it or is he, for once going to flabbergast me and act as a conservative and undertake to immediately repeal it, pointing out the damage done to the N. Sea oil tax take by Gordon's doubling of N. Sea oil companies supplementary tax a couple of years ago. Anyway, have a good time Fraser and beware young RR doesn't come under too many soc dem influences otherwise he might turn out like Dave. (BTW - Alex - did you chicken out or is your missus a Swedish SocDem who put her foot down?) Meanwhile, with you in Sweden, your aged alter ego, Tiberius, in Scotland and James in the Lakes who am I going to have to wind up? Perhaps, the Dear Editor will come to my rescue and become an omnipresence again in the Coffee House. That should do nicely. TiberiusAugust 4th, 2008 11:01pm So! The silly season is in full swing (someone even suggested Harridan could be PM), and TGF UKIP admits it was all a wind up! I told him he loves Dave really - but he persists in playing hard to get. Austin BarryAugust 5th, 2008 8:35am Fraser, have a good holiday, and at all costs avoid any thick-set, haunted-looking man in an ice-cream vendor's jacket who may dither towards you muttering imprecations in which the word 'Milibastard' may be prevalent. TankusAugust 5th, 2008 10:04am Leave your laptop , not just close it , because you will ,and you know it !, Like any junky , because its there..! Hava good 'un TGF UKIPAugust 5th, 2008 7:58pm Tiberius, you know me so well. It's true really, I do love Dave with all the passion and ferocity that DD does!
http://www.spectator.co.uk/coffeehouse/876891/a-holiday-farewell-and-some-thoughts-about-coffee-house.thtml
crawl-002
refinedweb
1,691
71.75
Microsoft has announced some new keywords and some new behavior of C# 6.0 in Visual Studio 2015.In this article we will learn the following topics. For testing allOpen Visual Studio 2015 and select "File" -> "New" -> "Project...".Click OK and then you will get a solution that you will see in the Solution Explorer.Now just do something with your program.cs file to test your compile time code.1. using StaticThis is a new concept in C# 6.0 that allows us to use any class that is static as a namespace that is very usefull for every developer in that code file where we need to call the static methods from a static class like in a number of times we need to call many methods from Convert.ToInt32() or Console.Write(),Console.WriteLine() so we need to write the class name first then the method name every time in C# 5.0. In C# 6.0 however Microsoft announced a new behavior to our cs compiler that allows me to call all the static methods from the static class without the name of the classes because now we need to first use our static class name in starting with all the namespaces. Code in 5.0 2. Auto property initializerAuto property initializer is a new concept to set the value of a property during of property declaration. We can set the default value of a read=only property, it means a property that only has a {get;} attribute. In the previous version of C# 5.0 we can set the values of the property in the default constructor of the class. Let's have an example. Suppose we need to set some property's value of a class as in the following: In C# 5.0Code 4. nameof Expressionnameof is new keyword in C# 6.0 and it's very usefull from a developer's point of view because when we need to use a property, function or a data member name into a message as a string so we need to use the name as hard-coded in “name” in the string and in the future my property or method's name will be changed so it must change all the messages in every form or every page so it's very complicated to remember that how many number of times you already use the name of them in your project code files and this avoids having hardcoded strings to be specified in our code as well as avoids explicit use of reflection to get the names. Let's have an example.Code 5. Exception filtersException filters are a new concept for C#. In C# 6.0 they are already supported by the VB compiler but now they are coming into C#. Exception filters allow us to specify a condition with a catch block so if the condition will return true then the catch block is executed only if the condition is satisfied. This is also a best attribute of new C# 6.0 that makes it easy to do exception filtrations in also that type of code contains a large amount of source code. Let's have an example. 6. Await in catch and finally blockThis is a new behavior of C# 6.0 that now we are able to call async methods from catch and also from finally. Using async methods are very usefull because we can call then asynchronously and while working with async and await, you may have experienced that you want to put some of the result awaiting either in a catch or finally block or in both. Let's suppose we need to call a async method and there is a try and a catch{} block so when the exception occurs it is thrown in the catch{} bock. We need to write log information into a file or send a service call to send exception details to the server so call the asynchronous method, so use await in catch{}, this is only possible in C# 6.0. Let's have an example.We have a class and there is a method that is async and we need to call this with two parameters and if there is an exception then that will we return an exception and will go to the catch{} block and then we will call an async method using await and finally we have called the same in the finally. 7. Null-Conditional OperatorThe Null-Conditional operator is a new concept in C# 6.0 that is very beneficial for a developer in a source code file that we want to compare an object or a reference data type with null. So we need to write multiple lines of code to compare the objects in previous versions of C# 5.0 but in C# 6.0 we can write an in-line null-conditional with the ? and ?? operators, so let's have an example and compare both versions, C# 5.0 vs C# 6.0. We will write the code for both version.The output when no object is null:The output when an object is null:Code 9. Easily format strings using String interpolationTo easily format a string value in C# 6.0 without any string.Format() method we can write a format for a string. It's a very usefull and time consuming process to define multiple string values by “\{ variable }”. So let's have an example on String interpolation. First we are writing the source code by string.Format(). Now by “\{variable}”.OutputThe output will be the same in both but by “\{variable}” is a very short way to write the same code.Code View All
http://www.c-sharpcorner.com/UploadFile/8ef97c/full-C-Sharp-6-0-in-single-article-on-visual-studio-2015-preview/
CC-MAIN-2018-09
refinedweb
953
71.85
This tutorial describes how to build an IoT soil moisture sensor that monitors the soil moisture using Arduino. Moreover, this Arduino IoT monitoring system implements a notification system so that when the soil gets too dry it sends a notification. As you know already, IoT is one of the most important topics nowadays, that promises to shape our future and the way we live. One interesting aspect of IoT is the fact we can experiment with an IoT system building it by ourselves. There are several prototyping boards available in the market and we can build amazing IoT projects without spending too much. IoT soil moisture project overview The idea that stands behind this project is building an Arduino IoT system that monitors the soil moisture using a soil sensor detecting when it gets too dry. The Arduino MKR1000 controls the sensor sending the data to the Carriots IoT platform (now Altair SmartCore).TTT the soil moisture sensor connected to Arduino In this first step, we have to read the sensor data. This IoT project uses YL-38 + YL-69 sensor. This is an analog sensor that can be inserted into the soil we want to monitor. The picture below shows how to connect the YL-38 and YL69 (moisture sensor) to Arduino: The code is very simple, we read values the IoT cloud platform. Moreover, to do it, Arduino MKR1000 has to connect to the internet so that it can send data. The code below describes how to connect Arduino to the WiFi: Code language: PHP (php)Code language: PHP (php) #include "WiFi101.h" WiFiClient client; void setup() { Serial.begin(9600); Serial.print("Starting..."); if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); while (true); } connectToWifi(); } where the connectToWifi() is: Code language: JavaScript (javascript)Code language: JavaScript (javascript). Connecting Arduino to the IoT platform Carriots Before sending data to the cloud, we have to configure our IoT platform in order to manage the data. Carriots uses a hierarchical structure to group and, which in turn belongs to the service. The service belongs to the project. The configuration step is very easy as shown in the picture below: That’s all. The configuration steps are complete., add this function to the sketch shown above: Code language: JavaScript (javascript)Code language: JavaScript (javascript)_5<< Implementing an Arduino alert system using IFTTT Carriots with another useful and interesting platform called IFTTT. This platform provides several integration services we can use and integrate into our IoT projects. Learn More: Internet of Things with Android and Arduino: Control remote Led How to Integrate Arduino and Google cloud platform How to implement an IoT notification system In order to alert the user we need two components: - a monitoring data system - alerting system As a monitoring data system, this IoT system uses Carriots listener. A listener is a process that analyzes the incoming values and applies a specific rule. When the rule is verified then it invokes a script. The interesting aspect of Carriots is that we can use Groovy as a scripting language to invoke external services. The alerting system is built on IFTTT. Before completing the work on Carriots, it is useful to configure the IFTTT. As stated before, we want to send a short message when the humidity hits a threshold level. In order to achieve it, we configure a short message service in IFTTT. It is required you have a free account in order to complete this task. Configuring IFTTT system As a first step, it is necessary to create a new Applet: Now click on plus sign to add the service and search for Maker service: Select Maker webhooks to enable IoT maker. Now we have to configure the maker service adding the event name that triggers the sending message process: Finally,: >>IMAGE. if you are interested you can learn How to build an Arduino data logger. At the end of this tutorial, you have learned how to use the soil moisture sensor with Arduino. Using the IoT moisture sensor, it is possible to monitor the soil humidity and check if it is too dry. In this case, using Arduino integrated with IFTTT, we send an alert to the user. Interesting sir… Can i have the procedure for loT system to monitor soil moisture with Arduino and cloud platform ? Please sir… Thanks
https://www.survivingwithandroid.com/iot-soil-moisture-arduino-iot-ifttt/
CC-MAIN-2022-27
refinedweb
722
62.07
On 4 September 2016 at 16:06, Pavel Stehule <pavel.steh...@gmail.com> wrote: > Hi > > minor update - using DefElem instead own private parser type I'm really glad that you're doing this and I'll take a look at it for this CF. It's quite a big patch so I expect this will take a few rounds of review and updating. Patch applies cleanly and builds cleanly on master both with and without --with-xml . Overall, I think this needs to be revised with appropriate comments. Whitespace/formatting needs fixing since it's all over the place. Documentation is insufficient (per notes below). Re identifier naming, some of this code uses XmlTable naming patterns, some uses TableExpr prefixes. Is that intended to indicate a bounary between things re-usable for other structured data ingesting functions? Do you expect a "JSONEXPR" or similar in future? That's alluded to by +/*---------- + * TableExpr - used for XMLTABLE function + * + * This can be used for json_table, jsonb_table functions in future + *---------- + */ +typedef struct TableExpr +{ ... If so, should this really be two patches, one to add the table expression infrastructure and another to add XMLTABLE that uses it? Also, why in that case does so much of the TableExpr code call directly into XmlTable code? It doesn't look very generic. Overall I find identifier naming to be a bit inconsisent and think it's necessary to make it clear that all the "TableExpr" stuff is for XMLTABLE specifically, if that's the case, or make the delineation clearer if not. I'd also like to see tests that exercise the ruleutils get_rule_expr parts of the code for the various XMLTABLE variants. Similarly, since this seems to add a new xpath parser, that needs comprehensive tests. Maybe re-purpose an existing xpath test data set? More detailed comments: ==== Docs comments: The <function>xmltable</function> produces [a] table based on [the] passed XML value. The docs are pretty minimal and don't explain the various clauses of XMLTABLE. What is "BY REF" ? Is PATH an xpath expression? If so, is there a good cross reference link available? The PASSING clause? etc. How does XMLTABLE decide what to iterate over, and how to iterate over it? Presumably the FOR ORDINALITY clause makes a column emit a numeric counter. What standard, if any, does this conform to? Does it resemble implementations elsewhere? What limitations or unsupported features does it have relative to those standards? execEvalTableExpr seems to be defined twice, with a difference in case. This is probably not going to fly: +static Datum +execEvalTableExpr(TableExprState *tstate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone) +{ +static Datum +ExecEvalTableExpr(TableExprState *tstate, + ExprContext *econtext, + bool *isNull, ExprDoneCond *isDone) +{ It looks like you've split the function into a "guts" and "wrapper" part, with the error handling PG_TRY / PG_CATCH block in the wrapper. That seems reasonable for readability, but the naming isn't. A comment is needed to explain what ExecEvalTableExpr is / does. If it's XMLTABLE specific (which it looks like based on the code), its name should reflect that. This pattern is repeated elsewhere; e.g. TableExprState is really the state for an XMLTABLE expression. But PostgreSQL actually has TABLE statements, and in future we might want to support table-expressions, so I don't think this naming is appropriate. This is made worse by the lack of comments on things like the definition of TableExprState. Please use something that makes it clear it's for XMLTABLE and add appropriate comments. Formatting of variables, arguments, function signatures etc is random/haphazard and doesn't follow project convention. It's neither aligned or unaligned in the normal way, I don't understand the random spacing at all. Maybe you should try to run pgindent and then extract just the changes related to your patch? Or run your IDE/editor's indent function on your changes? Right now it's actually kind of hard to read. Do you edit with tabstop set to 1 normally or something like that? There's a general lack of comments throughout the added code. In execEvalTableExpr, why are we looping over namespaces? What's that for? Comment would be nice. Typo: Path caclulation => Path calculation What does XmlTableSetRowPath() do? It seems to copy its argument. Nothing further is done with the row_path argument after it's called by execEvalTableExpr, so what context is that memory in and do we have to worry about it if it's large? execEvalTableExpr says it's doing "path calculation". What it actually appears to do is evaluate the path expressions, if provided, and otherwise use the column name as the implied path expression. (The docs should mention that). It's wasn't immediately obvious to me what the branch around tstate->for_ordinality_col is for and what the alternate path's purpose is in terms of XMLTABLE's behaviour, until I read the parser definition. That's largely because the behaviour of XMLTABLE is underspecified in the docs, since once you know ORDINALITY columns exist it's pretty obvious what it's doing. Similarly, for the alternate branch tstate->ncols , the XmlTableGetRowValue call there is meant to do what exactly, and why/under what conditions? Is it for situations where the field type is a whole-row value? a composite type? (I'm deliberately not studying this too deeply, these are points I'd like to see commented so it can be understood to some reasonable degree at a skim-read). /* result is one more columns every time */ "one or more" /* when typmod is not valid, refresh it */ if (te->typmod == -1) Is this a cache? How is it valid or not valid and when? The comment (thanks!) on TableExprGetTupleDesc says: /* * When we skip transform stage (in view), then TableExpr's * TupleDesc should not be valid. Refresh is necessary. */ but I'm not really grasping what you're trying to explain here. What transform stage? What view? This could well be my ignorance of this part of the code; if it should be understandable by a reader who is appropriately familiar with the executor that's fine, but if it's specific to how XMLTABLE works some more explanation would be good. Good that you've got all the required node copy/in/out funcs in place. Please don't use the name "used_dns". Anyone reading that will read it as "domain name service" and that's actually confusing with XML because of XML schema lookups. Maybe used_defnamespace ? used def_ns? I haven't looked closely at keyword/parser changes yet, but it doesn't look like you added any reserved keywords, which is good. It does add unreserved keywords PATH and COLUMNS ; I'm not sure what policy for unreserved keywords is or the significance of that. New ereport() calls specify ERRCODEs, which is good. PostgreSQL already has XPATH support in the form of xmlexists(...) etc. Why is getXPathToken() etc needed? What re-use is possible here? There's no explanation in the patch header or comments. Should the new xpath parser be re-used by the existing xpath stuff? Why can't we use libxml's facilities? etc. This at least needs explaining in the submission, and some kind of hint as to why we have two different ways to do it is needed in the code. If we do need a new XML parser, should it be bundled in adt/xml.c along with a lot of user-facing functionality, or a separate file? How does XmlTableGetValue(...) and XmlTableGetRowValue(...) relate to this? It doesn't look like they're intended to be called directly by the user, and they're not documented (or commented). I don't understand this at all: +/* + * There are different requests from XMLTABLE, JSON_TABLE functions + * on passed data than has CREATE TABLE command. It is reason for + * introduction special structure instead using ColumnDef. + */ +typedef struct TableExprRawCol +{ + NodeTag type; + char *colname; + TypeName *typeName; + bool for_ordinality; + bool is_not_null; + Node *path_expr; + Node *default_expr; + int location; +} TableExprRawCol; That's my first-pass commentary. I'll return to this once you've had a chance to take a look at these and tell me all the places I got it wrong ;) -- Craig Ringer PostgreSQL Development, 24x7 Support, Training & Services -- Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org) To make changes to your subscription:
https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg293122.html
CC-MAIN-2018-43
refinedweb
1,383
65.73
Provides Shelf middleware for defining routes. shelf_route is a powerful router that makes it easy to define routes in a modular way. shelf_route is designed to be:} See more detailed examples in the example folder under the project source. This section deals with basic customisations. These are powerful ways to customise how the routing works and will handle most cases for customising shelf_route. If you need more then see the section below on Extending The path arguments of all the router methods accept either:); If you can't achieve the customisations you need using the above techniques then you have come to the right place. But first helps to know a little about the architecture of shelf_route. shelf_route is broken into two main parts: shelf_route.. See the wiki for more details on all the options Contributions are welcome. Please: See open issues. attachmethod from Router Note: this is only backward incompatible if you rely on handlerAdapters not being merged. i.e. to override instead Note: should be backward compatible with 0.8.x unless you depended on deprecated methods that have been removed Router.addAllto take a typedef rather than a class implements Routeable. To fix this simply use extends Routeableinstead. This change makes it easier to set up hierarchical routes. e.g. var myRouter = router() ..addAll((Router r) => r ..get('/foo', (_) => new Response.ok('yeah foo')) ..get('/fum', (_) => new Response.ok('boo fum')) ..addAll((Router r) => r ..get('/yup/{title}', (req) => new Response.ok("Hello ${getPathParameter(req, 'name')}")) ..get('/nup', (req) => new Response.ok("Hello ${getPathParameter(req, 'name')}")), path: '/blah/{name}'), path: '/bar' ); Major release with lots of changes including: /:foo) var myRouter = router(handlerAdapter: bind.handlerAdapter) myRouter.get('/{name}', (name) => "Hello ${name}"); Use UriPattern and UriTemplate instead of custom path matching {}instead of : getPathVariablesto encapsulate extracting path variables stored in the request Added support for path variables. Improved tests. Add this to your package's pubspec.yaml file: dependencies: shelf_route: ^0.14.3 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:shelf_route/shelf_route.
https://pub.dev/packages/shelf_route
CC-MAIN-2019-26
refinedweb
367
60.61
How to debug in Django, the good way? [closed] Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 2 years ago. So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster? I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted. But can this be improved? Are there some good tools or better ways to debug your Django code? Solutions/Answers: Answer 1: There are a bunch of ways to do it, but the most straightforward is to simply use the Python debugger. Just add following line in to a Django view function: import pdb; pdb.set_trace() or breakpoint() #from Python3.7 If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code. However there are other options (I am not recommending them): * return HttpResponse({variable to inspect}) * print {variable to inspect} * raise Exception({variable to inspect}) But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you’d also want to have a look at IPDB that uses ipython for debugging. Some more useful extension to pdb are pdb++, suggested by Antash. pudb, suggested by PatDuJour. Using the Python debugger in Django, suggested by Seafangs. Answer 2: I really like Werkzeug‘s interactive debugger. It’s similar to Django’s debug page, except that you get an interactive shell on every level of the traceback. If you use the django-extensions, you get a runserver_plus managment command which starts the development server and gives you Werkzeug’s debugger on exceptions. Of course, you should only run this locally, as it gives anyone with a browser the rights to execute arbitrary python code in the context of the server. Answer 3: A little quickie for template tags: @register.filter def pdb(element): import pdb; pdb.set_trace() return element Now, inside a template you can do {{ template_var|pdb }} and enter a pdb session (given you’re running the local devel server) where you can inspect element to your heart’s content. It’s a very nice way to see what’s happened to your object when it arrives at the template. Answer 4: There are a few tools that cooperate well and can make your debugging task easier. Most important is the Django debug toolbar. Then you need good logging using the Python logging facility. You can send logging output to a log file, but an easier option is sending log output to firepython. To use this you need to use the Firefox browser with the firebug extension. Firepython includes a firebug plugin that will display any server-side logging in a Firebug tab. Firebug itself is also critical for debugging the Javascript side of any app you develop. (Assuming you have some JS code of course). I also liked django-viewtools for debugging views interactively using pdb, but I don’t use it that much. There are more useful tools like dozer for tracking down memory leaks (there are also other good suggestions given in answers here on SO for memory tracking). Answer 5: I use PyCharm (same pydev engine as eclipse). Really helps me to visually be able to step through my code and see what is happening. Answer 6: Almost everything has been mentioned so far, so I’ll only add that instead of pdb.set_trace() one can use ipdb.set_trace() which uses iPython and therefore is more powerful (autocomplete and other goodies). This requires ipdb package, so you only need to pip install ipdb Answer 7: I’ve pushed django-pdb to PyPI. It’s a simple app that means you don’t need to edit your source code every time you want to break into pdb. Installation is just… pip install django-pdb - Add 'django_pdb'to your INSTALLED_APPS You can now run: manage.py runserver --pdb to break into pdb at the start of every view… bash: manage.py runserver --pdb Validating models... 0 errors found Django version 1.3, using settings 'testproject.settings' Development server is running at Quit the server with CONTROL-C. GET / function "myview" in testapp/views.py:6 args: () kwargs: {} > /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview() -> a = 1 (Pdb) And run: manage.py test --pdb to break into pdb on test failures/errors… bash: manage.py test testapp --pdb Creating test database for alias 'default'... E ====================================================================== >>> test_error (testapp.tests.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error one_plus_one = four NameError: global name 'four' is not defined ====================================================================== > /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error() -> one_plus_one = four (Pdb) The project’s hosted on GitHub, contributions are welcome of course. Answer 8: The easiest way to debug python – especially for programmers that are used to Visual Studio – is using PTVS (Python Tools for Visual Studio). The steps are simple: - Download and install it from - Set breakpoints and press F5. - Your breakpoint is hit, you can view/change the variables as easy as debugging C#/C++ programs. - That’s all 🙂 If you want to debug Django using PTVS, you need to do the following: - In Project settings – General tab, set “Startup File” to “manage.py”, the entry point of the Django program. - In Project settings – Debug tab, set “Script Arguments” to “runserver –noreload”. The key point is the “–noreload” here. If you don’t set it, your breakpoints won’t be hit. - Enjoy it. Answer 9: I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it. Answer 10: I use PyCharm and stand by it all the way. It cost me a little but I have to say the advantage that I get out of it is priceless. I tried debugging from console and I do give people a lot of credit who can do that, but for me being able to visually debug my application(s) is great. I have to say though, PyCharm does take a lot of memory. But then again, nothing good is free in life. They just came with their latest version 3. It also plays very well with Django, Flask and Google AppEngine. So, all in all, I’d say it’s a great handy tool to have for any developer. If you are not using it yet, I’d recommend to get the trial version for 30 days to take a look at the power of PyCharm. I’m sure there are other tools also available, such as Aptana. But I guess I just also like the way PyCharm looks. I feel very comfortable debugging my apps there. Answer 11: Sometimes when I wan to explore around in a particular method and summoning pdb is just too cumbersome, I would add: import IPython; IPython.embed() IPython.embed() starts an IPython shell which have access to the local variables from the point where you call it. Answer 12: From my perspective, we could break down common code debugging tasks into three distinct usage patterns: - Something has raised an exception: runserver_plus‘ Werkzeug debugger to the rescue. The ability to run custom code at all the trace levels is a killer. And if you’re completely stuck, you can create a Gist to share with just a click. - Page is rendered, but the result is wrong: again, Werkzeug rocks. To make a breakpoint in code, just type assert Falsein the place you want to stop at. - Code works wrong, but the quick look doesn’t help. Most probably, an algorithmic problem. Sigh. Then I usually fire up a console debugger PuDB: import pudb; pudb.set_trace(). The main advantage over [i]pdb is that PuDB (while looking as you’re in 80’s) makes setting custom watch expressions a breeze. And debugging a bunch of nested loops is much simpler with a GUI. Ah, yes, the templates’ woes. The most common (to me and my colleagues) problem is a wrong context: either you don’t have a variable, or your variable doesn’t have some attribute. If you’re using debug toolbar, just inspect the context at the “Templates” section, or, if it’s not sufficient, set a break in your views’ code just after your context is filled up. So it goes. Answer 13: I highly recommend epdb (Extended Python Debugger). One thing I love about epdb for debugging Django or other Python webservers is the epdb.serve() command. This sets a trace and serves this on a local port that you can connect to. Typical use case: I have a view that I want to go through step-by-step. I’ll insert the following at the point I want to set the trace. import epdb; epdb.serve() Once this code gets executed, I open a Python interpreter and connect to the serving instance. I can analyze all the values and step through the code using the standard pdb commands like n, s, etc. In [2]: import epdb; epdb.connect() (Epdb) request <WSGIRequest path:/foo, GET:<QueryDict: {}>, POST:<QuestDict: {}>, ... > (Epdb) request.session.session_key 'i31kq7lljj3up5v7hbw9cff0rga2vlq5' (Epdb) list 85 raise some_error.CustomError() 86 87 # Example login view 88 def login(request, username, password): 89 import epdb; epdb.serve() 90 -> return my_login_method(username, password) 91 92 # Example view to show session key 93 def get_session_key(request): 94 return request.session.session_key 95 And tons more that you can learn about typing epdb help at any time. If you want to serve or connect to multiple epdb instances at the same time, you can specify the port to listen on (default is 8080). I.e. import epdb; epdb.serve(4242) >> import epdb; epdb.connect(host='192.168.3.2', port=4242) host defaults to ‘localhost’ if not specified. I threw it in here to demonstrate how you can use this to debug something other than a local instance, like a development server on your local LAN. Obviously, if you do this be careful that the set trace never makes it onto your production server! As a quick note, you can still do the same thing as the accepted answer with epdb ( import epdb; epdb.set_trace()) but I wanted to highlight the serve functionality since I’ve found it so useful. Answer 14: I just found wdb (). It has a pretty nice user interface / GUI with all the bells and whistles. Author says this about wdb – “There are IDEs like PyCharm that have their own debuggers. They offer similar or equal set of features … However to use them you have to use those specific IDEs (and some of then are non-free or may not be available for all platforms). Pick the right tool for your needs.” Thought i’d just pass it on. Also a very helpful article about python debuggers: Finally, if you’d like to see a nice graphical printout of your call stack in Django, checkout:. Just add pyinstrument.middleware.ProfilerMiddleware to MIDDLEWARE_CLASSES, then add ?profile to the end of the request URL to activate the profiler. Can also run pyinstrument from command line or by importing as a module. References - Database Administration Tutorials - Programming Tutorials & IT News - Linux & DevOps World - Entertainment & General News - Games & eSport
https://loitools.com/blog/how-to-debug-in-django-the-good-way-closed/
CC-MAIN-2020-10
refinedweb
2,037
74.08
Microsoft:52:48 PM Hug a Java Developer Today. [Objective] Chris Hollander responses in a much camler way then I did to Russell Beattie's fiery rant. 12:37:25 PM 2:07:31 PM Of COURSE I Hate Microsoft. ... Furthermore, if you work for - or with - Microsoft, you need to do a reality check. I've said this before, but the question still remains: how do you sleep at night? How do you take pride in your work? Do you like copying other people's innovations? Do you like working with felons? If you're just making a buck, hey, more power to you. If you're one of those gung-ho borged-out drones... Well, all you're doing is making the whole computing industry a worse place to work in. And you KNOW it. ... [Russell Beattie Notebook] I sleep just fine at night. My work is to make the components I work with more featureful, secure and stable. While most of what I work on is just operating system plumbing (http.sys, and now winhttp and wininet) it's hard to ignore the innovation that are built into it them. The basic concept of a kernel switch of a http namespace is not somewhere I've seen elsewhere, even though it such a simple useful idea. I see enough of what's going on around the company to stay convinced that there is plenty of new stuff that is exciting, cool and orginal. The technology and products that Microsoft makes is good enough that other copy it, and irreplacable enough that even you use it. I take pride when I talk to someone who likes windows XP. I take pride in things like windows error reporting. I feel shame in things like the "Sign up for a passport popup notifications". It's a big company doing cool thing; some bad, most good. I've only worked here for three and half years, so I missed most of the stuff that generated the antitrust trials, so maybe the comapny back then was the definition of evil, but today I can't find something to be pissed about other then which bug I think should be fixed before we ship, and what feature won't be done in time for the next release that I was really looking forward to. 11:15:21 AM Ok, Lets leave activewords out of it... but reading Scoble's response, I want to comment: First, Smarttags in IE wasn't meant to be on by default. It was turned on in a ealy beta as a way to get some coverage in the wild for the feature, but it wasn't meant to ship that way. Second, I still don't buy the "getting in between the author and the reader" arguement, since plugins that do so will get turned off by the reader. Utilities stay and get used only to the degree that they add value for the end user. If the user is reading your site, it's a safe bet that they want to read your content and he/she won't tolerate something that distorts it. Third, I miss the potential of the idea. It's every other week or so, a place that the technology would be useful for me pops up. Yesterday, it was stuff like a dictionary lookup on words I don't know the definition to. A week ago it was generating entries into my calandar when a date and time is specified. The week before it was making keyhole's earthviewer go to an address, coordinates, or a city+state when one shows up on a web page. Today I imagine that I could have started this weblog entry by a smarttag that understand individual items on scoble's weblog, understand what blog software I use, and gives me an option similar to radio's "post" link. I'm still a bit disappointed that some peoples' reactions were so violently against it that they couldn't see the good stuff, and try to find a middle ground that makes everyone happy. 2:27:04 PM One came from Microsoft and the other doesn't. It doesn't matter if it was a technology for other people to build on. It doesn't matter that it was on or off by the choice of the end user. Nothing in the design could have mitigated the fear that people had of Microsoft's power over the browser, especially at a time when the anti-trust case was still looming. A coworker and I started wondering today if the same lessons and dilemas that the US is occuring with Iraq is applicable to Microsoft. There is power in going multilateral and building organizations. There are problems when you don't. Also such organizations can get old and become too slow to be as useful or torn apart by differing intrests. Prehaps the trick is to take a "collition of the willing", bypass the stop energy and form a new organization. I expect that there is delicate balance between being a useful place to get work done, and a shell that is one player hiding under a different name. Sometimes you can not get anyone to take your side even if it is working fine for most; at that point you need to rethink what you are doing, and come back at it in a different direction. 1:16:35 PM Sam tells how IIS uses http.sys. My side note is that you too can use port 80 while IIS is running via the new Win2k3 Http API. ;) 5:53:02 PM /. somehow expects that office using xml will somehow make their own word replacements have the same features as word. Where the hell do they get these ideas? I expect that at some point people will develop a pretty decent xsl(t) that will help convert with the most minimal lossy-ness, but (if the office team keeps doing thier jobs) there will always be a more feature office then what the free-be office clone gives you. 11:44:25. [The Scobleizer Weblog] I think it's more accurate to say that the jury is out on this point. A lot of old stuff will probably still work, but there are a lot of architectual changes going on, and there will be compatability problems as a result. I hope the majority of the breaking changes should be visible around PDC time. Also the usual compatailbity technologies help reduce problems as they occur. If it's any consolation, I'm a Longhorn selfhoster, and I scream bloody murder if any app I use breaks. ;) 11:20:41 AM 12:17:33 PM Better Bandwidth Utilization. jtorin writes "Daniel Hartmeier (of OpenBSD fame) has written a short but interesting article which explains how to better utilize available bandwidth. In ... [Slashdot] This is sounds like a different way to solve a problem we worked on for Windows XP. Part of the problem is the big buffers that fill up on the modem that don't allow new connections to get to the stable state fast enough. We solved this with DRR Fair Queing. These folks are doing it via the acks. I think the Windows XP technique is more general, but I wonder which works better. UPDATE: They are somewhat unrelated in that the bsd work is for faster asymetrical links, while the xp stuff is for 56K and lower. 11:05:18 AM Bush Offers Taxpayers Another $300 If We Go To War [The Onion] The onion does a brillent job tying together three major political threads in to a really funny article. 10:48:56 AM
http://radio.weblogs.com/0100529/
crawl-002
refinedweb
1,290
69.92
(Note:. You can follow his Windows PowerShell and other system administrator antics at. The first step in troubleshooting this script is to comment out the opening line: #$errorActionPreference = "silentlycontinue" The default value of $errorActionPreference in Windows PowerShell is continue. This means that upon hitting an error, Windows PowerShell will flag the error, but attempt to carry on processing the script. By commenting out the first line, which has changed the value of $errorActionPreference to silentlycontinue, we will be able to troubleshoot what is wrong with the script. If we now run the script again we get the following error: “You cannot call a method on a null-valued expression as seen below.” From the second line of the error, we can see that the issue is with line 4: $Shell.popup($w.UserName) The method is the part of the line after the dot so we know that for some reason the variable $Shell is empty. This is because in line 3, the variable used to store the wscript.shell ComObject has been named $wshShell. So to correct that, line 4 should look like this: $wshShell.popup($w.UserName) If we run the updated script again, we receive the below message box. No error this time, but it is empty. So we know that we can create a message box, but there must be something wrong with populating the text. This is again partly to do with the naming of variables. In line 1, we used $wmi to store the results of the WMI query to retrieve the currently logged-on user. This is the variable we need to use in the popup method to display the correct text. So line 3 should be further corrected: $wshShell.popup($wmi.UserName) However, running the script again still returns an empty message box. Going back to the original WMI query in line 1, if we run it interactively we get the below result: The value of the Name property is the name of the computer, not the logged on user. Also this property is not called UserName, which we are trying to use in line 4. By changing the WMI query to instead use the UserName property, we get the correct logged-on user: Get-WmiObject -Class Win32_computerSystem -Property UserName The corrected script now looks like this: Beginner10_Fixed.ps1 #$errorActionPreference = "silentlycontinue" $wmi = Get-WmiObject -Class Win32_computerSystem -Property UserName $wshShell = New-Object -ComObject wscript.shell $wshShell.popup($wmi.UserName) When we run this corrected script, the following message box is displayed. A slightly more advanced way to create a message box would be to use the message box class within the System.Windows.Forms .NET Framework namespace. While not providing much extra in this particular example, more complex forms could be created using these tools. You first need to load the system.windows.forms assembly (only a subset of the .NET Framework is available by default in Windows PowerShell): [reflection.assembly]::loadwithpartialname('system.windows.forms') | Out-Null Run the same WMI query as before: $wmi = Get-WmiObject -Class Win32_computerSystem -Property UserName Then use the show method of the system.windows.forms.messagebox class to display the message box: [system.Windows.Forms.MessageBox]::show($wmi.username) Beginner Event 10 (VBScript) Georges Maheu is the Premier Field Engineer (PFE) Security Technology Lead for Microsoft Canada. As a Senior PFE, he focuses on delegation of authority (how many domain administrators do you really have?), server hardening, and doing security assessments using his own scripts. Georges has a passion for VBScript, Windows PowerShell, and WMI and uses them on a regular basis to gather information from Active Directory and computers. Georges also delivers popular scripting workshops to Microsoft Premier Customers worldwide. ------------ VBScript solution On Error Resume Next Set wmi = GetObject("winmgmts:") colitems = wmi.Execquery("Select user from Win32_computersystem") For Each item In colitem WScript.Echo item.username This is a classic: a script written by someone else without comments. In this situation, the first thing I do after examining the source code is to double-click the script in a test environment. Personally, I use Virtual PC for all my script development and testing. Never run a script in production until you fully and totally understand what it does. Well, running this script did not help. Nothing seems to happen. My next reflex is to comment out the first line and to add the Option explicit statement to force variable declarations: ' On Error Resume Next 'GLM: commented out Option explicit ’GLM: added The apostrophe character is used to add comments or descriptive text in a VBScript. In this case, it will prevent the error-handling statement On error resume next from executing. On error resume next makes your scripts ignore errors (no error messages either) and move on to the next line. I could have deleted the line but I like to keep the original code around while I debug. I also add comments preceded by my initials, GLM. Now, when I run the script, I get this dialog box: As a best practice, all variables should be declared, and adding the Option explicit statement makes this mandatory. Variables are declared with the Dim statement. I add the following: Dim WMI I then repeat the process until all the variables are declared: Dim colItems Dim item During this process, I notice there is a typo in colItem. An s is missing at the end! colItems = wmi.Execquery("Select user from Win32_computersystem") ' For Each item In colItem 'original code For Each item In colItems 'GLM: modified At this point, the code looks like this: ") ' For Each item In colItem 'original code For Each item In colItems 'GLM: modified WScript.Echo item.username And I get the following error message: A search (using Bing) on “vbscript error 800A01C2” may give you an indication of what the problem could be. Fortunately, I found a webpage with a similar problem and remembered that the WMI ExecQuery requires a Set to work: ' colItems = wmi.Execquery("Select user from Win32_computersystem") 'original code Set colItems = wmi.Execquery("Select user from Win32_computersystem") 'GLM: modified Let’s run the code and see what happens. OK, another error. And I thought this was going to be easy. However, line #10 (For Each item In colItems) seems to be fine. One thing you learn quickly when you write or debug scripts is that errors sometimes occur in cascades. If you can’t find anything wrong with a particular line, it could be the error occurred in the code before the line in which the error was reported. The question is, where? WMI, which stands for Windows Management Instrumentation, is in some respect Microsoft’s implementation of WBEM, a standard created by DMTF. WMI uses WQL, a query language similar to SQL. Knowing this, I decided to replace the WQL query with the following: ' colItems = WMI.Execquery("Select user from Win32_computersystem") 'original code Set colItems = WMI.Execquery("Select * from Win32_computersystem") 'GLM: modified I did this because the “*” is like a wild card character and will return all the properties associated with the Win32_computerSytem class. Unlike PowerShell, there is no simple way to list properties in VBScript. You could write some code (review Scriptomatic source code for an example), but this would probably be more work than debugging this code! Another option is to use CIM Studio from the free WMI tools. CIM Studio will give you a complete list of all the properties and methods for a given class. With this information, I could also have rewritten the line to: Set colItems = WMI.Execquery("Select userName from Win32_computersystem") Let’s run the script one more time. Yes! It works. Here is the working script after our debugging session: ") 'original code Set colItems = WMI.Execquery("Select * from Win32_computersystem") 'GLM: modified ' For Each item In colItem 'original code For Each item In colItems 'GLM: modified WScript.Echo item.UserName I save this version as a reference and then clean the code. You will notice I removed the On Error Resume Next statement. Because I’m not doing any error handling, there is no point using this statement. Here is the final script with added comments: ShowLoggedUserAccount.vbs '* File: ShowLoggedUserAccount.vbs '* Version: 1.06 '* Date: 2010/04/06 '* Author: Georges Maheu, Microsoft PFE '* '* Based on the original file '* File: VBScriptDoesNotWOrk.vbs '* Version: 1.0 '* Date: 2010/03/21 '* Author: John Doe '* Modifications: documented in file Debug-VBScriptDoesNotWOrk.vbs ' ' This script will display the name of the current logged-on user ' on a local or remote computer ' ================================================================ Option Explicit 'make variable declaration mandatory Dim WMI 'WMI service object Dim colItems 'collection of items returned by WMI query Dim item 'individual item from the WMI collection variable colItems Dim computerName 'name of computer to query 'LocalHost can be replaced by a remote computer name or IP address 'must be run from an account with sufficient permissions to see the data computerName = "localhost" 'create WMI service object and connect to CIMv2 namespace on computerName Set WMI = GetObject("winmgmts:\\"+computerName+"\root\CIMv2") 'retrieve userName property from Win32_computerSystem WMI class set colItems = WMI.Execquery("Select userName from Win32_computersystem") 'WMI ExecQueries returns a SWbemObjectSet collection data structure 'even when there is only one item in the collection. For this reason 'we use the For Each construct to list the userName property For Each item In colItems 'iterate through collection WScript.Echo item.userName 'display user name on screen Just for fun, I also created a very short version of this script: WScript.Echo GetObject("winmgmts:").Execquery("Select * from Win32_computersystem").itemIndex(0).userName Did I read somewhere recently that this syntax: [reflection.assembly]::loadwithpartialname('system.windows.forms') | Out-Null was deprecated in favour of Add-Type? (referenced at the end of the PS section above). Would love to have that link handy for a reference. Perhaps the scripting personages can answer.
https://blogs.technet.microsoft.com/heyscriptingguy/2010/05/28/expert-solutions-beginner-event-10-of-the-2010-scripting-games/
CC-MAIN-2017-34
refinedweb
1,632
55.34
Hi, i have a question about "how to run sikuli script in jython.exe or jython IDE" i'm not sure it's whether can be achieved,if could achieve in this way ,please let me know how ? i have worked with sikulix1.1.1 for 2 months and learned a lot. but still new for the sikuli and python. thanks very much. Question information - Language: - English Edit question - Status: - Solved - For: - Sikuli Edit question - Assignee: - No assignee Edit question - Solved: - 24 minutes ago - Last query: - 24 minutes ago - Last reply: - 2017-11-20 I've achieved to run SikuliX from Command Line in pycharm with relative path,like : ---------- import os os.system( ---------- my os is window 7.0. and i want to know how could i run sikuli code ,like: ---------- click(“x.png”) ---------- in pycharm with python script,but a sikuli script。 i am still study in this continue. thank you very very much,Raiman! You are a good man! it is suprise for me! I'll try this way in the link,and reply weather i work with it. now i had achieved to run sikuli scripts in pycharm with jython interpreter. and achieved to run sikuli scripts in eclipse with jython interpreter, or java application. in pycharm with jython interpreter is easy,can like this: ------- import sys sys.path. from sikuli import * from sikuli import Screen print "Hello World!Jython" x=1 print x any = Screen(0) any.click("1m.png") ------- the"C:\ ok, my english is not so good,if has any question about it,can email me:xiejiaohu@ i have readed the answer about"How we import sikuli.Sikuli.* module in python" /answers. launchpad. net/sikuli/ +question/ 136170 c:\Program Files\Sikuli\ sikulix. jar\Lib c:\Program Files\Sikuli\ sikulix. jar sikulix. jar" the page is https:/ i add path in os environment like: set JYTHONPATH= set CLASSPATH= set SIKULI="C:\Program Files\Sikuli\ but,the sikuli script in jython still not work.
https://answers.launchpad.net/sikuli/+question/660917
CC-MAIN-2017-51
refinedweb
328
84.27
This preview shows pages 1–3. Sign up to view the full content. View Full Document This preview has intentionally blurred sections. Unformatted text preview: Before introducing new material, here are the recursive versions of the algorithms from the previous days notes. Stacks A stack is a collection of items into which new items are inserted and from which items are deleted from only one end, called the top of the stack. Different implementations are possible; although the concept of a stack is unique. Example: Trays in the cafeteria. Stacks - 1 Data Structures: Stacks Practice: Create a recursive version of this function to create a linked list from an array of values. Answer will appear in the next set of notes. Practice: Create a recursive version of this function to count the nodes in a linked list. Answer will appear in the next set of notes. //Copies the contents of an array into a dynamically //growing list. struct node *array_to_list (int a[ ], int j, int n) { struct node *head; if ( j >= n) //base case return NULL; else { head = malloc(sizeof(struct node)); head -> data = a[j]; head ->next = array_to_list(a, j+1, n); return head; } } //Count the number of nodes in a list int count(struct node *head) { if (head == NULL) //base case return 0; else return (1 + count(head->next)); } A B C D E F G top There are two primary operations defined on a stack: o push : add a new item to the top of the stack.... View Full Document
https://www.coursehero.com/file/6296205/stacks14/
CC-MAIN-2017-13
refinedweb
253
70.73
DateField sample program in J2ME By: Jagan Printer Friendly Format First of all, notice that DateFieldDemo extends the Form class. The constructor simply adds a DateField object to the form and the necessary structure is in place. A DateField is simply a text element that displays a date and time. When you run this midlet, the first line in the output, "Date/Time in GMT," is the label and is specified in the first argument of the constructor. The second line is the date, and the third line is the time. The DateFieldDemo no-arg constructor in the program above demonstrates how to set the date of the DateField object using a java.util.Calendar object. This example displays the date and time because the constructor call specifies the display of both quantities. The DateField class defines three constants, which let you control what information is displayed. import java.util.Date; import java.util.Calendar; import java.util.TimeZone; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.DateField; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; /** Demonstrates the use of the MIDP UI DateField class. @see javax.microedition.lcdui.DateField */ public class DateFieldDemo extends Form implements CommandListener { private Command back = new Command("Back", Command.BACK, 1); private static Displayable instance; private DateField date = new DateField("Date/Time in GMT", DateField.DATE_TIME, TimeZone.getDefault()); /** Constructor. */ public DateFieldDemo() { super("DateField Demo"); Calendar cal = Calendar.getInstance(); date.setDate(cal.getTime()); append(date); addCommand(back); setCommandListener(this); instance = this; } /** Returns the single instance of this class. Calling this method before constructing an object will return a null pointer. @return an instance of this class. */ public static Displayable getInstance() { return instance; } public void commandAction(Command c, Displayable d) { if (c == back) { UIComponentDemo.getInstance().display(); } } } The third DateField constructor argument is the time zone specification, which is a java.util.TimeZone object. Beware of the fact that the MIDP specification requires implementations to support only one time zone. You should be aware of what time zones your implementation supports. It's quite possible that most MIDP implementations will only support one time zone. A DateField constructor call can specify a time zone that is not supported by your MIDP implementation. If the time zone you specify in the constructor is not supported by your MIDP implementation, your program will still execute without error or warning, but the DateField object's time zone will represent whatever time zone is supported by the implementation, not the one you requested. And the time displayed on screen will reflect the time zone used by the DateField object instead of the time zone you specified in the constructor call. DateField objects are editable. To edit them, 1. First, select the date field. 2. Click the Select button. You'll see the display change. 3. Scroll up and down to highlight the year, month, or day, and change each as desired. Notice that the implementation has placed a Back soft button and a Save soft button on the display. This interface presentation is typical of all editable components. When you finish editing and revert to the previous screen, the displayed date and time will have
https://java-samples.com/showtutorial.php?tutorialid=423
CC-MAIN-2019-47
refinedweb
531
50.53
I've been struggling with this assignment for some time, but I feel as though I've finally got a hold on it. Problem is, I got it to work ONCE, then changed one tiny thing and broke it. Okay, so the assignment was to write a program that computes how much an investment would be worth in a few years. Lots of cin for the various values and a formula that was a little bit annoying to figure out. Simple stuff, so you're probably all giggling at how I screwed it up. Laugh it up, fuzzball. So here's the formula: amount = principal(1 + rate / n) (n [A power. Dunno how to raise it in the post])(t [power again]) principal is the amount invested rate is the decimal percentage rate n is the number of times to compound per year t is time in years This is in math-speak, not attempted code. I'm not that dumb yet. So here's the sample run on the assignment paper: Enter: Principal: 5000 Rate as a %: 6 Number of years: 10 Number of times to compound: 4 If $5000 had been invested for 10 years at 6%, the investment would now be worth $9070.09. I feel the need to say this again: I got this to work. I put all the values in my code before trying the cin version, and it got it right. Not so anymore. So here's the code I've got: Code://Program to compute the value of and investment #include <iostream> #include <cmath> using namespace std; void main() { double principal, amount, rate, n, t, percent; cout << "Enter: " << endl; cout << "Principal: "; cin >> principal; cout << "Rate as a %: "; cin >> percent; rate = percent / 100.0; cout << "Number of years: "; cin >> t; cout << "Number to compound: "; cin >> n; amount = principal * pow(1 + rate / n, (n * t)); cout << "If " << principal << " had been invested for " << t << " years at " << rate << " %, the investment /n would now be worth " << amount << "." << endl; }
https://cboard.cprogramming.com/cplusplus-programming/70458-annuity-bank-interest-program-help.html?s=77b60c8103d54a44282e00186f3133d1
CC-MAIN-2020-40
refinedweb
331
75.44
#507 – Expander Control Lets you Expand/Collapse a Set of Controls March 5, 2012 4 Comments You can use an Expander control to hide a set of controls. When you click on the Expander, the hidden controls are shown. When you click again, they are hidden again. The Expander control is a ContentControl, so contains a single child element. This is typically a panel control, so that you can then include multiple controls in the panel. <StackPanel> <Expander Header="Goals" Margin="10" > <StackPanel Orientation="Vertical"> <CheckBox Content="Read Ulysses"/> <CheckBox Content="Visit Bruges"/> <CheckBox Content="Take out the trash"/> </StackPanel> </Expander> <Label Content="Next guy in vertical StackPanel is down here"/> </StackPanel> Notice that when the Expander is expanded, it takes up more room in the container (a StackPanel in this example) and other child elements are shifted. Pingback: Dew Drop – March 5, 2012 (#1,279) | Alvin Ashcraft's Morning Dew Pingback: #912 – Expanding an Expander Will Trigger Layout | 2,000 Things You Should Know About WPF Which namespace and assembly is used for this expander? System.Windows.Controls namespace, in PresentationFramework.dll.
https://wpf.2000things.com/2012/03/05/507-expander-control-lets-you-expandcollapse-a-set-of-controls/
CC-MAIN-2022-05
refinedweb
183
50.06
It should be rather easy to make this possible. We should also offer to merge declaration from ivy files with dependency declarations in the gradle build file. implementation if 'config by ivysettings.xml' should have priority IMO. Is there a target version for this ? Being able to have Ivy files would allow me to reuse the Ivy dependency information in the build process as well as in the IDE's of our developers, which is quite an important requirement for us. Alternatively having gradle support in our IDE's (in the sense that the IDE's can get their module configurations from the gradle build scripts) would also be acceptable, but then IntelliJ as well as Eclipse should be supported. I think it's easier if you can parse the ivy.xml files in gradle and let the existing IDE-Ivy plugins (ie. IvyIDEA and IvyDE) handle the IDE configuration. We might do it step-by-step. What would be very easy to implement is an Ivy-plugin that allows you to generate an ivy.xml and ivysetting.xml file from the Gradle dependency information. Gradle does this anyhow internally. The other way round is more difficult but has also a pretty high priority to use. I hope we can ship a first version of the Ivy plugin in 0.8. For me highest priority is to have ivy.xml per module of multi-project build. This feature would speed up or enable the adoption of gradle by companies who have an ivy based build in and also by allowing integration with IDEs via ivy plugins as mentioned above. What else is critical is to have the option to override the dependencies that are in the Gradle build file from the ivy.xml settings (and hopefully ivysettings.xml as well). This is important for a reproduceability of build reason - you need to know exactly what versions of what artifacts were resolved when the module was built and tagged and released. If you cannot rebuild the exact same release with the exact same versions of your dependencies, you don't have the same build. I say the ivysettings.xml as well, as some of us have different version range resolvers for compile scope vs run scope. That said, the resolvers themselves won't change in the Gradle build file, so it is less important. For me and my company, I don't think we can adopt Gradle until it can read ivy.xml files for module dependencies, for two reasons: The ivysettings.xml is less of an issue for us as that is a single file that can be manually maintained in parallel with a Gradle file. This feature would aid adoption of gradle. @Carl I absolutely see your point. But usually there are reasonable, pretty easy, work arounds. This issue here is for a generic import of ivy.xml's including the corner cases. We plan to solve this as part of a 1.0 milestone when we add further functionality to our dependency DSL. But for most enterprise use cases, where the structure of the ivy.xml is not using every degree of freedom Ivy allows, it is easy to write your own adapter which imports the ivy.xml into Gradle at runtime. We did this for a number of builds and it worked fine. We are talking about something like 30 lines of code. We did this for example as a POC for the Ant build of the spring core framework. BTW: I'm confident that IntelliJ and Eclipse will soon be able to understand build.gradle files. With the adapter approach, you then have the choice. Another thing we should and will provide is a script that coverts ivy.xml into build.gradle files. Thanks Hans. Please can you post some sample code for the adapter to allow import of ivy.xml into Gradle at runtime. I absolutely agree with Carl. We would like to adopt Gradle but need to solve this issue for the same two reasons that Carl described. Hans, would it be possible to see some example of those "30 lines of code"? I believe I would be able to tailor the adapter for our needs but it is difficult to write one from scratch. At my company we would migrate our old ant style build scripts (with no deps management) to gradle, but we need real IDE support to reflect dynamically resolved dependencies. Ivy integration is good on IDEs, while I haven't found yet a way to share gradle dependencies to the IDE (generating i.e. eclipse project artifacts is really not the same thing). So, the optimum for us would be having the IDE understand gradle dependencies (something like IvyDE). That said, we could fall back to use ivy descriptors into gradle scripts, but because of this issue, we should duplicate our dependencies declaration writing them both in gradle and also in Ivy descriptors: that makes the migration not acceptable. The alternative would be to write the adapter Hans mentioned above, but the fact that those "30 lines of code" example is not yet available sounds somewhat strange... PS: Please beware that the old copy of this issue has more votes than this one. I think it is due to the fact that people can still vote there and don't know about the new issue tracker (or at least I didn't know till some minutes ago and started voting there). Finally I have attached an import snippet which I used as a proof of concept for the spring-core build. Hi Hans, I've just easily adapted your snippet for my GWT project: it works like a charm! For other people interested on these details, this is the adapted snippet: import org.apache.ivy.core.settings.IvySettings import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor import org.apache.ivy.plugins.parser.xml.XmlModuleDescriptorParser import org.apache.ivy.core.module.descriptor.DependencyDescriptor import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency import org.apache.ivy.core.module.id.ModuleRevisionId //... configurations { compile runtime.extendsFrom compile testCompile.extendsFrom runtime } def rootProjectConfigurations = [ compile: configurations.compile, runtime: configurations.runtime, test: configurations.testCompile] IvySettings ivySettings = new IvySettings(); ivySettings.load(new File("ivysettings.xml")); DefaultModuleDescriptor moduleDescriptor = (DefaultModuleDescriptor) XmlModuleDescriptorParser.getInstance().parseDescriptor(ivySettings, new File("ivy.xml").toURL(), false); rootProjectConfigurations[mappableConfiguration].addDependency( new DefaultExternalModuleDependency(id.organisation, id.name, id.revision, descriptor.getDependencyConfigurations(mappableConfiguration)[0]) ) } } repositories { mavenCentral() ivySettings.getResolvers ().each { add(it) } } //... Thanks a lot to Hans. Cheers Davide UPDATE 20110519: I noticed that directly calling rootProjectConfigurations[mappableConfiguration].addDependency( new DefaultExternalModuleDependency(id.organisation, id.name, id.revision, descriptor.getDependencyConfigurations(mappableConfiguration)[0]) looses the changing attribute value, thus missing to get new version for snapshot deps marked as changing=true into ivy.xml, so it should be converted to DefaultExternalModuleDependency dep = new DefaultExternalModuleDependency(id.organisation, id.name, id.revision, descriptor.getDependencyConfigurations(mappableConfiguration)[0]) dep.setChanging (descriptor.changing) rootProjectConfigurations[mappableConfiguration].addDependency(dep) Thanks, Hans. I am among those who did not know about the Jira transfer to a new server. Not getting an answer on codehaus, I somehow managed to write my own script yesterday, similar to the one above. Today, I found this new thread. And I will be able to use it to make my script better and shorter. @Martin So you did not get any update emails for this issue from issues.gradle.org? Haven you been watching this issue on codehaus? Or just voted? @Davide how would you get it to work with the default configuration? @Leonard I'm not sure I understand your question: what do you mean with default configuration? As per my previous post I modified my gradle script to get dependencies from ivy resolvers and then merged them into the gradle standard compile classpath, and that's all: sourceSets { main { compileClasspath = configurations.compile + configurations.sdk //the latter is only for gwt } test { compileClasspath = compileClasspath + configurations.sdk } } But maybe you would mean something else... @Davide Yes I mean something else. In ivy you don't have to define a configuration like 'compile' or 'runtime' and if you don't the dependencies will get added to the 'default' configuration. My question is how can you adapt this script to work with the 'default' configuration. And could you please post the minimal ivy.xml and ivysettings.xml to get it to work with this script. I keep getting the error "Could not resolve all dependencies for configuration ':compile'. Cause: Unexpected cache manager default-cache for repository xyz" but using IvyDE in eclipse it works fine. @Leonard I declared ad-hoc named configurations on my ivy.xml and ivysettings.xml. I followed this example cause I have to produce gwt libraries. I've never used ivy default configuration directly from gradle, but I'd try adding to the compiler classpath that configuration as any other of interest with code similar to sourceSets { main { compileClasspath = configurations.default } PS: You'll notice some variables into xml files: I put them there when I had to duplicate deps between ivy descriptors (for IDE support) and the gradle script (the matter this issue solved). Now I could directly write most of them directly into ivy descriptors instead of reading them from gradle.properties. Just starting to try this out now using snippets from Hans and Davide (thanks guys). I think this is going to force me to learn the inner workings of Gradle on Ivy First thing I hit is that my resolvers are all instances of: org.apache.ivy.plugins.resolver.URLResolver, ChainResolver, and FileSystemResolver, and after they are added to the resolvers collection, their cache property is null. I think Ivy would then just use the default cache, but Gradle is having trouble with this: Cause: Unexpected cache manager default-cache for repository nfrepo-everything (nfrepo-everything) If anyone has some hints that would be great. I'm thinking that I'll need to pass more settings down from the local ivySettings to Gradle. So then the next big question is: how can I configure Gradle's underlying Ivy settings to be exactly like my Ant's Ivy settings? I don't mind writing DSL or Groovy to mimic what I do in ivysettings.xml, but I am having a hard time finding how to get at the general bits other than the resolvers. And even those seem to be specialized in Gradle and may not match what I have in my Ivy. Hey Carl, >Cause: Unexpected cache manager default-cache for repository nfrepo-everything (nfrepo-everything) For consistency reasons, gradle requires all remote resolvers to share the same instance of the repository cache manager. Hence this exception. My understanding is that you're initiating resolvers from the ivy xml files? I'd suggest that your script should make sure that the for each remote resolver the repository cache manager is null (that means it will use the 'global' default repository cache manager. >So then the next big question is: how can I configure Gradle's underlying Ivy settings to be exactly like my Ant's Ivy settings? It may depend on the complexity of your ivy configuration. At this moment I can think of 2 ivy features not supported by gradle: remote resolvers with separate repository cache managers (see above) and this GRADLE-1583. However, it does not mean that you cannot migrate your ivy project setup into gradle! I means that certain complex ivy configuration will have a different, possibly simpler implementation in Gradle. Let me know how we can help more! I have gotten past my resolver issues, and mostly using GradleIBiblioResolver. I am not sure what I had wrong before, but creating various resolvers from scratch and then adding them to the repositories containers works fine for me now. The next question is regarding some of the other settings that are generally used in ivysettings.xml: I extended the snippet to include transitive, artifacts, and exclude settings. There are still some things not mapped from the ivy.xml but this is another step in the right direction. import org.apache.ivy.core.module.descriptor.DependencyArtifactDescriptor import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency import org.gradle.api.internal.artifacts.dependencies.DefaultDependencyArtifact; import org.gradle.api.internal.artifacts.DefaultExcludeRule; //...// DefaultExternalModuleDependency dep = new DefaultExternalModuleDependency(id.organisation, id.name, id.revision, descriptor.getDependencyConfigurations(mappableConfiguration)[0]); dep.setChanging (descriptor.changing) dep.setTransitive(descriptor.transitive) descriptor.getAllDependencyArtifacts().each { DependencyArtifactDescriptor depArt -> dep.addArtifact(new DefaultDependencyArtifact (depArt.name, depArt.type, depArt.ext, null, depArt.url)); } def excRuleContainer = dep.excludeRules; descriptor.excludeRules?.values().each { def ruleList -> ruleList.each { def rule -> excRuleContainer.add(new DefaultExcludeRule(rule.attributes)) } } rootProjectConfigurations[mappableConfiguration].addDependency(dep) } } Could anyone please describe the exact steps needed to integrate the above script into a simple project (with a single build.gradle, for instance). Preferably for the 1.0-milestone-3 or above. I have tried using apply from: 'import-ivy.gradle' and copying the contents to ../build.gradle but neither approach works. Well, it half-works: I get appropriate output from dependencies task, but running compileJava or eclipse seems to behave as if no dependencies were resolved (e.g. I get an empty .classpath file). Is there a certain order in which this script, 'java' plugin and 'eclipse' plugin have to be evaluated? Update: I have experimented and found the following: 1. Doing project.configurations.myConf.addDependency(new DefaultExternalModuleDependency(...)) does not work 2. Doing project.dependencies.add("myConf", new DefaultExternalModuleDependency(...)) does not work 3. Doing project.dependencies.add("myConf", "${id.organisation}:${id.name}:${id.revision}") works! I am guessing DefaultExternalModuleDependency is not being initialised correctly, but not sure what exactly is the problem. No one else having issues with this?? I just published Ivyxml Plugin, that loads Ivy dependency files. The code snippets here got me started, but it's been much broadened and hardened since. It does not load ivysettings files, only ivy.xml files. @Blaine, thanks for the plugin and the reference! Thanks for addressing this and placing a plugin out there. After going through the readme here:, I'm failing to see what a proper ['confName'] will be, so my result is a BUILD FAILED "Cause: Configuration with name 'confName' not found." Chad: If you have any other issue with the plugin, please register an... Issue for it. You can use any Gradle Configuration name there, but it would demonstrate something useful regarding Ivy configuration if you entered an Ivy conf name (which will automatically mirror a Gradle Configuration name). I updated my Ivyxml plugin to support Gradle 2.x and have registered it on the Plugin Portal.
https://issues.gradle.org/browse/GRADLE-197.html
CC-MAIN-2021-31
refinedweb
2,418
50.43
Hi, I am running stable on a production machine (uptime > 1 year) on a 6000 hits/week system: (CentOs 64 bit) I solved problems with hanging connections (cousing "memory leaks") some hints and tips: Never ever connect to mysql globally but connect to mysql in you handler stage Not even consider connection pools, mysql is fast enough. make the connection a part of the request object so you can pass the request object around so req.connection and req.cursor exist. right after you make the connection do a req.register_cleanup to a function similair to: def closedb(req): req.cusor.close() req.connection.close() Now when users stop the downloading (by pressing the stop button)or when a python error occurs the connection is closed too. Otherwise mysql will keep the connection and runs out after a while (for me this happenend at around 19000 request but that depends on system configuration and installed memory. Off topic: when I started using SQLAlchemy i had to find a way to to this (since sqlAlchemy is using mysqldb) because this problem started to come back. I have found a way around it by using a "hidden" feature of SQLAlchemy, If people are interested please let me know, i'll post it. Martijn On Jul 19, 2006, at 11:04 PM, Deron Meranda wrote: > On 7/19/06, Jim Gallacher <jpg at jgassociates.ca> wrote: >> CentOS kernel issues resulting in similar problem (but not just >> mysql): >> > > Ah, I did not know about that one. From reading it, this sounds > almost exactly like the problem Martijn is probably experiencing. > I doubt mod_python memory leaks would exhibit the same type > of behavior Martijn describes. This is why I suggested > monitoring with vmstat...if this is the problem it should show up > quite obviously. (Of course I don't know what kernel Martijn > is running at this point in the thread) > > BTW, I'm also running everything under CentOS 4 as well > (with the 2.6.9-34.0.1.ELsmp kernel), but have not seen any > problems at all. But then I'm in IA32, and not IA64, which is > what this bug report as well as Martjin are running. So it looks > like a possible bad Linux kernel for 64-bit. > > Martijn, can you provide your kernel version, etc.? > > Good news is that a new fixed kernel is apparently on the way. > -- > Deron Meranda
http://modpython.org/pipermail/mod_python/2008-December/025853.html
CC-MAIN-2017-51
refinedweb
401
61.77
Large codebases are more difficult to maintain when they are written in dynamic languages. At least that's what Yevgeniy Brikman, lead developer bringing the Play Framework to LinkedIn says in a video presentation recorded at JaxConf 2013 (minute 44). Why does he say this? What are the reasons? See the full, original question here. The student has become the teacher Yevgeniy Brikman comments (2 votes): I'm the author of the Play Framework talk mentioned in the question. I was going to write a reply, but Eric Lippert's answer below says it better than I could have, so I upvoted it instead and recommend everyone reads it. The epic answer Eric Lippert answers (232 votes): dynamic languages make. Let me begin by saying that it is hard to maintain a large codebase, period. Big code is hard to write no matter what tools you have at your disposal. Your question does not imply that maintaining a large codebase in a statically-typed language is "easy;" rather the question presupposes merely that it is an even harder problem to maintain a large codebase in a dynamic language than in a static language. That said, there are reasons why the effort expended in maintaining a large codebase in a dynamic language is somewhat larger than the effort expended for statically typed languages. I'll explore a few of those in this post. But we are getting ahead of ourselves. We should clearly define what we mean by a "dynamic" language: by "dynamic" language I mean the opposite of a "static" language. A "statically-typed" language is a language designed to facilitate automatic correctness checking by a tool that has access to only the source code, not the running state of the program. The facts that are deduced by the tool are called "types." The language designers produce a set of rules about what makes a program "type safe," and the tool seeks to prove that the program follows those rules; if it does not then it produces a type error. A "dynamically-typed" language by contrast is one not designed to facilitate this kind of checking. The meaning of the data stored in any particular location can only be easily determined by inspection while the program is running. (We could also make a distinction between dynamically scoped and lexically scoped languages, but let's not go there for the purposes of this discussion. A dynamically typed language need not be dynamically scoped and a statically typed language need not be lexically scoped, but there is often a correlation between the two.) So now that we have our terms straight let's talk about large codebases. Large codebases tend to have some common characteristics: - They are too large for any one person to understand every detail. - They are often worked on by large teams whose personnel changes over time. - They are often worked on for a long time, with multiple versions. All these characteristics present impediments to understanding the code, and therefore present impediments to correctly changing the code. In short: time is money and making correct changes to a large codebase is expensive due to the nature of these impediments to understanding. Since budgets are finite and we want to do as much as we can with the resources we have, the maintainers of large codebases seek to lower the cost of making correct changes by mitigating these impediments. Some of the ways that large teams mitigate these impediments are: - Modularization: Code is factored into "modules" of some sort where each module has a clear responsibility. The action of the code can be documented and understood without a user having to understand its implementation details. - Encapsulation: Modules make a distinction between their "public" surface area and their "private" implementation details so that the latter can be improved without affecting the correctness of the program as a whole. - Re-use: When a problem is solved correctly once, it is solved for all time; the solution can be re-used in the creation of new solutions. Techniques such as making a library of utility functions, or making functionality in a base class that can be extended by a derived class, or architectures that encourage composition, are all techniques for code re-use. Again, the point is to lower costs. - Annotation: Code is annotated to describe the valid values that might go into a variable, for instance. - Automatic detection of errors: A team working on a large program is wise to build a device which determines early when a programming error has been made and tells you about it so that it can be fixed quickly, before the error is compounded with more errors. Techniques such as writing a test suite, or running a static analyzer fall into this category. A statically typed language is an example of the latter; you get in the compiler itself a device which looks for type errors and informs you of them before you check the broken code change into the repository. A manifestly typed language requires that storage locations be annotated with facts about what can go into them. So for that reason alone, dynamically typed languages make it harder to maintain a large codebase, because the work that is done by the compiler "for free" is now work that you must do in the form of writing test suites. If you want to annotate the meaning of your variables, you must come up with a system for doing so, and if a new team member accidentally violates it, that must be caught in code review, not by the compiler. Now here is the key point I have been building up to: there is a strong correlation between a language being dynamically typed and a language also lacking all the other facilities that make lowering the cost of maintaining a large codebase easier, and that is the key reason why it is more difficult to maintain a large codebase in a dynamic language. And similarly there is a correlation between a language being statically typed and having facilities that make programming in the larger easier. Let's take JavaScript for example. (I worked on the original versions of JScript at Microsoft from 1996 through 2001.) The by-design purpose of JavaScript was to make the monkey dance when you moused over it. Scripts were often a single line. We considered ten line scripts to be pretty normal, hundred line scripts to be huge, and thousand line scripts were unheard of. The language was absolutely not designed for programming in the large, and our implementation decisions, performance targets, and so on, were based on that assumption. Since JavaScript was specifically designed for programs where one person could see the whole thing on a single page, JavaScript is not only dynamically typed, but it also lacks a great many other facilities that are commonly used when programming in the large: - There is no modularization system; there are no classes, interfaces, or even namespaces. These elements are in other languages to help organize large codebases. - The inheritance system—prototype inheritance—is both weak and poorly understood. It is by no means obvious how to correctly build prototypes for deep hierarchies (a captain is a kind of pirate, a pirate is a kind of person, a person is a kind of thing...) in out-of-the-box JavaScript. - There is no encapsulation whatsoever; every property of every object is yielded up to the for-inconstruct, and is modifiable at will by any part of the program. - There is no way to annotate any restriction on storage; any variable may hold any value. But it's not just the lack of facilities that make programming in the large easier. There are also features that make it harder. - JavaScript's error management system is designed with the assumption that the script is running on a Web page, that failure is likely, that the cost of failure is low, and that the user who sees the failure is the person least able to fix it: the browser user, not the code's author. Therefore as many errors as possible fail silently and the program keeps trying to muddle on through. This is a reasonable characteristic given the goals of the language, but it surely makes programming in the larger harder because it increases the difficulty of writing test cases. If nothing ever fails it is harder to write tests that detect failure! - Code can modify itself based on user input via facilities such as evalor adding new scriptblocks to the browser DOM dynamically. Any static analysis tool might not even know what code makes up the program! - And so on. Clearly it is possible to overcome these impediments and build a large program in JavaScript; many multiple-million-line JavaScript programs now exist. But the large teams who build those programs use tools and have discipline to overcome the impediments that JavaScript throws in your way: - They write test cases for every identifier ever used in the program. In a world where misspellings are silently ignored, this is necessary. This is a cost. - They write code in type-checked languages and compile that to JavaScript, such as TypeScript. - They use frameworks that encourage programming in a style more amenable to analysis, more amenable to modularization, and less likely to produce common errors. - They have good discipline about naming conventions, about division of responsibilities, about what the public surface of a given object is, and so on. Again, this is a cost; those tasks would be performed by a compiler in a typical statically-typed language. In conclusion, it is not merely the dynamic nature of typing that increases the cost of maintaining a large codebase. That alone does increase costs, but that is far from the whole story. I could design you a language that was dynamically typed but also had namespaces, modules, inheritance, libraries, private members, and so on—in fact, C# 4 is such a language—and such a language would be both dynamic and highly suited for programming in the large. Rather it is also everything else that is frequently missing from a dynamic language that increases costs in a large codebase. Dynamic languages which also include facilities for good testing, for modularization, reuse, encapsulation, and so on, can indeed decrease costs when programming in the large, but many frequently-used dynamic languages do not have these facilities built in. Someone has to build them, and that adds cost. Related: "How to 'future-proof'.
http://arstechnica.com/information-technology/2014/06/why-do-dynamic-languages-make-it-difficult-to-maintain-large-codebases/
CC-MAIN-2014-52
refinedweb
1,754
58.32
Smart Phone (WiFi) Controlled Garage Door Opener With ESP8266 You can control anything with your phone nowadays. And it's never been easier for DIYers to make their own home automation components. Not long ago, you had to shop online for "smart home" gizmos, but now even the home improvement stores have a pretty decent selection in stock. And they aren't cheap. While some of these gadgets are pretty sophisticated, a LOT of them do one simple thing: switch a device on or off. That's all a garage door opener does - the wired button you likely have next to the door is a simple momentary switch. In this Instructable, we're going to recreate that momentary switch, and with ESP module, make it web enabled. With the addition of a magnetic door sensor, we get the added benefit of knowing whether the door is open or closed. For the price of around $10, you can control and check the status of your garage door from anywhere! Here's my disclaimer: THIS IS ONLY AS SECURE AS YOUR WIFI NETWORK. You are fully responsible for anything that happens to your garage if you use this prototype. This door opener can only be accessed by people on your home network. If you share your internet with other people, they will potentially be able to access your door. Step 1: Gather Your Parts To prototype it, you'll need: - An FTDI upload board like the one I covered here - Breadboard (example) - Power Supply (example) - Variable Breadboard Voltage (3.3/5V) Regulator (example) - 8 Pin ESP8266 to breadboard adapter (example) - ESP8266-01 (example) - Jumper Wires (example) - 220 Ohm Resistor (example) - Magnetic Reed Switch (common door sensor) (example) - Relay (example) To do a full build, you'll also want: Step 2: Upload Your Code With the FTDI upload board, load the following code to the ESP8266. You'll need to change the Router SSID/password variables, but that should be it. Before you upload the code, open the serial monitor in the Arduino IDE. Once the code uploads, it will write the module's IP address to serial - you'll want to make note of that. #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char*\n"; htmStr += "<meta http-equiv=\"refresh\" content=\"5; URL=/sdoor\"> \n"; htmStr += "<body>\n<center>\n<h1>\n"; if (switchStateCur==1){ htmStr += "Your Door is Open"; } else { htmStr += "The Door is Closed"; } htmStr +="</h1>\n<br><a href=\"/"; if (switchStateCur==0){ htmStr += "odoor"; } else { htmStr += "cdoor"; } htmStr += "\">\n<button>\n"; if (switchStateCur==0){ htmStr += "Open Door"; } else { htmStr += "Close Door"; } htmStr += "</button></a>\n"; htmStr += "<br><br><br><a href=\"/sdoor\"><button>Recheck</button></a>"; htmStr += "</center>\n</body>\n</html>\n"; return htmStr; } void setup(){ pinMode(switchPin, INPUT); pinMode(relayPin, OUTPUT); digitalWrite(relayPin, HIGH); Serial.begin(115200); WiFiCon(); server.on("/odoor", [](){ server.send(200, "text/html", htmlServe(0)); }); server.on("/cdoor", [](){ server.send(200, "text/html", htmlServe(1)); }); server.on("/sdoor", [](){ server.send(200, "text/html", htmlServe(2)); }); server.begin(); } void loop(){ switchStateCur = digitalRead(switchPin); server.handleClient(); delay(1000); } Step 3: Notes on the Code This is a BASIC garage door opener. You can get WAY fancier than what I've built here, and I encourage you to do so. This code leverages some ESP building blocks that I have covered before. If you want more detail, or a more simplified explanation of the component code, check out these Instructables: In this case, we amped up our web server code to include checking some variables and changing the message we display based on them (is the door open or closed), but the basic outline is still followed. One line of HTML I added here was: htmStr += "<meta http-equiv=\"refresh\" content=\"5; URL=/sdoor\"> \n"; When this string loads in the user's browser (your phone), it tells it to automatically refresh the screen every 5 seconds. AND it tells it to refresh it to "/sdoor". You'll notice that the action buttons on the webform call the URLs "odoor" and "cdoor" (open and close) - we don't want to refresh to those and re-initiate the action - so we go to "sdoor" (s for status) which takes no action on it's own. My garage door takes about ten seconds to open or close. The point of this refresh is to update the browser with the current status of the door without the user having to manually refresh the page to check. You can change the 5 seconds to whatever suits your door best. Step 4: Build Your Prototype Board Build out your breadboard.If you are using a breadboard power module, you can simplify this a bit, but the layout shown here is what will go into your final build. You could also directly build this to the proto-board, though my recommendation is to breadboard it first. Once the circuit is built plug your ESP in and fire it up. In a web browser, go to the sdoor "page" on the IP of the ESP. If the IP you got from the serial monitor was 192.168.0.153, then you need to enter this in the address bar: You should see a very simple page that tells the status of the door, and an action button to open or close it. Hold the magnet near the reed switch, and when the browser refreshes, you should see the status change. Hit the action button in the browser to open or close the door - you should hear a short click as the relay momentarily triggers. If you aren't getting these results, check your wiring and your code for issues. Step 5: Final Build Out Transfer your circuit from the breadboard to the proto board. I prefer proto board that has the connected strips. You can use my picture as a guideline, but any way you set up is fine. If you use board with connected strips, you need to break the strips between the two rows of the 2/4 female header that the ESP will sit in. A utility knife works fine, though I use a little cut off wheel on a small rotary tool. I also use the same cutoff wheel to slice little slits in the board for the barrel jack to sit in, since it has wide legs, not pins. Once your soldering is done, and BEFORE you plug the ESP in, use a multi-tester to check your connections. If they check, plug power in, and test the voltage going across various point, especially making sure that the ESP is only getting 3.3 V. Now you can plug the ESP in, and repower it to test it out like we did in the breadboard phase. I'll also use my rotary tool to make cutouts in the project box. Hot glue the proto board and relay to the bottom. Make some marks on the enclosure for where the plug goes in and the wires need to pass through, then use the cutoff wheel to cut them out. Step 6: Installation To install it, you need to find a place where the door sensor can reach the door, where you have access to an outlet, AND where your ESP can get a WiFi connection. The wired part of the sensor goes on the door frame. The magnet part goes on the door. Go ahead and laugh as you think about people setting it up the other way around. You will need some type of low voltage DC rated two-wire wire to connect the module to the garage door opener. I used thermostat wire, because that's what I had laying around - I needed about 15 feet. On the garage door opener, you should see where the two wires from the manual button connect - you are connecting to these same terminals. Connect the other end to our opener module's relay - one to the common pole, the other to the NO (normally open) pole. TEST IT OUT! If everything works, staple the wiring down to pretty it up, use some double-sided tape to stick the project box to the wall, and you are DONE! Step 7: Access From Anywhere As it stands, our opener is only accessible from clients connected to your home router. I won't cover here the exact steps to open it up to full access from outside your network here - as that varies greatly depending on your router. I will give you two suggestions though to help you further: 1. If you are familiar with port forwarding, it is easy to add a rule in most routers to funnel certain outside calls from the internet to specific devices. Check your router's manual on how to manage port forwarding rules. 2. We did NOT set a static IP on our ESP. Potentially, it could get a different address if it reconnects. We could add code to the ESP to have it tell the router what address it wants. Instead, I prefer to let the router manage this. Most routers allow manual setting of IP addresses for certain clients, usually in the DHCP Server settings. Again, check your router's manual for instructions. I hope you've enjoyed this Instructable!
http://www.instructables.com/id/Smart-Phone-WiFi-Controlled-Garage-Door-Opener-Wit/
CC-MAIN-2017-17
refinedweb
1,544
69.92
Learn more about Scribd Membership Discover everything Scribd has to offer, including books and audiobooks from major publishers. Professional Pilots Ray Preston 2010Navigation for Professional Pilots Page 2Navigation for Professional Pilots Introduction: This text was created for use in the course Avia 160 as part of the Selkirk College Professional AviationProgram, which leads to the Canadian Commercial Pilot License with Multi-engine and Instrument Rating. This text is intended as an adjunct to a 48 hour lecture series on the topic of navigation. Assignments,tests, and exams supplement this text and the lectures. Flight planning exercises include both VFR and IFRcross-countries. Students will become expert at preparing VNC maps and completing navlogs for VFR crosscountries. They will also use LO charts and the Canada Air Pilot to plan IFR cross-countries. This book explains both theoretical and practical principles of flight navigation, including visual and radionavigation based on VOR, ADF, and DME. This course covers principles of intercepting and maintaining aradio course. It also covers flying DME arcs. An introduction to procedure turns is included. The text is supplemented by several computer simulations of the Selkirk College Aviation Intranet, which ison the web at Selair.selkirk.ca. Students in this course are expected to become expert at the use of the CR(or 6) navigation computer. This text was written based on the assumption that readers hold a private pilot license and as such havecertain basic knowledge about aviation in general and navigation in particular. Page 3Navigation for Professional Pilots Page 4Navigation for Professional Pilots Table of Contents:Chapter 1 .......................................................................................................................................................13 Chapter 2 .......................................................................................................................................................35 Definition of Velocity, and two useful deductions from the definition .................................................35 ICE-T ................................................................................................................................................38 Page 5Navigation for Professional Pilots Chapter 3 .......................................................................................................................................................59 Bracketing .................................................................................................................................................64 Page 6Navigation for Professional Pilots Chapter 4 .......................................................................................................................................................95 LO Charts ..............................................................................................................................................95 HI Charts...............................................................................................................................................96 Page 7Navigation for Professional Pilots Longitude...................................................................................................................................... 141 Page 8Navigation for Professional Pilots Page 9Navigation for Professional Pilots Page 10Navigation for Professional Pilots Page 11Navigation for Professional Pilots Page 12Chapter 1Text OverviewEveryone knows what it means to “have a plan.” In “flight planning” we develop a plan for a flight. Forexample your plan might require knowing: What navigation equipment (from eyeballs, to VOR, to GPS, etc.) will be used Accommodation at destination Customs arrangements ETC The above list is not complete; the point being made here is that flight planning is a large undertakingcovering many different items of concern regarding a flight. At an airline many people are employed toensure that all the passenger handling aspects of flight planning are looked into. Experts also plan routesfor optimum advantage (cost) taking wind, ATC fees, departure and arrival fees, etc. into account. Theprocess can be very complex. For example, many international airline flights don’t fly by the shortest routefor two reasons: For one every nation they over fly charges a fee, so flights may detour around someNavigation for Professional Pilots airspace spending more money on fuel, but saving in the long run by avoiding high ATC fees. In addition,the shortest route is not always the quickest, if a strong tailwind (jet stream) can be located, or a strongheadwind avoided. By the end of this course you must be fully competent at planning VFR flights, but, most commercial airlineflights are IFR flights, and as such are governed by a set of regulations that you will learn to take intoaccount during this course. For example, one requirement is to have an alternate airport to divert to in theevent that landing at the primary destination becomes impossible. By the end of this course you will befully competent to plan an IFR flight from any point within Canada to any other point. International flightswill covered in second year. In this course we will concentrate on the planning time and fuel for a flight. Route selection will becomparatively simple. We will consider the preferred IFR routes published in the Canada FlightSupplement, and terrain and weather. We won’t usually concern ourselves with avoiding ATC fees orpolitical boundaries because most of our flights will be domestic. Airline flight planners often adjust toavoid these, but we will concentrate on choosing an altitude that is optimum for the wind given a specifiedroute. Flight logistics such as arranging food for passengers, where to park and service the airplane, etc won’treceive a lot of attention due to our limited time. But you must recognize that these things are crucial toreal world commercial flight operations. You will learn where to find the required information, and someof these matters will be included in the exercises. After graduation, expect passenger handling and logistics aspects of flight planning to take considerablymore of your time than calculating time and fuel. By the end of this course you should be able determinetime and fuel for a given flight within a few minutes. For your commercial pilot flight test you are allowed45 minutes, but that should be twice as much time as you actually need. Your skill at doing this level ofbasic flight planning quickly and accurately will free up the time for the logistics aspects of flight planningthat your employer will expect you to master. Pilotage means flying from point to point by visually following features on the ground. It is the way youdrive your car and it is often a practical way to fly an airplane. For example: to fly from Castlegar toRevelstoke simply follow the Columbia River. Dead-reckoning (DR) means to determine the one heading and time that will take the airplane directly to apoint, allowing for wind. DR is by definition flight along a straight line path. Most of this course is devotedto learning how to dead-reckon. Radio navigation means that the location of the airplane is determined by referring to instruments such asVOR, ADF, or GPS. This is necessary when flying IFR. In this course you will learn the basics of IFR radio Page 14Navigation for Professional Pilots navigation. Radio navigation is NOT distinct from pilotage or DR; in fact both can be applied to radionavigation. In real-world VFR navigating, pilots use a combination of pilotage and DR. DR dominates on long flights,especially over terrain that lacks distinctive features. Any VFR flight over water must be a DR flight forexample. Pilotage dominates on shorter flights, but it can only be used when the ground has distinctivefeatures so that the pilot can accurately determine position visually. Even on a long flight some portions ofall VFR flights require pilotage. Usually the leg just after takeoff until established at the set heading pointrequires pilotage. And the final circuit joining and landing is also a pilotage leg. DR is the most efficientmeans of navigation, but if the terrain has good, distinctive, features some pilotage is practical especiallywhen doing things such as diverting around poor weather or special use airspace. Often some radio navigation will be used, even on a VFR flight – thus most flights require pilotage, DR, andradio navigation. In this course we will generally keeps these techniques separated for instructionalpurposes, but in the real world they should be used together to achieve an efficient flight with the lowestpossible workload for the pilot. Page 15Navigation for Professional Pilots Sample Questions 1 1. A pilot sees a local shopping mall and flies toward it. a. This is DR navigation 2. A pilot is over a town s/he recognizes and turns south to join left base for the active runway 3. A pilot tunes a VOR and determines the track to the station is 030°. S/he then turns to that heading without concern for the strong westerly wind. The pilot turns left, then right, then left again, following the VOR needle until s/he gets to the station. 4. A pilot is trying to find a small lake. S/he flies a heading of 220 until the lake comes into sight, then flies directly to the lake. Page 16Navigation for Professional Pilots 5. A pilot follows a road to a particular intersection then flies heading 360 until the airport comes into view. Page 17Navigation for Professional Pilots The ISA is simply a temperature model, i.e. it specifies how temperature changes in the atmosphere. TheISA is divided into temperature layers known as the troposphere, stratosphere, and thermosphere. Thestandard temperature is 15 C at sea level and decreases 1.98 C per thousand feet in the troposphere. By36,100 feet the temperature has reached -56 C. In the Stratosphere temperature remains isothermal(constant temperature) at -56 C. In the thermosphere temperature begins to rise again, but no civilianaeroplanes fly that high so we will ignore the thermosphere. The chemical makeup of the atmosphere does not change with altitude. The temperature, chemistry of theatmosphere, and the force of gravity collectively determine the pressure and density of the air throughoutthe ISA. It is important to realize that temperature, pressure, and density are inextricably connected toeach other by a law of physics called the gas law. The gas law states that pressure is proportional todensity and temperature. You can find more details on this in your aerodynamics text. Page 18Navigation for Professional Pilots Aircraft performance depends on air density but airplanes do not come with an instrument to measure it.They do however have a thermometer to measure temperature and an altimeter, which measures airpressure. The gas law relates air density to these two values. In the ISA the following values apply: Pressure ISA Temp Density 3 Altitude C Inches Hg slugs / ft Pressure AltitudeThe most convenient instrument available to pilots for measuring air pressure is the aircraft altimeter.Pilots do not have a barometer (an instrument for measuring air pressure) to measure pressure in units ofinches of mercury. When a pilot sets the altimeter scale to 29.92 it reads an altitude, but in effect it isgiving the air pressure from the table above. Once set to 29.92 altimeter reads an altitude called pressurealtitude. If the pressure altitude is 4,000’ the air pressure is 25.84 as shown in the table above. Fill in thevalues for air pressure in the table below: Page 19Navigation for Professional Pilots Inches Hg Sea level 3000’ 5,000’ 7,000 9,000 The only way to get a precise pressure altitude is to set a calibrated altimeter to 29.92 and read the valueon the instrument. This is not convenient for flight planning however, so we need a method to estimatepressure altitude. Notice that in the ISA pressure drops about one inch of mercury for every thousand feet up to 10,000’. Thisis an approximation, but it is pretty close. Armed with this knowledge it is possible to calculate thepressure altitude without using an actual altimeter. This is convenient since it means we can flight planwithout needing access to an altimeter. To calculate pressure altitude we need to know the currentaltimeter setting and the actual altitude of the altimeter setting source. First a very simple example: An airport at sea level (such as CYVR) reports an altimeter setting of 28.86. Inthis case the air pressure is 28.86 and the pressure altitude is 1000’ as we can see from the table above.How would we calculate this mathematically? Difference +1.06 Page 20Navigation for Professional Pilots Notice that the calculation gives a value of 1060’ when the correct value is 1000’. This small error isacceptable for flight planning purposes. You should keep in mind that the calculation of pressure altituderesults in estimation. To get a precise pressure altitude you must use a calibrated altimeter. Below is a more complex pressure altitude calculation in which the altimeter source is not at sea level. Difference -0.75 TIP: You may find it hard to remember whether to add or subtract the correction from the altimeter sourcealtitude. Remember that when the altimeter setting is more than 29.92 it is like flying at a lower altitude,and vice versa. Density AltitudeDensity altitude represents the altitude in the ISA with the equivalent air density. Once you know thepressure altitude (in effect the air pressure) and air temperature, density altitude can be calculated inaccordance with the gas law, which states that air density is proportional to air pressure and inverselyproportional to air temperature. Page 21Navigation for Professional Pilots Many Pilot Operating Handbooks are designed so that it is not necessary to calculate density altitude sincethe manufacturer provides performance charts based on pressure altitude and temperature. This is wiseon their part because calculating density altitude accurately requires a complex formula. The C-172 and King Air manuals you will use in this course have charts based on pressure altitude andtemperature. In effect the density altitude calculation is incorporated into the charts. For these airplanes itis not necessary to calculate density altitude. Our B95 charts are based on density altitude, and therefore you must calculate its value. Becausetemperature is usually close to standard a reasonable estimation of density altitude can be made byadjusting pressure altitude 120 feet for every degree the temperature varies from standard. For example ifthe temperature is 3 C colder than ISA then density altitude will be 3 x120 = 360 lower than the pressurealtitude. If air temperature is 5 C above standard then density altitude will be 600 feet higher than thepressure altitude. Warm air is less dense air and thus density altitude is greater when the air is warm. The KLN90b GPS has a built in density altitude calculator. You can use it to get a more accurate densityaltitude. The KLN90b in the piston simulators can be used just as well as the ones in the airplanes. Page 22Navigation for Professional Pilots Sample Questions 2 1. The altimeter source altitude is 1000, altimeter setting is 28.92, temperature at 1000 feet is 15 C. Calculate the pressure altitude (PA) and the density altitude (DA) 2. The altimeter source altitude is 7000, altimeter setting is 28.92, temperature at 7000 feet is 15 C. Calculate the pressure altitude (PA) and the density altitude (DA) 3. The altimeter source altitude is 8500, altimeter setting is 30.86, temperature at 8500 feet is - 22 C. Calculate the pressure altitude (PA) and the density altitude (DA) 4. altimeter source altitude is 1624, altimeter setting is 30.35, temperature at 1624 feet is 18 C. Calculate the pressure altitude (PA) and the density altitude (DA) 5. The altimeter source altitude is 1624, altimeter setting is 29.71, temperature at 1624 feet is 7 C. Calculate the pressure altitude (PA) and the density altitude (DA) Page 23Navigation for Professional Pilots This table is correct for an altimeter set with the Colesman scale on 29.92 The table shows that an altimeter “assumes” pressure will drop 1.10 inches of Mercury betweensea level and 1000 feet and then drop 1.06 between 1000’ and 2000’ etc. Consequently an altimeter set to29.92 will read 7000 feet when the air pressure is 23.09 regardless of how high the airplane really is. The Colesman scale on the altimeter simply “slips” the above scale to reset the zero point, asshown in the diagram below, which is for an altimeter set to 30.44 Page 24Navigation for Professional Pilots This table is correct for an altimeter with the Colesman scale set to 30.44. When the actual airpressure is 30.44 the altimeter reads zero. Page 25Navigation for Professional Pilots IMPORTANT: altimeter settings are determined with an instrument located at the airport. Takingthe above table as an example, if a particular airport is at 3000 asl an altimeter adjusted to read 3000 atthat airport will “report” an altimeter setting of 30.44. The pressure difference between 3000 and sea levelshown in the above table (30.44 – 27.37) is only hypothetical. The actual sea level pressure may not be30.44 on that day, but the altimeter will read 0 feet if the actual air pressure is 30.44. Since this is only ahypothetical possibility it is not important. The thing to realize is that an altimeter setting permits thealtimeter to read the correct altitude at the airport (3000 in the example), because that is where thealtimeter setting instrument is located. Any temperature correction that an over flying airplane makesneed only be applied to the atmosphere between ground level and the true altitude of the airplane. In the table above you can see that when the air pressure is 18.82 the altimeter reads 13,000 feet.This will happen regardless of the true altitude. If the air pressure between ground level and 13,000 dropsexactly as shown in the table the altitude will be correct. More likely the pressure drop will vary from thatshown and thus the true altitude will not correspond to the indicated altitude. If the air pressure declines with altitude more rapidly than the above table the true altitude willbe lower than the indicated altitude. This is very dangerous for any pilot flying in instrument conditionsand using the altimeter to avoid mountain tops. Pressure decreases more rapidly in cold dense air. Thus we must correct for temperature error anytime the temperature is cold. RAC 9.17 specifies our legal obligation to calculate a temperature correction. A correction isrequired any time temperatures are significantly below standard. Normal practice among pilots is to makea correction anytime ground temperature is 0°C or colder. Three methods of making the correction will bepresented in this course. In order of preference in use they are: 3. CR RAC 9.17 recommends allowing 4% height increase for every 10°C below standard temperature.This rule of thumb should only be used down to temperatures of -15°C. Memorize the rule of thumb andbe able to use it; the corresponding formula is: The above formula gives the required correction, which should then be added to the desiredaltitude to get the indicated altitude you will fly in order to be safe. Remember to keep ATC informed ofwhat altitude you are flying. This is particularly important if you will deviate from any specified altitudesuch as a missed approach altitude or an altitude on a DME arc, etc. RAC 9.17 specifies that you shouldalso report deviations from FAF crossing altitude and MDA, but as these are minimum altitudes that you Page 26Navigation for Professional Pilots can choose to be above on any approach most pilots do not report these deviations. However, you mustconsider carefully whether any conflict with other traffic could result from your temperature correctionand keep ATC informed as necessary. For temperature colder than -15°C use the table in the CAP GEN. This table can also be used fortemperatures of 0°C and -10°C; however it is based on an airport at sea level and therefore givesconservative corrections for airports that are higher than sea level. If you use the equation above you get amore accurate correction for airports that are above sea level. To use the table in the CAP GEN follow theinstructions provided with the table. Note that RAC 9.17 states that the table is not valid for heights morethan 5000 ASL. Many mountain approaches however have procedure turn and intermediate segmentaltitudes higher than 5000 AGL. It is common practice among pilots to use the table by summing values,for example adding 5000 and 3000 to get 8000. When doing this always round up each value obtained inorder ensure safety. Page 27Navigation for Professional Pilots Performance ChartsYou must master the use of all the performance graphs, charts, and tables in the C-172P POH, BeechcraftTravelair Pilot Information Manual, and your Alsim (King Air) manual. Supplements to the C-172P POH arefound in Appendix 14 of your Program Manual. A complete explanation of how to use each chart, table,and graph cannot be provided here, but most are self explanatory. Assignments are provided for you topractice using these planning aids and to confirm that you are using them accurately. The aviation Intranet provides links to many electronic aids that ease your flight planning chores, making itpossible to plan a flight in a much shorter time. You will be using these aids daily as you prepare for flightsbut it is CRITICAL that you can perform the calculations without them should the need arise. Consequentlythe assignments in this course – and the quizzes and exams – are to be completed without these onlineaids, unless the instructions indicate otherwise. Normal aviation industry practice is for flight departments to establish a cruise power setting and use it forall but “special” flight situations. A special situation is one in which either an unusually long range isneeded, or an unusually high speed, or some other situation requires a non-standard power setting. Forexample you might be asked to ferry an airplane over a distance that exceeds its normal range, but thatcan be achieved if slower than normal speeds are used. Alternatively, you might be asked to brake-in anew engine by operating it at 75% power for a certain number of hours. In such cases you must flight planfor a power setting different from that normally used. a. BE95 a. C-172 manual Both these skills are vital. You will be given assignments to practice these skills, but if these are not enoughyou must practice until you perfect the skill. Practice these skills using the computer simulations provided for that purpose. Page 28Navigation for Professional Pilots On our Intranet website several electronic aids have been provided. These electronic planning aids aremuch quicker and easier to use than the paper products. They are similar to the professional flight trainingaids used by modern airlines. You will use these electronic aids for your day-to-day flight operations in theaviation program. For the C-172P you will find: The Normal Takeoff distance graph is an electronic version of the two graphs in the C-172 Flight PlanningSupplement. It gives Normal Takeoff Distance, and Accelerate Stop Distance. It is much quicker and easierto use, and always gives the correct answer. Use it prior to all flights to get your normal takeoff distance.Use the tables on pages 5-12 and 5-13 when short field operation is called for. The ENL has a built in weight and balance sheet, a cruise performance calculator, and a Navlog calculator.The weight and balance calculator eliminates the need to use the charts in section 6 of the POH. Thenavlog automatically determines TAS, CAS, IAS, rpm, eliminating the need to use any charts in section 5 ofthe POH. It also calculates drift, groundspeed, ETE and fuel required for the flight i.e. it performs thefunctions of a flight computer. Navlogs are covered later in this course. Remember that even though you will be using the electronic navlog for your day-to-day flying, whichmakes things very quick, easy, and accurate, you must be able to do all the calculations long-hand whenneeded. On your exams you will have to calculate without the electronic aid. When doing assignments youshould do all the calculations by hand and then use the electronic navlog to see if you made a mistake. The ENL contains a weight and balance calculator for quick, easy and accurate weight and balancecalculations. Page 29Navigation for Professional Pilots Most “good” grass runways require 25% more distance than a paved runway 90% - (headwind component / rotation speed)% = percent change in takeoff roll and distance to clear obstacle. (e.g. 12 knot headwind and Vr = 94 therefore 90% - 12/94 = 77% 110% + (tailwind component / rotation speed)% = percent change in takeoff roll and distance to clear obstacle. In Avia 100 you will learn to use the above rules of thumb to make reasonable go – no go decisions intricky takeoff situations. Page 30Navigation for Professional Pilots The above question is a Transport Canada favorite on the commercial pilot and ATPL exams. The solutionis quite simple if you remember the meaning of the concept known as moment. A moment is: weight xarm. At present we know the moment of the airplane is: The difference in moment, which is 1000 could be created by an infinite number of possible weight shift.For example we could shift 1000 pounds forward 1 inch, or 500 pounds by 2 inches, etc. In this case wehave been told to shift 400 pounds of freight, so it must be moved 1000/400 = 2.5 inches. An important point to notice is that it makes no difference what the current location of this freight is, onlythat we move it forward at least 2.5 inches. In summary: Step 1: Calculate the current moment and desired moment, subtract to get the desired moment shift. Page 31Navigation for Professional Pilots Here is a typical transport Canada exam question, choose the correct answer: An airplane weighs 9000 pounds. The CG is 73 inches aft of the datum, The aft CG limit is 71 inches aft ofthe datum. There is 600 pounds of freight at 104 inches aft of the datum. Shift this weight to at least: a) 85 b) 75 c) 65 d) 55 M-change = 18000 The answer is therefore: 104 – 30 = 74. Most people will therefore choose b, but that is WRONG. If youmove the weight to arm 75 it is still one inch too far back. Since the next lowest option is 65 that is thecorrect choice on this multiple choice question. Page 32Navigation for Professional Pilots Page 33Chapter 2This chapter introduces you to the fundamental concepts of navigation. Everything in this chapter is vital.If you don’t understand and retain it 100% there will be a problem, so review this material often. 1. Mass 2. Distance 3. Time All other concepts from simple ones live velocity and acceleration to complex concepts such as work,power, energy, etc. are all composites of these three concepts. Even concepts that may not at first appear to be composites of the above three actually are, for exampletemperature is really just a measure of the velocity of particles, which in turn is the composite of distanceand time. Velocity is a vector quantity. In other words it has both magnitude and direction. The direction is impartedto the velocity by the orientation of the distance. Think about what this means and we will discuss it inclass. d = Vt T = V/d To be more precise Groundspeed and direction of flight are the fundamental concepts in navigation. Oncewe know our groundspeed (GS) and track-made-good over the ground (TMG) we know everything we needto know to predict the time it will take to complete a flight. Unfortunately there is a confusing array of speeds that we must learn to sort through:Navigation for Professional Pilots You should already know that an airspeed indicator (ASI) does not show TAS. What a pilot actually requires to fly safely is the Equivalent Airspeed (EAS.) An airplane always stalls at acertain EAS, and we always fly our approach at a certain EAS. Think of EAS as the pressure you would feelon your face if the airplane had an open cockpit. Unfortunately airspeed indicators do not show EAS either, so we must learn to convert indicated airspeed(IAS) to Calibrated Airspeed (CAS) and then to EAS and finally TAS. In summary – life for pilots would be much better if there was only EAS and TAS. Unfortunately we mustlearn to deal with the undesirable IAS and CAS You can also determine TAS in flight by reading your IAS and applying correction for: Compression error Density error Page 36Navigation for Professional Pilots Mathematically: TAS = EAS/√σ [σ is the density ratio, i.e. density of air divided by sea level standard density] The good news is that there is usually not much difference between IAS and EAS. Most of the time it isreasonable to assume that the indicated speed is the same as equivalent speed. At very slow speeds (highangle of attack) there will be a significant error, and also at very high speeds and high altitudes, above 200knots and 20,000 feet there will an error. Indicated airspeed is by definition the speed shown on the airspeed indicator. Like any instrument andairspeed indicator is imperfect and as such a calibration chart must be provided. The calibration chart isfound in the POH. The calibration chart compensates for the imperfect measurement of Pitot tube andstatic port on the airplane. Once you apply the correction factor you will have calibrated airspeed (CAS.)Most of the calibration error is due to the position of the static vent on the fuselage, therefore calibrationerror is frequently called position error. Calibrated airspeed is pretty close to equivalent airspeed in most cases. In fact the difference between EASand CAS is less than one knot for airplanes flying less than 200 knots and less than 20,000 feet. That coversboth the C-172P and Travelair. So, for these airplanes you may feel free to say that EAS = CAS. Page 37Navigation for Professional Pilots For any airplane flying above 20,000 feet (which includes the King Air) it will be necessary to apply acompression correction factor. Compression refers to the fact that air entering a Pitot tube is compressedand thus its pressure rises; consequently airspeed indicators always over read. CAS is always more thanEAS. So an airplane flying at 250 KCAS at 30,000 feet is experiencing less than 250 KEAS. Your CR flight computer automatically applies compression correction, if you use the “professionalmethod” for converting CAS to TAS. The “simple method” DOES NOT allow for compression error. ICE-TTo convert from IAS to TAS it is necessary to apply the corrections in the proper order. Always convert IASto CAS, then CAS to EAS, then EAS to TAS. To remember the sequence, use the pneumonic ICE-T. Remember that with the CR you go directly from CAS to TAS, but that is because the EAS compensation isbuilt into the computer. We cover use of the CR later. Page 38Navigation for Professional Pilots Heading is expressed as an angle from north. Heading can be expressed in magnetic, true, or grid, butalways in units of degrees. The earth spins around an axis that passes through the north and south poles. Straight lines drawnbetween the poles are called meridians of longitude. These lines define true north. Meridians appear onyour map and you will learn to orient your protractor to these lines of longitude when measuring the truetrack (TT.) In the northern domestic airspace pilots set their heading indicators to true. In that case the headingsdisplayed on the heading indicator are true headings. In the southern domestic airspace, pilots set their heading indicators to magnetic. The magnetic NorthPole is many miles from the real North Pole and thus there is a difference between magnetic headings andtrue headings. The difference is called variation, and you will find it marked on your maps. We will becovering map theory in detail later. When flying over the poles neither true nor magnetic heading reference is satisfactory. In such casesanother reference system known as grid is used. Compass DeviationLike any piece of equipment a compass is never calibrated perfectly. The error in the compass is calleddeviation. Each aircraft compass comes with a deviation card that shows the extent of the error. As a pilotyou must consult the deviation card and take it into account when setting the heading indicator tocorrespond to the compass. Imagine that your balloon rises a few hundred feet and then maintains that altitude. You follow it anddiscover that it more-or-less drifts in a straight line. This is important because it will be difficult to flightplan if air moves in random fashion. Fortunately it generally moves in a steady continuous fashion, at leastover a distance of a few miles. The primary complication in navigation planning involves allowing for thismovement of the air (wind) i.e. allowing for drift. Wind is described by specifying the direction the air is coming from and how fast. When we say the wind isnorth at 15 knots we are saying that it is coming from the north, i.e. moving south, 15 nautical miles everyhour. If you release your balloon into this air mass it will be 15 NM south after one hour, 30 NM south aftertwo hours, etc. Page 39Navigation for Professional Pilots Most people find it pretty easy to visualize a balloon drifting in the wind. The main difficulty is in realizingthat wind is a large scale phenomenon not a stream within the air but the whole air. Do NOT think of windas something that happens in the air but as a property of the whole air mass you fly in. While it is obvious that a balloon drifts it is equally true, if less obvious, that an airplane does also. Anairplane moves through the air, which a balloon does not, but the movement of the air (wind) adds to thenet movement of the airplane never-the-less. An airplane’s net motion is the sum of true airspeed andwind. True airspeed is a vector quantity that expresses how quickly an airplane moves through the air, andin what direction. To explore the meaning of drift examine the simulation called Drift on the Intranet website. GS = TAS + wind All three of these entities are vectors. So, all we have to do is remember how to add two vectors. When dead reckoning you start with a known true airspeed and a forecast wind plus a track you wish tofly. Your task is to determine the heading that is required to maintain that track and the resultinggroundspeed (so that you can calculate time to destination.) We will now learn the simplest method of solving the above problem. No calculators or mathematics isrequired. We will simply draw a picture. But it must be an accurate picture so get out your navigation-rulerand protractor and follow along. For our first sample problem we wish to fly from airport A to airport B. The distance between them is 240NM and the true track is 050°. The wind is from 270° at 20 knots. The airplane flies at a true airspeed of100 knots. 1. Draw a vertical line roughly in the center of the paper which we will use to represent a meridian of longitude (i.e. it represents true north.) 2. Make a small “x” in the lower left quadrant of the sheet to represent airport A. We put it in the lower left quadrant because we are going to fly north-east so we want to allow room to draw the line to airport B. Page 40Navigation for Professional Pilots 3. Center your protractor on airport A and orient it to north using the line of longitude. Mark 050° and then draw a line from airport A in the direction 050°. At this point your paper should look like the one below: The line represents the track to airport B. We call this the track-made-good (TMG.) We don’t need to markon airport B. 4. Next we will draw a vector representing the wind. Place your protractor on the TMG somewhere in the upper right quadrant. (When drawing TAS-Wind triangles always place the wind vector near the destination end of the TMG.) Orient your protractor using the meridian and then mark a dot at the center of your protractor and another mark at 270° (the wind direction.) 5. Take your ruler and laying it accurately from the wind dot to the 270° mark measure the distance 20 NM from the TMG in the direction of the wind. Your sheet should now look like the one below: Page 41Navigation for Professional Pilots The most accurate way to perform the next step is with a measuring instrument known by geometers as acompass. If you don’t have one it is possible to measure with a ruler, but it will likely be less accurate. 6. Set your measuring compass (shown above) to exactly 100 NM (the TAS.) Put the tip of the compass at the beginning of the wind vector and draw an arc that intersects the TMG near airport A. Your diagram should now look like the one below: Page 42Navigation for Professional Pilots To work properly a TAS-Wind triangle must be drawn accurately. The TMG must be exactly 050°, the windvector must be exactly 20NM long and the arc must be exactly 100NM long. If these conditions are metyou will get an accurate wind triangle. 7. Draw a line from the point where the arc cuts the TMG to the beginning of the wind vector. This line is exactly 100 NM long and it represents the true airspeed. The diagram is now complete, and it should look like the one below: Page 43Navigation for Professional Pilots The angle labeled (da) above is called the drift angle. The heading you must fly is represented by the TASvector and you can measure it with your protractor. If you drew your diagram accurately true heading is042°, and drift angle is 8°. Measure the distance from the arc to the point where the wind vector intersects the TMG. This representsthe distance flown in one hour – i.e. it is your groundspeed. The distance is 115 NM. We now have all theitems we set out to determine: From this we can calculate the amount of time it takes to fly the 240Nm from airport A to airport B. It isNOT necessary to draw the full picture but if we did it would look like the one below: Page 44Navigation for Professional Pilots The purpose of the above diagram is to convince you that the net drift for the entire trip is proportional todrift for one hour. The flight from airport A to airport B takes 2:05 during which time the airplane drifts atotal of 42 NM, which is represented by the line labeled “wind/whole trip” above. But, as you can see it isin proportional to the length of the trip, so da is the same in both triangles. Page 45Navigation for Professional Pilots The wind vector in the above diagram has been broken into two components, crosswind (XW) and tailwind(TW) that are perpendicular and parallel to TMG respectively. It is critical to remember that XW and TWare by definition relative to TMG not TAS, this is a common mistake. In slang pilots refer to tailwind as“wind on the tail” which implies that it is relative to the airplane, but this is NOT correct. Tailwind,headwind, and crosswind are all relative to the TMG, which is the course that is to be flown. To see anactive version of this definition examine the simulation called Crosswind, tailwind, tailwind, drift angle -definitions on the Intranet website. da = Sin-1(XW/TAS) Groundspeed DefinedThe following diagram extends the one above to define groundspeed (GS) Page 46Navigation for Professional Pilots Note that TAS forms the hypotenuse of a right-triangle the base of which equals cos(da) x TAS. To thisvalue the tailwind must be added to get groundspeed. The formula is: GS = cos(da) x TAS + TW It is very worthwhile to realize that as long as da is small there is not much difference between cos(da) xTAS and TAS. That is to say that cosine of a small angle is almost one. Thus when performing a quickestimate of groundspeed it is usually acceptable to add tailwind directly to TAS, but to get the precisevalue the cosine of drift angle must be applied. It is quite obvious that you can do this with an electroniccalculator, but the CR also makes this allowance as we will see. Page 47Navigation for Professional Pilots The relative wind angle is the absolute value of the angle between the wind direction and the track madegood. In the example above the wind direction is 090° and the track made good is 050°. The relative windangle is therefore 40°. Once we know the relative wind angle the crosswind and tailwind can be calculatedby simple trigonometry as: XW = sin(rwa) x Windspeed TW = cos(rwa) x Windspeed The above formulae can be used to determine crosswind and tailwind with an electronic calculator. The CRflight computer performs the same calculation. In the example problem the wind speed is 20 knots and the relative wind angle is 40° therefore XW =sin(40) x 20 = 13 knots and TW = cos(40) x 20 = 15 knots. Using these values the drift angle and -1groundspeed can be calculated, as described above. Drift angle is da = sin (13/100) = 7° and groundspeedis GS = cos(7) x 100 + 15 = 115 knots. Note that these values match the ones previously determined usingthe TAS-Wind Triangle. Page 48Navigation for Professional Pilots There are a few minor terminology differences between your CR manual and those used in this text. Forexample TMG is the same as what Jeppesen calls true course (TC.) Jeppesen draws a distinction betweendrift angle and crab-angle; we will use the term drift angle for both. Read pages 30 to 50 doing all the sample problems (the short section on addition and subtraction on page32 can be skipped.) Once you have worked through the CR manual try the following sample problems: Sample Problems:Given TAS, wind, and desired true course (TC) determine XW, TW, da, and GS: 80 120/25 090 80 120/25 210 Drift EstimationThe accurate mathematical calculation of drift angle and groundspeed as explained above can beperformed with an electronic calculator, a CR, a spreadsheet, or a computer program. However, whenflying it is often necessary to change course without the opportunity to accurately recalculate the drift.Numerous IFR examples come to mind, for example when cleared to hold or to do an approach the pilotmust establish a designated course (TMG) or when the assigned route is changed drift must be determinedon the new route. In VFR flight you are already familiar with the need to plan a diversion should weather Page 49Navigation for Professional Pilots or some other circumstance require you to change course. It is therefore extremely valuable to have atechnique for estimating drift and groundspeed using only mental calculation (estimations.) Estimate XW and TWThe first step is to estimate crosswind and tailwind. You will need to know the magnetic wind. A good pilotalways knows the wind direction and speed. Remember that the upper wind forecast is in true, so youmust apply variation to get the magnetic wind. To estimate crosswind and headwind use your heading indicator (HI) or preferably and HSI, as though it isa CR. If your aircraft has an HSI set the desired course on the course-bar. Locate the magnetic winddirection on the heading indicator and determine how many degrees from the nose or tail of the coursebar the wind is. The is the relative wind angle. Page 50Navigation for Professional Pilots Page 51Navigation for Professional Pilots In the above diagrams it is assumed that the pilot turned so that the desired course TC or TMG is “on thenose.” (This point is covered again below in the description of the simulation called Drift EstimationChallenge.) If the wind is 30° from the course or tail then 50% of it is crosswind and 90% tailwind orheadwind. If the wind is 45° from the course or tail then 70% is crosswind and 70% is tailwind or headwind.And finally, if the wind is 60° from the course or tail then 90% is crosswind and 50% is headwind ortailwind. These percentages must be memorized. If there is a 30 knot wind and 50% is crosswind and 90% is headwind then crosswind is 15 knots andheadwind is 27 knots. This example corresponds to a wind 30° from the course. Had the wind been 30°from the tail (reciprocal of course) the only difference would be that the tailwind would be 27 knots. Usethis method to estimate the XW and TW for the following sample problems: 20 30 from course 20 45 from course 20 60 from course 30 30 from tail 30 45 from tail 30 60 from tail 40 On the course 40 On the tail Note that when the wind is “on the nose” it is all headwind with zero crosswind. When “on the tail” it is alltailwind with no crosswind. Similarly, if the wind is “on the wingtip” it is all crosswind with no headwind ortailwind. It is crucial to realize that in this case we are using the word nose to represent the course, not theheading. Once we know the headwind or tailwind we can estimate the groundspeed by subtracting or adding to thetrue airspeed. We learned previously that we should first multiply TAS by cos(da) but this typically makesonly one or two knots difference, so for estimation purposes we can say that GS = TAS + TW or GS = TAS –HW. -It seems like it will be much more difficult to estimate da since we need to evaluate the equation da = sin1 (XW/TAS). While this sounds impossible to do in your head there is a simple mathematical trick that Page 52Navigation for Professional Pilots makes it quite simple. To explain we will review the definition of the angle unit called radians, and theformula for circumference of a circle. It is important to recognize the close relationship between arc-length and the subtended angle (ra.) Theangle ra can be precisely determined, in units of radians, by dividing arc-length by radius. To convert ra tounits of degrees multiply by 180 and divide by pi. This may not be sounding like something that will be easyto do in your head but stick with me. Note that so far no approximations have been made, i.e. the abovedefinitions are precisely valid. Next we will look at how we can substitute the definition of the radian as anapproximation for estimating drift angle. Page 53Navigation for Professional Pilots Examine the diagram above that redefines XW as the wind component perpendicular to TMG. The point tonotice is that the length of XW is very nearly the same as the length on an arc drawn from TAS to TMG. Forsmall values of da it is reasonable to say that acr-length = XW. That being the case da in radians equalsXW/TAS. Since we want da in units of degrees the formula becomes: You may be thinking, “This still doesn’t seem too easy to do in my head.” There is one final step thattransforms the above equation into a simple method; it is called the “Magic Number.” Since TAS is thesame from day-to-day we can calculate the value TAS time pi divided by 180 and memorize this number,we call it the magic number. Once you know the magic number for your airplane drift is easy to estimate,it is simply: da = XW / Magic Number Magic NumberMagic number was introduced in the previous section. Magic number is simply TAS x Π / 180 i.e. TAS /57.3. It is important for you to memorize the magic number of the airplanes you fly. It is helpful to know Page 54Navigation for Professional Pilots your magic number for both cruise and hold/approach speeds so that you can estimate drift in cruise aswell as holds and approaches. Since magic number is used for estimations there is no sense in calculating itoverly accurately. For true airspeeds up to 180 KTAS determine magic number to the nearest ½, above 180KTAS determine magic number to the nearest whole number. In the table below some magic numberscorresponding to the C-172, Travelair, and King Air have been left blank for you to fill in, other exampleshave been provided: If you are flying a Piper cub with a 20 knot crosswind drift is 20°, what would it be in a King Air. The answeris 5° (20/4.) What would drift be in a jet airliner with a magic number of 8? The answer is 2.5° (20/8.) Page 55Navigation for Professional Pilots 1 25 1 30 2 20 2 30 2 45 3 25 4 30 6 30 8 30 Two-bit MathThe magic number of a Beech 95 in cruise is 2.5, therefore drift equals XW/2.5. You may find it challengingto divide by 2.5 in your head but there is a simple trick that makes it easy. Answer the following question: You go to the 7-11 store to by a snack for $1.67. You reach into your pocket and discover you have a bunchof quarters. How many do you give the clerk? You probably had no trouble realizing you needed seven quarters to pay for your snack. You do thisparticular calculation so often that it seems trivial to you, but you have actually just divided 1.67/0.25. Youwould have freaked if I had asked you to divide 1.67 by 0.25 in your head, but it seemed simple when youthink of it as money. You most likely just remember that each dollar is four quarters and you know thatone additional quarter covers items up to 25 cents, two are required for items up to 50 cents, and three foritems up to 75 cents. Anything over 75 cents would have required an eighth quarter. And so on. Now compare the above calculation to the one you wish to do in your head XW/2.5. This is the same assaying (XW/10)/0.25. Of course dividing any number by 10 is very simple since all you have to do is shiftthe decimal one place left, for example 20/10 is 2, 33/10 is 3.3, etc. Can you see how to use this trick toestimate drift angle? Simply take the XW and divide it by 10, then think of the result as the price of yoursnack and pay for it in quarters. For example if the crosswind is 15 knots, that becomes $1.50, which willtake six quarters; therefore da = 6°. Try the following examples for yourself: Page 56Navigation for Professional Pilots 2.5 10 $1.00 4 2.5 15 $1.50 2.5 17 $1.70 2.5 20 2.5 22 2.5 24 2.5 28 2.5 32 2.5 36 Page 57Navigation for Professional Pilots The drift estimation techniques from this simulation combined with the bracketing technique in the nextsimulation will give you all the skills you need to efficiently navigate IFR. Page 58Chapter 3Introduction to Radio NavigationIn this section you will learn how VOR, ADF, DME, and GPS work. These radio aids are used to guide pilotsduring the enroute phase of flight. When doing radio navigation a VOR, ADF, or GPS is used to define a track over the ground, i.e. the desiredcourse (TC, or TMG.) Once a course is established drift theory, covered above, applies. Your task is tocalculate the heading that will keep you on course and the groundspeed. It is important to realize thatthere is no difference at all in the objectives or methods of flight planning for IFR flight and VFR flight. It is important to have a basic understanding of how VOR, ADF, DME and GPS work. On the Intranet, underSim-Multimedia there are several interactive tutorials covering: “How VOR Works” “How ADF Works” and“How DME Works.” You will find further clarification about how DME works by reviewing the simulations:“DME Jitter” and “Squitters, and Auto-standby.” AFTER you have reviewed all the simulations continuewith the following. Read all of section 2 (Navigation Systems) in your Instrument Procedures Manual before continuing; thiswill explain all the navigation aids. On the KLN-90B GPS (in the B-95 and piston simulators) the map “super-nav 5 mode” can be set to VORTLH. T stands for terminal VORs, which are the ones between 108.00 and 111.85. L stands for low altitude,which are all the VORs on Victor airways (see LO charts below.) H stands for high altitude, which are all theVORs used on high altitude airways (see HI charts below.) Between 108.00 and 111.75 those frequencies in which the first digit after the decimal is odd are ILSfrequencies, while those where the first digit is even are VORs. From 112.0 to 117.75 all frequencies areVOR. To help you grasp what I mean look in your CAP and write down the frequencies for the following ILStransmitters:Navigation for Professional Pilots Victoria (CYYJ) 09 Victoria (CYYJ) 27 Abbotsford (CYXX) 07 Kelowna (CYLW) 16 Calgary (CYXC) 28 Calgary (CYXC) 34 To confirm your understanding of the frequency allocation system complete the following table: 109.15 ILS 111.30 ILS 107.55 111.60 Page 60Navigation for Professional Pilots 115.30 117.95 109.85 112.15 114.70 There are a total combined 200 VOR and ILS frequencies, 40 ILS and 160 VOR. Because of the numberingprotocol there are two VOR frequencies then two ILS frequencies, etc. up to 112.00. DME channels are numbered according to the military TACAN channel. There are more TACAN channelsthan VOR channels so the first DME channel used in civilian flying is 17 and TACANs 57 to 66 inclusive arenot used either. DME channels alternate between X and Y, with X channels corresponding to VOR and ILSfrequencies that end in decimal 00 while the Y channels correspond to VOR and ILS frequencies that end indecimal 05. Operationally there is no difference between an X channel and a Y channel – both transmitsquitters on the same frequency but listen for interrogation on different frequencies therefore they willinterfere with each other and must not be used in the same area. By convention, on LO charts and in theCAP the X is dropped from DME channels – only the Y is shown; for example YVR frequency 115.9corresponds to DME channel 106X, but if you look on the map it just says DME Channel 106. But ILS 26R isfrequency 111.95, which corresponds to DME channel 56Y, which is shown on the charts. There is no reason to memorize the DME channel assignments although you should understand how thefrequencies are assigned. It is important to realize that a specific DME channel always goes with a specificVOR / ILS frequency and that is how your Nav radio is able to tune the DME without you needing to inputthe DME channel. The complete list is found in your CFS section D2. In the diagram that follows no shadow effect is considered, but in reality if the VOR signal is blocked bybuilding, mountains, etc the reception range will be less than indicated by the formula. Page 61Navigation for Professional Pilots In the diagram it is clear that the aircraft’s altitude plus the radius of the earth forms the hypotenuse of aright triangle with r and distance from VOR (s) as the other sides. Using Pythagoras’ theorem and solvingfor s results in an equation. But actual reception range is not zero when at ground level. Thus therecommended formula is: To receive a VOR you must be within the slant range (s) given by the equation above. A few sample valuesare: 1,500 50 5,000 87 10,000 123 Page 62Navigation for Professional Pilots An ADF, if working properly, always points at the station. It does so even if the heading indicator is setincorrectly. As a result you will be flying on the WRONG course if your heading indicator is not accurate.On the other hand, you can always find your way to the station even with a failed heading indicator, whichyou cannot do with a VOR. The bottom line for pilots is to know and understand the differences betweenVOR and ADF in normal and heading-reference-failed modes of flight. Usually you use your ADF radio with non-directional beacons (NDBs) but it can also tune commercial AMradio stations. The ADF in Selkirk College airplanes can tune frequencies up to 1200 (higher bands are notuseable.) A complete list of every radio station in Canada is on page D27 of your CFS. It is important to know that DME gives “slant-range” which is the actual distance from the airplane to theDME station. When you fly over the station a DME shows your altitude in nautical miles. Because of theslant range error groundspeeds calculated by a DME are not accurate when close to the station. The ruleof thumb is to consider DME based groundspeed accurate only when distance from station in nauticalmiles is greater than altitude in thousands of feet. In other words, if you are at 4000 agl you need to be atleast 4NM away to get an accurate groundspeed, but if you are at 40,000 feet you need to be 40NM awayto get an accurate groundspeed. There is a simulation on Intranet that fully explains the indications of the various navigation displays youwill encounter in this program. It examines the most common navigation indicators: Page 63Navigation for Professional Pilots Each navigation display has its advantages. You will learn what each of these indicators looks like, what itdisplays and what it doesn’t. You will see for example that as wonderful as an HSI is it doesn’t work withADF. You will also see that while an RMI is a great thing to have, it doesn’t work with ILS, etc. In the following description of the Nav Displays simulation marker beacons and ILS is mentioned forcompleteness. The theory of their operation is not part of this course. They will be covered in Avia 260. GPS NavigationThe basic operating principles of GPS are explained in a slide-show on our Intranet. The link can be foundunder Avia 100, Avia 160, and Avia 260. Read this entire slide show before continuing. Also read section2.2 (Navigation systems) in the Instrument Procedures Manual. An important thing to realize is that a properly functioning GPS is a very accurate source of time. Pilotsshould always set their clock (watch) accurately for IFR flight, and your GPS is a legal source of accuratetime. Take every opportunity to set your watch to the GPS in the airplane. (Note: the GPS in the simulatorsdoes not give accurate time.) When using VOR and ADF navigation accuracy is greatest close to the stations and less accurate fartheraway. Since GPS has no stations, the accuracy of GPS is the same regardless of where you are on theairway. Consequently GPS is more accurate than VOR or ADF for the enroute phase of flight. A major problem with GPS is that it can fail in certain ways without giving a warning to the pilot. RAIM isone method of improving warning that a failure has occurred. You will learn all the legal requirements forRAIM in Avia 120 and 220. This material is also covered in the readings assigned above. Distance values displayed on a GPS are horizontal, i.e. they are NOT slant range. Thus GPS gives accurategroundspeed even when close to “the station” (of course there really is no station, so this is obvious whenyou stop to think about it.) GPS gives distance off track rather than angle off track (VOR and ADF give angle off track.) There are prosand cons to this and you MUST learn to translate between both in your mind (more on that later.) BracketingIt might not seem so at first but radio navigation can be done in accordance with the principles of DR orpilotage. When we defined these terms (review if you don’t remember the meanings) we said that DR is amore sophisticated form of navigation. Sadly, many pilots use pilotage anyway. Pilotage in terms of VORor ADF navigation means “chasing the needles.” If you simply turn so as to push the needle back where itbelongs (centered for a standard VOR indicator) you will stay on course, but you won’t determine theheading that keeps you on track and will thus tend to chase wildly back and forth when you get furtherfrom the station where the signal is less sensitive, and you will also have a very hard time avoiding wildswings in close proximity to the station where the needle can move very quickly due to increasedsensitivity. Page 64Navigation for Professional Pilots The secret to avoiding needle chasing is to use a technique called Bracketing. This is covered in asimulation on the Intranet. In the previous simulation we learned to estimate wind drift based on the forecast wind. This is aninvaluable technique and one you should use every day as an IFR pilot, but it can only get you roughly tothe correct heading. Because winds aloft forecasts are not perfect you will need to adjust your headingenroute until you find the exact amount of drift. The technique used to find the exact amount of drift iscalled bracketing. In the simulation, just to make things more challenging, you are not given any wind information at all. Youwill see that even in this worst-case scenario you can use bracketing to figure out drift. Sadly many IFR pilots never master bracketing. They just wallow around the sky chasing needles back andforth. But, you won’t be one of those guys, will you? To master bracketing one thing that is needed is to fly precisely, so you can observe which way theairplane is drifting. In the simulation flying accurately is easy, in the real world it can be more challenging,although it is easy if you use the autopilot. When you fly the airplane you must try to fly headings asprecisely as possible. If you can’t fly precisely you won’t be able to take full advantage of the proceduresyou are learning in this course. The other thing you must do when bracketing is remember what headings you have been flying. It shouldbe pretty easy to remember them, but for the first few times through this simulation you might like to havea pad of paper and write down what you have done. Examining a written record of the headings you haveflown will show whether you are “zeroing in” on the required heading, or wallowing. There are several secret codes built into this simulation. The main ones are: A = All H = HSI R = RMI You may choose any navigation display you wish. However, I recommend that you start with HSI or ALL, asthese are easier to see drift on. Page 65Navigation for Professional Pilots The following explanation will take you through a tutorial using the Bracketing simulation – pleasecomplete this section while using the simulation. The secret code places the airplane on course 090, 12 miles west of the navaid. Set time compression to 1Xunless you have a very slow computer. The flying instructor is flying. Read the “instructors mind” (thegreen box at the lower right.) Initially it says that the instructor is evaluating the heading 090. I.E. theinstructor is waiting to see which way the airplane will drift. Pretty soon the instructor sees that the needle is moving left (picture above.) Therefore he knows that 090is too far right. Whatever heading is needed to stay on course it MUST be less than this heading. The “instructor’ mind” says 090 is the maximum heading he will ever fly. We call this the right handbracket. Tip: as you observe the simulation you should press the 2-key to restart the sequence if it gets ahead ofyour reading. Tip: set time compression to zero to freeze the motion after each turn the instructor makes, so you cankeep up with the process. The instructor has begun searching for a left limit (see comment in instructor’s mind.) Page 66Navigation for Professional Pilots Here is what you will see. First the instructor turns 5 degrees left. He then waits to see what the needledoes. The IMPORTANT point is that it only matters WHICH WAY THE NEEDLE IS MOVING. So, the instructor fliesheading 085 for a few seconds until he realizes that the CDI is still moving left. Next he tries heading 080, but the needle still moves left. So, he tries 075. All this time the instructor’smind says, “searching for left limit.” The needle still moves very slightly left on heading 075, so the instructor tries heading 070. After a few seconds on heading 070 the instructor sees that the CDI has begun to move to the right. If you miss part of process, or just want to see it happen again, either press the 2-key again, or click the“Start Over” button. Minimum: 070 Evaluating: 080 Maximum: 090 Page 67Navigation for Professional Pilots Left-limit established If it doesn’t say the above you need to give the instructor a few more seconds to think, so increase timecompression until he has time to think, then return time compression to zero. Reading the instructor’s mind you now see that he realizes that heading 070 is less than the heading thatWILL be required to stay on course. His mind now states that the minimum heading will be 070. This iscalled the left hand bracket. NOTE: The instructor will remain on heading 070 until the CDI re-centers. NOTE: Whenever the airplane is off course always fly the corresponding bracket heading until back oncourse. 1. The instructor realized the airplane was drifting right on heading 090, so he established 090 as the maximum heading (right hand bracket) 2. After searching, the instructor discovered that 070 was the first heading to the left that caused the CDI to move to the right. So, he establishes 070 as the minimum heading (left hand bracket) Based on the above, the instructor knows FOR SURE that the required heading to keep on course isbetween 070 and 090. Note that whenever the airplane gets off course the instructor will always go to (but NEVER beyond) thebrackets – and will hold that heading until the airplane gets back on course. This commitment preventswild chasing of the needle back and forth (a common mistake of new IFR pilots.) A really good pilot could tell from all that has happened so far that the correct heading is closer to 070than 090 (see comments below about “beating” the computerized flying instructor.) However, theinstructor is programmed to just split the bracket into half. In this case the brackets are 070 and 090 so theinstructor decides that when he gets back on course he will try heading 080. In his mind he indicates 080 asthe heading he is evaluating. Page 68Navigation for Professional Pilots The instructor remains on the left bracket (070) until back on course, and then tries heading 080 to seewhat happens: Watch the instructor. He will fly heading 070 until he gets back on course. As soon as he is on course hewill turn to the evaluation heading, 080. Set time compression to zero once the instructor gets to heading 080. Now read the instructor’s mind. He still states that the brackets (minimum and maximum) are 070 and090. The comment in his mind says that he is “trying evaluation heading.” i.e. he on course and flyingheading 080. 1. The CDI does not move, indicating that 080 is the required heading. 2. The CDI moves right, indicating there is less than 10-degrees of drift. 3. The CDI moves left, indicating there is more than 10-degrees of drift. Increase time compression from zero to see what happens. See how long it takes for you to realize the CDIis moving. After a few seconds the CDI moves a bit to the left. The instructor immediately turns to his left bracketheading of 070. First, notice that as soon as the instructor realizes he is drifting off he turns to the bracket heading (but notbeyond the bracket.) The instructor now realizes that 080 is not the correct heading to stay on course. In fact he now knows, forsure, that the CDI moves left on heading 080. So, he revises his maximum heading (right hand bracket) to080 (From now on, even if he gets left of course at some point there is no need to fly a heading more than080.) Read the instructors mind. The revised brackets are 070 and 080. So, he chooses the midpoint, 075, as theheading he will evaluate next, once he is back on course. Page 69Navigation for Professional Pilots After a few seconds on the left bracket (070) the CDI is again centered and the instructor turns to heading075. His mind now says that he is evaluating heading 075 (i.e. guessing that there is 15-degrees of drift.) After one bracketing cycle the brackets have been reduced from a 20 degree span to 10 degrees. Can younow see how things keep going? Each time we evaluate a heading we reduce the span of the brackets inhalf. Soon they will span only 5 degrees, then 2½ (in theory.) Usually there is no practical need to get the brackets closer than 5 degrees to each other, although theinstructor will keep going as far as he can. Now the instructor is flying heading 075. The same three possibilities exist: 1. The CDI does not move, indicating that there is exactly 15-degrees of drift. 2. The CDI moves right, indicating there is less than 15-degrees of drift. 3. The CDI moves left, indicating there is more than 15-degrees of drift. The brackets are at 070 and 080 respectively. So no matter what happens we will have narrowed down thedrift to a five-degree range. If the CDI moves left the brackets will again be adjusted, becoming 070 & 075,if it moves right the brackets will become 075 & 080. The CDI remains centered for a long time. This tells the pilot that the drift MUST be very close to 15degrees. Eventually the CDI starts to move right, slowly. This tells the instructor that there is less than 15degrees of drift. A wise pilot would take the amount of time it took the CDI to move into account and revise the driftestimate to 14-degrees. See comments below about beating the computerized flying instructor. The computerized flying instructor is a stickler for purity so he revises the brackets to 075 and 080 andrevises his drift estimate to 12.5 degrees (heading 077.5.) He now turns to his right bracket heading of 080 to get back on course and then tries heading 078. Once the airplane is within a mile of the station it is best to STOP bracketing and simply fly the evaluationheading until a mile beyond the station. Increase time compression and watch the instructor fly past the station. Page 70Navigation for Professional Pilots Theoretically the process continues exactly the same on the outbound leg. However, because you usuallyare slightly off course (just a few feet, we hope) at station passage it is wise to “open up” the bracketsslightly once bracketing begins again on the outbound leg. The computerized flying instructor isprogrammed to open the brackets by +/- 3-dgrees. Outbound bracketing then continues exactly as before If you use bracketing faithfully you can establish drift within one or two degrees in short order. After thatall you have to do is maintain heading accurately and you have things made.. Repeat secret code 2 as many times as you need to until you fully understand all the logic of bracketing.Make liberal use of setting time compression to zero, usually after each turn, so you can think about whatthe logic is. Try secret coed 3, 4, and 5 for more practice. All the computerized flying instructor to demonstrate if youlike. If you “blow” a particular attempt use the “Start Over” button to try again. You can click the “You have control” button at anytime to have the computerized flying instructor takeover and demonstrate the procedure to you. If you followed the advice above you started by practicing bracketing with an HSI. However, you MUSTmaster bracketing with: RMI Press the S-key to switch to standard VOR indicator and practice bracketing. Press the F-key to switch to Fixed Card Indicator and practice bracketing. I fully expect that you will spend several hours with this simulation before you are comfortable withbracketing, but it will be time very well spent. Page 71Navigation for Professional Pilots By default the wind is hidden but all the other visual aids are visible. However, most airplanes don’t havemoving map displays, so you need to be able to navigate with only “raw” navigation data. So, click the“Hide All” button at the bottom of the simulation to make the process more challenging. Include Outbound By default the computer generates inbound bracketing exercises. However, if you check the box at thelower left of the simulation the computer will randomly include some outbound bracketing exercises foryou. As you have seen, there is no real difference between bracketing inbound and outbound, but you shouldstill do some outbound bracketing practice. In secret code 2, above, when the instructor tries heading 075 and the CDI doesn’t move for a long timeany human would realize that the drift is close to 15, and would only revise the heading to 076. Similarly ahuman would move the left bracket NOT from 070 to 075 but only to about 073 (or so.) Review secret code2 above until what I have said here makes sense. The point is that you don’t always have to divide each bracket exactly in half. Use common sense(something the computerized flying instructor never does.) Break-out LogicA FUNDAMENTAL principle of bracketing is that you commit to NEVER fly outside the brackets. Thisprevents the wild chasing of the CDI or RMI needle that commonly plagues new IFR pilots. The idea of bracketing is that you always have two brackets in mind that you KNOW FOR SURE make theCDI move left and right (but only just.) But, if the wind changes, or your heading indicator precesses, the brackets won’t work anymore. IMMEDIATELY that you notice you are off course always turn to the relevant bracket heading. Within a fewseconds the CDI should start to slowly come back to center. If it doesn’t what do you do? If precession is not the culprit then there are only two possibilities: Page 72Navigation for Professional Pilots If you have no reason to believe the wind changed then test the navigation radios. Check the Morse codeidentifier to make sure the station has not gone off the air. If the radio has a test button press it. (Forexample the ADF radio can be switched from ADF to ANT then back to ADF. See if that changes theindication. For a CDI turn the OBS a few degrees, then reset the OBS.) ADF is particularly prone to giving false indications so if you have no reason to believe the wind haschanged just keep flying your heading for a minute and see what happens. Usually the false indication willgo away and you will see that you were on course the whole time. VOR and ILS are much less likely to give false indications, although it is amazing how many ILS approacheshave bows in them caused by electronic interference on the ground. Once you determine that the off course indication is real, if your bracket heading does not center the CDIyou must CHANGE the bracket. In computer programming this is called breakout logic. The computerizedflying instructor has breakout logic. If he flies the bracket heading for 30 seconds and does not get at least0.25 degrees closer to course he moves the bracket out by three degrees. The question is, when you move the bracket should you change the evaluation heading? That depends onwhat you think caused the problem. If it was a wind shift then you should change the evaluation headingin the same direction you opened the bracket, but half as much. If you think the problem was a temporarynavigation signal deflection then don’t change the evaluation heading, also stand ready to close thebracket back in to where it was before. Bracketing SummaryBracketing is a fundamental tracking procedure. In this simulation the bracket always starts from the zeropoint, with a totally unknown wind. In the real world you should always know roughly what the wind is.Therefore you start with your best estimate of the heading to stay on course, using the technique of driftestimation covered earlier. Then you set your initial brackets at +/- 10-degrees from there. With this headstart you should have a near perfect heading bracketed out within a couple of minutes. If you start with a +/- 10-degree bracket it should only take a minute until you can tell whether you need toadjust your evaluation heading left or right. When you do, move the bracket in, but NOT all the way toyour original evaluation heading. Pretty soon you will have adjusted your heading and brackets so that youhave two brackets about +/-5 degrees from your best estimated heading. You then react to even small CDIdeflections by turning to the appropriate bracket immediately. Using your judgment you revise yourestimated heading, tweaking it one degree at a time. Note: you can only tweak the evaluation headingone degree at a time if you can fly your heading accurately enough to make such judgments. Page 73Navigation for Professional Pilots Because bracketing is so powerful you can easily see that when combined with the drift estimationtechnique covered earlier you can perform very accurate DR radio navigation even in the absence ofcompletely precise wind forecasts. DME arcs are used on many IFR approaches and terminal arrival procedures. They allow airplanes to getlined up for approaches without the high workload (for controllers) of radar vectors. DME arcs are normally flown using an RMI. Therefore the simulation includes an RMI. The navigationdisplay also includes an HSI, a standard VOR indicator and an RMI. If an airplane has an HSI but no RMIyou can still do an arc by manually turning the HSI to keep it centered, so that it acts like an RMI. If youhave neither RMI nor HSI it is not good practice to fly DME arcs. I have not provided the option for doingarcs without an RMI in this simulation. DME arcs can be assigned at any distance from a DME station from 7.0NM up. Smaller arcs are neverused. To fly an arc you must first fly a path that crosses the arc. The simplest way to do this is to fly directlytoward the VOR until you reach the desired distance to arc. Another common way is to be vectored untilyou intercept the arc. Once you intercept the arc turn so that the RMI needle points at the wingtip. If you are arcing right, thatmeans the RMI points at the right wingtip. A left arc means the RMI points at the left wingtip. The easiest way to explain arcing is through an example. Please load the simulation and follow along withthe example below. This simulation is for practicing DME arcs. You can also fly arcs using the Alsim simulation, but it is best tomaster this simulation first. “Pilot 200, you are cleared for a practice DME arc. Intercept the 8 DME arc from the 120 radial and arccounter-clockwise to intercept the course 180. Your lead radial will be 014.” Page 74Navigation for Professional Pilots The picture below shows the computerized flying instructor about half way through complying with thisclearance. Let’s start by breaking down the clearance to make sure we understand it. 8 DME arc means that the airplane must fly a circular orbit around the VORTAC at a distance of 8.0 Nm.(Indicated on DME radio.) From the 120 radial means that the arc starts at the 120 radial Intercept course 180 means that the objective is to wind up flying inbound on the 000 radial. Lead radial will be 014 means that when the airplane crosses the 014 radial it will be 2 NM from theassigned course. Think of lead radials like a wakeup call. When you get to the lead radial you are almost atyour assigned course, so you generally stop arcing and turn to intercept the assigned course (at 45°.) Watch the Flying Instructor demonstrate the arc. (Press the 1-key to restart if necessary.) Initially the airplane is flying outbound along the 120 radial, which is the designated start radial. (Later wewill do an example where the airplane flies inbound on the 120 radial.) Page 75Navigation for Professional Pilots The instructor’s mind can be read at the lower right. He states that he intends to lead the turn onto thearc. He plans to turn when the DME reads 7.2 (the value will be different if you chose a cruise speed otherthan 150 KIAS.) The above diagram shows that the turn to intercept an arc should start at a distance equal to the radius ofturn of the airplane. Assuming that the turn will be at rate one a simple mathematical formula for radiusof turn can be derived: R = Groundspeed / 200 In other words: r = .5% of Groundspeed For example an airplane flying 156 Knots groundspeed would need to lead the turn by about .8 Nm. (1% =1.6 Nm, so ½% is about .8 Nm.) Keep in mind that the airplane must be in the turn at the designated distance. Allowing about six secondsto get up to rate one turn, you should add an extra 0.1 to 0.2 to the calculated value. In this demonstration the wind is zero, so the groundspeed equals the TAS. At the calculated lead distance the instructor starts his turn. The pilot must turn so that the RMI is on theleft wingtip. Simply look at the tip of the RMI needle and turn 90° from that. In the example the RMI pointsto 300 so the first heading must be 300 + 90 = 390 degrees – but that is 030. Watch the flying instructor. At 7.2 Nm he makes a left turn to heading 030. If the lead was correct theDME should read 8.0 Nm as he rolls out on that heading. Page 76Navigation for Professional Pilots The only instruments needed to arc are the RMI and DME. To understand an arc you must remember what your high school math teacher taught you; a line tangentto a circle is always at right angles to the radius. Consequently the RMI needle, which shows your radial,must always be at or near the wingtip when flying an arc. In this case we are flying a counter-clockwise arcso the RMI needle must point near the left wingtip. In zero wind all you need do, in theory, is keep the RMI needle on the wingtip and the DME will not change.The airplane would fly a perfect arc. Unfortunately it is not possible to do such a perfect arc. Therefore, weuse a technique of making a series of short straight legs that approximate the arc. Watch the flyinginstructor fly the demonstration and note how it is done. The instructor turns so that the RMI needle is five degrees ahead of the left wingtip. He then maintains aconstant heading until the RMI needle drops to five degrees behind the wingtip. He then turns 10 degreesleft, bringing the RMI needle five degrees ahead of the wingtip again. This pattern repeats over and over. The instructor constantly monitors the DME. If the airplane gets a bit wide (DME reads 8.1 or more) heturns so that the RMI needle is MORE than 5 degrees in front of the wingtip. As long as the RMI needle iskept in front of the wingtip the airplane will move in, closer to the VORTAC. If the DME is remains atmore than 8.0 as the RMI needle approaches the wingtip the instructor will turn to keep the needle aheadof the wingtip. If the DME drops to 7.9, the instructor realizes that he is inside the designated arc. Correcting this issimple. Just like a rock on the end of a string moves out instantly if you let go of the string the instructorrealizes that if he simply stops turning, (i.e. maintains whatever heading he is on) the airplane will moveout on the arc. As this happens the RMI needle will move past the wingtip. Once the needle is below thewingtip DME will start to increase. Once the DME reaches 8.0 the instructor resumes the usual arcprocedure by turning to bring RMI needle near the wingtip again. The HSI and OBS are not needed to fly the arc. Therefore, once the airplane is established on the arc theinstructor will set the HSI to the assigned course (180 in this example) and set the OBS to the lead radial(014 in this example.) With the HSI set the pilot can visualize how the arc is going. The airplane will be slightly more than 90-degrees from the final course when the lead radial is reached, and that is easy to see on the HSI. The #2CDI will center as the airplane crosses the lead radial. (Prior to reaching the lead radial the CDI alwaysdeflects to the center of the arc.) Page 77Navigation for Professional Pilots As the airplane crosses the lead radial the instructor will STOP arcing and turn to make a 45-degreeintercept of the assigned course. He simply holds the 45-degree intercept heading until on the course, thentracks inbound using the usual bracketing technique. Whenever the RMI needle is ahead of the wingtip there is a small DME groundspeed. Common sense tellsus that we are “cutting in” on the arc, and DME is telling you how quickly. Whenever the RMI needle is behind the wingtip there is a small DME groundspeed. In this case we aremoving away from the DME station at the indicated rate. An important to rule to note is that if the groundspeed is decreasing the airplane is getting closer to theVORTAC. If the groundspeed is increasing the airplane is getting further away from the VORTAC. Thesestatements are only true if the airplane is flying straight (i.e. not turning.) Press the 1-key, again. Then press the “I Have Control” button. Now it is your turn to fly the arc. Practice the procedure until you can keep the DME within 0.1 of theassigned value. You will find it impossible to prevent 0.1 variations, but you should not permit 0.2deviations from the assigned DME. Tip: remember to set the HSI to 180 and the OBS to 014 once you are established on the arc. The assigned practice arc is exactly the same as the previous one. The only difference is that this time theairplane is flying inbound to the arc along the 120 radial. Once again the instructor calculates that 0.8 Nm lead is needed, so he starts the turn at 8.8 Nm. As beforethe first turn is to heading 030. Press the 2-key, again. Then press the “I Have Control” button. Now try the intercept from outside the arc on your own. Page 78Navigation for Professional Pilots This time the same arc clearance is issued, BUT the difference is a 30-knot west wind. From the map you can see that the wind is going to blow the airplane wide on the arc. What adjustmentsto the previous procedure will be needed? First notice that the groundspeed as we fly along the 120 radial is almost 180 knots. So, we must lead theturn to the arc by 0.9 Nm this time (these values will be different if you chose a different cruise speed.) A wise pilot would realize that the first heading should not be 030, because of wind drift. But, thecomputerized flying instructor has not been blessed with common sense. Watch and see what happenswhen he turns to 030. As the airplane is blown wide on the arc the instructor sees the DME reach 8.1. At that point he turns tomove the RMI needle 10 degrees ahead of the wingtip. He then monitors the DME. If the distance does notdecrease he turns to move the RMI needle further in front of the wingtip. Eventually he discovers anamount that causes the DME do decrease. He then keeps turning to maintain the RMI needle ahead of thewingtip until the DME returns to 8.0 In the previous example, when the wind was zero, we saw that the closing speed was zero when the RMIwas exactly on the wingtip. But, in this case the closing speed is zero when the RMI is slightly ahead of thewingtip. And, the “zero point” changes as the airplane proceeds around the arc, because the angle thewind makes to the arc keeps changing. A wise pilot would use this information to arc better. Rather than using the wingtip as the zero referenceuse the point where the groundspeed reads zero. Unfortunately the computerized flying instructor doesn’tknow that, so every time he gets back on the arc he turns to place the RMI only 5-degrees in front of thewingtip, and that is not enough. So, he keeps being blown outside the arc. When it is your turn you will dobetter. Right? The good news is that even with his limited intelligence the instructor keeps the airplane within half a mileof the arc, and most of the time within ¼ mile. That is good, but not excellent. See if you can do better. Press the 3-key, again. Then press the “I Have Control” button. Now it is your turn to try arcing with a wind blowing you outside the arc. Repeat this exercise until you can stay within 0.2 Nm of the arc (i.e. until you are better than the instructor. Page 79Navigation for Professional Pilots Having the moving map to help you judge the arc makes it easier. Unfortunately most airplanes don’t havethis feature. So, click the “Hide All” button at the bottom of the page and try repeating the arc with nomap to help you. Once again we have the exact same arc clearance, but now the wind is 30 knots from the east. Watch theinstructor demonstrate this arc. This time the groundspeed along the 120 radial is only 130 knots, so the arc need only be lead by 0.6 Nm. The wind will keep blowing the airplane inside the arc. The instructor will therefore keep flying straightlegs, allowing the RMI needle to drop further behind the wingtip to get back on the arc. Take note of thegroundspeed on the DME (too bad the instructor doesn’t do that.) A wise pilot would realize that in this situation the RMI needle should be kept behind the wingtip. But, theinstructor is a bit too dense for that. Every time he gets back on the arc he turns to put the RMI needle fivedegrees ahead of the wingtip (as you would in zero wind.) Predictably he is blown back inside the arc andhas to correct again. Press the 4-key, again. Then press the “I Have Control” button. Now it is your turn to try arcing with a wind blowing you into the arc. Learn from the instructor’s mistakes. You can do better than he. Try keeping the RMI needle further behindthe wingtip than you did with zero wind. You should be able stay within 0.2 Nm of the arc. This time there is a new arc clearance. This arc goes clockwise. It is also at a different distance, 10.0 DME. Watch as the instructor flies the arc. The start radial is 270, so the first turn is to heading 270 + 90 = 360.There is a 20-knot wind from the southeast so the wind is blowing the airplane outside the arc. As usualthe instructor doesn’t keep the RMI needle far enough ahead of the wingtip, so he keeps blowing outsidethe arc. Press the 5-key, again. Then press the “I Have Control” button. Page 80Navigation for Professional Pilots Now it is your turn to try the clockwise arc. All the procedures you have learned so far still apply.Remember that with the wind blowing you out of the arc you need to keep the RMI needle slightly in frontof the wingtip. At this point we have covered all the techniques of arcing. What you need now is lots of practice. Everytime you click the “Do Another” button the computer generates a random arc clearance with a randomwind. The arcs are at distances from 6 miles to 12 miles. The two checkboxes at the bottom of the simulation labeled “Inside Intercept” and “Outside Intercept”are both checked by default. Thus you will get both intercepts from inside and outside the arc. If you wishto limit your practice to only one of these situations adjust the checkboxes. Make sure you are practicing successfully with all the visual aids hidden before moving on. If you are ableto arc successfully with this simulation you should be ready to try it in the real airplane. 1. Intercepts Inbound 2. Intercepts Outbound To intercept a course inbound we use a simple little saying, “Desired to the head, plus 30.” You will soonsee what that means. You can only complete an inbound intercept if you are currently within 60 degrees ofthe course you wish to intercept. If you are off course more than that go directly to the station andperform a procedure turn to establish yourself on the assigned course. To intercept a course outbound we use another simple little saying, “Tail to desired, plus 30.” Outboundintercepts can be completed regardless of how many degrees you are currently off course. As usual choose your cruise speed before clicking the “begin” button to start the simulation. Before we begin you must choose a navigation display. You can make your choice from: Page 81Navigation for Professional Pilots The procedure for conducting predetermined intercepts (PDT) and flying procedure turns is exactly thesame regardless of what navigation display you have. However it is MUCH easier with an HSI and RMIthan without. Indeed the very reason people spend so much money to have HSI in airplanes is to makeintercepts easier to visualize. Therefore I recommend you start with the option “A” for all, or “H” for HSI. By default the simulation generates a random inbound intercept. Leave the checkbox at the bottom of thesimulation set to “Within 60 PDTs” for now. At the right side of the screen the red box contains the clearance. “Pilot 200, you are cleared to intercept the 180 degree radial inbound to the YPB VOR.” Alternatively, if you have chosen either the “R” for RMI or “F” for fixed card navigation displays theclearance reads: “Pilot 200, you are cleared to intercept the course 360 inbound to the CM beacon.” Note the difference in terminology. When dealing with VOR or VORTAC navaids the controller (red box)uses the terminology radial to refer to the course. But when dealing with NDBs the controller uses the termcourse. Page 82Navigation for Professional Pilots The clearance requests the pilot to intercept the 180 radial inbound, as depicted in the picture above. From the picture it is pretty easy to see that we need to fly eastward. But, in a real airplane there won’t bea map (in most cases) so we must learn to figure out which direction to fly by looking at the HSI, standardVOR, or RMI indicators. As you are reading this, the instructor is flying. He figures out that he needs to fly a heading of 070 tointercept the course. Once on heading 070 everything falls into place. The question is; how does he knowthat he should fly heading 070? We must define: 1. Assigned Course 2. Desired Course 5. Head 6. Tail 7. Track Error 8. “Within 60” Page 83Navigation for Professional Pilots For an inbound intercept the assigned course is always the direction TO the station. Therefore if thecontroller has assigned the intercept in terms of radial you must take the reciprocal to get the assignedcourse. For an outbound intercept the assigned course is always the direction FROM the station. There is no needto take a reciprocal when dealing with outbound courses. The present bearing is the direction that, at present, would take you to the station. If you have an RMI thepresent bearing is the direction the RMI needle is pointing. If you have only a standard VOR indicator youmust center the CDI with a TO flag to get the present bearing. The present radial is the direction that, at present, you are FROM the station. If you have an RMI it is foundby reading the tail of the RMI needle. If you have only a standard VOR indicator it is the bearing you getwhen you center the CDI with a FROM flag. The difference between the assigned course and the present bearing is called the track error. (It is easy tovisualize on an RMI/HSI combination instrument (see picture below), as the angle between the RMI needleand the Course bar.) The PDT procedure we are about to learn only works if you are within 60 degrees. If track error is morethan 60 you must fly directly to the station and do a procedure turn. Your first task is to set the HSI to the assigned course (if you have an HSI.) For a radial put the tail of thecourse bar on the assigned radial to set the inbound course. Page 84Navigation for Professional Pilots Next, make sure you are within 60. Usually in a real world context you will know how far the airway youare trying to intercept is away from you, so this will be an obvious step. But, in the context of thissimulation you must find your present bearing (head) and compare that to the desired course (arrow onHSI) confirming the difference is less than or equal to 60. Once you know you are within 60 you simply following the little rhyme “Desired to head plus 30.” This simply means that you locate your desired course on the HSI then move your eyes to the head of theRMI needle, then move your eyes a farther 30 degrees. That is the heading you need to turn to. Now that you know the procedure watch the computerized flying instructor execute it. Make use of thetime compression, setting it to zero, when you need time to read the instructor’s mind, or observe wherehe is pointing. As the instructor does the PDT he points at the HSI (if available) or the RMI if there is no HSI, or theheading indicator if there is neither. It is much easier to follow his explanations if there is an HSI, so Irecommend starting with that navigation display. Later you can have him demonstrate the procedure withother navigation displays. Notice that the instructor sets the HSI to the assigned course right away. Next he locates the present bearing on the RMI and compares that to the course bar. Look at where hisfinger is pointing (between the course bar and RMI head.) Then he returns his finger to the desired course (head of course bar. See picture above.) Page 85Navigation for Professional Pilots Then he moves his finger to the head of the RMI needle. (Labeled in picture above.) Then he moves his finger another 30-degrees. In this example that is a heading of 070. (See picture above.) Finally he turns to the heading of 070 and flies that heading until he is on the assigned course. NOTE: When we say plus 30, we mean 30 beyond the desired course. Now repeat the PDT yourself. Make sure you go through the procedure methodically. After confirming youare within 60 say to yourself “desired, to head, plus 30.” When that makes sense to you move on. The airplane is back at the exact same starting point, and the exact same clearance is given. Because you set time compression to zero the instructor is on hold. Repeat the rhyme to yourself and try it.The desired bearing is 360, the head is at 040, so once again the required heading is 070. It is important to realize that the heading you must turn to depends on where you are, but NOT on yourstart heading. Because the airplane is moving the present bearing is more than 040 by the time the instructor getsaround to checking it. Therefore the heading he decides to turn to is more than 070. The other thing that probably surprised you is that he decided to turn left, rather than right. Why does hedo that? Page 86Navigation for Professional Pilots The picture above shows what the instructor does. The picture below shows what you might have expectedhim to do. You can see that if he had turned right he would have intercepted the course much closer to the station.That could be a good thing in many cases. But, if the airplane is already close to the station it can createdifficulties. I find that in real world IFR flying you never really need to worry about this sort of thing. Justturn the most direct way to the chosen heading. But, if you and your instructor are practicing PDTs andremaining within 10 miles or so of the station you will find it prudent to take care which way you turn. Therule programmed into the computerized flying instructor is that if the RMI needle is ahead of the wingtiphe simply turns to the chosen heading. But, if the RMI needle is behind the wingtip he will never turnthrough the RMI needle. In the example given he is turning to heading 080 but the RMI needle points toabout 050. So, if he turned right he would fly right through heading 050. Since he is programmed not to dothat he turns the other way. Page 87Navigation for Professional Pilots Once again the clearance is to intercept the same course. But, this time we are on the other side of thecourse. The procedure however is exactly the same. Watch the instructor do the PDT. Pay attention to hisfinger. Set time compression to zero when you need time to analyze what he is doing. Once again we are assigned to intercept the same course. And we are at the same starting point as theprevious secret code. But the airplane is flying northeast bound, so things are changing. As in secret code 2 the instructor will turn the long way around. Here is your chance to see what happens if you turn left rather than right. Do so at your own discretion. Before moving on to do outbound PDTs you will need lots (and lots and lots) of practice doing inboundPDTs. Keep the checkbox at the bottom of the simulation set to “Within 60 PDTs” only, and do lots of PDTs. It’s a lot harder with the map hidden. Click the “Hide All” button at the bottom of the simulation. I recommend mastering PDTs fully with HSI before using the other navigation displays. However, if youwish to do some PDTs with the RMI, standard VOR indicator or Fixed Card indicator you may do so now. Ifyou do, allow the computerized flight instructor to demonstrate the differences in where you must look toget the required information. Note that the procedure is always the same. The difference is only in whereyou get the required information, and in how easy it is to visualize. TIP: When you first start doing PDTs you should set time compression = 0 BEFORE clicking the “DoAnother” button. That way you have all the time you need to figure out what heading you want to turn to.However, once you are getting the PDTs correctly you need to be able to do them in real time. You caneven challenge yourself by setting the time compression to more than real time. Page 88Navigation for Professional Pilots Outbound PDTsNow we will learn to intercept a course outbound from the station. The good news is that this is eveneasier than inbound intercepts. Turn the Visual Aids On. Reset navigation display to “All” or “HSI.” If you have the visual aids turned off click the button at the bottom of the simulation labeled “Show All.” I also recommend returning to the “A” for all or “H” for HSI navigation display. “Pilot 200, you are cleared to intercept the 000 degree radial outbound from the YPB VOR.” When intercepting the course outbound I will teach you to use an intercept of 30-degrees. To perform an outbound intercept we have a different rhyme. “Tail to Desired plus 30.” Page 89Navigation for Professional Pilots Notice that this is a different rhyme than for inbound intercepts. In this one we start at the tail of the RMI,then we move our eyes to the desired outbound course (set on the HSI) then move our eyes a further 30-degrees to find the required heading. (If you wish to do a 45-degree intercept just move your eyes 45 pastthe desired instead.) Then he looks a further 30 degrees. The required heading in this example is 330. You may be thinking to yourself that all these steps are not really needed. All you actually have to do islook at the HSI. If the CDI were deflected left you fly a heading 30 left of the desired course, if the CDI weredeflected right you would fly a heading 30 right of the desired course. This is true. But, I recommendchecking the RMI for two reasons. The first is that without doing this you don’t know if you are off track 11degrees, or 111 degrees. The second reason is that only the procedure described here will work with an RMI or Fixed Card indicator.The picture above shows the instructor demonstrating the same PDT but with an RMI indicator. To see thispress the R-key then click the “Start Over” button. Now, you will see that you MUST do the procedure asdescribed above. Page 90Navigation for Professional Pilots This time we are assigned the same course to intercept and we are at the same starting point. But, ourstart heading is different. Despite this the instructor comes up with the same intercept heading, 330. With the airplane frozen you now have all the time you need to go through the procedure. Keep saying toyourself “tail to desired plus 30.” Click the “I have control” button, then set time compression to more than zero. Change the checkbox at the bottom of the simulation to “Include Outbound.” If you wish to do onlyoutbound PDTs turn off the “Within 60 PDTs” checkbox. Make sure the “Over 60 PDTs” checkbox is NOTselected. Initially set the time compression to zero before clicking the “Do Anther” button so you will have time tothink the procedure through. Then set time compression to more than zero when you know what headingyou want to turn to. Do several PDTs until you are getting comfortable with the procedure. If you desire, practice outbound PDTs with standard VOR indicator, RMI and Fixed Card indicator. Page 91Navigation for Professional Pilots 1. Include Outbound 2. Within 60 PDTs 3. Over 60 PDTs Every time you click the “Do Another” button the computer will generate a random PDT. Some will be over60, some won’t. Some will be inbound and some outbound. Read the clearance carefully then try tocomply. If you need a demonstration you can give the instructor control at any time. Initially feel free to set time compression to zero to give yourself time to think what you should do. But,you must work your way up to doing the exercise in real time. Most airplanes don’t have a moving map. Using the map makes it far too easy to do PDTs. So, once youunderstand the procedure hide the visual aids and practice with only the navigation instruments. Be sure to practice PDTs with all the navigation displays. If you decide not to use a particular display, suchas the Fixed Card indicator you must be certain you won’t encounter one in your real world IFR flying. Ifyou know for certain that the airplane you are doing your IFR rating in has an RMI you may considerskipping Fixed Card indicator – perhaps returning to learn how to use it later. You also know how to fly a circular arc around a VORTAC using a DME and RMI. You know what a leadradial is and how to set up the HSI and OBS when flying an arc. Page 92Navigation for Professional Pilots You know how to intercept any course, inbound or outbound, from a VOR or an NDB. When an inboundcourse is within 60 degrees you can go right to it. When the course is more than 60-degrees from yourpresent bearing you know how to fly to the station and perform a procedure turn. With the above skills you have all the knowledge you need to master holds and approaches. In the nextchapter we will learn to perform holds. Keep your bracketing skills at the ready. In chapter 6 we will learnto do approaches where you will be able to use al l the skills you have just learned, including arcs andprocedure turns. Page 93Navigation for Professional Pilots Page 94Chapter 4IFR ChartsRead section Map 3.2 in your AIM. LO HI Terminal LO ChartsLO charts are used for enroute navigation within the low level airspace. They show the “low altitude”airways and air routes, which are for airplanes flying less than 18,000’. High level airways are shown onthe HI charts discussed below. Airways are based on either VOR or ADF. Even if you are navigating with GPS or Loran-C the airways youfly on are based on the positions of VORs and NDBs. The LO charts give the magnetic tracks for theseairways. The charts also show distances so no ruler or protractor is necessary when flight planning with LOcharts. To fly IFR on an airway you need an IFR clearance, which is explained below. LO charts also show air routes, which are similar to airways but uncontrolled. You will learn the regulationsgoverning these in Avia 130. If you have worked through the designated simulations you know how to tune and interpret VOR and ADFradios with either HSI or standard VOR indicators and fixed card or RMI. If not then review that materialbefore proceeding. In Canada all airways are based on either VOR or ADF. The VOR airways are called “Victor airways.” AllVictor airways have a number which is preceded by the letter V, for example V100, or V302. In an IFRclearance these would be referred to as Victor one zero zero and Victor three zero two. ADF airways arecommonly called “Low frequency airways,” they are always designated with the letter A,B,G, or R. Thestandard phonetic terminology is used, for example airway B22 is referred to as “Bravo two two.” Review the legend on your LO1 chart and then do the assignment to confirm you know all the symbols onthe charts.Navigation for Professional Pilots HI ChartsHI Charts are used for enroute navigation in the high altitude airspace, i.e. at and above 18,000 feet in thesouthern domestic airspace (all flight in high level airspace is IFR.) Most high altitude airways are basedon VORs but some are based on NDBs, all are named with a letter “J” followed by a number, for exampleJ585. In a clearance this is referred to as “Jet five eight five.” Examine the legend of your HI altitude chart and then do the assignment to confirm you understand it. Note that HI charts do not symbolically indicate which direction corresponds to even and odd cruisealtitudes because these altitudes change according to the cruising altitude orders. You will learn about thisin Avia 130 and Avia 260. Airplanes flying along airways in opposite direction cannot pass the way cars on a highway do. Cars passeach other at combined speeds of 200+ KPH missing head-on collisions by four or five feet (pretty terrifyingwhen you stop to think about it. Imagine trying to do it blindfolded.) Airplanes are separated by havingopposite direction airplanes at least 1000 feet apart vertically. Eastbound airplanes fly at “odd thousand”altitude (1000, 3000, 5000, etc.) while westbound flights are at “even thousand” altitudes. VFR airplanesare “separated” from IFR by 500 feet (you already know the cruise altitudes for VFR.) This system workswell for airplanes in cruise but is problematic when many airplanes need to climb or descend. Obviously anairplane climbing to 9000 feet (eastbound flight) must climb through 2000, 4000, 6000, and 8000 creatinga risk of colliding head-on with westbound traffic in each case. Air traffic controllers are charged withmaking sure no collision takes place (and your life depends on them doing it, every time.) Cruising altitude rules for separating opposite direction flights is not satisfactory in the vicinity of busyairports because large numbers departing and arriving airplanes are climbing and descending creating anight-mare scenario for the controller. Preferred IFR routes, STARs, and SIDs are the answer. These are notunlike one-way streets you find in big cities. Page 96Navigation for Professional Pilots When planning an IFR flight one task you must obviously do is choose a route. It might seem obvious thatyou would simply look at the LO or HI chart (LO for airplanes that cruise below 18,000 and HI for airplanesthat cruise at and above) and choose the airway(s) that most directly take you from your departure airportto the destination. Before doing that however you should look to see if there is a published “preferredroute.” This is the aeronautical equivalent of one-way streets that you have probably driven on in largecities. ATC finds it easier to control the flow of climbing and descending traffic (departures and arrivals)when outbound airplanes take one route (or set of routes) and inbound airplanes another. Departingairplanes can be cleared to climb without fear of opposite direction traffic, and similarly arrivals can bepermitted to descend. The controller only needs to ensure that faster and slower airplanes don’t “over-run” each other, which is still a substantial task for ATC, but at least one problem is eliminated. Preferred IFR routes are published starting on page C98 of your CFS. If a preferred route exists you shoulduse it. While the CFS indicates that the system is not mandatory you will find it impossible to get aclearance that does not comply unless you indicate a safety concern (bad weather) or a special operationalneed (lack of pressurization, special ferry flight, etc.) The bottom line is to use preferred routes. When departing from a small airport there is often no listed preferred route but if you are headed for amajor airport you should use common sense and pickup a preferred route; for example departingCastlegar for Vancouver intercept the preferred route for Calgary to Vancouver. IFR flight makes it possible for airplanes to fly in cloud from departure to destination, thus largelyremoving weather as an impediment to flight. A few problems arise when flying in cloud however: 1. Airplanes cannot see each other in flight, so some method of separating them must exist 2. Airplanes cannot see the ground, so some method of avoiding it must exist 3. Airplanes cannot see the runway, so some method of descending and establishing visual contact with the runway is needed in order to land The ATC system exists PRIMARILY to keep airplanes from colliding during flight. Some aspects of this taskhave been indicated above. Any other services that controllers provide are secondary to the primaryfunction. In short the ATC system solves only problem 1 above. Pilots follow prescribed procedures and climb at specified climb gradients to avoid terrain duringdeparture and when enroute they fly above minimum enroute altitudes (MEA.) MEAs are shown on LOcharts. The key word in the previous sentence is procedure and we say that terrain avoidance in IFR flight Page 97Navigation for Professional Pilots is “procedural.” Note that it is NOT the responsibility of ATC to prevent terrain collision. Pilots areresponsible for that through the correct application of IFR procedures. IFR approach procedures are published in the Canada Air Pilot (CAP) which you have purchased. These arefor the purpose of making a safe descent (taking terrain into account) to a point where the pilot MUST seethe runway in order to land on it. So problem 2 and 3 above are both solved procedurally. It is always possible that the weather will be so bad that the pilot does not see the runway at the end of anIFR approach procedure. In this case an alternate airport, where the weather is good, is needed. You willlearn all the regulations for this elsewhere, but it should be obvious that the alternate airport must havegood weather so that there is NO CHANCE of being unable to land there. You will learn to assess the FORECAST to determine that an airport is a “legal alternate.” The requiredweather is specified in the CAP GEN and in RAC 3.14. On all IFR nav-logs you will include time and fuel toget to an alternate airport. Page 98Navigation for Professional Pilots Page 99Chapter 5The CR ComputerYou have already learned to use the wind side of the CR, now it is time to master the front-side. Workthrough your CR manual from page 1 to 29 (you should already have done the rest of the book.) A Ratio MachineThe outer two rings on the front-side of the CR are a “ratio-machine.” You will learn to do many usefulratios all of which have practical application in your flying. First a quick review of what a ratio is: ½ = 2/4 = 3/6 = 18/36, etc. These are simple examples of ratios and fractions, for our purposes, ratiosshould be thought of as fractions. One half equals two quarters, three sixths, and eighteen thirty-sixths,and an infinite number of other ratios. The CRUCIAL thing to realize is that you can set any ONE of theseratios on your CR and it will give you ALL the others. In the photo below you can see that all the ratios aregiven. Get out your CR and set one of the above ratios and see that you have them all. Before we go further it is important to note how numbers are displayed on the CR. On a CR 10 canrepresent 1, 10,100, 1000, etc. Thus 10/20 in the photo above represents ½ as well as 10/20, 100/200 andso on. 18/36 also represents 180/360 and 1.8/3.6 and so on. It is your job to keep track of the decimalNavigation for Professional Pilots points when using your CR. It is important to know that not only does ½ = 2/4 also equals 20/40 and2000/4000, etc. From the photo above, or your own CR, you can see that ½ equals 17/34 and 17.5/35 and an infinitenumber of other ratios not previously listed. But in a given situation only a few of these ratios are ofpractical interest – even so it is important to understand that there are an infinite number of equivalentratios The secret to making good use of a CR is in knowing which ratios are interesting. This depends on whatquestion you are trying to answer. A common problem is time and distance, which we will deal with underthe topic of speed ratios below. But there are many other ratios of importance in aviation. For exampleclimb gradients, distance to a radio navaid, unit conversions, etc. Solving problems with a CR requires youto ask, what relationships are relevant? For example IFR departures require a minimum climb gradient of200 feet per nautical mile (ft/NM.) To use a CR effectively you must realize that this is a ratio (200/1.) Agood clue is the word “per”; when you know that something happens “per” something else it is probably aratio that you can solve with a CR. For example if you are paid $14 per hour and want to know how muchyou earn in 40 hours the CR can tell you. The photo below shows that you earn $560 dollars in (per) 40hours. How many dollars do you earn in 8 hours? Page 102Navigation for Professional Pilots Unit ConversionsMost unit conversions are simple ratios. Examples include pounds/kilograms, liters/gallons, statute-miles/kilometers and nautical-miles/kilometers. If you establish ANY relevant ratio relating these valuesyou can use it to determine ALL others, using your CR. For example you may have noticed on thespeedometer of your car that 80kph equals 50 mph – set this ratio up on your CR and fill in the tablebelow: Page 103Navigation for Professional Pilots To solve the above problem we started with the ratio 80/50 which we remembered from the speedometerof a car – but the CR has most of the common ratios marked on its face. Remember that any ratio will do,so Jeppesen simply marks the ratios wherever they fit without cluttering the face of the computer toomuch. The photo above shows a ratio for km/sm. Once this ratio is set all others can be read. The KM and Statutemarkings are found on both the outer and inner ring so you can set the CR up either way. Page 104Navigation for Professional Pilots Feet to meters Pounds to Kilograms Remember that if you know a conversion ratio from memory you can save the need to locate one on theCR. For example if you know that 2.2 pounds equals one kilogram simply set that ratio on the CR to savethe trouble of locating the marked ratio shown below: Set the above ratio and confirm that 2.2/1 is an equivalent ratio. The CR does not have a conversion from Nautical miles to feet. You will often need to know that 1.0NM =6080 feet. If you forget you can figure it out with a CR through a two-step process. First determine howmany KM = 1NM and then convert from meters to feet. Try it yourself to confirm you get the expectedvalue. The same process can be used to discover there are _______ feet in a statute mile. Page 105Navigation for Professional Pilots -40°C = -40°F but 1°C does not equal 1°F. The reason ratios don’t work is that 0°C does not equal 0°F. Forall the other conversions we looked at so far the zero points match. That is a requirement for using ratiosas a conversion method. The CR has a temperature conversion scale on the front face (see photo below.) You can see that -40°C = -40°F but that 0°C = 32°F. 20°C = ____? Mach NumberYou will use Mach number extensively in flight planning. It is a ratio. Assume the speed of sound is 600 knots and set the ratio 600/1 on your CR, as shown below. With your CR set as above 1200 knots is what Mach number? The answer is 2.0 Page 106Navigation for Professional Pilots A C-172 cruising at 105 knots has what Mach number? What is the Mach number of a King Air cruising at240 knots? The above conversions from TAS to Mach number are simple but only accurate if the ratio 600/1 is correct.In fact this ratio is only approximately correct; the real speed of sound varies with air temperature. You willnotice that once you set 600/1 on the CR a Mach index is visible that allows you to “fine tune” the ratio forthe actual air temperature. You can see the index in the photo below. Set the Mach index to -25°C (the ISA temperature at 20,000’.) What is the speed of sound? This amounts to 1saying what TAS corresponds to Mach 1.0 . An airplane cruising at Mach 2.0 has a TAS of _____ knots. Anairliner cruising at Mach 0.8 has a TAS of _____ knots. What would the TAS of the airliner be if the air 2temperature was -56°C? 1 610 KTAS2 490 KTAS Page 107Navigation for Professional Pilots To be cheeky you could say, “My speed is 17 miles per 11 minutes.” That is a pretty weird unit, but it isindeed your groundspeed. It is however traditional to specify speed in units of Knots. Knot is defined as NM per hour, but in reality it is NM per 60 minutes. It is VITAL to realize that the symbol, even thoughit has 1:00 written on it, actually represents six (6) or 60 on the CR, as you can see in the photo below: Thus we would say that our groundspeed is 93 knots, which means 93/60. How far do we go in 30 minutes,how far in 12 minutes? You can determine these and an infinite number of other ratios once17/11 hasbeen set – it’s just that you don’t usually think to ask such questions. There are however other ratios that are important beyond the simple 93/60 ratio that is “ourgroundspeed.” For example how many miles do we go in one minute. The photo that shows the 17/11ratio also shows the ratio 1.54/1. This is an important value to know, sometimes. The airplane is covering1.54 NM every minute. If the total length of the trip is 170 NM, how long will it take to get there? Note that since we areresponsible for the decimal points the same ratio 17/11 gives the answer. Common sense says that it will Page 108Navigation for Professional Pilots 3take 110 minutes to fly 170 NM. How long would it take to fly 88NM? How long would it take to fly214NM? Make up your own distances and confirm that you can find the time for any distance you choose. To approach this problem from the other direction, if you are flying 1 nautical mile per minute what is yourgroundspeed? In this case set 1/1 and look up x/60. Note that the answer is 60 KTAS. At 60 knots how longdoes it take to fly 18NM? How long for 78NM? How long for 156NM? The answer to all these is trivial andyou should not require your computer. 60 knots – i.e. 1.0 NM/min is an IMPRORTANT speed that we will use extensively so you must rememberit. If you are flying 2 miles per minute your groundspeed is _____ Knots. If you are flying 3 miles per minute your groundspeed is _____ Knots. 3 57 minutes4 1.5 NM/min Page 109Navigation for Professional Pilots The airplane in the diagram is flying around a circle. At the moment shown it has flown 17° of arc in 11minutes. What is the arc-speed? Arc-speed has units of degrees per hour, which of course really means degrees per 60 minutes. Simply setyour CR for the ratio 17/11 and lookup the answer. The result is exactly the same as the groundspeedexample above in which the airplane flew 17NM in 11 minutes, but this time the arc-speed is 93degrees/hour. How long will it take to fly 20 degrees? How long will it take to fly 60 degrees? Hopefully your reaction to the above is that it is trivially obvious (but you may be thinking it is unimportant– trust me it is VERY IMPORTANT.) Be sure to examine the above until you fully understand it. Here are afew sample problems for you to work through just to be sure: You fly 14 degrees in 7 minutes; your arc-speed is ______ degrees/hour. It will take _____ minutes to fly 60degrees; it will take ______ minutes to fly 57.3 degrees. Page 110Navigation for Professional Pilots You fly 37 degrees of arc in 3 minutes. Your arc-speed is _____ degrees/hour. It will take ______ minutesto fly 60 degrees; it will take ______ minutes to fly 57.3 degrees. It is now time to review some high school trigonometry. First recall what an equilateral triangle is: An equilateral triangle is one that has all three sides the same length and all three angles equal. The threeangles must all be 60 degrees (the sum of the three angles in every triangle is 180°) The three sides of an equilateral triangle are equal to each other. In the diagram above distances AB = AC= BC. Page 111Navigation for Professional Pilots The diagram above is the same as the previous one with an arc added. The center point of the arc is B.Look at the diagram and estimate the length of the arc compared to AC. Obviously the arc is longer, buthow much - 1%, 10%, what do you think? It should be obvious that there is some angle, just a bit less than 60°, such that the length of the arc is thesame as the length of the sides AB and BC. Obviously AC will have to be shortened, consequently thetriangle will not be exactly equilateral any more, but it will be close. Consider the diagram below. Page 112Navigation for Professional Pilots In the diagram above the angle through which the arc sweeps is reduced to 57.3 degrees. This is the“special” angle for which the length of the arc is exactly equal to the radius. I.E. AB = AC’ = arc. AB and AC’have been labeled r in the diagram to remind us that they are the radius of the arc. 57.3° is known as oneradian. The sample problems above asked you to determine the time to fly 60 and 57.3 degrees of arc, we will nowexamine why. Returning to a previous example in which the airplane few 17° of arc in 11 minutes (setup your CR for theratio 17/11.) The time to fly 57.3° of arc is 37 minutes. But, since the length of the arc equals the radius itobviously also takes 37 minutes to fly directly to the center of the arc (point B.) The time to fly 60° is 39minutes. Most pilots use this as the answer because it is a lot easier to remember 60 rather than 57.3 (57.3= 180/Π.) Time to the station is a common problem in aviation. You will even more commonly need to know distanceto the station, but that is a two-step process which we will cover in just a moment. First let us consider themost common situation in which the above theoretical facts comes into actual practice. In the above diagram the airplane is flying an eastbound track that passes north of a VOR. The pilot wishesto know how long it would take to get to the VOR if s/he turned southbound directly to it. To find out,without the need to actually do it, record the time from A to B and the angle X. To be effective AB mustapproximate flying an arc, so the station must be essentially abeam the airplane (as in the diagram.) Theangle X is usually fairly small, typically less than 15° (but not too small or there will be “round off error.”)Angle X is arbitrary, so it doesn’t matter if it is 4°, 7°, 11°, 15°, etc. simply time whatever is convenient. Once you have a “time / x-degrees” ratio setup on your CR all you do is lookup time for 57.3°or 60°.Neither will be precisely accurate, but either will give an answer that is within 5% of the correct value. The above use of “arc-speed” to determine time to a station when flying abeam is one of the mostcommon uses of arc-speed theory. As you can see, it is an approximation since the airplane actually flies a Page 113Navigation for Professional Pilots straight line forming a triangle with the station, but the previous analysis that showed an equilateraltriangle is very similar to a one-radian arc. It is recommended that in these calculations you use 60° as thereference angle rather than 57.3 (i.e. think of the equilateral triangle analogy to help you remember howto do it.) Next we will consider a more precise use of arc-speed theory. Consider the modified approach plate 5below : To fly this arc you start at the point marked and maintain a constant 9 DME arc to intercept the 087 radial(which lines you up for landing on runway 09.) On the right side of the plate a Lead Radial (LR) is published, but its value has been erased on the abovephoto. The LR is always 2NM prior to intercept of the final approach course (087 radial in this case.) Whatshould the LR be? See if you can figure it out based on arc-theory before reading the next paragraph. To answer the question we need to realize that 57.3° of arc will be 9NM, since it is a 9 DME arc. So set theratio 9/57.3 on your CR and look up 2/a. The answer is 12.7°. Note that if you had used 9/60 as your ratioyou would get 13.3°. Either way you will round off to 13° and predict the 074 radial as your answer. 5 The original is in the CAP3 under Brandon Page 114Navigation for Professional Pilots Imagine you are flying the above arc arrival and wish to slow down and start your pre-landing checklist5NM prior to intercepting the final approach track, what radial should you start to slow down at? If youkept your CR set to 9/57.3 the answer is right in front of you. Look it up before reading the next paragraph. With your CR set to the ratio 9/57.3 lookup 5/a. The answer is 32°. So you will need to slow down at the055 radial. The above uses of arc-speed are very typical of ones you will experience everyday as a commercial pilot.Learn them well and get comfortable with them. Imagine the above DME arc had been 14NM instead of 9. What would the lead radial have been? Distance to StationBelow the same diagram previously examined has been repeated. It is much more likely that the pilot wishes to know the distance to the VOR rather than time to the VOR.Imagine the situation in which the flight plan route passes a certain number of miles north of the VOR. Thepilot wishes to determine if s/he is on track (the airplane could be in IFR weather conditions, over water, orfeatureless terrain, so that this method is the only method of fixing position. If the airplane is equippedwith DME the position check would be easy, the pilot would simply note the distance as s/he passedabeam the VOR, but this particular airplane does not have a DME so we will have to do it the “hard way.” Page 115Navigation for Professional Pilots First, it is important to note that we cannot solve this problem unless we already know the groundspeed ofthe airplane. We will assume that the pilot has been doing his/her job well and knows the groundspeed. Assume the following data and follow along with your CR. The airplane crossed the 355 radial at time 0:00and crossed the 005 radial 7:00 minutes later. The groundspeed is known to be 144 knots. How far north ofthe VOR are we? This is going to be a two-step process. What is the first relevant ratio? Think it through on your own beforereading the next paragraph. (Tip: what is the angle X?) The airplane has flown through an angle of 10° in 7 minutes. Setup the ratio 10/7 on the CR. Nowdetermine how long it would take to fly 60°. The answer is 42 minutes (10/7 = 60/42.) So time to thestation is 42 minutes. In the second step we will determine distance to the station. We know it would take 42 minutes to getthere, but how far is it? We know that groundspeed is 144 knots. What ratio do we need to setup? Reasonit out before reading the next paragraph. We setup the ratio 144/60 which represents distance in 60 minutes. The relevant ratios are 144/60 = a/42,where a represents the answer. The answer is 101 nautical miles. In summary: When flying abeam a station, calculate distance to the station by: 1. Determining how long it would take to fly a 60° arc (or one side of an equilateral triangle.) Pilots routinely plan arrivals at a descent gradient of 320 ft/NM (which corresponds to 3°.) Often otherdescent gradients are required, especially for non-precision approaches in mountainous environments. Wewill thoroughly examine gradients in what follows. Keep in mind that climb gradient and descent gradienttheory is fully interchangeable. Anything you learn about planning descent rates can be applied to climbrates, and vice versa. 6 This relates to the “procedural” terrain separation previously mentioned in the Overview of IFR Flight Page 116Navigation for Professional Pilots Unfortunately climb and descent gradients are not directly usable by pilots. Our aircraft are equipped withrate instruments, not gradient instruments. We have an airspeed indicator and often a DME or GPS all ofwhich give our speed (a rate) and we have a vertical speed indicator (VSI) that gives our rate of climb anddescent. Our challenge is to translate the published climb and descent gradients into useable vertical-speed/airspeed ratios (rates.) We will start with a very simple problem, but one that applies to all IFR departures. As stated previouslythe minimum acceptable climb gradient is 200 ft/NM, as shown in the diagram below. We can quite simply answer questions such as; what is the minimum safe altitude 5NM after takeoff? Canyou setup the required ratio? Try to do so before reading the next paragraph. The ratios are 200/1 = a/5, where a is the answer. The answer is 1000 feet, i.e. you must be at least 1000’agl 5NM after takeoff to meet the gradient. When you reach 2000’ agl the maximum distance you should be from the airport is ______ NM. The problem we most need to solve is; what vertical speed must we maintain to safely meet the gradient?This is almost trivially simple to answer if you remember that 60 knots is 1.0 NM/min (previously I said thatyou needed to remember that fact.) If you forget then set your CR to the ratio 1/1 to remind yourself that1.0 NM/min means 60 miles per 60 minutes. Examine the above diagram and imagine the airplane climbing along the flight path at a groundspeed of60 knots. After one minute it would be at the 1.0 NM point and its altitude would be 200 feet. After twominutes it would be at the 2.0NM point and its altitude would be 400 feet, etc. It must be clear to you thatit requires a vertical speed of 200 fpm. To make rate conversions it is CRUCIAL to realize that an airplane with a groundspeed of 60 knotsrequires a climb rate equal to the gradient. In this case the relevant ratio is therefore 60/200. What climbrate do you need at 75 knots? Figure it out on your own before reading the next paragraph. Page 117Navigation for Professional Pilots Set the CR to the ratio 60/200 and lookup 75/a. The answer is 250 fpm. At 85 knots the minimum safe 7vertical speed is _____ fpm. At 95 knots it is _____ fpm. At 105 knots it is _____ fpm . At 120 knots it is_____ fpm. Not all departures can be made safely at a gradient of 200 ft/NM. When a larger gradient is required thedeparture chart will specify the required value. The plate below is an example: You can find the above plate in your CAP2 under Victoria International, Mill Bay SID. Depending on whichtransition ATC assigns, a climb gradient of 330 ft/NM or 220 ft/NM applies. Let’s work out the requiredvertical speed for each case – starting with 330 ft/NM. What ratio should you setup on your CR? Try tofigure it out before reading the next paragraph. We must realize that at 60 knots the required vertical speed is 330 fpm. So set the ratio 60/330 and lookupyour-speed/a. [Tip: it makes no difference whether you setup 330/60 or 60/330 as long as you keep trackof whether groundspeed or vertical speed is on the top of the ratio.] If your groundspeed is 75 knots the required vertical speed is 415 fpm. At 85 knots it is ______ fpm. At 105 8knots it is ______ fpm . Make sure that the above calculations are effortless for you. You must routinely check the minimum climbrate for IFR departures. Before we move on to the next important point it should be pointed out that you can approach the aboveproblems from the opposite direction. If you know your groundspeed and vertical speed you can use the CR 7 350 fpm8 580 fpm Page 118Navigation for Professional Pilots to determine your actual climb gradient. This is also helpful for flight planning purposes. We will use itquite often, so it is worth covering now. Imagine that you know your groundspeed is 115 knots and thatyour vertical speed is 800 fpm. What is your climb gradient? What ratio should you setup, and how do youget the answer? Figure it out before reading the next paragraph. The relevant ratio is 115/800 = 60/a. The secret is to realize that the ratio groundspeed/vertical speed, i.e.115/800 establishes the gradient. To get the value in units of ft/NM remember that 60 knots is 1.0NM/min, and look up the vertical speed at 60 knots. In this case the answer is 416 ft/NM. As long as thisvalue exceeds the published climb gradient the pilot need not worry. This calculation can also easily beextended to answer questions of the form; what altitude will this airplane be at when 6.4 miles aftertakeoff? [Tip: this is step two of a two-step problem.] Try to figure out the answer before reading the nextparagraph. We know the climb gradient is 416 ft/NM so setup the ratio 416/1 and lookup a/6.4. The answer is 2660feet. A particular airplane climbs at 160 knots and 1000 fpm. What is the climb gradient, and what altitude willit be at 3.7NM after takeoff? The first ratio is 160/1000 = 60/a. This gives a climb gradient of 222 ft/NM. The second step is to use the climb gradient, so set the ratio 222/1 = a/3.7. The airplane will be at 830agl3.7NM after takeoff. You can see that the above two-step calculation is quite useful for flight planning. Go over it until it makescomplete sense to you. Next we examine a very important, but not significantly different, situation related to approach planning.Consider the following approach plate, which is quite typical. Page 119Navigation for Professional Pilots The approach plate above can be found in your CAP2 under Abbotsford NDB RWY 07. On this approach theairplane must cross the XX NDB at 1700 (or above) and then land on runway 07, which has a touch downzone elevation (TDZE) of 174. The XX beacon is 4.3NM from the runway. All this information is presentedon the above plate; be sure you can locate it for yourself. The airplane must descend 1526 feet (1700 – 174.) The pilot will of course not land exactly at the runwaythreshold; normal touchdown is made about 0.2NM past the threshold, so the descent must be completedin 4.5NM. What is the descent gradient? Try to figure it out yourself before reading the next paragraph. The relevant ratio is 1526/4.5 = a/1. The answer is 340 ft/NM. What vertical speed is needed? Try to setupthe required ratio on your own before reading the next paragraph. The relevant ratio is 60/340 because at 60 knots 340 fpm would be required. The required vertical speeddepends on your groundspeed such that 60/340 = groundspeed/a. If you fly the approach at 105 knots thevertical speed must be 600 fpm. At 90 knots the vertical speed must be ______ fpm. At 140 knots thevertical speed must be ______ fpm. The above calculation will be needed for every non-precision IFR approach you fly, so it is important tobecome comfortable with it. You should open your CAP at random and calculate the descent gradient forthe final approach segment of many non-precision IFR approaches (i.e. not ILS approaches), and resultingvertical speed at your airplane’s approach groundspeed, until you can do the calculation quickly andeffortlessly. Examining the Abbotsford approach plate once again, we see that in the intermediate approach segmentthe airplane must descend from 2500 to 1700. How far back from the XX NDB should this descent begin ifthe pilot wishes to maintain a descent gradient of 340 ft/NM (the previously calculated gradient for thefinal segment)? Setup your CR as required before reading the next paragraph. Page 120Navigation for Professional Pilots The airplane must descend 700 feet (2500 – 1700.) The relevant ratio is 340/1 = 700/a. The answer isabout 2.1NM. If the pilot wishes to limit the intermediate segment to a gradient of 320 ft/NM the descent should start______ NM from the XX beacon. Most precision approaches are set to a descent angle of 3°, which is a gradient of 320 ft/NM. Someprecision approaches use other gradients. Legally a precision approach can have glidepaths in the range2.5° to 4.0°. The above diagram shows a 3° descent, which corresponds to 320 ft/NM. This can be calculated usingbasic trigonometry. Tan (3) = a/6080 (recall that 1.0NM is 6080 feet.) Using an electronic calculator aequals 318.7, which we will round off to 320. How many nautical miles are required for a descent of 1000 feet on an ILS? Setup the required ratio onyour CR before reading the next paragraph. The above relationship is VERY IMPORTANT. However, most pilots round it off to 1000 feet per 3.0NM,which is close enough for typical purposes and allows quick and easy calculations in your mind withoutneeding a CR. Below are some typical applications. Work them out based on the ratio 1000/3; if you likeyou can rework them based on the more accurate 320/1 to see if the difference is significant. The tower asks you to report 2NM on final; what altitude will you be at? Setup your CR before reading thenext paragraph. Page 121Navigation for Professional Pilots The ratio is 1000/3 = a/2. You should report 2.0 final when you are 666 above ground level (note that youcan thus report 2.0 final even if your airplane is not equipped with DME.) If you had used the more preciseratio 320/1 your answer would be 640agl. From a practical point of view reading the difference on youraltimeter and then reporting would be impossible. You are going to intercept the glidepath at 3000agl, how far from touchdown will you be? Setup your CRbefore going on. If you set 1000/3 = 3000/a; the calculation is so simple you hardly need a CR. You will be 9.0NM fromtouchdown. If you set the more precise ratio 320/1 the answer is 9.4NM. This is the actual distance, butsince your primary purpose in such calculations is usually just to keep a mental image of how far you arefrom touchdown the difference between 9.0 and 9.4 is probably not significant. You are flying an ILS approach with a groundspeed of 120 knots, what vertical speed do you require? Setupyour CR before reading the next paragraph. The required ratio is 60/320 = 120/a. The answer is 640 fpm. This is an important calculation, but giventhat positive guidance is provided by the glidepath it is really only necessary to approximate thiscalculation. With your CR set to 60/320 what is the value of 1/a. Note that a equals 5.3. This ratio tells usthat we need 5.3 fpm for every knot of groundspeed. Pilots routinely round this off to 5.0. From this comesthe rule of thumb that vertical speed should be 5 x groundspeed. Using the 120 knot example we get 5 x120 = 600 fpm. We know the correct answer is 640, but 600 fpm will get you started close enough, youthen follow the glidepath indicator, which will take you directly to the runway. Summarizing what we have learned about flying 3° precision approaches. In order to facilitate mentalcalculations while flying ILS approaches pilots use the ratio 1000/3 or 100/.3 to approximate the descentgradient. Pilots also use the formula 5 x groundspeed to approximate the descent rate. Use the approximations to answer the following questions without using your CR or any other calculator. Your company SOP is to call 100 above as you approach the glidepath check altitude. You will be ____ NMfrom the checkpoint when you make this call. You will intercept a glidepath 600 feet above the glidepath check altitude. That will be _____ NM from theFAF. Your groundspeed is 100 knots; the required descent rate is ______ fpm. You are 400 agl when the tower asks, “How far back” you are. Your answer is _____ NM. Page 122Navigation for Professional Pilots It is important to know that the actual air temperature is NOT -21°C; the friction of the air rushing past thetemperature probe causes an error and the actual temperature is colder than -21°C. We will see how muchcolder shortly. FL250 means that your altimeter is set to 29.92, so your pressure altitude is 25,000’. From the King-Air POH we look at the calibration chart to see what our CAS is. At 170KIAS there is no error,so our speed is 170 KCAS. On the CR (CAS window) set 170 KCAS opposite 25,000’ pressure altitude, as shown below. Keeping the CR in that position, rotate it so you can look at the TAS window. Set the indicated temperaturehairline to -21°C and read the TAS on the scale, see photo below. Page 123Navigation for Professional Pilots Temperature rise (see photo below) is 8.2°C, in other words the actual temperature is -29.2°C. There are lots of sample problems like the one above in the assignments. Remember that when doing thissort problem with your CR you would be in flight and checking that your TAS is working out as flightplanned. Page 124Navigation for Professional Pilots It is much simpler to do this for airplanes that fly less than 200 knots and less than 20,000 feet because wecan disregard compression error. The CR has two techniques: 1. A quick and simple technique that does NOT compensate for compression; for aircraft slower than 200 knots 2. A two-step procedure that accurately allows for compression. This can be used for all airplanes, both fast and slow; but MUST be used for fast airplanes. You are expected to learn both procedures and apply the two-step procedure when needed (i.e. for anyairplane flying faster than 200 knots, or higher than 20,000 feet.) Of course you can always use it, but ittakes longer and is not needed for slow airplanes like the C-172 or B95; for the King Air you must useprocedure 2. Obviously jet pilots always use procedure 2. 65% power Page 125Navigation for Professional Pilots Line up the temperature of -12°C with the PRESSURE ALTITUDE of 8070’, as shown in the photo above. Take care to keep the above values aligned while you locate the TAS on the outer ring. CAS appearsdirectly below it; in this case 111KTAS equals ~101 KCAS. To get the indicated airspeed look in the calibration chart on page 5-8 of the POH. In this case indicatedairspeed is about 2 knots more than calibrated so the final answer is 103 KIAS. Page 126Navigation for Professional Pilots You will be using the above procedure over and over, on all your flight plans for the C-172P and Beech 95,so make sure you can do it without hesitation. The procedure works because temperature affects calibrated airspeed and the speed of sound equally andtherefore the effects offset. For a given Mach number there is one CAS for each pressure altitude,regardless of TAS. An IMPORTANT point to note before we go further is that since the TAS window on the CR works withINDICATED temperature (see photo below) and indicated is NOT the same as actual air temperature, youcannot use the TAS window to predict CAS by reversing the procedure covered above. The proper procedure is to first determine your Mach number. To do that you need to know TAS and thespeed of sound. Your POH gives you TAS and the CR gives you the speed of sound. Page 127Navigation for Professional Pilots Mach number is simply the ratio TAS/speed-of-sound. Using the method described earlier reveal the MachIndex by setting 600 knots over 1 on the outer scales (this is shown below.) Next set the actual air temperature on the Mach index to get the “real” speed of sound. The photo belowshows the Mach index set to -30°C. On the outer scale you should now see that Mach 1.0 corresponds to606 knots. If you were at Mach 2.0 your TAS would be 1212 KTAS, what is your TAS if you are at Mach 0.8, 9what is it a Mach 1.4? 9 850 KTAS Page 128Navigation for Professional Pilots Returning to our problem, we know that our TAS is 277. What is the Mach number? You can read it on thescale as shown below. Locate the TAS on the outer scale and read the Mach number. In this example true airspeed of 276corresponds to Mach 0.455. Notice that when air temperature changes Mach number changes, butaltitude per se is irrelevant. You are now ready for the second step. Go to the TAS window and set the Mach number as shown below. Page 129Navigation for Professional Pilots With the Mach number set look in the calibrated airspeed window across from 23,000’ pressure altitude toget the CAS. The photo below shows the result. In this example CAS is 195 KCAS, which is roughly 197 KIAS according to the POH. This procedure works because ANY airplane at FL230 and Mach 0.455 has a calibrated airspeed of 195KCAS, regardless of temperature. You will be using the above procedure many times in flight planning so make sure you go over it until youcan do it without hesitation. Page 130Navigation for Professional Pilots Setting the Mach index to -12°C the speed of sound becomes 628 knots. More importantly cruising at 111KTAS corresponds to Mach 0.1765. Set this in the TAS window as shown below: In the CAS window locate the pressure altitude, which is 8070’ and read the calibrated airspeed, as shownbelow: The result is ~100 KCAS, which is exactly what we got using the slow airplane procedure. So bothprocedures clearly work for the C-172P. Now let’s find out what happens if we use the slow airplaneprocedure for the King Air problem. Page 131Navigation for Professional Pilots In the pressure altitude window set the temperature of -30°C over the pressure altitude of 23,000 asshown below: Now locate the TAS of 276 on the outer scale and read the CAS. This is shown below: The value of less than 192 is obviously wrong. We know the correct value is 196. The four knot error maynot seem like a big deal, but it is certainly enough to get the wrong answer on your ATPL written exams.The error gets larger as you fly higher (as in jets.) So we have confirmed that we cannot use the slowairplane procedure for the King Air. Page 132Navigation for Professional Pilots Sample Questions 5Use the “Professional Method” to complete the last two columns of the table below: Read the section labeled “Old” Method on page 21 of the CR Handbook. Repeat the calculationsusing the old method. This time you do not need to determine Mach number: 105 12°C 105 -20°C 145 5°C 235 -12°C 380 -56°C 440 -56°C Page 133Navigation for Professional Pilots 0.16 8,500 0.17 8,500 0.224 6,000 0.373 21,000 0.67 32,000 0.775 38,000 Page 134Navigation for Professional Pilots Page 135Chapter 6The Canada Flight SupplementThe Canada Flight Supplement (CFS) is one of the most important documents for flight planning. You mustbecome familiar with all the information it contains and be able to locate what you need quickly andefficiently. The most used part of the CFS is section B, which gives data about all the registered airports andaerodromes in Canada. However, to get maximum value from this data you must use the index in thegeneral section, part A. Get to know the codes used to describe public facilities (PF) lighting, etc. You willbe given a number of assignments to develop expertise in decoding the CFS. As mentioned previously the CFS contains many useful pieces of information in the later sections. Thisincludes preferred IFR routes for both high and low altitude. In the assigned cross country flights you willneed to consult these. These can be found in section C, Flight Planning. Section D contains a lot of useful information about the location of navigation radios, VOR/DME frequencyallocations etc. Section E is perhaps the most neglected yet vital section. It contains various emergency procedures such asintercept orders and procedures in the event of an emergency landing. Every pilot should read andunderstand this section. Become familiar with all the information in the CFS. Expect questions drawn from the CFS on all yourexams. Page 138Chapter 7Navigation TheoryIn this section you will learn about the compass, the shape of the earth, maps and globes and other theoryelements that impact on navigation. The earth spins around an axis that astronomers can locate. This defines the north and south poles. Wewill learn about the magnetic North and South Pole later. For now simply realize that the true North andSouth Poles are based on the spin of the earth and are NOT the same as the Magnetic Poles. The original definition of the metric distance unit “meter” was that the distance from the equator to thepole is 10 million meters, i.e. 10,000 Km. Therefore the circumference of the earth is 40,000 Km measuredaround the poles. Because the equator is a bit fatter, as mentioned above, the equatorial circumference is40,076 Km. The aviation unit of distance is the nautical mile, which is also defined in accordance with thecircumference of the earth. Every degree of latitude is by definition 60 NM, so the circumference of theearth is 360 x 60 = 21,600 Nm, measured around the poles. The distance around the equator is an extra 41NM. From the above discussion you should memorize the definition of the nautical mile and take note that thedifference in circumference of the earth around the poles vs. the equator is less than .00002%. If the earthwas shrunk down to the size of a billiard ball it would be a smoother rounder billiard ball than any you willfind in a pool hall. The earth spins around an axis that runs through the north and south poles. It spins once every 24 hours,which defines one day. Due to the gravitational effect of the moon and sun the earth’s spin is graduallyslowing down, but it will take billions of years before it stops spinning relative to the sun. The rate ofslowing is however enough for atomic clocks, such as those in GPS satellites, to measure so they must beresynchronized with the rotation of the earth every 1000 weeks (roughly every 20 years.) Other clocks aresynchronized just before midnight on December 31 each year making the last day of the year the longestby a few millionths of a second. An interesting anomaly that results from this variant resynchronization isthat earth clocks and GPS clocks move out of synchronization over the 1000 week GPS cycle. A computerprogram in your GPS receiver calculates the difference so that the time displayed to you is approximatelyequal to earth time, and different than “GPS time.” LatitudeNavigation for Professional Pilots A grid system known as latitude and longitude has been devised so that the location of any spot on theearth can be specified, rather like the (x,y) Cartesian coordinate system you already know. Take note thatthe latitude/longitude system is devised on a model of the earth that assumes a perfect sphere. Asmentioned above the earth is not a perfect sphere, but the difference is such a tiny fraction of 1% that itcan be ignored for our purposes. Lines of latitude run around the earth east to west and exactly parallel to each other and perpendicular tothe earth’s axis of rotation. Latitude is measured as the angle from the center of the earth with theequator defined as zero degrees, and therefore the North Pole is 90°N latitude and the South Pole is 90°Slatitude. This is shown in the diagram below. Every degree of latitude is 60 NM. The subunits of latitude are called minutes. There are sixty minutes perdegree, so each minute of latitude is one nautical mile. If you know the latitude of two places you can calculate the north/south distance between them. Castlegaris at N49 17.76 while Prince George is N53 53.37 (note the format, more on that shortly.) The difference is Page 140Navigation for Professional Pilots 4 degrees 35.61 minutes. 4 degrees equals 240 NM and 35.61 minutes equals 35.61 NM so the totaldistance is 275.61 NM. Please note that this is the north/south distance only, there is also an east/westcomponent that we turn to next. LongitudeBecause the earth has poles there was no controversy about setting up a latitude system. The lines oflatitude run parallel to each other and are equidistant apart. But there is no equivalent to the equator toact as a starting point for a grid system in the perpendicular orientation. All locations on the earth areequal in the sense that the earth spins once per day so every spot on earth has a noon and a midnight,these are different for each location. In the historical period when accurate measuring of the earth first became possible the British were thedominant world force, therefore the PRIME MERIDIAN runs through London England, specifically theGreenwich observatory. Meridians of longitude are straight-lines that run north/south through the poles.Every location on the earth has one, but the one that runs through Greenwich is designated as 0°longitude. Every other location is therefore specified as east or west of the Prime Meridian with 180E or180W (the same place) being the maximum longitude. 180W is about the middle of the Pacific Ocean, andruns very close to New Zealand, so it is true to say that New Zealand is on the opposite side of the earth toEngland. Castlegar is W117 37.95, i.e. 117 degrees and 37.95 minutes west of the Prime Meridian. Meridians of longitude DO NOT run parallel to each other. Every one passes through the North and SouthPoles, so the distance between them is zero at the poles. What is the distance between them at theequator? Based on the model of the earth that says it is a perfect sphere the distance between lines of longitude atthe equator is 60NM. What is the distance between lines of longitude in Castlegar? Page 141Navigation for Professional Pilots Castlegar is at N49 latitude and so is Gander Newfoundland. The picture above shows a view of the globefrom above the North Pole, the outer ring represents the equator, so both Castlegar and Gander are on the th49 parallel of latitude. The diagram is drawn to scale, so it might seem odd to you that N49 is closer tothe equator than the North Pole, but a sphere’s circumference does not vary linearly, it varies with thecosine of the latitude. Castlegar is at W117, which means it is 117° west of the prime meridian in Greenwich England (Greenwichis about N52 latitude, but that doesn’t matter.) Gander is only 54° west of Greenwich, so it is a lot closer to England than Castlegar. Between Castlegarand Gander the difference is 63° degrees of longitude. How many nautical miles is that? If Castlegar and Gander were on the equator each degree would be 60NM so it would be easy to figurehow far apart they are. But clearly each degree of longitude is less than 60NM in Castlegar. The distancebetween degrees of longitude is given by: 60cosine(latitude). The cosine of 49° is about .66 so each degreeof longitude equals ~39 NM at that latitude. The distance from Castlegar to Gander is 2598 NM. Page 142Navigation for Professional Pilots Given the latitude and longitude of any two places on earth the distance between them can be estimatedusing Pythagoras theorem. The diagram below shows two points marked by Xs and the east-west distance 10(EWD) and north-south distance (NSD) between them. NSD is very easy to figure out as we have seen.EWD is almost as easy to figure – you should use the mid-latitude between the two points when taking the 2 2 0.5cosine of the latitude. Distance is simply (EWD + NSD ) . The ENL has a latitude-longitude calculator that uses the above formula. It also determines true trackbetween the points, but we will defer discussion of that until we examine some map theory. Great-circlesA Great-circle is a circle on the surface of the earth whose center passes through the center of the earth. 10 The technical term for EWD is “departure.” Page 143Navigation for Professional Pilots The equator is a Great-circle but the other lines of latitude are NOT. An important fact about Great-circles is that, except for the meridians and equator, they change direction(angle) relative to true north as you fly along them. To visualize look at the diagram below and rememberthat true track is the angle between meridians and the desired track (DTK.) Any eastbound flight mustchange heading to the right continuously to stay on the Great-circle. A westbound flight must continuouslyturn left. Small CirclesAny circle on the surface of the earth whose center does not pass through the center of the earth is a smallcircle. An important point to note here is that no circle can be drawn on the surface of the earth that islarger than a Great-circle, so all other circles are smaller than Great-circles, hence the name. Page 144Navigation for Professional Pilots All the parallels of latitude except the equator are small circles. Is a segment of a small circle the shortest thdistance between two points? For example the 49 parallel runs from Trail to Vancouver, and can bevisually seen in flight because the trees have been cut down along it. If you fly this line, on a true headingof 270°, is that the shortest distance between Trail and Vancouver? thThe answer is no. Imagine that the 49 parallel as a ring resting on the globe (see photo above); it is asmall circle. Imagine what you must do to change this small circle into a Great-circle. You must enlarge thecircle and rotate it so its center passes through the center of the earth (and keep Trail and Vancouver as thpoints on the circle.) In the process the Great-circle line would arc north of the 49 parallel. Following thisGreat-circle track would be the shortest route to Vancouver, but you would no longer be able to fly aconstant heading. We turn to that matter next. Page 145Navigation for Professional Pilots ConvergenceConvergence is the angle that a Great-circle track changes over its length. In the above diagram DTK 1 is030° and DTK4 is 100° so convergence is 70°. The pilot must change heading by 70° from the start of theflight to the end in order to follow the Great-circle route. A flight along the equator (latitude 0; sine (0) is 0) has no convergence, but a flight near the poles has agreat deal (sine (90) is 1, so convergence equals change in longitude at the poles.) A flight from Castlegarto Gander has a convergence of _______. Try to figure it out yourself before turning the page. The lat andlong of each airport is given above. What is the convergence between Castlegar and Vancouver? Longitude in Castlegar is W117 andVancouver is W123 (difference of 6°.) To fly a Great-circle from Castlegar to Vancouver the true track start as 272.25°, half-way the track is 270°and as the airplane flies into Vancouver the track is 267.75°. The total change in heading is 4.5°, and aspreviously noted a westbound flight must change heading to the left. Try to figure out for yourself the initial, mid, and final heading to fly the Great-circle from Castlegar toGander. Most pilots would say that it is much more convenient to fly on constant heading for the entire flighthowever. We turn to that point next. Rhumb-LineA Rhumb-line is a constant-track line between two points. In other words it is a line that crosses all themeridians along the route at the same angle. The advantage of a Rhumb-line is that you can fly one true-heading (TH) to get from departure to 11 thdestination . In the Castlegar to Vancouver example above, following the 49 parallel, and maintaining a 11 Note that the magnetic heading will still change if variation differs along the route (as it usually does.) Page 146Navigation for Professional Pilots true heading of 270°, constituted flying a Rhumb-line. Pilots generally find this much more satisfactorythan constantly changing heading as they must to fly a Great-circle. The distance penalty for flying a Rhumb-line as opposed to a Great-circle is not significant for flights up to500 NM at moderate latitudes (i.e. flights not near or over the poles.) Therefore on short flights pilotsroutinely fly Rhumb-lines. On longer flights, such as international airline flights, a Great-circle can beapproximated by plotting a series of checkpoints along the Great-circle 500NM or less apart and thenflying Rhumb-lines between them. In the above diagram a long-range airline flight approximates a Great-circle by flying over a series ofcheckpoints (Xs) along the Great-circle but a constant heading is flown between these checkpoints. I.E. aRhumb-line is flown between the checkpoints. The pilot has a nav-log showing checkpoints and oneheading between checkpoints (just what pilots like.) In the days before flight management systems (FMS)this was the normal navigation method. Modern FMS makes accurate navigation along Great-circlesfeasible, and that is now the norm. Notice that the Great-circle track is ALWAYS closer to the pole than the Rhumb-line, or if you prefer, theRhumb-line is always closer to the equator. Remembering this will help you figure out which way headingmust be adjusted to fly a Great-circle. Map TheoryNow that we know all about Great-circles and Rhumb-lines it is time to talk about maps. It is not practicalto flight plan using a globe, and we certainly can’t take one in the airplane, so we need a map, which is aflat piece of paper representing the surface of the earth. Obviously there is a problem because the surfaceof the earth is curved, NOT FLAT. Imagine cutting open a tennis ball and trying to spread it out flat. You Page 147Navigation for Professional Pilots could not do it. Therefore ALL MAPS ARE DISTORTED. The method of creating the map determines whattype of distortion, but all maps are distorted. All maps are created by “projection” which you can visualizeas meaning that a glass globe is created with all the surface features on it. A light is placed at the center ofthe globe and photographic paper is then held over or wrapped around the globe. The surface features ofthe earth are therefore projected onto the photograph and a map is created. The only difference betweenone map and another is the way the photographic paper is wrapped around the globe. The dominant projection used in Aviation is the Lambert Conformal, Conic projection. In Canada it is usedfor: The other projection that is widely used is the Transverse Mercator. In Canada it is used for: Polar charts Page 148Navigation for Professional Pilots The photo above is from a Vancouver VNC chart, commonly used for VFR navigation. Circled is the notethat it is a Lambert Conformal Conic Projection. Lambert is the name of the person who invented it. Wewill examine what conformal and conic mean. The word “conform,” according to the dictionary means: “to be similar or identical.” A conformal map is one that shows the earth in the same shape that it has in the real world. We alreadysaid that this is impossible however, so a more technical definition is needed. A map is conformal if atevery location on the map the scale distortion north and south equals the scale distortion east and west.Lambert’s conic projection comes very close to meeting this standard. It is not perfect, but good enough tobe designated conformal. On a perfectly conformal map a straight-line is a Great-circle. On a LambertConformal Conic projection a straight-line can be accepted as “close enough” to a Great-circle fornavigation purposes. The error is less than 0.5%. To be useful a map must have a scale. You obviously don’t want a map that is as large as the earth. Thephoto above shows the scale on a VNC is 1:500,000, which means that one inch on the map equals500,000 inches in the real world (1cm equals 500,000 cm etc.) 500,000 inches equals 6.9 NM so one inchon the map equals 6.9 nautical miles. On a perfectly conformal map the scale is constant throughout the map, but real maps are never perfectlyconformal. The scale of 1:500,000 is therefore the average scale of the map. In the middle of the map it isa bit more, but near the top and bottom it is a bit less. The difference is less than 0.5% and therefore youcan ignore it. Let’s see why there is an error at all. Page 149Navigation for Professional Pilots Imagine a sheet of photographic paper formed into a cone and set over the globe (like a hat) with its apexat above the North-pole. This would be a standard conic projection, and it would touch the earth alongonly one parallel of latitude. Lambert’s innovation was to sink the cone into the earth so that it touchesalong two parallels of latitude, as shown in the photo above. Between the standard parallels the surface ofthe real earth is above the cone, and north and south of the standard parallels the surface of the earth isbelow the cone. The consequence of this to map scale is shown below. Page 150Navigation for Professional Pilots The diagram above shows projection lines emanating from the center of the earth and passing through thesurface of the earth and the map. It is important to consider where a given point on the actual surface ofthe earth appears on the map. North and south of the standard parallels points on the map are furtherapart than on the earth’s surface (if you measure a distance of say 100 NM on the map the real distanceon the surface of the earth is less.) Between the parallels the opposite effect takes place. Along thestandard parallels the scale of the map is precise. The photograph at the beginning of this section showed that the standard parallels for the Vancouver VNCare N49 20 and N54 40. Along these lines map scale is accurate. As stated previously the scale error overthe entire map is about 0.5% so you can feel free to measure distance anywhere on the VNC for navigationplanning purposes. Different standard parallels are used on VNCs to suit the latitude of the area depicted. Because Rhumb-lines are not straight, if you want to fly a Rhumb line you must measure the true track atmid-leg. At mid-leg a Rhumb-line track and a Great-circle track are equal. Page 151Navigation for Professional Pilots Originally Mercator projections were developed for use near the equator. The Lambert Conic projectiondoes not work for areas near the equator. In the original Mercator (not a transverse Mercator) the photographic paper is rolled into a cylinder ratherthan a cone. This cylinder is wrapped around the earth so that it touches along the equator. On the Mercator projection the lines of latitude and longitude come out perpendicular to each other. Thishas the advantage that a straight-line drawn on the map is a Rhumb-line, but the map is NOTCONFORMAL. In other words it distorts shapes, and a straight-line is NOT a Great-circle. At the equator the lines of longitude and latitude really lie perpendicular to each other so the Mercatormap is relatively conformal near the equator; but is not useable in Canada. The Transverse Mercator also wraps the globe in a cylinder but it is rotated 90 degrees so that it touchesthe earth along a meridian of longitude rather than the equator. The cylinder can be rotated so that ittouches on any of the 360 meridians. The map scale is accurate only along the reference meridian. Page 152Navigation for Professional Pilots A transverse Mercator map is NOT conformal, but as long at only a small section, close the referencemeridian, is used the distortion is minor. It has the advantage of creating a grid in which lines of latitudeand longitude cross perpendicular to each other. Consequently a straight-line drawn on the map is aRhumb-line. The Transverse Mercator projection is only suitable for small scale maps such as terminal charts. It is usedfor VTA and IFR terminal charts. stIn the 21 century as GPS navigation becomes dominant it is probable (or at least possible) that true tracksand true north will become the only references used for navigation. But, not all airplanes have suchequipment today, so a magnetic compass must be used. Unfortunately the Magnetic North Pole is notcollocated with the real North Pole. The photo below shows the location of the Magnetic North Pole. Page 153Navigation for Professional Pilots A compass points at the Magnetic North Pole. A compass on the white line in the photograph also pointsat the true North Pole. But a compass in British Columbia, as shown in the photograph, points too far east.The error is called variation, and it is the angle between true north and magnetic north. The variationshown in the photograph is easterly; in Montreal variation is westerly. On a line running through Manitobathere are locations where variation is zero (as shown in the photograph.) An isogonic line joins locations with equal variation. All aeronautical maps have isogonic lines printed onthem. These lines are labeled as shown in the photo below. Page 154Navigation for Professional Pilots In flight the heading indicator is normally set to magnetic north and all heading are referred to asmagnetic headings. Flight planning is normally done in true however, so true heading must be convertedto magnetic before the flight. The following rhyme may help you remember whether to add of subtractvariation. This means that when variation is easterly the magnetic heading is always less than true heading. Whenvariation is westerly magnetic heading is always more than true. Even though the above rhyme is fairly simple it is best to use your CR to convert between magnetic andtrue so that no mistake is made. This procedure was demonstrated previously. Compass DeviationThe topic of deviation is out of place here since it is not related to map theory, but it does fit logically herebecause of its relationship to variation. Deviation is an error in the compass of the airplane. As suchdeviation is specific to an individual airplane. It is caused by the magnetic fields of the metal parts of theairplane and is significantly affected by electrical equipment such as the alternator. These things cause anerror in the compass known as deviation. Deviation changes from time to time. That is to say that the magnetic field of the airplane changes overtime. Consequently it must be measured and recorded on a regular basis. The process of measuring Page 155Navigation for Professional Pilots deviation is called a compass swing. A compass swing is required every year and also any time electricalequipment is removed or replaced in the airplane. An AME performs the compass swing and provides a compass card in the cockpit which the pilot uses tocorrectly set the heading indicator. The pilot should read the compass then the deviation card and set theheading indicator to the corrected magnetic heading. Deviation is seldom more than 2 or 3 degrees so ignoring it, as most pilots do, results in only minor error. Contour lines are lines that join points of equal elevation above sea level. The above photo shows contour lines on a VNC. On VNC charts there is a 500’ contour but from 1000’ andabove contours are every 1000’. The contour interval is described at the bottom of the Hypsometric scale,explained next. To make terrain easier to visualize Hypsometric tinting is used, according to scale below: Page 156Navigation for Professional Pilots The above scale is found on the white edge of every VNC. At the top of the scale you find the maximumelevation for the map. The example above is 19,524’ asl, the highest point in Canada; located at N60 34W140 24, also shown just above the hypsometric tint scale. A 500’ intermediate contour line appears within the lowest hypsometric tint, and intermediate contours at4000’, 6000’, 8000’, 10,000 and 11,000 are also plotted. Use these to refine the information provided bythe tinting. Map LegendEvery map has a legend printed along the edge that shows all the symbols used on the map. All thesymbols are important but will not be covered here as you can read the legend for yourself. Page 157Navigation for Professional Pilots Airport data is provided on VNC charts but this should only be used for preliminary planning. Always lookin a current CFS for up-to-date airport data. Map ScaleThe scale of the map is always printed on the map. The picture below shows the scale on the VancouverVNC chart is 1:500,000. The same scale is used on all VNC charts in Canada. WAC charts use a scale of 1:1,000,000. VTA charts have a scale of 1: 250,000. An appropriate Navigation ruler must be used to measure distances on these maps. Make sure you use thecorrect scale. Always measure distance in Nautical Miles, not statute miles. The inner scale is used on VNCand the outer scale on WAC charts. For a VTA chart use the VNC ruler scale then double the distance. Grid NavigationThe picture below is of a globe from above the North Pole. Imagine you wish to fly from the checkpointmarked as departure to the one marked as destination. What is the true track? Page 158Navigation for Professional Pilots If you are willing to fly a Rhumb line, then heading of 090 true would take you to the destination along theline shown below: But this is clearly not the shortest route. The desired route is “over the pole.” Page 159Navigation for Professional Pilots In the diagram below the desired Great-circle route is drawn in as well as some lines of longitude forreference. We already know that in order to fly a Great-circle we must change heading as we fly, make atable of required true headings for the locations marked with the Xs. Remember that each line of longituderepresents a true track of north (0°.) I.E. you must orient your Douglas protractor to north on each line oflongitude. X1 019 X2 045 Page 160Navigation for Professional Pilots X3 082 X4 137 X5 160 Imagine what would be happening on the flight deck as you make this flight. The airplane departs on aheading of 019° (essentially northbound) and flies a straight-line. But, the heading indicator must beadjusted so that as the airplane passes X2 it reads 045°. At X3 the HI is rotated to 082°; at X4 to 137°.When the airplane arrives at destination it has made no turns, but the heading must be 160° true(essentially southbound.) For ideal effectiveness HI would be continuously updated for convergence, inpractice it is usually updated every 6° change in longitude. Every flight over the poles starts off “northbound” and finishes “southbound.” Pilots must accept thatbrain teaser, but grid navigation eliminates the need to continuously update the HI enroute. Examine thediagram below. Page 161Navigation for Professional Pilots A rectangular grid is laid over the pole as shown in the diagram above. This grid can be oriented to byreference to any meridian, but the standard procedure is to use the Prime meridian as the reference. To use the grid simply put your Douglas protractor on the grid with north aligned with the Prime meridian.For the track in the example the track is 219G (read “219 Grid.”) Examine the diagram to convince yourself that the Grid heading is simply the true heading plus westlongitude, or minus east longitude. The 160E median has been labeled in the diagram. You should label the other meridians corresponding toX2, X3, X4, and X5. Page 162Navigation for Professional Pilots To use Grid navigation, as the airplane approaches the departure point (it probably took off somewheremuch further south) the pilot switches the HI to grid. This amounts to rotating the HI an amount equal tothe longitude of the airplane. In practice grivation is applied to the magnetic compass. Once the HI is adjusted to Grid the pilot can maintain a constant heading for several hours (in the examples/he maintains 219°.) Even though this is usually considered a southbound heading the airplane isobviously still heading north. But things will work out in the end. The pilot holds this grid heading for a fewhours until arriving at the destination (point where the transition back to magnetic headings will be made)at which point the heading is reset to magnetic by changing it from 219 to about 160° plus variation. Notethat despite all these adjustments the airplane actually flies a straight line the whole time. GrivationGrivation is by definition the difference between magnetic track and grid track. As previously noted thedifference between true and grid tracks equals the longitude (from the reference meridian.) Thereforemathematically grivation equals longitude plus variation. Lines on a map joining points of equal grivationare called isogrivs. Pilots can use these to set the HI to Grid the same way they use variation to set thecompass to true. However, the magnetic compass is quite unreliable in the extreme Polar Regions so it ismuch more common to use INS as the reference (the INS “knows” the airplanes true track) eliminating theneed to use grivation. The two relevant equations are: You will examine grid navigation a bit more in Avia 240. For now this simple introduction to the concept isall that you need. You should see that grid navigation is necessary because of the extreme amount ofconvergence in polar crossings. Keep in mind that basing the grid to the Prime meridian is arbitrary. For some purposes it could bepreferable to establish a grid based on a different meridian. For a Canadian arctic survey expedition mightfind it desirable to have a grid oriented to a meridian within Canada. Can you see the benefit of this? Ifthey used the Prime meridian instead what direction would it be to fly from the Yukon to Greenland (eastor west)? When they are done exploring the polar region do they fly north or south to return toVancouver? Page 163Navigation for Professional Pilots In the above diagram radial 1 represents one LOP and radial 2 is the second. Where they cross is the“fixed” position, or fix for short. Pilots frequently refer to the procedure as taking a fix. The process is quite straight forward, but there are a few important details. Most importantly fixes shouldbe plotted using true bearings, not magnetic. But, most VORs are oriented to magnetic north, whichmeans the nav radio tells you the magnetic radial you are on. Let’s say in the above example that radial 1is 010R and radial 2 is 290R. You CANNOT put a protractor on each VOR and draw two lines based directlyon these bearings. Each radial must be converted to a true bearing by applying variation. What variationshould be applied to radial 1; which to radial 2? Choose your answer before reading the next paragraph. The important thing to realize is that you must apply the variation at the VOR, NOT at the airplane.Therefore radial 1 must be adjusted by 12° and radial 2 by 10°. Use the wind side of your CR to make sureyou don’t make any mistakes. Page 164Navigation for Professional Pilots In the above photograph the 010R is set across from 12E variation. The true course is clearly 022°. Repeatthe same process for 290R with variation 10E to confirm the true course is 300°. Plot the two tracks 022 and 300 by putting a Douglas protractor over each VOR in turn and aligning it withmeridian 1 and 3 respectively. Draw the lines carefully to find the fix. To obtain an LOP from a VOR it is essential to center the CDI needle with a FROM indication. This gives adirect reading of the radial. If you center the needle with a TO indication you need to take the reciprocal(but it is safer to simply rotate the OBS knob until a FROM flag shows.) In the arctic VORs are oriented totrue north, which eliminates the need to make the conversion demonstrated above. It is could be the casethat you must plot a fix based on one VOR in magnetic and another in true. This is not difficult, just becareful to convert the magnetic radial to true while making no adjustment to the true radial. Do not attempt to plot a fix by extending the markings on the compass roses on the VNC. These are notaccurate enough. IMIPORTANT. The legend of your VNC and LO chart warns you that in some cases VOR symbols are offsetfrom their actual position, but the compass rose is centered on the actual location of the station. Checkthis carefully to ensure you are plotting the fix from the actual location of the VOR. Expect to see questions of the above type on Transport Canada’s Commercial Pilot Written exam. Watchfor tricks such as offset VOR locations (previous paragraph) and mixed magnetic and true VORs (alsomentioned above.) Now we will consider the process of establishing a fix based on bearings from two NDBs. There are two orthree differences to note, but the overall process is the same. Page 165Navigation for Professional Pilots The diagram below is deliberately identical to the one above expect that the VORs have been replacedwith NDBs. The first difference to think about is the process by which the pilot determines what bearing 1and 2 are. How is this done? Formulate your answer before reading the next paragraph. The basic process of obtaining a bearing from an NDB is the same regardless of the equipment theairplane has, but it is much easier with an RMI than with a fixed card ADF (Note that if you have a GPS thiswhole process is redundant since it will provide your current latitude and longitude, which you can plot tofix your position without the need to do any of this process. We therefore assume you have no suchequipment available.) With an RMI read the bearing from the tail of the RMI needle. Good airmanship demands that you confirmthe HI is set accurately before accepting this bearing. Usually the HI is set to magnetic so the bearing is amagnetic bearing. If you happen to be flying in the arctic with your heading indicator set to true then thebearing is true. And if your HI is set to grid you have a grid bearing. If you have a fixed card ADF you must follow the usual procedure to convert relative bearing to magneticbearing. MB = RB + Heading. Since the diagram above is identical to the previous VOR based one, and the airplane is in the samelocation, you may expect that the magnetic bearings will be 010 and 290. They will NOT be. Think whybefore reading the next paragraph. Page 166Navigation for Professional Pilots In reality an ADF may not be accurate enough to detect the theoretical difference here, but the radio wavefrom the ground stations come to the airplane along straight-lines corresponding to Great-circles (bothVOR and NDB.) This amounts to saying that the true bearings will be the same, but not the magneticbearings. The variation correction for the VOR is applied at the station, while that for the NDB is applied inthe airplane. Therefore both NDB bearings must be corrected by 11E. Go back and examine the VORexample above if you have forgotten which variation was applied in that case. Therefore magnetic bearing1 is 013 and bearing 2 is 289 magnetic. Correct each of these magnetic bearings by variation of 11E exactlyas described above for the VOR case. What values to you get? Once again the true bearings are 022° and 300°. Plot these exactly as before to get the fix. Summary: When plotting a fix convert all bearings to true. Apply variation at the station for VOR and atthe airplane for ADF. Use the CR for converting between true and magnetic to avoid mistakes. Use aDouglas protractor centered on the station to plot the true bearing. Make sure the protractor really iscentered on the station by checking the compass rose. Extend the lines until they cross, giving you a fix. Ona Lambert Conic chart the straight-lines are Great-circles, which correspond to radio waves so thisprocedure works. On a Mercator chart straight-lines are Rhumb lines so an error equal to convergence isintroduced, which you must correct for. Fortunately Mercator charts are only used for VTA and T charts inCanada, where position fixing is an unlikely procedure. It is quite possible to obtain a fix from one VOR and one ADF bearing. The process is identical to thatdescribed above. Just remember where to apply the variation. Watch out for combinations of true,magnetic, and grid navaids, especially on exams. Page 167Navigation for Professional Pilots Page 168Chapter 8Flight PlanningIn this section we will take all the knowledge we have developed and use it to plan flights. It must bestated that we presume that dead reckoning (DR) will be the dominant form of navigation, with pilotageused only for brief periods usually on departure and arrival. In the section on mountain flying toward theend of the text some comments about planning for a flight when pilotage is dominant are included. Definition of a LegAll flights are broken into legs. A leg is a defined path the airplane follows. Most legs are either straight-lines or arcs. Future navigation systems may define paths that have more complex shapes, but that isbeyond the scope of this text. Modern flight management systems (FMS) are programmed by entering a series of legs beginning at theairport of departure and ending at the destination. The entire route must be input as a series ofcontinuous legs with no breaks at any point. The FMS computer recognizes a variety of leg types, whichthe pilot selects from a menu. When a flight is fully defined by a series of legs with no breaks we say theflight plan is closed. If a waypoint is designated Fly-over, you must fly directly over it before turning to the next leg. At a Fly-bywaypoint you start to turn prior to the waypoint so that you intercept the next leg without overshooting it. You should normally treat waypoints as Fly-by unless they are specified as Fly-over. An exception is whenusing NDBs as waypoints, without GPS for assistance. It is far too easy to be misled about station passagewith an NDB so it is preferable to treat all NDBs as Fly-over waypoints. In recent years it has become very common for aircraft to be equipped with GPS and or other types ofprecision navigation equipment that provide extremely accurate range information. These systems providehorizontal distance rather than the slant range the older DME systems provide. When the pilot has thistype of instrumentation available it is possible to precisely determine when to turn for a Fly-by waypoint.The diagram below shows the required formula. The equation r=.0053 is fully explained in theaerodynamics text Aerodynamics for Professional Pilots. Page 170Navigation for Professional Pilots The formula might not seem user friendly but all you have to do is calculate .0053TAS once and memorizeit. You already have memorized values for the sine of several angles for the purpose of estimating drift (seepage 50.) To calculate .0053 TAS take TAS and divide by 100 then divide by two. For example if your airplane cruisesat 120 knots divide by 100 to get 1.2 then divide by 2 to get 0.6. Remember this number. Whenapproaching a 90° turn lead by 0.6NM. For a 45° turn lead by 70% of 0.6, i.e. about 0.4NM, etc. Introduction to Nav-logsA nav-log is a document that helps you organize your flight planning so that you don’t forget anyimportant details. It should chronicle your entire flight from takeoff to destination and then to thealternate airport if IFR. A nav-log should also include time and fuel allocations for contingencies(unavoidable delays due to weather, traffic, etc.), approaches, and reserve (reserve is a legal as well aspractical requirement.) In this course you will prepare nav-logs both electronically and manually. On your commercial pilot flighttest you are required to prepare the nav-log manually, and of course exams, most assignments, and ALLquizzes and tests in this course require manually generated nav-logs. On your actual cross-country flightsand simulator exercises you are encouraged to use the ENL because it is quicker, easier, neater, and less Page 171Navigation for Professional Pilots likely to contain math errors. You were introduced to the ENL when we examined cruising altitudes,although we only scratched the surface on using it. Further details are provided later. Nav-logs are usually laid out in a grid with columns representing the parameters to be evaluated (planned)and with rows representing “legs.” . 1. Departure legs 2. Enroute legs 3. Arrival legs 4. Approach 6. Enroute to alternate 7. Arrival at alternate 8. Approach at alternate All these groups are needed for every IFR navlog. Groups 5 to 8 are not needed for VFR navlogs. On Selkirk College navlogs the departure, arrival, and approach leg groups are usually simplified so thatone line on the navlog represents the entire group. We normally group the arrival legs with either theenroute or approach. The approach group is normally reduced to a single leg (for both IFR and VFRnavlogs.) Departure legs can also be called “climb legs.” The departure legs end at the Set Heading Point (SHP.) TheSHP is usually specified in an IFR departure procedure, but must be chosen by the flight planner for VFRflight. Advice on choosing a SHP is given below. There is a variable point at which the airplane reaches topof climb which is conveniently labeled as top of climb (TOC.) TOC may come before or after SHP. If afterthen it is technically part of the enroute group. On occasion TOC and SHP are the same point. Some VFRpilots find it convenient to “rig” the situation so that this happens. In this case label the point as SHP orSHP/TOC (preferred.) The largest part of most navlogs consists of several enroute-legs (also called cruise-legs.) These legs runfrom turning point to turning point. i.e. a new leg should start at every point where the track changes. The arrival legs end at an initial approach fix (IAF) for IFR flight plans. For VFR flight plans arrival legs endwhen the aircraft joins the circuit at the destination airport. Sometimes it is expedient to just treat theselegs as cruise legs rather going to the trouble of estimating the reduced fuel flow used during the descent. Page 172Navigation for Professional Pilots Selkirk College nav-logs also contain rows allocating time for contingencies, and reserve (both explainedbelow.) There is logic to the order that navlog rows are laid out that results in the pilot having the requiredinformation at hand in flight to make decisions about fuel status. Consider the nav-log below, which is fora flight in a Beech 95. Even though you have never flown one before answer the following questions byreferring to the nav-log. 1. As you taxi out in Calgary your fuel quantity should read _________ gal. 2. As you pass YNY your fuel quantity should read ________ gal. 12 3. As you reach BOOTH your fuel reads 35 gallons – is fuel remaining as expected? 4. Upon arrival at BASRA, if ATC requires you to hold (perhaps because a runway is closed) your contingency fuel is used up when your fuel gauges read _______ gal (assume you wish to retain 13 50 minutes reserve.) Notice that you can answer these questions quite easily because of the logic by which the nav-log is laidout. 12 No. You are supposed to have 37.8, so either the gauges are not accurate, or you have used a couple ofgallons more than expected. You should assume the later.13 27.2 Page 173Navigation for Professional Pilots Page 174Navigation for Professional Pilots 1. The fuel for the trip is specified in advance and you determine consequent reserve 2. You plan for a desired amount of contingency and reserve fuel and determine how much ramp fuel you need for the flight If situation 1 applies, begin by filling out the ramp fuel in the upper right corner of your nav-log. As youcomplete each leg subtract the fuel used to get fuel remaining; whatever you have when you get toreserve, which is always the last row, is your reserve. Assess reserve fuel value to confirm that it isadequate before committing to the flight. If situation 2 applies, leave ramp-fuel and fuel-remaining blank until all legs have been planned. Fill out thereserve fuel and work backwards until you determine the required ramp fuel. The first fixed checkpoint is called the set heading point (SHP) on a DR cross-country and choosing itrequires considerable thought. For VFR flight you should select a SHP that is easy to locate and relatively close to the departure airport.Exactly how close depends on several factors: 3. How well you know the area and the SHP checkpoint On a VFR flight you normally use pilotage to find your way to the SHP. On IFR flights the SHP is usually anavaid such as a VOR or NDB so finding your way there is straight forward. VFR pilots can also use beaconsand VORs for navigation but before doing so consider whether you will conflict with IFR traffic. It isfrequently safer to choose a visual point rather than a radio navigation point when VFR. Because pilotage is used to locate the SHP be sure to pick one that has distinctive ground features leadingto it. An ideal SHP is on a road, railway, river, or other similar feature that you can follow to locate it. A Page 175Navigation for Professional Pilots SHP must also be distinct so that you can visually identify it. It must also be small enough to constitute apoint – for example using “the city of Vancouver” as a SHP is not acceptable. Instead pick a particular pointsuch as the intersection of two major roads, a park on a particular road, etc. If the ground around the departure airport lacks distinctive navigation features, as is often the case withsmall airports in northern Canada, use the airport as the SHP. This is called an “overhead departure.” Yousimply takeoff and climb over the airport to set course. Weather permitting you should be 2000agl orhigher when you reach the center of the airport in order to avoid conflict with any circuit traffic. If youwere making a closed navlog the first and third checkpoints would both be the airport and the secondcheckpoint would be 1000 feet. In reality you will probably open the navlog and only have one leg, i.e. thefirst and second checkpoints will be the airport of departure but the distance flown must represent that tofly out to 1000 and then return while climbing to 2000. Traffic congestion is a factor in choosing a SHP for two reasons. In the case of an airport with very littletraffic it is quite feasible to make an overhead departure or use a SHP very close by. The lack of trafficmeans that no conflict will result. But, at a busy airport it may not be possible to do an overhead departureor use a nearby point as SHP; traffic congestion could force you to choose a SHP clear of the airport zone,i.e. more than 5 miles from the airport. In this case make sure to choose a SHP on a very prominentpilotage feature that you will have no trouble seeing and flying to. A point on a major road, river, orshoreline would be a good choice. Of course a radio navigation beacon could also be a practical choice ifthe airplane is suitably equipped. How well you know the area is a factor in choosing a SHP. At an airport you know well you can locate SHPsthat would be too obscure if you didn’t know the area well; for example the intersection of two minorroads. Keep in mind that some objects that look prominent on a map are in fact quite difficult to see on theground. For example locating a radio transmission tower, in daylight, is quite difficult and thus does notmake a good SHP. But, if you know the tower well and can identify it relative to other local landmarks itmay be an acceptable SHP. Page 176Navigation for Professional Pilots Normally the above closed departure would be opened up by collapsing it into two legs, as shown below. An interesting special case involves setting up the navlog for an overhead departure (remember this meansusing the departure airport as SHP) If you are doing an overhead departure the distance flown is certainlynot zero (the straight-line distance) it is likely 5NM or more. An ENL navlog showing an overheaddeparture is shown below to demonstrate this. Page 177Navigation for Professional Pilots 3. Collapse the departure into one or two legs (more if needed for clarity.) Once you have the distance use the time fuel and distance to climb chart to figure out what your altitudewill be at the end of leg 1. Estimate the average wind in this calculation. Enter the fuel used and the timein the appropriate columns of. In 99% of cases, especially in the mountains, the distance required to climb to altitude will exceed thedistance to the SHP. Therefore the first enroute leg will also be a climb leg (leading to TOC) as describedbelow. When using the ENL, for departure legs, estimate how high you will be when you reach the SHP. The ENLdetermines distance, time, and fuel. If the resulting distance does not match your estimated distance tothe SHP revise the altitude estimate. In most cases you do not reach your final cruise altitude before SHP and therefore will be climbing enroute.The trick is figuring out how far after. If you did a reasonable job of estimating your distance and altitude to the SHP then the remainder of theclimb must be allocated to this leg. For example if you estimated you would be at 5000 over Robson andyou are climbing to 8500 then this leg is for a climb from 5000 to 8500. Use the charts in your POH todetermine: 1. Time to climb 2. Fuel to climb 3. Distance to climb Page 178Navigation for Professional Pilots The only complication is allowing for wind. It is critical for you to realize that wind will NOT AFFECT timeor fuel to climb, it only affects distance. Don’t move on until you have reasoned that claim out and areconvinced that it is true. It is necessary to allow for wind in the climb or your flight planning will not be accurate. Wind changes asyou climb so it can be quite different at 5000 than at 8500. In addition true and indicated airspeeds changeas you climb in accordance with the climb charts (previously covered.) We need a rule of thumb todetermine distance covered in a climb. For normally aspirated piston airplanes such as the C-172P and Travelair rate of climb drops off quicklywith altitude so that mid-time in a climb happens at higher than mid-altitude. You should thereforedetermine your groundspeed at 2/3 of the way up to your cruise altitude and calculate distance coveredusing that value (remember you know the climb time.) Using the example of climbing from 4500 to 8500the difference is 4000 feet and 2/3 of that is 2700, so determine GS at 7200 (4500 + 2700.) Once you knowthis GS, and given the time to climb, use your CR to calculate distance. In turbo-charged and turbo-prop airplanes climb rate does not drop off as quickly so determine GS halfwayup to cruise altitude and calculate distance covered based on that (in the example, calculate GS at 6500.) Once you know how many miles past SHP it is to TOC use your ruler and mark TOC on the map and thenmeasure the distance from TOC to the next waypoint (mystery lake in the navlog shown above.) Thisdistance is used on the next leg. In the example navlog the total distance from Robson to mystery lake is50NM, so the distance from TOC to mystery lake is 37NM. When using the ENL enter the altitude that is 2/3 or ½ your cruise altitude with wind and temperature forthat altitude. Initially enter the distance from your time to climb chart, but once the ENL calculatesgroundspeed and time you will have to increase or decrease the distance until the time and fuel matchwhat you determined from the climb chart. Page 179Navigation for Professional Pilots (circuit joining point) or in the case of an IFR navlog it is usually the location where the IFR approach willbegin. Flights should be broken into manageable legs. A 1000 mile VFR leg is hard to fly and is subject toproblems covered previously in map theory. Even transoceanic airliners fly from checkpoint to checkpointover the ocean so don’t be afraid to break your trip into manageable legs. On the other hand don’t makethe legs too short or your nav-log will be so extensive it will over-load the airplane. Use your ruler tomeasure the length of each leg in nautical miles. Use a protractor to measure the true track (coveredbelow.) When planning with an LO or HI chart read the distance and magnetic track directly from the chartand use the CR to determine the true track. For example the LO1 chart below shows the track from CG toWHATS on R119 is 301°M and the distance is 41 NM. Variation is 18°E (the dashed line just south ofWHATS.) To get the true track use the back-side of your CR. Set the magnetic track (301M) opposite variation (18E)as shown below. The true track (TC) is 319. Page 180Navigation for Professional Pilots IFR checkpoints are VORs, NDBs, or intersections; every location where your track changes is a checkpoint(WHATS is an intersection.) VFR checkpoints should be distinct geographical features you can positively identify yourself over andthereby confirm you are on course (and start the next leg accurately.) Towns, airport, small lakes, etc makegood checkpoints. Normally true-track changes (at least slightly) over a checkpoint. Draw a straight linewith a pencil between each checkpoint. Measure the length of the line with a ruler of the appropriatescale. Measure the true track by aligning your protractor to north with a line of longitude near the mid-point of the leg. In cruise TAS speed and fuel flow are in accordance with the cruise performance charts. Be sure to writethe power setting and fuel-flow in the proper column for reference. Fill in the actual wind and temperature at your cruising altitude and use your CR to determine GS and trueheading based on the TAS. Remember that you will need to determine pressure altitude and or densityaltitude to determine TAS. Fill in the variation and then calculate the magnetic heading. Remember the old saying: This means that with easterly variation (such as in British Columbia) magnetic heading is always less thantrue heading. In eastern Canada, where variation is west, magnetic heading is always more than trueheading. To avoid any chance of a mistake it is safer to use the back-side of your CR when convertingbetween true and magnetic, as shown in the photo above. Page 181Navigation for Professional Pilots Use your CR to determine CAS, and then use the calibration chart in the POH to determine IAS. You needthis so that you can check in flight that the airplane is performing as planned. Of course you also use theCR to determine time and fuel for the leg. All airplanes fly faster, for a given amount of fuel flow, at a higher altitude. However, fuel is used climbingto altitude, so there is an altitude above which further climb increases the total time for the flight. The criteria for saying on altitude is “optimum” could be saving time or fuel. Most commercial airoperations place a premium on time rather than fuel. The optimum altitude is therefore either: 1. The altitude that results in the least time for the flight 2. The altitude that results in the least fuel used for the flight 1. Aircraft type 2. Power setting 6. Wind For piston engine airplanes the benefits of flying at a higher altitude are very minimal in terms of savingfuel. Only on very long flights is any fuel saved at all – so in most cases you can fly at any altitude you wishas far as fuel consumption is concerned. Therefore it is best to decide your cruising altitude based on otherfactors such as the improved safety of flying higher in a single-engine airplane. Of course it is important toavoid headwinds, so try to avoid climbing into a strong headwind aloft unless safety demands you do so(as it often does in British Columbia.) Climbing to high altitude to pick up a strong tailwind is howeveralways a good idea. In a turbine engine airplane flying at a higher altitude is much more advantageous. The resons will becovered in your aerodynamics course. It is very worthwhile for you to examine the cruise performance Page 182Navigation for Professional Pilots charts for the King Air, which you have an FIM for, and calculate the specific range foe the airplane atvarious altitude. You will quickly see that it is much better at high altitude Top of DescentWhat goes up must come down, so the saying goes. But with an airplane the pilot has control of when tocome down and this is a matter that deserves more thought than it is sometimes given. If descent isstarted too late then the airplane arrives at the airport too high to land and must circle down, wastingtime, or requiring a high descent rate that is uncomfortable for passengers and may cause damage to theengine in some cases. The turbocharged engines typical of working airplanes are quite sensitive to large power reductions. Theshock-cooling will damage the engine. Thus professional pilots learn to start descent early enough that agentle descent with gradual reductions in power can be made. Conversely, pilots of turboprop and jetairplanes can close the throttle without fear of damage to the engine. For these airplanes descent isdelayed as long as reasonable in order to take advantage of the better fuel economy at altitude. In single-engine mountain-flying it is particularly unwise to descend early. The terrain is rugged, with fewplaces to land in the event of an engine failure. The ideal descent is usually one that reaches circuit altitudejust slightly before joining the circuit. At times it may even be necessary to plan to circle down over theairport, although this should be avoided if possible. The most commonly used descent gradient is 1000 feet every 3 nautical miles. This is used by most jet andturboprop pilots and also works reasonably well in the C-172 and B95. For high performance turbochargedairplanes a gentler gradient such as 1000 feet every 4 nautical miles may be more appropriate. It isimportant for you to get to know what is best for your airplane. Once you have established the idealdescent gradient designating a top of descent (TOD) is straight forward. To designate a TOD calculate the altitude to be lost in thousands of feet then multiply by 3 (or 4 as thecase may be.) Assuming you are planning to join the circuit the altitude to be lost is obtained bysubtracting circuit altitude from cruise altitude. If you are planning a straight-in landing then subtract fieldelevation from cruise altitude. The value should be rounded to the nearest thousand feet. For example ifdescending from 8500 to join the circuit in Castlegar at 2600 you get 6 thousand feet. Multiply 6 x 3 to get18 Nautical miles. Your TOD is 18 miles form where? The answer is; from the place you wish to reachcircuit altitude. This is likely 3 miles from the airport, so start descent 21 miles out. TOD should be calculated in flight, but need not appear on your navlog. ContingenciesRAC 3.13 requires pilots to allow for contingencies when flight planning. Even if no such regulation existedit would only be prudent to do so. We have already seen that flying at a different altitude than plannedaffects required fuel. Obviously the wind can be different than forecast. There are a great many factorsthat can affect your flight. The longer the flight the more likely it is that errors in planning will arise, yet itis the long flights that have the least margin for error. Page 183Navigation for Professional Pilots If you are headed for a small airport with only one runway is there any chance the runway could beunusable when you arrive there? Of course there is. An airplane could land gear-up while you are enroute,or any number of other things could happen. It is pretty much a guarantee that these things will happen toyou a few times in your life. If you don’t leave yourself with some options (exactly what contingenciesmeans) then you will be, as we say, SOL. Often our flights have lots of options built into them. A flight in a C-172 from Castlegar to Boundary Baycan equally well land in Langley, Abbotsford, Delta, etc. So a gear-up on a runway in Boundary Bay is not acircumstance that requires contingency planning. But, you may well have to divert due to weather enrouteand wind up flying farther than planned in the process. Contingency time should be allocated for thispurpose. The point being made is that allocating contingency time means allocating fuel. Simply ask yourself howmuch extra time you might need for contingencies, then calculate the fuel for that time based on cruisepower. It is important to realize that if you actually need to use your contingency fuel you DO NOT have to burn itat the “normal” cruise rate. For example if you are holding (VFR you might be circling while the runway isplowed) you should fly at less than 65% power and thus you would have more contingency time than youindicated on your nav-log. This is where it is nice to have accurate fuel gauges so you can tell when you arereaching the end of your contingency fuel. Most turbo-prop and jet airplanes have reliable fuel gauges, butmost small piston airplanes do not. Note that contingency time should not be included in time enroute you file on your flight plan. Filing flightplans is covered later. On the ENL set an amount of contingency time and the ENL allocates the required fuel at the normal cruisepower setting. Note that contingency time is NOT included in time enroute. Approach at DestinationFor VFR flights your last enroute checkpoint is normally the destination airport, i.e. the point where youjoin the circuit (if the airport has a published VFR arrival procedure it should be the point where thatprocedure begins, as for example in Kelowna or Victoria For IFR flights the last enroute checkpoint is usually the IAF (initial approach fix) which is where you startyour instrument approach (explained previously.) Therefore time and fuel must be allocated for the approach, and possible missed approach. If your lastcheckpoint is the beginning of the arrival procedure then you must also allocate time for the arrival as wellas the approach (circuit if VFR). You must learn to estimate this time reasonably accurately. A single VFR Page 184Navigation for Professional Pilots circuit takes about 6 minutes. If you require a low pass and a second circuit before landing the time willdouble, or more. So apply a suitable estimate for approach and landing time. On VFR flights approach and landing time should be included in the time you file on your flight plan. Wewill discuss this further later. On IFR flight plans you DO NOT include approach time in the filed time. The ENL does not include approach time in the IFR enroute time but it does in the VFR time enroute. VFR flights don’t legally require an alternate, and don’t generally need one. But, in some cases it might bewise. For example if you are going to a remote strip where you intend to make a precautionary approachand land (time for the precautionary would be in contingencies) then you will need an alternate in caseyou determine that you cannot land. ReserveThe last row of every nav-log is “Reserve.” There are legal requirements for reserve fuel. Normally this isthe value that should go on this line. Extra reserves that you wish to carry should be entered undercontingencies on the navlog. Reserve is the amount of fuel that you plan to have left in your tanks when you land. Its purpose is NOT forcontingencies – those must be planned and allowed for separately. Reserve is really just for calculation andoperational errors. It is almost impossible to set the power to exactly the planned value, and no one evergets the mixture set 100% perfect, etc. Reserve simply gives you a margin for error. The law requires 30minutes for day VFR and 45 minutes for night VFR and IFR flights. You are stuck with these values, butrealistically reserve should be more on a long flight, especially in a light airplane with inaccurate fuelgauges. An important point to think about for light aircraft operation is in initial loading of the airplane. You mightcalculate that you should depart with 23 gallons of fuel, but how do you get exactly that amount in thetanks. On a C-172P with standard tanks it would be just a bit more than ½ tanks, but just how much? Youcan’t really trust the fuel gauges, so you do your best to dip the tanks but there is bound to be some error.Most pilots try to fill the tanks to “at least” the intended amount, but it can be quite difficult. Consequentlythe reserve you enter on your navlog has considerable error in it. Take note on page 4-17 of the C-172P POH that you can get 4% greater range than the cruise performancecharts predict if you lean the mixture to peak EGT. At Selkirk College we don’t normally do that, but it isworth knowing in case an emergency should arise. Here is something to think about: if an adjustment of50°F in EGT makes a 4% difference in range and this corresponds to about 25rpm change how accuratelywould you say you normally lean the mixture and what is your percent error? Page 185Navigation for Professional Pilots Use the TAB-KEY to advance through the nav-log, that way you won’t miss anything. Read the “balloons” that pop-up as you tab through the nav-log, these tell you how to fill it in. Wind, temperature, and variation are automatically copied from one row to the next to save the timerequired for entering these values on each row. However, should a value change you can enter a new valueany time and it will propagate throughout the remainder of the navlog. After filling in reserve time the next TAB-STOP is for airport data at the lower left of the nav-log. Typing inthis data is much neater than filling it in by hand. When the ENL is completely filled out hide all unused rows in order to avoid clutter – but be sure theycontain no data before hiding them. Locate the departure and destination airports on your VNC. If you aren’t sure which VNC you need lookupthe airport in the CFS where the REF section tells you which VNC and WAC chart the airport is on, as well aswhich LO chart if you are IFR. Locate a suitable SHP, taking into account the factors discussed above. If the flight is in the mountains, or there is restricted airspace near the destination locate a descent point(DP.) Descent points are discussed in detail later under the topic of mountain cross countries. If the trip is more than 300 NM choose some intermediate checkpoints so that no leg is longer than300NM. This reduces convergence to an insignificant factor and allows us to plan each leg as a Rhumbline. You may also find it practical to choose intermediate checkpoints in order to avoid directly over flyingrestricted airspace, high terrain, etc. Note that if you are planning a very long flight, say 1000NM or more, you will need a large scale planningchart if you wish to establish a Great-circle route. Once you have chosen your route draw straight track lines, starting at the SHP between each pair ofcheckpoints with the last track line ending at the destination airport (or DP if applicable. See mountain Page 186Navigation for Professional Pilots flying below for more information about DP.) When a track-line must cross from one side of a VNC or WACto the other use the procedure described in the next section to draw the line. Once the track lines are drawn make 10NM reference marks along each line, as shown below. Next, make 10° drift lines at each checkpoint, starting with the SHP. Note that if you have two SHP, as issometimes the case in mountain flying, the drift lines should start at the second SHP. Make drift lines foreach leg with the last set of closing drift lines at the destination airport or DP as the case may be. Page 187Navigation for Professional Pilots VNC charts are printed on two sides. It is therefore often necessary to draw a straight line between two points that are on opposite sides of the chart. In the figure below imagine that you want to fly directly from point A, on the north side of the chart, to point B on the south side. 1. Layout a separate piece of paper over the north chart and mark point A. In addition mark TWO points that are common to both the north and south side of the chart; these are points D and E. 2. Position the paper on the common points on the south side of the chart, as shown above. 3. Draw the straight line from point B to point A on the separate paper. 4. Mark a point C on the straight line on the south chart that is common to the north chart. 5. Draw the line from point C to point A on the north chart (not shown in the diagram.) Page 188Navigation for Professional Pilots As you can see it only takes a few minutes to prepare the map for a VFR cross country. Once the map isprepared you are ready to start filling in the navlog. You will of course need to measure the true track andlength of each leg. Measure the length of each leg, using an ICAO ruler, and enter it on your navlog. Then measure the truetrack by placing your protractor at the midpoint of each leg. (Remember the theory of convergence,covered previously, where you learned that at the midpoint of each leg a Great-circle track and Rhumb lineare equal.) You navlog should now have all the required information. Simply proceed as already covered to fill in therest of the data and you will be ready to go. In this section I will comment on a few common errors or oversights in filling out flight plans. It is assumedthat you understand the basics as described in RAC 3.15 and 3.16 It is quite common when filling a VFR flight plan to include an intermediate stop. Normally this is notpermitted IFR, although it can be done if the IFR flight is in uncontrolled airspace. The rules regarding thisare in RAC 3.10. Two points that seem to be missed by many pilots are that the intermediate stop isindicated in the route section of the flight plan in the form shown below. And the total duration of theflight must include the intermediate stop. I have noticed that many pilots who lack experience in long tripsvastly underestimate the time required for an intermediate stop. A fuel stop can only be completed in ½ anhour if everything is precisely arranged and organized. A more typical fuel stop takes 45 minutes to anhour. So, allow sufficient time. Pay particular attention to the rules for filing changes to altitude and true airspeed. This is covered in RAC3.16.6. On many of the flight plans assigned in this course you will change cruise altitude and consequentlycruise speed. You are expected to know how to record this properly on the flight plan form. A common mistake is to put arrows or similar symbols in the route section. This is NOT acceptable. ReadRAC 3.16.6 carefully and follow the prescribed format. Also, see the examples provided at the end of thesection. In the Canadian format no symbols or words are required between checkpoints when the route isdirect. If the route in an airway you should name the airway. It is as simple as that, so don’t make itcomplicated by adding anything else. Page 189Navigation for Professional Pilots Page 190Navigation for Professional Pilots Page 191Chapter 9Mountain Cross CountryThere is an entire section in your FTM/IPM on mountain flying that you must read. In this text I will onlymake some remarks about the considerations for laying out a navlog and filing a flight plan for a VFRmountain cross-country. By far the most important aspect of mountain flying is selecting an appropriate route and determiningthat the weather is adequate for the flight. This is discussed in the FTM/IPM and not repeated here. In the mountains distinctive, rivers, and valleys, peaks, roads, railways, etc. provide the ideal circumstancefor pilotage navigation. When the ceilings are low VFR pilots must fly in the valleys, if they are to fly at all,and in such cases pilotage becomes the only viable form of navigation. Even when ceilings are high and DRis used it is very easy to slip back and forth between DR and pilotage due to the numerous easy to identifygeographic features. Any experienced mountain pilot soon becomes a master of pilotage. But it isimportant not to turn your back totally on DR. The ideal form of mountain navigation weaves pilotage andDR into a seamless, almost effortless, procedure. In the mountains you will often be below the tops of the mountains when you pass the SHP and as suchyou may be unable to fly the calculated heading. What should we do?Navigation for Professional Pilots The first tip is pretty obvious. Try to pick an SHP such that the subsequent track follows a valley so that youcan climb on the pp-leg as planned. What if you can’t do that though? Again the answer is pretty obvious. You will have to use pilotage until you clear the top of the mountains.In this case we recommend that you plan a second SHP from which you can begin DR. It is always muchmore accurate to begin DR from a specific SHP. Sometimes pilots skip the procedure of selecting the second SHP, but this is usually because they areovercommitted to pilotage. In other words, they are not going to do DR at all. I recommend this only forrelatively short trips on familiar routes. But, if the route is less familiar and you want to achieve efficientnavigation always have a specific SHP and use DR. This frequently means having two SHPs. When the route directly to an airport crosses high terrain you should always check that a descent to theairport will be possible. If it is not possible then on alternative is simply to circle down over the airport, andtime for this should be allocated, normally under approach and landing on the navlog. But, circling downover the airport is seldom the most efficient way to handle the situation. Take the example of an airplane arriving in Castlegar from Vancouver. The straight-line route runs over theridge just west of the airport and would leave the airplane at 7000’ or so within a mile of two of theairport. Pilots almost naturally divert slightly off this straight-line route and descend along the Arrow Lake.In short they plan the flight NOT to CYCG but to a DP at Deer Park. In all mountain cross-countries be sure to examine the route and determine if you need a DP. The creation of a navlog, as described so far, is based on the presumption of DR. When we open the flightplan, as we have recommended for departure and arrival, we are really saying that pilotage will be used inthese phases of flight. Now we are saying that pilotage is to be used throughout the flight, so the navlogmust be very open. On a valley crawl legs should be grouped (that’s what open means.) Heading obviously changes every fewminutes as the pilot follows a valley. Having a leg for every change in heading is totally unrealistic. Instead Page 194Navigation for Professional Pilots the legs are chosen based only on major changes of direction and or between major checkpoints such aslarge towns, lakes, etc. This is a very open format. The track in this case requires a bit more consideration than usual. A single track from departuredirect to destination usually doesn’t provide enough reference, while a separate leg for each little twistand turn is too cumbersome to plan and to execute. We need something in between. As a practicalexample, a valley crawl from Castlegar to Grand Forks could be planned as three legs: One from theKeenleyside dam to Renata, one south to Christina and one east to Grand Forks. The usual method of measuring the length of a leg, by using a ruler, will not give an accurate distance. Youmust learn to estimate the actual distance flown due to weaving around the snaking turns of the valley.You should certainly start by measuring the straight-line distance from the beginning of the leg to the end,with a ruler, but then you must add an estimated amount to allow for the turns of the valley. There is NO SENSE calculating wind drift, drift angle, and heading for the leg. Indeed you can only estimatethe average track (because it changes continually as you fly.) Don’t worry about drift, your eyes will keepyou on track using pilotage. There is no need to put drift lines on the map. Groundspeed must be estimated in order to calculate time and fuel for the flight. Based on your averagetrack and the wind you can estimate the average groundspeed. The hard part is often determining whatthe wind will actually be. FD forecasts are of limited applicability. Reported ground winds and winds aloftare obviously used to estimate wind at your chosen cruise altitude. Keep in mind that under thecircumstances of a valley crawl you often have to change cruise altitude frequently enroute. Windnormally is funneled to follow the valley, so your main task is to guess whether there will be a headwind ortailwind and how strong it will be; if in doubt always estimate low for tailwinds and high for headwinds. Inthe wind column of the navlog write only the headwind or tailwind estimate – e.g. +10 or -5. You will be given several assignments to plan valley cross-countries to develop the skills described above. Itis crucial that you learn to efficiently open your flight planning so that you can prepare the navlog in only afew minutes, because by far the most important part of valley crawl planning has nothing to do withmaking a navlog. The most important aspect of valley crawl planning is route analysis. You must examinethe route looking for difficult points, such as passes, and most important of all, looking for alternateroutes. In the discussion about diversions later in this text it is pointed out that a safe diversion in themountains is only possible if you have planned for it in advance. Given that diversions are very commonyou must have every safe route option in your mind before you go on a flight. It is very common that theshortest route for a mountain flight is not the one with the lowest terrain. There is nothing wrong withplanning the shorter route, but if you run into low ceilings and decide to divert to the longer lower routeyou want to have figured out ahead of time that you have enough fuel for that. You must know that if youdon’t have enough fuel for a particular diversion option, where you will make fuel stops, etc. Don’t set outon a mountain cross country in marginal weather without all the above thoughts and options sorted out inyour mind. Page 195Navigation for Professional Pilots accurately maintains – the intended track. This makes it all too easy to lose track of time and over fly aturning point. While it might be difficult to imagine a pilot missing the turn at Christina (for Grand Forks)and picking up the road to Republic, some 20 miles south, it is not impossible and it is really easy, whenfollowing Highway 3 west from Cranbrook, to miss the turn at Yahk and continue on Highway 95, goingsouth-east down to Copeland. This is not a complete disaster but in marginal VFR conditions it is verydisconcerting and re-orientation can take several minutes. There is little need to recalculate headings, since that information is only approximate to start with. It isimportant, however, to update the ground speed information – again, in order to monitor the progressalong the track. If the leg is long enough to warrant a couple of 10-mile marks then these can be used justas they are on a regular navigation leg. More often however, the legs are barely long enough to justify one10-mile mark so it is more appropriate to wait until reaching the next turning point, where the pilot caneither compare the ETE to the actual time enroute (ATE) in order to derive a time differential or simplydivide the distance by the ATE for a ground speed. In either case, it is important to remember that aheadwind component on one leg can easily become a tailwind component on the next leg: With windsaloft out of the north, a tailwind on a leg headed south east could well become a head wind if the valleymakes a turn around to the north east. Situational awareness is always critical while valley crawling. Page 196Navigation for Professional Pilots Page 197Chapter 10Time Saving Flight Planning TechniquesIn all that we have done so far we have planned flights by breaking flights into climb, cruise and descentlegs. We have simplified our task by opening the flight plans, and this is an important time savingprocedure. There are some other commonly used “short cuts” to flight planning that I would like you to beaware of. Hour one covers 180NM. Subsequent 420NM require 1.9 hours (420/220.) Total trip time is therefore 2.9hours, which will cost $5800. If the customer says, “yes” to your quote you quickly file the flight plan for 3.9 hours and have 1070 lb offuel, plus contingencies and reserve loaded. The fuel is calculated as 500 + 1.9 x 300. Block flight planning is only safe when the airplane always flies at essentially the same cruise altitude andwind is not a factor. This is clearly a dangerous assumption, so block planning must be used with greatconsideration. An important point I must make before explaining how this is done is that it doesn’t work. In other words,climb penalty planning is a myth. Still, it is so commonly used that you need to know the concept if for noother reason than so you can see its limitations. (Actually, we will conclude that penalties work in the rightcircumstance.) Climb penalty planning starts by saying, “wouldn’t it be easy to flight plan if the departure airport was ona mountain exactly at the cruise altitude for the trip. This imaginary situation is shown in the picturebelow:Navigation for Professional Pilots If the above situation actually existed there would be no need to plan a climb leg. The airplane wouldalready be at cruise at the moment of liftoff. The next step in climb penalty planning is to ask what thedifference in time and fuel for the trip would be in the following situation: Obviously the airplane in this situation must climb from the departure runway to the cruise altitude. Takinga C-172P as an example, it will climb at 85KIAS (TAS is higher) and then cruise at about 105KTAS (the exactvalue depends on the cruise altitude.) This airplane will “fall behind” the other airplane at about 15 knots.Obviously the trip will take longer this way. Similarly it will use more fuel, due to the higher rate of fuelflow in the climb, and the slightly longer flight time. Page 200Navigation for Professional Pilots The idea behind climb penalty planning is simply to determine the difference between the above cases andthen add that onto case I as a penalty. We can do this quite easily using the ENL. First examine the third leg of the above navlog. It shows a cruise leg of 100NM. The airplane is level forthis entire leg, so it corresponds to the part I diagram above. The leg requires 55 minutes and consumes6.6 gallons. Next examine the first two legs of the above navlog. Together they also cover a distance of 100 NM, butthe airplane climbs from sea level to the cruise altitude of 6000 feet. This takes 58 minutes and 7.9 gallonsare consumed. This corresponds to the part II diagram above. The time penalty is obviously 3 minutes per 6000 feet, i.e. 30 seconds per thousand feet. The fuel penalty is1.3 gallons per 6000 feet, which is a bit less than ¼ gallon per thousand feet. To use the penalties for a C-172P simply plan the trip as though the entire flight was in cruise, i.e. asthough the part I diagram applies. Once you have done this add a penalty of 30 seconds and .25 gallonsfor each thousand feet the cruise altitude is above the takeoff altitude. Repeat the above ENL analysis for the B95 and determine the climb penalties for that airplane. At the beginning of this section I said that the real problem with climb penalties is that they don’t work.Can you spot the flaw in the logic behind this procedure? Think about it before reading the nextparagraph. In our earlier cruise altitude analysis we learned that depending on the length of a trip there not only is nopenalty for climbing, there is a penalty for not climbing. Take the airplane on the 500NM cross country onpage Error! Bookmark not defined. a pilot planning this flight for cruise at 9500’ and then adding apenalty would be completely mislead. Climb penalties are only applicable to flights at relatively low altitudes and over relatively short distances.In this case they do reflect the penalty due to climbing that we already discovered on page Error!Bookmark not defined.. Page 201Navigation for Professional Pilots Page 202Chapter 11Enroute Navigation SkillsThis section covers several navigation skills that you will need to develop and apply in flight. The primaryemphasis in this course is on preflight planning, most of the in-flight skills are developed in Avia 100 and200, but there are some things you should keep in mind. Map ReadingIts pretty obvious that a fundamental skill in navigating VFR is the ability to interpret a VNC chart andlocate the corresponding geographic features on the ground. The first principle of map reading is work from map to ground, NOT the other way around. In other wordsyou locate a geographic feature on the map and then look out the window until you spot the same featureon the ground. You do NOT spend time with your eyes down on the map trying to find some feature, suchas a small lake or road that you have spotted out the window. The latter procedure results in too muchtime with eyes in the cockpit. Good airmanship is to have your eyes out the window 99% of the time. You must learn which features will be distinctive “out the window” and which won’t. on the map certainthings such as VORs, NDBs, towers, runways, small town, and power lines are quite distinctive, but out thewindow they are nearly impossible to see. There are exceptions of course. For example power lines overmountain ridges can be quite easy to see because a wide swath of trees is cut down along the line. Andradio towers are very easy to see at night. The specifics of night cross countries are discussed in yourFTM/IPM and are covered in Avia 201; they will not be covered further here. The best procedure is to choose four or five geographic points on your map and then look out the windowuntil you spot them. These could be a town, a river, a road, and a mountain or valley. Once you have this“list” of items gleaned from the map you scan the ground until you locate the corresponding locations.There are of course lots of towns, rivers, roads and mountains in the world so how do you tell one fromanother? The key here is to analyze the map and develop a mental image of the distinctive characteristicsof the ones you are looking for. For example does the town have a river running though it? How manyroads run in and out? And is there a nearby mountain? Try to have at least three distinctive features thatwill distinguish the location you are looking for from others. These features can be anything, as describedabove, as well as relative position, size, etc. A common mistake is to choose geographic points that are too close to the airplane. In flight you can see along way and you should take advantage of that. It is much easier to locate a geographic point that is 5 or10 miles ahead rather than one directly below you (the airplane doesn’t have a glass floor.) You can oftensee large geographic features, such as distinctive mountains, lakes and rivers, 30 or more miles away.Doing so reduces a lot of navigation effort, so it is highly recommended.Navigation for Professional Pilots Another frequent mistake is becoming too obsessive about spotting a particular geographic point. Forexample you may be looking for a small town but not seeing it. Some pilots will keep looking and lookingand looking for this town until they are completely lost. This is due to a lack of time awareness, discussednext. Time AwarenessWhen you choose a geographic point on your map that you will be looking for a critical thing to do isestimate roughly how long it will take until you reach the point. To do this simply be aware of how manymiles per minute (roughly) you are covering. Most airplanes cover at least 2 miles per minute, and manygo much faster than that. Therefore a geographic point 6 miles ahead will be beneath you in 3 minutes. Ifyou haven’t spotted it by then you’ve missed it. It isn’t critical to identify every point, so don’t worry aboutit. In light of the above, it is important to always be looking for more than one geographic point. Usuallythree is a good number. If you miss one it won’t really matter. Also, finding one often makes it easier tospot the others. Most importantly, be aware of time passing. If logic says you are past a checkpoint thenforget it, choose another one and look for that. Failure to follow this advice is what will get you lost. Reorienting if LostThe first question you must ask is; am I really lost? As a new pilot you may feel lost if you miss onecheckpoint, but you really aren’t. This was mentioned above. Don’t panic. As long as you fly a straight-line you can always find your way back by simply “doing a 180.”But it is important that you fly the specific heading on your navlog. The best way to get lost is to wanderaround on random headings that are not recorded. As long as you are flying one heading (as opposed towandering) you can do a 180 and go back. Of course if you have a working GPS you can read the latitude and longitude and immediately locateyourself on the VNC. So, we will assume you don’t have such equipment. If you are truly “lost” stay calm and keep your wits about you (which means you mustn’t panic.) When youthink about it you really aren’t “totally lost.” You can state your location in a hierarchy such as that you arein Canada, B.C., Southern B.C. east of Vancouver, and so on. You probably know where you are within afew miles tolerance. You could draw a circle on the map and say, “I am somewhere in here.” From thisknown area of probability there are several things you can do: If you have been flying a steady heading you can simply reverse it and go back to where you came from.Remember to write down the time you turn around so you can estimate how long it will take to get back tothe starting point. Your previously recorded departure time will give you all the information you need.Lucky you always record these things, right? If the weather is suitable, climb to a higher altitude so you can see farther. If you can climb high enough toget ATC on the radio you will be able to get radar or DF assistance from them. Radar is available in most ofsouthern Canada, but if you happen to be lost in the far north there is also the defense radar system. Theprocedure for using this in the event of an emergency is covered in section F of your CFS. Page 204Navigation for Professional Pilots If you have been wandering around, which got you lost, consider using the navigation technique calledlandfall, which is described below. It is almost always possible to use a landfall to reorient yourself. If yourdesired destination is not on an extended geographic feature suitable for landfall then pick an interimdestination from which you will be able to continue on. In the prairies most small towns have the town name written on their grain elevator. If you fly anydirection you will come across a road within a short time. Follow it to a town and as you fly by you canread the name on the elevator to identify your location. Keep track of your fuel. If you brought lots of reserve you will be fine, but if fuel gets low and you are stilllost you may have to do a precautionary approach. Much more likely however is that you will reorientyourself and be able to continue your flight. But be sure to recalculate your reserves. If they have shrunktoo low divert to another location and refuel. Most fuel starvation incidents follow getting lost. Navlog keepingOn your navlog you must record the takeoff time and time past each checkpoint enroute. You should alsorecord ETA revised ETA for each checkpoint. These are standard procedures applicable to any log keepingexercise. In addition your company may require many other pieces of information be recorded. On the Selkirk College navlog we write the takeoff time in the designated location just before takeoff. Onceclear of the departure airport we then write down the ETA and Fuel Expiry time in the designatedlocations. We then fill out the ETA column so that we have the ETA for each checkpoint. The finalcheckpoint ETA should match the previously calculated destination ETA. If it does not then an addingmistake has been made, which you must locate and correct. Selkirk College navlog keeping involves writing down the time we pass each checkpoint enroute in the ATAcolumn. The ATA should be quite close to the ETA previously filled in. At a glance you will be able to seethat you are ahead of or behind schedule. If the groundspeed is revised pencil the corrected value over the value on the navlog, then enter a revisedETA in the designated column. TIP: it is really quite rare for the winds aloft forecast to be wrong by more than 5 knots. This amounts tosaying that you normally will have a groundspeed within 5 knots of the planned value. If your calculatedgroundspeed is substantially different than the flight planned value you should recheck your calculationsbefore jumping to any conclusions. When the wind is substantially different than the forecast there isusually evidence such as turbulence or un-forecast storm activity. TIP: when doing a groundspeed check your calculations are subject to round-off error. For example, youmeasure a distance of 11NM and then measure a time of 4 minutes. Based on this your CR tells you thatthe groundspeed is ____ Kts. Ask yourself what tolerance you would apply to this value. Consider thisbefore reading the next paragraph. The groundspeed according to your CR is 165 kts. But the distance is rounded off to the nearest nauticalmile and the time is rounded off to the nearest minute. This amounts to saying that the actual distance is Page 205Navigation for Professional Pilots between 10.4 and 11.4 and the time is between 3:31 and 4:29. Using these values your groundspeed couldbe anywhere between 149 and 196 kts! (Check these values for yourself with a CR.) That is a very largespread of “correct” values. If your navlog predicted a groundspeed of 150 knots should you revise your ETAor not? The answer is that you don’t have an accurate enough groundspeed to decide. To make an accurate groundspeed check you need more accurate data. The best you can usually do ismeasure distance plus or minus ½ nautical mile Even after you do this you will find it difficult specify theprecise moment you pass the checkpoint, which adds another error bringing distance tolerance to at least1 NM. You can use a stopwatch to get a more accurate time value, but it is still difficult to achieve anaccuracy right down to the second (see previous point.) Consequently, if you want a groundspeed checkaccurate to the nearest knot you would have to fly a groundspeed check of at least one hour (60 minutes.)Put another way, a six minute groundspeed check is at best accurate to plus or minus 10 knots. And a 3minute groundspeed check is accurate plus or minus 20 knots, which is to say just about useless. So, makesure you use fairly long groundspeed checks (10 to 15 minutes minimum), and know the tolerance of theiraccuracy (4 or 5 knots at best.) If the obtained value lies within the tolerance of your flight planned speedit is usually wise to take this as confirmation of the navlog and make no revision to your ETA. Top of DescentAt some point you must start a descent from your cruise altitude so that when you reach the destinationairport you are at the desired altitude. This is the top of descent point (TOD.) Choosing it wisely isimportant. A lot of VFR pilots are in the habit of descending quite early. If you are approaching a major airport with alot of traffic, and in an area with lots of good forced approach sites, it might be wise to descend to circuitaltitude 10 miles before the airport (I am thinking about single engine airplanes here.) But in more ruggedterrain you want to reach circuit altitude only one or two miles prior to joining the circuit, in order to keepas many safety options open as possible. On the other hand, you don’t want to descend too late, if you reach the airport well above circuit altitudeyou will have to circle down (which wastes time and fuel) or will dive (which is uncomfortable forpassengers and you.) Most pilots plan descents based on a certain gradient. Three miles per thousand feet is the most common.If you are flying a turbo-charged piston airplane it might be better to use four miles per thousand feet.Simply calculate how may thousand feet you need to descend and multiply by three (or four) then startyour descent that number of miles from the location you which to reach circuit altitude. DiversionsA diversion means changing your route and or destination while in flight. Diversions are very very commonoccurrences in both IFR and VFR flight. IFR flights routinely divert around areas of bad weather. The specific techniques for this however will bedeferred to Avia 260 Page 206Navigation for Professional Pilots VFR flights also often divert around areas of bad weather. It is not always necessary to change destinationwhen bad weather is encountered, frequently you can skirt the area of poor weather and re-intercept theroute beyond the area affected. But you must keep track of time so that you don’t run low on fuel. Whendiverting around weather you are by definition using your contingency fuel, so as long as your navlogshows that you have lots of contingency fuel you are fine. But if you have not allowed contingency fuelthen you will have to change your destination in order to refuel. Transport Canada has established a specific diversion exercise that you must demonstrate on thecommercial pilot flight test. It is important to realize that this is only an exercise. It actually bears almostno resemblance to 99% of real life diversion scenarios. On the flight test exercise you are required to drawa free-hand line to a designated destination then estimate the heading and distance without using aprotractor or a ruler. You must then calculate (estimate) the time enroute in your head without a flightcomputer. This is a great exercise in mental approximation but it is important for you to realize that if youare actually doing a diversion there is nothing wrong with using a ruler, or a calculator. To meet the Transport Canada diversion challenge most pilots estimate the distance by using the minutemarks on the VNC’s lines of longitude as a scale. Your instructor will show you how to do this if you haven’tdone it before. In the real world, just use a ruler if you have one. To estimate the track to the destinationyou can just “eye-ball-it” or use a VOR rose to help you be a bit more accurate. You will be surprised howclosely you can eye-ball-it with a bit of practice. This is however a skill that requires practice. The bestthing to do is estimate all tracks before putting a protractor on them. To estimate the time enroute if you don’t have a CR computer there are numerous mathematical tricks.These are laid out on the ProfessionalPilot.ca website in the miscellaneous section. Anyone can do it, it justtakes a bit of practice, and it is well worth the effort. When diverting in the mountains, on a valley crawl, usually means taking a totally different route. Thesecret to success is in knowing all the routing options before you takeoff. Scanning the map looking for analternate route once you have run into poor weather is a recipe for disaster. I am sure than many of thepilots who have killed themselves in the mountains (and there are a lot of them) did so when they had todivert but were unprepared to do so. If you run into bad weather in the mountains and have to divert thenthere should only be two possibilities. You either divert to an alternate route that you have previouslyanalyzed and planned, or you do a 180 back to the last suitable airport and land there until you getorganized to go on. NEVER plan a substantial diversion in-flight in the mountains. The contents of a VFR position report are listed on the back cover of your CFS. Ideally position reports should be made about every half hour on a cross country. In the mountains thereare often limited opportunities to make position reports, especially on valley crawl trips. In such cases the Page 207Navigation for Professional Pilots best advice is to make every position report that you can. This sometimes means making two reports only10 minutes apart and then other times an hour or more might pass due to lack of ground stations. It is vital to realize that when you make a position report the information is recorded, for use if you don’tarrive at your destination, but it DOES NOT update your flight plan. Many pilots misunderstand this fact.For example, if you are falling behind schedule and will arrive 45 minutes late, if you file a position reportin which you give an ETA for your destination that correctly predicts your new arrival time FSS will stillinitiate a search for you at the original ETA based on your flight plan. To prevent this you must specificallyrequest that your flight plan be amended to your revised ETA. Imagine you wish to sail a ship across the ocean from France to Montreal. The ocean currents present thesame problem for ship navigation that wind does for pilots. In modern times you would use GPS or Loran-C thto navigate accurately in a straight-line between the ports. But imagine it is the 16 century and no suchsystem exists. If you sail west from France you are most definitely going to hit North America. When you do sailors saythey have “made landfall.” But you are probably going to drift so if you aimed directly at the SaintLawrence there is no way to know if you are north or south of it. The strategy used is to deliberately aim to one side or the other of the intended destination so that whenyou do make landfall you know for sure which side of the desired point you are on and can follow the coastto your destination. The same technique can be used by pilots. For example if you are in Kelowna and fly east you really cannotmiss the Arrow Lake. Once you find the lake you can follow it to Castlegar. The first step is a rough DR (justaccurate enough to guarantee you don’t miss the target (Arrow Lake)) the second leg is pilotage (followArrow Lake to Castlegar.) Laying a landfall only works if the destination is on an extended geographically distinct feature that youcan lay landfall for and be certain you won’t miss. The Arrow Lake meets that criterion. Many airports inthe Prairies are along major highways, which can be used the same way, other towns are on railwaytracks, and so on. If you are going to lay landfall simply estimate a heading that will put you one-way-or-the-other from your intended destination. Once you make landfall use pilotage to find the destination. Thistechnique is often practical on a diversion around poor weather or for reorienting yourself if you get“slightly” lost. Page 208Navigation for Professional Pilots Page 209Chapter 12Oceanic FlightThe full details of oceanic flight are beyond the scope of this course. You will learn more about them insecond year. However, two points of navigation, which are usually considered important for oceanic flight,will be covered here. These are the point of no return (PNR) and critical point (CP.) Each of these concepts can be applied to any flight, even a short over land flight in a C-172; but they reallydon’t make a lot of sense in that context. Still, the mechanics of doing the calculation is the same nomatter what type of airplane you fly. On many of the short flights you have made in C-172 and similar airplanes in your flying career youprobably carried enough fuel to fly all the way to destination and then return to departure point. In such acase you never reached a point of no return (PNR.) PNR is simply what the name says, the point beyondwhich you do not have enough fuel to return to the departure aerodrome. Endurance EuWe will represent endurance with a capital E. E is the amount of time in hours that the airplane can fly. Etis the total endurance to dry tanks. For example a C-172 with standard tanks has 38.9 gallons at takeoffand an endurance of 5:18. It would be very unwise to calculate PNR based on this number howeverbecause that would imply proposing to return and land just as fuel runs out – a very scary idea. Eu willrepresent the useable endurance, which must include at least reserve fuel, and possibly some contingencyfuel. For the C-172 with standard tanks we could set the value of Eu at 4:40 for example. If there was no wind the airplane would reach PNR by flying out to half its endurance, or in other word PNRwould equal total range divided by two. We also define engine-out-PNR in which we assume all engines operating prior to the 180° turn and oneengine out after the turnaround. I.E. GS home-SE will be based on the engine out performance, but GS out isalways based on all engines operating normally. PNR FormulaIn zero wind PNR is determined very easily by calculating total range (E x GS) and dividing by two: It is always a good idea to do the above calculation as a first estimate; then use the formula below toaccount for wind. The result is always a distance LESS than the zero wind distance above. I.E. wind alwaysreduced PNR. For example an airplane with a zero wind GS of 100 Kts and an endurance of 4 hours has a PNR of 4 x 100 /2 = 200. Page 212Navigation for Professional Pilots If the airplane in the previous example experiences a 20Kt tailwind outbound the PNR will be 4.5 x 120 x 80/ (120+80) = 216Nm. As expected, this is slightly less than the zero wind DPNR. Important: PNR with wind is always less than PNR with no wind. Note that PNR questions will be on the ATPL and IATRA written exams IMPORTANT: if a question asks for engine-out-PNR calculate GSout with all engines operating normally andGShome with one engine inoperative. Note that you can always apply the DPNR formula to any flight but in many cases the PNR is beyond thedestination. I.E. the airplane can turn around at any point on the flight and return to departure point. Thisis good to know; therefore PNR should be routinely calculated and if it is beyond destination – great. Here is the “proof” of the formula. It is not necessary for you to memorize the proof but you should knowthe first line, i.e. the definition, and the last line. By using only the first line you can find the correct answerfrom among a selection on a multiple choice exam. Page 213Navigation for Professional Pilots It should be obvious that in zero wind the CP is exactly at the mid-point of the flight. In other words on a1000 NM flight CP is 500 NM. But CP will move into the wind. I.E. if there is a tailwind you will reach CPbefore the mid-point or if there is a headwind you will reach CP after the midpoint – see if you can visualizewhy this is so. CP can be calculated for all engines operating normally and also for engine-inoperative. In the later casethe CP represents the, on one engine, to return to base or continue to destination IMPORTANT: when calculating CP always use the speed as it will be after the CP. Thus, if you are asked forthe single-engine CP use single engine speeds, if asked for all engines CP use all engine speeds – NEVER mixspeeds in a CP calculation (this is different than a PNR calculation.) Page 214Navigation for Professional Pilots Let’s calculate where CP is with a 20 Knot tailwind outbound. GSon is 120 KT and GSreturn 80KT. Therefore CP= 400 x 80 / (120 + 80) = 160. So, with a tailwind CP comes before the halfway point. Let’s calculate where CP is with a 20 Knot headwind outbound. GS on is 80 KT and GSreturn is 120KT.Therefore CP = 400 x 120 / (120 + 80) = 240. So, with a headwind CP move to beyond halfway point. Page 215Page 216Appendix 1– C-172 Interpolation Tables Power setting ___________ feet RPM TAS ___________ temp _______% 65% ______% ________ feet Page 217________ feet Page 218Appendix 2 - Inbound PDT Practice Sheet In the sheet below fill in the heading you must turn to, or if it is an over-60 write down PT (for procedure turn.) 150 100 300 280 240 290 040 120 135 165 In the table below fill in a random selection of bearings to beacon in the first column: Page 219Next fill in desired bearings considering the first column and making the bearing within 60 most of thetime. Page 220Appendix 3 - Outbound PDT Practice Sheet In the sheet below fill in the heading you must turn to. There is no “over 60” limit for outbound PDTs. 210 250 340 240 005 320 140 180 280 270 In the table below fill in a random selection of bearings from beacon in the first column: Page 221Next fill in desired bearings in the second column. There is no 60 degree limit, but normally the desiredshould be within 180 (to make sense.) Page 222Appendix 4 – Definitions Deviation: The difference between actual magnetic heading and the compass indications. This error is shown on a compass correction card. Variation: The difference between magnetic track and true track. This due to the magnetic north pole NOT being at the actual north pole. Variation is shown on both IFR and VFR charts as lines of equal variation, known as isogonic lines. Convergence: Meridians of longitude converge at the north and south poles, as such they are not quite parallel to each other. The angle at which they converge is known as convergence. Convergence is zero at the equator and increases the closer to the pole you fly. An aircraft flying along a Great Circle route much change heading to compensate for convergence. Great Circle: A line on the surface of the earth that when extended completely encircles the earth and has its center coincident with the earths center. Such a line is the shortest distance along the surface of the earth between any two points on the line. Rhumb Line: A line on the surface of the earth between two points such that the true track along the line is constant. A Rhumb Line is only coincident with a great circle if it is also a Meridian, or the equator. All other Rhumb lines vary from the Great Circle (see above definition.) Rhumb Lines are popular with pilots because you can fly a constant heading rather than changing headins as you would on a Great Circle. Page 223 Much more than documents. Discover everything Scribd has to offer, including books and audiobooks from major publishers.Cancel anytime.
https://www.scribd.com/document/46754212/Navigation-for-Profesional-Pilots
CC-MAIN-2020-10
refinedweb
45,289
64.1
Vista To Get Symlinks? 565 TheRealSlimShady writes "According to a post by Ward Ralston on the Windows server team's weblog, Vista server is to get symlinks as part of the SMB2 protocol." From the)." Duplication... (Score:5, Insightful) Re:Duplication... (Score:2, Funny) Duplication... (Score:5, Funny) Re:Duplication... (Score:3, Funny) More Dupe than you think (Score:4, Informative) Re:More Dupe than you think (Score:3, Informative) is one place to start. [microsoft.com] Still, it'll be very nice to have real symlinks instead of shortcuts. It's what the shortcuts should have been all along. Yet more great (Score:5, Funny) Re:Yet more great (Score:5, Funny) Re:Yet more great (Score:3, Informative) Five years to late [slashdot.org] Re:Yet more great (Score:3, Funny) Funny thing is... (Score:5, Insightful) Re:Funny thing is... (Score:4, Funny) Re:Funny thing is... (Score:4, Funny) Dennis Thompson? I didn't know that Dennis Ritchie [bell-labs.com] and Ken Thompson [bell-labs.com] fused and merged together back in the 60s to become ... Dennis Thompson. Re:Yet more great (Score:5, Funny) Forward slashes? Text files without ^m's? Re:Yet more great (Score:3, Funny) Now that would be demanding a little bit much in so short time, wouldn't it? We will have to wait at least until the avarage workstation has 30GHz dualcore CPUs and at least 10GBs of ram. Re:NTFS already had symlinks? (Score:4, Insightful) Re:Yet more great (Score:5, Funny) Vista Will Probably Be BSD-Based (Score:4, Interesting) To review the previous clues: First, there was Microsoft's announcement that Vista (Longhorn) will use UNIX-like User Permissions: See Longhorn to use UNIX-like User Permissions [slashdot.org] Why would Microsoft do that, when even many Linux supporters agree that Windows permissions are finer grained? But if the new Windows is BSD-based, Microsoft would be forced to do that, or face rewriting a lot of the underlying BSD code. Second, there was Microsoft's announcement that Unix compatibility will be "built in" to Vista: See: Microsoft to Stop Releasing Services for Unix [slashdot.org] Third, there is the fact that Microsoft ported Fourth, there was Steve Ballmer talking about the Vista "reset" which started around 18 months ago. See: Ballmer Pushes Microsoft Innovation, Talks Vista Reset [windowsitpro.com] Does anyone really think that Microsoft could succeed in doing a major rearchitecturing of the Windows code now, in only 18 months, after they had tried and failed to do so many times over the last decade? Besides, when has Microsoft ever shown the confidence or ability to succeed on their own? DOS, Windows NT, Internet Explorer, and And now we have this new report that another basic feature of Unix, symbolic links, will be part of Vista. Given all this evidence, I am fairly convinced that Vista will be based on one of the Open Source BSD distributions. Unlike Apple, however, Microsoft will probably try to keep it a secret, and claim it as their own innovation. What will be the result? On one hand, a BSD-based Vista might be a good thing, since it will result in a more stable, and less virus-prone Windows. On the other hand, if Microsoft remains true to their history, they'll just screw it up with all the lock-in features they'll add on top. Like the VMS-and-OS/2-based Windows NT, which started out strong (version 3.51) then gradually degraded, I expect the benefits of a BSD-based Vista to be temporary. Then again, Microsoft is just playing for time, as they continue their strategy of locking in the Internet. Thus, they only need Windows to be better for long eneough to fool their customers, again, while they tie them up with a new set of decommoditized protocols (.Net, Palladium, DRM, Windows Media, Office 12, and so on). Re:Vista Will Probably Be BSD-Based (Score:3, Insightful) So you have three reports on From these three technologies, al Re:Vista Will Probably Be BSD-Based (Score:3, Funny) Re:Nevermind (Score:5, Insightful) Re:Nevermind (Score:4, Informative) As far as users are concerned, I suspect they won't know/see the difference. Creating symlinks will just work like creating shortcuts. Symbolic links? (Score:3, Funny) Microsoft 'innovating' once again, and giving the people what the want (10 years after everyone else). Go Redmond! Re:Symbolic links? (Score:5, Insightful) It's not like Linux never copied an idea from another OS, yet it seems MS is not allowed to add a feature unless they thought of it themselves. But then I guess everyone here gets a bit bitter when there is one less thing to complain about MS. Re:Symbolic links? (Score:5, Informative) Also, FAT had initially a flag indicating that an object is not a file, nor a folder, but a symlink. Unfortunately, the attribute got later used as a "Long Filename Part no. X" flag... talk about bad design.. Re:Symbolic links? (Score:3, Informative) There is a huge difference between the two: a hard link is filesystem-level (simply a second entry in a directory to a file); a symlink is OS-level. One cannot cross filesystem boundaries (being filesystem-level), the other can. Re:Symbolic links? (Score:4, Informative) Windows 2k and above have both hardlinks (which are available via standard tools) as well as symlinks, restricted to directories only and not available via the OS' tools. Check Juctions [sysinternals.com] for the creation and handling of symlinks. Re:Symbolic links? (Score:3, Informative) That would be really funny if it was true. It is, alas, false, and junctions do not become "a drive letter", they are virtual folders akin to Linux' directory symlinks (since junctions sadly don't handle the file level but only the directory one). Re:Symbolic links? (Score:4, Informative) Re:Symbolic links? (Score:3, Insightful) Re:Symbolic links? (Score:3, Informative) And, more "F.U.D." attempts by the 'pro-Unix/Linux/BSD' brothers @ "/.", as-per-usual... or, the usual "partially informed/incomplete data spouting rumor mill" is @ work here again, as-per-usual. Take a read, so you are better informed: l [sysinternals.com] ----- Win2K's version of NTFS supports directory symbolic links, where a directory serves as a symbolic link to another directory on the Re:Symbolic links? (Score:3, Informative) Actually, 95% of the world's computers are embedded microproccessors, most of which don't even run anything classified as an "operating system", let alone windows. I expect that what you meant was that 95% of PC's are running Windows NT based operating systems. I doubt that, there are still plenty of older, pre-XP home machines in use today, so probably as many as 15-20% of PC's are running Windows 9x-based operating systems. Yo Allow me to be the first to say... (Score:5, Funny) (Who was it who said: 'Those who don't know UNIX are condemned to recreate it. Badly.' ?) Re:Allow me to be the first to say... (Score:4, Insightful) Re:Allow me to be the first to say... (Score:5, Insightful) Backward compatibility is absolutely indispensable for Microsoft - the only reason it's still the market leader after all the lawsuits, bad publicity and downright talented competition of the last few years is because nobody wants to break compatibility with their existing software, documents, networks and hardware. Microsoft understands this, and while I'm sure it drives a lot of MS developers insane, backward compatibility is always given top priority, even if it makes the architecture horribly ugly and illogical. (If you want to see the Unix equivalent, read the chapter on terminal I/O in Stevens' Advanced Programming for the UNIX Environment. There are backward compatibility hacks in there that are so ugly you'll wish you'd been born blind.) Ah, the "backwards comptibility" card... (Score:3, Insightful) That's the same excuse that they used for using FAT32 in Win9x, but OS/2 proved them wrong even before the first Win9x release when OS/2 2.0 allowed DOS and Windows programs to install and run on an HPFS partition. Even Windows 3.1 itself could be Re:Allow me to be the first to say... (Score:5, Informative) $ fortune -m 'condemned' ... Those who do not understand Unix are condemned to reinvent it, poorly. -- Henry Spencer And those who don't understand fortune(1) are condemned to ask about quotes =) OMG (Score:2, Funny) Obligatory quote (Score:3, Funny) It's worse (Score:3, Funny) Different than shortcuts (Score:5, Informative) Re:Different than shortcuts (Score:3, Insightful) If you open the file up in XP, Word will be very confused, and if anything, display the 1000-byte gibberish. In Vista, Word (and Outlook, and everything else) will automatically do the right thing, and read the contents of MyDocument1.doc without having to change any code in Word/Outlook/etc. Since it's aan automatic part of the operating system, all previou Only on BSD and Linux... you want readlink. (Score:3, Informative) NAME SYNOPSIS DESCRIPTION "Virtual folders", I believe it's used for (Score:5, Informative) Re:"Virtual folders", I believe it's used for (Score:5, Informative) Security risk? (Score:5, Interesting) "Now why is this relevant to the SMB2 protocol? This is because, for symbolic links to behave correctly, they should be interpreted on the client side of a file sharing protocol (otherwise this can lead to security holes). " Is it not rather: "If the client does not interpret symbolic links then nothing will work?" Re:Security risk? (Score:5, Interesting) If the server did no special behaviour for symlinks then they would appear to the client as a duplicate of the symlink target, an ordinary file. NTFS already does it since Win2K ! (Score:5, Informative) Any feature new in Vista but the look and feel ? What about booting the OS with less than about 20 services started and 256MB of memory used ? Re:NTFS already does it since Win2K ! (Score:3, Informative) The links in the summary are broken though. Re:NTFS already does it since Win2K ! (Score:3, Insightful) I've been wishing Windows would support this elemental feature for a long time now. I would have used it to create a directory tree with the structure I wanted to burn on CD, without having to move all the actual files around. The CD burning software I've tried doesn't understand shortc Re:NTFS already does it since Win2K ! (Score:3, Informative) Re:NTFS already does it since Win2K ! (Score:3, Informative) Soft links are represented as a special text file that contains the name of the linked file. The default behavior on opening a soft link is to redirect and open the target file ins Re:NTFS already does it since Win2K ! (Score:5, Informative) NTFS does support hardlinks and, as the developers of the NTFS driver for Linux recently discovered (see details in this thread [theaimsgroup.com]), it also supports symlinks, provided Microsoft Services For Unix are installed. The important part of all this, is, I think, that open source tools ranging from the linux fs drivers (ntfs and cifs/smb) to the cygwin stuff should get updated and start managing the thing the way MS does it (on MS filesystems, of course). Re:NTFS already does it since Win2K ! (Score:3, Insightful) The pain (or feature) with junctions is the source directory doesn't have to be empty. As a System Administrator in the Managed Storage group this can be an incredible pain. If the destination points to another drive you don't want to include it in the backups since things will get backed up twice (since the os w FAT does it too... (Score:5, Funny) Well. So does FAT, except it is called a crosslink, and aparently scandisk and various disk defragmentation tools do not handle it correctly ;-) Re:NTFS already does it since Win2K ! (Score:3, Informative) Junction points, at least the ones created by the utility referred to, are in fact hard directory links. You can mount any directory from any NTFS volume as a directory at any point in any NTFS volume's tree, not just whole partitions. I have used junction.exe many times to save a lot of reorganization by mounting a directory from one volume onto another when the other is full and there is no unallocated space to add. For example, you can move directories from "c:\Program Files" to "d:\Program Files" and t Re:NTFS already does it since Win2K ! (Score:5, Insightful) The problem with Junction.exe is that the Explorer shell and all other applications do not differentiate between links and real folders. That is, applications never expect two different paths to point to the same object, which makes Junctions much less useful in practice. For example, file search results take much longer to complete and display duplicate results. I believe that is why they initially limited Junctions to just directories. Now, if Vista got persistent file handles, that would be interesting. Re:NTFS already does it since Win2K ! (Score:4, Interesting) Even more annoyingly, if you "delete" a junction point directory through the shell it will do a recursive delete just as it would for a folder, thus deleting all of the contents of the junction's target directory. If you set up the junction point then this is expected, but if it's someone else who isn't familiar with the concept they can easily mistake it for a bunch of duplicate files (since the shell displays them identically, and gives misleading disk usage information) and delete both copies. Fantastic! (Score:4, Funny) I had to check.... (Score:2, Funny) NTFS already has symlinks, has done for years (Score:4, Informative) New strapline? (Score:3, Funny) Great... but (Score:3, Interesting) These features are incredibly useful (arguably more so than symlinks), and the only Linux fs that comes close to implementing them is reiser4, which is not even part of the kernel. Re:Great... but (Score:4, Funny) Multiple streams are an absurdity. "Ok contestants, repeat after me: 'A file is a variable-length array of bytes.'" Steve Jobs: "A file is two variable-length arrays of bytes." BZZT. "Sorry Steve, thanks for playing." Bill Gates: "A file is N variable-length arrays of bytes." BZZT. "Whoops Bill, that's a directory. Looks like you're out too! Join us next week on 'Who wants to be an architect!'" Reparse points are more commonly known in the UNIX community as 'mount points.' Re:Great... but (Score:4, Interesting) Two are running Battlefield 2 servers 24x7, one is running a web server and a database server to aggregate statistics on players. All have been in service doing this kind of thing for over two years. Never defragged, still running as good as new. Lol, symlinks (Score:5, Informative). [bell-labs.com] NT *was* going to have executables that pretended to be files, i.e. when you opened the executable to get the contents it would run and return the output rather than the by bytes of the executable, with a special NT syscall to read the *real* contents. Kind of like a named pipe. I was looking forward to this but it didn't work out. Re:Lol, symlinks (Score:2) Re:Lol, symlinks (Score:3, Interesting) For example, i have dozens of webapps deployed in their own directories, and they all need a configuration file in a their own directory. Since this config file is the same for each webapp, it certaily makes a lot of sense to have the file be a symlink to a real file somewhere else, in a kind of meta directory. Re:Lol, symlinks (Score:4, Informative) or rather, I'll just provide a link to this The Use of Name Spaces in Plan 9 Rob Pike Dave Presotto Ken Thompson Howard Trickey Phil Winterbottom Bell Laboratories, Murray Hill, NJ, 07974 USA [bell-labs.com] Symlinks were a BSD invention (Score:4, Informative) The commercial product, SysV, got symbolic links, but they had to compete in the real world. Re:Lol, symlinks (Score:4, Informative) You're confused. Files in Unix filesystems have no hierarchy, with or without symbolic links. Files are quite independent of file names. Multiple directories may contain entries for the same file, the names need not even be the same. The same directory may reference the same file with multiple names. Note for examples that renaming a file changes the modification time of the Symbolic links are a bit of a hack though, yes. But mostly because they must expose the limitations of "files are not the same as filenames" - not because they allow multiple paths to the same file. --paulj Re:Lol, symlinks (Score:3, Insightful) He never mentions hard-links at all, with which the namespace remains quite hierarchical and cycle-free. Symbolic links suck not because of the multiple-name thing, but because they're an implementation hack that both can turn the namespace into spaghetti and produce inconsistent results across applications due to how exposed their guts are to appl Re:I think we have a new kind of troll... (Score:5, Informative) This story is a case in point. Symlinks are a hack that hides the fact that disk drive based namespaces are a crock. And a crock that's easily solved. Unix is 30 years old, Linux copies it. Windows is not in the picture. Linux / BSD et. al. offers very little innovation any more. Instead anything new is coming in through the user space and we end up with stuff like GnomeVFS and smb:// handlers. The only real place where any real Unix like innovation has occured in recent times was in Bell Labs and the expresssions of that are Plan 9 and Inferno. You can try some of the concepts out in user space through [swtch.com] "Plan 9 from User Space (aka plan9port) is a port of many Plan 9 programs from their native Plan 9 environment to Unix-like operating systems. supported systems : Linux (x86 and PowerPC), FreeBSD (x86), Mac OS X (Power PC), NetBSD (x86), OpenBSD (x86 and PowerPC), SunOS (Sparc)." Good grief! (Score:3, Funny) not news (Score:2) I expect even more "inspiration"... (Score:2) And Microsoft, with its stance on patents vs copyright in software, already demonstrated it can do shameless 180 degree turns. Microsoft: how much can you trust us today? Gates on patents [corante.com] So, will they also get hard links? (Score:3, Interesting) MS Motto (Score:5, Funny) How sad (Score:3, Insightful) The Unix guys finally figure out how to move past symlinks to something better (private per-process inherited namespaces and bind() overlay mounts ala Plan 9 - coming to a Linux box near you soon), and now Windows starts implementing it for the first time (well ..and about time, too! (Score:2, Insightful) In Windows Explorer, the topmost level is the desktop, while in the CLI, there's as many 'topmost' levels as there are drives in the machine. I never thought I'd say this, but I think they should adopt a *nix-like heirarchy, so that anything can be 'mounted' anywhere. Of course, they'd have to change the structure significantly, and have a built-in translator for "C:\things\stuff" type commands and whatnot. But then, i FOUR, er FIVE symlink styles, all kinda *wrong* (Score:5, Interesting) oops, isnt there still: Make that FIVE ways. All of them looking somewhat alike, but all with subtly different syntax, semantics, overhead, and security implications. Sweet! Improve on symlinks? (Score:5, Informative) 1) When you move a destination object, symlinks don't follow the target . This leaves "broken" symlinks that refer to nothing. Why doesn't the mv command move these too? 2) When you symlink a symlinked folder, the root symlink is ignored. Let's say you symlink 3) Symlinks cause all kinds of weirds around chrooted file systems , especially ones on a different underlying filesystem. If you're not very careful, nothing is as it seems! Files go nowhere, files are accessable only sometimes, etc. It's logical when you understand and appreciate a symlink for what it is, just a referral, but it can be maddening when security contexts get distorted around a chroot... only way to improve on slinks is to get rid of FSs (Score:3, Interesting) The only way to really improve on symlinks is to get rid of file systems, and use a database instead. Symlinks are useful for simulating database views anyway. The purpose of using a computer is to manage information, and not binary data. Files are relics of the past. Operating systems should have databases for managing persistence. Benefits whould be tremendous: The Fix: Aliases (Score:4, Informative) Not the first time (Score:3, Interesting) The evidence is no longer on MS's website put you can find it here [spinnwebe.com] Already has this (Score:3, Informative) Reparse points (like links) Junctions (to mount file systems) Sparse files (highly underutilized) and of course the plain old short cuts that are really symbolic links in the traditional unix world. I remember architecting a product to implement all unix based functionality in NT (IPC, memory mapped files, etc) and found NT40 to have that and more. Thats the time I really appreciated windows as a OS more mature than Unix. The unfortunate part is people still think of DOS/Win95 code base when they think of windows. As a OS, W2K is much more mature in terms of the facilities they offer and as a filesystem, NTFS is way ahead. Give me a feature in Unix and Im sure there is an equivalent in NT. Thousands of smart people working at Redmond are not idiots and millions of corporate architects proposing NT based solutions are not stupid either. They propose windows based technologies not just for looks (though end users do appreciate that). Re:Already has this (Score:4, Insightful) and of course the plain old short cuts that are really symbolic links in the traditional unix world. Try sharing that shortcut over Samba. Didn't work you say? Then, absolutely nothing UNIX-like about it. The unfortunate part is people still think of DOS/Win95 I use Windows XP and it still has lots of shortcomings. However it's multimedia support is waay ahead of Linux, and I use my machine mainly for multimedia. So whatever criticism I may serve, that's based on WinXP and modern Redmond-OSes. Give me a feature in Unix and Im sure there is an equivalent in NT. You'd think any serious server-OS would implement this... A reinstall with the textmode interface doesn't count. For whatever reason, increased security, lightweight editions, added native FS support... Just to list a few. I do however have a job to do :-D This is rich (Score:3, Funny) Vista escapes the Matrix (Score:3, Funny) *nix Developer 1: He still needs a lot of work. Vista: What are you doing? *nix Developer 2: Your source code has atrophied, we're rebuilding them. Vista: Why do the symbolic links in my file system hurt? Vista blinks *nix Developer 2 : You've never used them before. Vista looks confused *nix Developer 2 : Rest, Vista, the answers are coming. Vista passes out again. Re:Ah yes (Score:2) No. (Score:5, Informative) Re:Ah yes (Score:5, Interesting) The basis of it is that a shortcut is just a file - the exact same thing as a shortcut can be achieved by having a file with the target path just written in ascii inside, and assuming that the reader can tell it's a shortcut then it could get the target path sure, but if the reader is not equiped to specifically handle those shortcuts then it'll get muck. A symlink masquerades as the actual file or folder, and the app doesn't need any specific handling to read the file. You can for example go into bash and write "cd symlink/" and it'll go to that folder. A shortcut is just a file, a symlink is an attribute of the filesystem. Re:Ah yes (Score:5, Insightful) When shortcuts were invented for Win95 the Win32 API should have been built to treat a shortcut as the object it pointed to. That way they would have had real working links up front. Now they are going to be stuck with two types of link which work in different ways. Re:useful? really? (Score:3, Informative) Man, you need to use symlinks to see how useful they are. As someone pointed before, symlinks are great to create compilations of files on a directory. Also, they are very useful if you want to use different types of libraries (DLLs) on different programs (in different directoires). As for the "average user", as someone else said also, this s Re:We can only hope (Score:5, Informative) Re:We can only hope (Score:3, Insightful) I wonder if this attitude leads to all those race conditions when creating files in Re:We can only hope (Score:3, Informative) >supposed to do? >It can: > > * Close the program (= Possible data loss) > * Slow the speed at which the program is allowed to access certain files (= Increase >the chance of race conditions, sometimes by a lot. It doesn't really solve anything >either) > * Make the symlinks "disappear" after a certain level of recursion (= Inconsistent data) > * Do nothing (= Solves nothing) WTF..... The an Re:We can only hope (Score:3, Informative) MS did it to themselves (Score:3, Insightful) Microsoft brought this on themselves by running around calling themselves "innovative" pretty much several times per sentence during the anti-trust trial, and then continuing with an ongoing PR campaign that still today tries to paint them as being a truly "innovative" company. If you go call yourself innovative, and then proceed to produce a new "modern" operating system for 2006/7 whose primary advancements are all features that were commonplace in many other products anywhere from five up to nearly thirt Mac OS X already does it the RIGHT way. (Score:3, Informative) Mac OS X (and all the way back to System 7 in 1990) did it right by creating aliases which use a two-factor plan to locate its target:
http://it.slashdot.org/story/05/10/31/0657217/vista-to-get-symlinks?sdsrc=prevbtmprev
CC-MAIN-2015-35
refinedweb
4,431
62.68
John Lakos Mentioned 72 am looking for the definition of when I am allowed to do forward declaration of a class in another class's header file: Am I allowed to do it for a base class, for a class held as a member, for a class passed to member function by reference, etc. ? In a C++ project I'm working on, I have a flag kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be: Now, for each record I wish to keep this attribute, so I could use an enum: enum { xNew, xDeleted, xModified, xExisting } However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: showRecords(xNew | xDeleted); So, it seems I have three possible appoaches: #define X_NEW 0x01 #define X_DELETED 0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08 or typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; or namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8; } Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with enum I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With const I think I also lose type safety since a random uint8 could get in by mistake. Is there some other cleaner way? If not, what would you use and why? P.S. The rest of the code is rather clean modern C++ without #defines, and I have used namespaces and templates in few spaces, so those aren't out of question either. Based on KISS, high cohesion and low coupling, ask these questions - There is a great book "Large-Scale C++ Software Design", this promotes base types externally, if you can avoid another header file/interface dependancy you should try to. I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp file. Are there any good tools for detecting both of these cases? If you're interested in this topic in general, you might want to check out Lakos' Large Scale C++ Software Design. It's a bit dated, but goes into lots of "physical design" issues like finding the absolute minimum of headers that need to be included. I haven't really seen this sort of thing discussed anywhere else. So I finished my first C++ programming assignment and received my grade. But according to the grading, I lost marks for including cpp files instead of compiling and linking them. I'm not too clear on what that means. Taking a look back at my code, I chose not to create header files for my classes, but did everything in the cpp files (it seemed to work fine without header files...). I'm guessing that the grader meant that I wrote '#include "mycppfile.cpp";' in some of my files. My reasoning for #include'ing the cpp files was: - Everything that was supposed to go into the header file was in my cpp file, so I pretended it was like a header file - In monkey-see-monkey do fashion, I saw that other header files were #include'd in the files, so I did the same for my cpp file. So what exactly did I do wrong, and why is it bad? I will suggest you to go through Large Scale C++ Software Design by John Lakos. In the college, we usually write small projects where we do not come across such problems. The book highlights the importance of separating interfaces and the implementations. Header files usually have interfaces which are supposed not to be changed so frequently. Similarly a look into patterns like Virtual Constructor idiom will help you grasp the concept further. I am still learning like you :) We have a large, multi-platform application written in C. (with a small but growing amount of C++) It has evolved over the years with many features you would expect in a large C/C++ application: #ifdefhell Since this code is targeted for embedded devices, it's a lot of overhead to run it on the actual target. So we would like to do more of our development and testing in quick cycles, on a local system. But we would like to avoid the classic strategy of "copy/paste into a .c file on your system, fix bugs, copy/paste back". If developers are going to to go the trouble to do that, we'd like to be able to recreate the same tests later, and run in an automated fashion. Here's our problem: in order to refactor the code to be more modular, we need it to be more testable. But in order to introduce automated unit tests, we need it to be more modular. One problem is that since our files are so large, we might have a function inside a file that calls a function in the same file that we need to stub out to make a good unit test. It seems like this would be less of a problem as our code gets more modular, but that is a long way off. One thing we thought about doing was tagging "known to be testable" source code with comments. Then we could write a script scan source files for testable code, compile it in a separate file, and link it with the unit tests. We could slowly introduce the unit tests as we fix defects and add more functionality. However, there is concern that maintaining this scheme (along with all the required stub functions) will become too much of a hassle, and developers will stop maintaining the unit tests. So another approach is to use a tool that automatically generates stubs for all the code, and link the file with that. (the only tool we have found that will do this is an expensive commercial product) But this approach seems to require that all our code be more modular before we can even begin, since only the external calls can be stubbed out. Personally, I would rather have developers think about their external dependencies and intelligently write their own stubs. But this could be overwhelming to stub out all the dependencies for a horribly overgrown, 10,000 line file. It might be difficult to convince developers that they need to maintain stubs for all their external dependencies, but is that the right way to do it? (One other argument I've heard is that the maintainer of a subsystem should maintain the stubs for their subsystem. But I wonder if "forcing" developers to write their own stubs would lead to better unit testing?) The #ifdefs, of course, add another whole dimension to the problem. We have looked at several C/C++ based unit test frameworks, and there are a lot of options that look fine. But we have not found anything to ease the transition from "hairball of code with no unit tests" to "unit-testable code". So here are my questions to anyone else who has been through this: Note, our build environment is Linux/UNIX based, so we can't use any Windows-only tools. G'day, I'd start by having a look at any obvious points, e.g. using dec's in header files for one. Then start looking at how the code has been laid out. Is it logical? Maybe start breaking large files down into smaller ones. Maybe grab a copy of Jon Lakos's excellent book "Large-Scale C++ Software Design" (sanitised Amazon link) to get some ideas on how it should be laid out. Once you start getting a bit more faith in the code base itself, i.e. code layout as in file layout, and have cleared up some of the bad smells, e.g. using dec's in header files, then you can start picking out some functionality that you can use to start writing your unit tests. Pick a good platform, I like CUnit and CPPUnit, and go from there. It's going to be a long, slow journey though. HTH cheers, Michael Feathers wrote the bible on this, Working Effectively with Legacy Code: Reading the reviews at Amazon and ACCU suggests that John Lakos' book, Large-Scale C++ Software Design may be the Rosetta Stone for modularization. At the same time, the book seems to be really rare: not many have ever read it, and no pirate electronic copies are floating around. So, what do you think? [Since this is Number 3 at Google search for the book title, left my vote for reopening, it would be a pity to loose all the helpful discussion here (which I always thought was the place right for it).] I've read it, and consider it a very useful book on some practical issues with large C++ projects. If you have already read a lot about C++, and know a bit about physical design and its implications, you may not find that much which is terribly "new" in this book. On the other hand, if your build takes 4 hours, and you don't know how to whittle it down, get a copy, read it, and take it all in. You'll start writing physically better code quite quickly. [Edit] If you want to start somewhere, and can't immediately get a hold of the book, I found the Games From Within series on physical structure useful even after reading Large Scale C++ design. Interestingly, "More C++ Gems" contains a shortened (to 88(!) pages) version of Lakos' book, which can also be browsed (fully, I believe, as it belongs to the first half of the book) online at Google books. So, enjoy everyone interested:) What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice? Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first. Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else. This then means that you can answer your question any way you like. It doesn't matter what order you include them in. For further great tips, try this book: Large-Scale C++ Software Design - it's a shame it's so expensive, but it is practically a survival guide for C++ source code layout. I just noticed a new term pimpl idiom, what's the difference between this idiom with Bridge design pattern? I am confused about that. I also noticed the pimpl idiom is always used for swap function, what's that? Could anybody give me an example? PIMPL is a way of hiding the implementation, primarily to break compilation dependencies. The Bridge pattern, on the other hand, is a way of supporting multiple implementations. swap is a standard C++ function for exchanging the values of two objects. If you swap the pointer to the implementation for a different implementation, you are essentially changing the mechanism of the class at runtime. But in its basic and common form, a class using PIMPL points to a single implementation, so there is no abstract class with distinct subclasses — just one class, forward declared, and compiled elsewhere. Changing the implementation class does not require any recompilation of sources that include the main header. For example, say you have a lot of private member functions, private enums, and private data. And these private "bits" change fairly frequently as the class is developed and maintained. If the #include dependencies are such that touching this header file causes a large number of sources to be recompiled, you have a good candidate for PIMPL. So the Bridge pattern is about object-oriented design, while the PIMPL idiom is about physical design of files. (For more on physical design, I recommend the book Large-Scale C++ Software Design by John Lakos.) I once worked on a C++ project that took about an hour and a half for a full rebuild. Small edit, build, test cycles took about 5 to 10 minutes. It was an unproductive nightmare. What is the worst build times you ever had to handle? What strategies have you used to improve build times on large projects? Update: How much do you think the language used is to blame for the problem? I think C++ is prone to massive dependencies on large projects, which often means even simple changes to the source code can result in a massive rebuild. Which language do you think copes with large project dependency issues best? The best suggestion is to build makefiles that actually understand dependencies and do not automatically rebuild the world for a small change. But, if a full rebuild takes 90 minutes, and a small rebuild takes 5-10 minutes, odds are good that your build system already does that. Can the build be done in parallel? Either with multiple cores, or with multiple servers? Checkin pre-compiled bits for pieces that really are static and do not need to be rebuilt every time. 3rd party tools/libraries that are used, but not altered are a good candidate for this treatment. Limit the build to a single 'stream' if applicable. The 'full product' might include things like a debug version, or both 32 and 64 bit versions, or may include help files or man pages that are derived/built every time. Removing components that are not necessary for development can dramatically reduce the build time. Does the build also package the product? Is that really required for development and testing? Does the build incorporate some basic sanity tests that can be skipped? Finally, you can re-factor the code base to be more modular and to have fewer dependencies. Large Scale C++ Software Design is an excellent reference for learning to decouple large software products into something that is easier to maintain and faster to build. EDIT: Building on a local filesystem as opposed to a NFS mounted filesystem can also dramatically speed up build times. This book Large-Scale C++ Software Design has very good advice I've used in past projects. For OOP languages, there are many books describing how to design software, and design patterns are mainly for OOP languages. I am wondering whether there are any books/good articles teaching how to use C in a big project, like it is a good practice to use static functions when this function is only used in a single file. You must read Expert C Programming by Peter van der Linden. Code Complete 1st Ed by Steve McConell is more oriented towards C, that may be worth a look as well. At any rate his books are great reading for any professional programmer. G'day, While heavily focused on C++, John Lakos's excellent book "Large-Scale C++ Software Design" has a lot of information that is very relevant to the design of software written in C. Edit: Oooh. After seeing @Jackson's suggestion for the excellent "The Practice of Programming" I'd also highly recommend Eric Raymond's excellent book "The Art of UNIX Programming.". Thanks for the reminder @Jackson. HTH cheers,. I'm currently reviewing a very old C++ project and see lots of code duplication there. For example, there is a class with 5 MFC message handlers each holding 10 identical lines of code. Or there is a 5-line snippet for a very specific string transformation every here and there. Reducing code duplication is not a problem in these cases at all. But I have a strange feeling that I might be misunderstanding something and that there was originally a reason for this duplication. What could be a valid reason for duplicating code? A good read about this is large scale c++ software design by John Lakos. He has many good points about code duplication, where it might help or hinder a project. The most important point is asking when deciding to remove duplication or duplicate code: If this method changes in the future, do I want to change the behaviour in the duplicated method, or needs it to stay the way it is? After all, methods contain (business) logic, and sometimes you'll want to change the logic for every caller, sometimes not. Depends on the circumstances. In the end, it's all about maintenance, not about pretty source. I am very interested in some studies or empirical data that shows a comparison of compilation times between two c++ projects that are the same except one uses forward declarations where possible and the other uses none. How drastically can forward declarations change compilation time as compared to full includes? #include "myClass.h" vs. class myClass; Are there any studies that examine this? I realize that this is a vague question that greatly depends on the project. I don't expect a hard number for an answer. Rather, I'm hoping someone may be able to direct me to a study about this. The project I'm specifically worried about has about 1200 files. Each cpp on average has 5 headers included. Each header has on average 5 headers included. This regresses about 4 levels deep. It would seem that for each cpp compiled, around 300 headers must be opened and parsed, some many times. (There are many duplicates in the include tree.) There are guards, but the files are still opened. Each cpp is separately compiled with gcc, so there's no header caching. To be sure no one misunderstands, I certainly advocate using forward declarations where possible. My employer, however, has banned them. I'm trying to argue against that position. Thank you for any information. #include "myClass.h" is 1..n lines class myClass; is 1 line. You will save time unless all your headers are 1 liners. As there is no impact on the compilation itself (forward reference is just way to say to the compiler that a specific symbol will be defined at link time, and will be possible only if the compiler doesnt need data from that symbol (data size for example)), the reading time of the files included will be saved everytime you replace one by forward references. There's not a regular measure for this as it is a per project value, but it is a recommended practice for large c++ projects (See Large-Scale C++ Software Design / John Lakos for more info about tricks to manage large projects in c++ even if some of them are dated) Another way to limit the time passed by the compiler on headers is pre-compiled headers. Have a look in John Lakos's excellent Large Scale C++ Design book -- I think he has some figures for forward declaration by looking at what happens if you include N headers M levels deep. If you don't use forward declarations, then aside from increasing the total build time from a clean source tree, it also vastly increases the incremental build time because header files are being included unnecessarily. Say you have 4 classes, A, B, C and D. C uses A and B in its implementation (ie in C.cpp) and D uses C in its implementation. The interface of D is forced to include C.h because of this 'no forward declaration' rule. Similarly C.h is forced to include A.h and B.h, so whenever A or B is changed, D.cpp has to be rebuilt even though it has no direct dependency. As the project scales up this means that if you touch any header it'll have a massive effect on causing huge amounts of code to be rebuilt that just doesn't need to be. To have a rule that disallows forward declaration is (in my book) very bad practice indeed. It's going to waste huge amounts of time for the developers for no gain. The general rule of thumb should be that if the interface of class B depends on class A then it should include A.h, otherwise forward declare it. In practice 'depends on' means inherits from, uses as a member variable or 'uses any methods of'. The Pimpl idiom is a widespread and well understood method for hiding the implementation from the interface and allows you to vastly reduce the amount of rebuilding needed in your codebase. If you can't find the figures from Lakos then I would suggest creating your own experiments and taking timings to prove to your management that this rule is absolutely wrong-headed. I have seen many explanations on when to use forward declarations over including header files, but few of them go into why it is important to do so. Some of the reasons I have seen include the following: Coming from a .net background I find header management frustrating. I have this feeling I need to master forward declarations, but I have been scrapping by on includes so far. Why cannot the compiler work for me and figure out my dependencies using one mechanism (includes)? How do forward declarations speed up compilations since at some point the object referenced will need to be compiled? I can buy the argument for reduced complexity, but what would a practical example of this be? How do forward declarations speed up compilations since at some point the object referenced will need to be compiled? 1) reduced disk i/o (fewer files to open, fewer times) 2) reduced memory/cpu usage most translations need only a name. if you use/allocate the object, you'll need its declaration. this is probably where it will click for you: each file you compile compiles what is visible in its translation. a poorly maintained system will end up including a ton of stuff it does not need - then this gets compiled for every file it sees. by using forwards where possible, you can bypass that, and significantly reduce the number of times a public interface (and all of its included dependencies) must be compiled. that is to say: the content of the header won't be compiled once. it will be compiled over and over. everything in this translation must be parsed, checked that it's a valid program, checked for warnings, optimized, etc. many, many times. including lazily only adds significant disk/cpu/memory increase, which turns into intolerable build times for you, while introducing significant dependencies (in non-trivial projects). I can buy the argument for reduced complexity, but what would a practical example of this be? unnecessary includes introduce dependencies as side effects. when you edit an include (necessary or not), then every file which includes it must be recompiled (not trivial when hundreds of thousands of files must be unnecessarily opened and compiled). Lakos wrote a good book which covers this in detail: am working on a large project that uses the STL and have a question about your preferred way to organise your STL #includes. foo.cppand bar.cpprequire std::string, then both will #include <string>. The advantage of the first method is that the .cpp file is an independent unit and can be used in a different project without having to worry that you're missing a #include. The advantages of the second method is that you can take use your compilers pre-compiled header support plus you can wrap STL #includes in pragmas that disable some warnings (for example, some Boost headers will cause warnings when compiling at level 4). Which do you prefer to use? I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible. Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So even if something gets declared via the included precompiled headers, I still include the 'regular' header, which will get skipped by the include guard mechanism and won't add anything significant to the compile times. As precompiled headers are a compiler specific thing. Optimizing / changing precompiled headers should have no effect on the correct functioning of the code in my opinion. The main advantage of having dependencies as low as possible is that refactoring gets easier (or rather: feasible) Great book on all this is Large Scale C++ Design from Lakos. One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private members (add a cache-variable, extract a private method, ...). The problem you are facing is that in C++, even private members are declared in the public header file, so your build system needs to recompile everything. What do you do in this situation? I have sketched two solutions which I know of, but they both have their downsides, and maybe there is a better one I have not yet thought of. John Lakos' Large Scale C++ Software Design is an excellent book that addresses the challenges involved in building large C++ projects. The problems and solutions are all grounded in reality, and certainly the above problem is discussed at length. Highly recommended. Are function declarations/prototypes necessary in C99 ? I am currently defining my functions in a header file and #include-ING it in the main file. Is this OK in C99 ? Why do most programmers declare/prototype the function before main() and define it after main() ? Isn't it just easier to define them before main and avoid all the declarations/prototypes ? Contents of header.h file: int foo(int foo) { // code return 1; } Contents of main file: #include <stdio.h> #include "header.h" int main(void) { foo(1); return 0; } How and where to prototype and define a function in C : Your function is used only in a specific .c file : Define it static in the .c file. The function will only be visible and compiled for this file. Your function is used in multiple .c files : Choose an appropriate c file to host your definition (All foo related functions in a foo.c file for example), and have a related header file to have all non-static (think public) functions prototyped. The function will be compiled only once, but visible to any file that includes the header files. Everything will be put together at link time. Possible improvement : always make the related header file, the first one included in its c file, this way, you will be sure that any file can include it safely without the need of other includes to make it work, reference : Large Scale C++ projects (Most of the rules apply to C too). Your function is inlinable (are you sure it is ?) : Define the function static inline in an appropriate header file. The compiler should replace any call to your function by the definition if it is possible (think macro-like). The notion of before-after another function (your main function) in c is only a matter of style. Either you do : static int foo(int foo) { // code return 1; } int main(void) { foo(1); return 0; } Or static int foo(int foo); int main(void) { foo(1); return 0; } static int foo(int foo) { // code return 1; } will result in the same program. The second way is prefered by programmers because you don`t have to reorganize or declare new prototypes every time you declare a new function that use the other ones. Plus you get a nice list of every functions declared in your file. It makes life easier in the long run for you and your team. In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules? Also take a look at: Large-Scale C++ Software Design (Addison-Wesley Professional Computing Series) Recently I've been writing code similar to this: messagehandler.h: #include "message.h" class MessageHandler { public: virtual ~MessageHandler() {} virtual void HandleMessage(Message *msg) = 0: }; persistmessagehandler.h: MessageHandler *CreatePersistMessageHandler(); persistmessagehandler.cpp: #include "messagehandler.h" #include "persist.h" class PersistMessageHandler : public MessageHandler { private: PersistHandle ph; size_t count; InternalCheck(); public: PersistMessageHandler(int someParam); virtual ~PersistMessageHandler (); virtual void HandleMessage(Message *msg): }; PersistMessageHandler::PersistMessageHandler(int someParam) { ph.Initialize(); } ... rest of implementation. MessageHandler *CreatePersistMessageHandler(int someParam) { return new PersistMessageHandler(someParam); } The reasoning here is to hide the PersistMessageHandler. Clients don't need to include a header for the PersistMessageHandler class, with all the includes and types the implementation might need, and to more cleanly seperate the interface and implementation. . It'll always be dynamically allocated anyway, All PersistMessageHandler users will just call CreatePersistMessageHandler(..); directly or indirectly get one from a factory. But. I've not seen this approach used much elsewhere. Is the above good practice ? Are there other/better alternatives for simple cases ? The process of hiding the implementation details is called Encapsulation. The process of minimizing build dependencies for your users is called Insulation. There is a great (but aging) book by John Lakos devoted to both topics: can deal with only the easiest case, when there are only 2 modules A and B A is dependant on B, so I build B as a library and include B's header file in A, also link to B library when building A. This won't work when A and B are inter-dependant, and even worse when the number of modules grow .. So what's the general way to carry out modularized development in c/c++? UPDATE Sorry, seems my title is inacurate, the rephrased version is: how can I divide a module into many .h and .cpp files(not a single one)? The solution is to make sure your modules form a directed acyclic graph... I.e. if A depends on B, make sure B doesn't depend on A. It takes a lot of discipline but is worth it in the long run. If you are interested in this stuff, Large Scale C++ Software Design is a good read. I'm thinking specifically of the Strategy pattern (Design Patterns, GoF94), where it is suggested that the context passed to the strategy constructor can be the object which contains the strategy (as a member) itself. But the following won't work: //analysis.h class StrategyBase; class Strategy1; class Strategy2; class Analysis { ... void ChooseStrategy(); private: StrategyBase* _s; ... }; //analysis.cpp void Analysis::ChooseStrategy() { if (...) _s = new Strategy1(this); else if (...) _s = new Strategy2(this); ... } //strategy.h #include analysis.h ... and then StrategyBase and its subclasses then access the data members of Analysis. This won't work because you can't instantiate Strategy* classes before they've been defined. But its definition depends on that of Analysis. So how are you supposed to do this? Replace ChooseStrategy with void SetStrategy(StrategyBase* s) { _s = s; } and do the instantiation in files which #include both analysis.h and strategy.h? What's best practice here? You will always have circular dependencies in the State/Strategy Pattern, except for very general States/Strategies. But you can limit the in-size (Lakos) use of the respective other class such that it compiles, at least: Analysis( analysis.hor strategies.h) StrategyBaseand subclasses (don't inline methods that use Analysis) ( strategies.h) Analysis(may already use inline methods that use strategies) ( analysis.h) Analysisand the strategy classes' non-inline methods ( analysis.cpp).... When I do a fresh compilation for my project, which includes 10+ open-source libs. It takes about 40mins. (on normal hardware) Question: where really are my bottle necks at? hard-drive seeking or CPU Ghz? I don't think multi-core would help much correct? --Edit 1-- my normal hardware = i3 oc to 4.0Ghz, 8GB 1600Mhz DDR3 and a 2tb Western digital --Edit 2-- my code = 10%, libs = 90%, I know I dont have to build everything everytime, but I would like to find out how to improve compiling performance, so when buying new pc for developer, I would make a smarter choice. --Edit 3-- cc = Visual Studio (damn) multicore compilation will help, tremendously in most cases. you'll have to analyze your projects, and the time spent in each phase in order to determine where the bottlenecks are. in typical large c++ projects, the process is typically CPU bound, then disk bound. if it's the other way around, you're probably in header dependency hell. there's actually a ton of ways to reduce compile times and dependency in your projects. the best singular reference i know of is by Lakos: it's one of the most important/practical c++ books i've read. you can typically reduce compile times dramatically (e.g, over 40x faster if you take it very seriously), but may take a lot of work/time to correct existing codebases. An aspect of C++ that periodically frustrates me is deciding where templates fit between header files (traditionally describing the interface) and implemention (.cpp) files. Templates often need to go in the header, exposing the implementation and sometimes pulling in extra headers which previously only needed to be included in the .cpp file. I encountered this problem yet again recently, and a simplified example of it is shown below. #include <iostream> // for ~Counter() and countAndPrint() class Counter { unsigned int count_; public: Counter() : count_(0) {} virtual ~Counter(); template<class T> void countAndPrint(const T&a); }; Counter::~Counter() { std::cout << "total count=" << count_ << "\n"; } template<class T> void Counter::countAndPrint(const T&a) { ++count_; std::cout << "counted: "<< a << "\n"; } // Simple example class to use with Counter::countAndPrint class IntPair { int a_; int b_; public: IntPair(int a, int b) : a_(a), b_(b) {} friend std::ostream & operator<<(std::ostream &o, const IntPair &ip) { return o << "(" << ip.a_ << "," << ip.b_ << ")"; } }; int main() { Counter ex; int i = 5; ex.countAndPrint(i); double d=3.2; ex.countAndPrint(d); IntPair ip(2,4); ex.countAndPrint(ip); } Note that I intend to use my actual class as a base class, hence the virtual destructor; I doubt it matters, but I've left it in Counter just in case. The resulting output from the above is counted: 5 counted: 3.2 counted: (2,4) total count=3 Now Counter's class declaration could all go in a header file (e.g., counter.h). I can put the implementation of the dtor, which requires iostream, into counter.cpp. But what to do for the member function template countAndPrint(), which also uses iostream? It's no use in counter.cpp since it needs to be instantiated outside of the compiled counter.o. But putting it in counter.h means that anything including counter.h also in turn includes iostream, which just seems wrong (and I accept that I may just have to get over this aversion). I could also put the template code into a separate file (counter.t?), but that would be a bit surprising to other users of the code. Lakos doesn't really go into this as much as I'd like, and the C++ FAQ doesn't go into best practice. So what I'm after is: A rule of thumb (the reason of which should be clear). You can often avoid having to include lots of headers by making names be dependent, thus delaying lookup and/or determination of their meaning. This way, you need the complete set of headers only at the point of instantiation. As an example #include <iosfwd> // suffices class Counter { unsigned int count_; public: Counter() : count_(0) {} virtual ~Counter(); // in the .cpp file, this returns std::cout std::ostream &getcout(); // makes a type artificially dependent template<typename T, typename> struct ignore { typedef T type; }; template<class T> void countAndPrint(const T&a) { typename ignore<std::ostream, T>::type &cout = getcout(); cout << count_; } }; This is what I used for implementing a visitor pattern that uses CRTP. It looked like this initially template<typename Derived> struct Visitor { Derived *getd() { return static_cast<Derived*>(this); } void visit(Stmt *s) { switch(s->getKind()) { case IfStmtKind: { getd()->visitStmt(static_cast<IfStmt*>(s)); break; } case WhileStmtKind: { getd()->visitStmt(static_cast<WhileStmt*>(s)); break; } // ... } } }; This will need the headers of all statement classes because of those static casts. So I have made the types be dependent, and then I only need forward declarations template<typename T, typename> struct ignore { typedef T type; }; template<typename Derived> struct Visitor { Derived *getd() { return static_cast<Derived*>(this); } void visit(Stmt *s) { typename ignore<Stmt, Derived>::type *sd = s; switch(s->getKind()) { case IfStmtKind: { getd()->visitStmt(static_cast<IfStmt*>(sd)); break; } case WhileStmtKind: { getd()->visitStmt(static_cast<WhileStmt*>(sd)); break; } // ... } } }; I am using SUSE10 (64 bit)/AIX (5.1) and HP I64 (11.3) to compile my application. Just to give some background, my application has around 200KLOC (2Lacs) lines of code (without templates). It is purely C++ code. From measurements, I see that compile time ranges from 45 minutes(SUSE) to around 75 minutes(AIX). Question 1 : Is this time normal (acceptable)? Question 2 : I want to re-engineer the code arrangement and reduce the compile time. Is there any GNU tool which can help me to do this? PS : a. Most of the question in stackoverflow was related to Visual Studio, so I had to post a separate question. b. I use gcc 4.1.2 version. c. Another info (which might be useful) is code is spread across around 130 .cpp files but code distribution varies from 1KLOC to 8 KLOCK in a file. Thanks in advance for you help!!! Edit 1 (after comments) @PaulR "Are you using makefiles for this ? Do you always do a full (clean) build or just build incrementally ?" Yes we are using make files for project building. Sometimes we are forced to do the full build (like over-night build/run or automated run or refresh complete code since many members have changed many files). So I have posted in general sense. Read John Lakos's Large-Scale C++ Design for some very good methods of analysing and re-organising the structure of the project in order to minimise dependencies. Ultimately the time taken to build a large project increases as the amount of code increases, but also as the dependencies increase (or at least the impact of changes to header files increases as the dependencies increase). So minimising those dependencies is one thing to aim for. Lakos's concept of Levelization is very helpful in working out how to split several large monolothic inter-dependent libraries into something with a much better structure. From Large-Scale C++ Software Design (Lakos), page 652: The question is, "In which unique translation unit will the compiler deposit the virtual table definition(s) for a given class?". The trick employed by CFRONT (and many other C++ implementations) is to place the external virtual tables in the translation unit that defines the lexically first non-inline function that appears in the class (if one exists). Is this still the case with the most used compilers (GCC and Visual C++)? Or was it ever? GCC happens to document that it behaves as described in the question (): VTables will still be emitted in every translation unit which defines it. Make sure that any inline virtuals are declared inline in the class body, even if they are not defined there. However, even in situations where there might be several vtables across several object files (as can happen if the 'key method' turns out to be inline), the compiler arranges for the duplicates to be ignored if possible, but the duplicates may end up using space in the final binary if the target doesn't support COMDAT:. FWIW, GCC seems to use a symbol that starts with __ZTV for the vtable. As far as MSVC is concerned, some empirical testing with VC++10 (I don't think MS documents the behavior) shows that it seems that VC doesn't attempt to limit the vtable to a single object file. Since Microsoft knows that it can rely on the linker supporting COMDAT sections and since constructors are the only functions that use a vtable directly (all other vtable uses are indirect through the object pointer, I believe), it looks like VC just places a copy of the vtable in any object file where a constructor is instantiated. For classes that use the compiler generated ctor, that would be anywhere an object of that type is constructed. How do I turn one file with lots of classes to many files with one class per file? (C\C++) So I have that file with such structure: Some includes and then lots of classes that sometimes call each other: #include <wchar.h> #include <stdlib.h> //... class PG_1 { //... } class PG_2 { //... } //...... class PG_N { //... } There might not be an easy way to do this. The problem is you have to get the #includes right, split the code correctly to different header and cpp files, and if your classes have cyclic dependencies among themselves, you have to deal with them correctly, or better, try to resolve those dependencies to make them non-cyclic. Best suggestion I can give you: first try to do this manually for two or three classes. Then decide what kind of physical class layout you need. Afterwards, try to write a program. Don't try to write a program unless you fully understand what to do. By the way, how many classes/files do have? EDIT: To get a better notion of what a good physical class-to-file layout may be, I suggest to read Large Scale C++ Design from John Lakos. Is a little bit outdated, since it contains nothing about precompiled headers, but still useful. I'm currently in the process of trying to organize my code in better way. To do that I used namespaces, grouping classes by components, each having a defined role and a few interfaces (actually Abstract classes). I found it to be pretty good, especially when I had to rewrite an entire component and I did with almost no impact on the others. (I believe it would have been a lot more difficult with a bunch of mixed-up classes and methods) Yet I'm not 100% happy with it. Especially I'd like to do a better separation between interfaces, the public face of the components, and their implementations in behind. I think the 'interface' of the component itself should be clearer, I mean a new comer should understand easily what interfaces he must implement, what interfaces he can use and what's part of the implementation. Soon I'll start a bigger project involving up to 5 devs, and I'd like to be clear in my mind on that point. So what about you? how do you do it? how do you organize your code? You might find some of the suggestions in Large Scale C++ Software Design useful. It's a bit dated (published in 1996) but still valuable, with pointers on structuring code to minimize the "recompiling the world when a single header file changes" problem. I would like to know about books that talk about design issues like when to use namespaces and other coding standards to write good quality efficient C++ code. One that talks about Code testing will also be appreciated. book about refactoring: "Large-Scale C++ Software Design" by John Lakos worked great for me years ago on how to organise code in large projects. On testing, this is not my area, and I cannot recommend a great book. What I can do is discourage you from getting "Testing Computer Software", 2nd edition by Cem Kaner, Jack Falk and Hung Q. Nguyen. I found it severely dated and extremely clumsy. But please take this with a grain of salt. For big projects, it is essential to follow a common design and coding style. Consistently. I found the following book useful to have a common ground in a big project. C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Andrei Alexandrescu, Herb Sutter My C++ application depends on Boost. I'd like someone to just be able to check out my repository and build the whole thing in one step. But the boost distribution is some 100MB and thousands of files, and it seems to bog down source control -- plus I really don't need it to be versioned. What's the best way to handle this kind of problem? I've found the book "Large-Scale C++ Software Design" by John Lakos very useful as far as organising large C++ projects is concerned. Recommended.). Does including the same header files multiple times increase the compilation time? For example, suppose every file in my project uses <iostream> <string> <vector> and <algorithm>. And if I include a lot of files in my source code, then does that increase the compile time? I always thought that the guard headers served important purpose of avoiding double definitions but as a by product also eliminates double code. Actually, someone I know proposed some ideas to remove such multiple inclusions. However, I consider them to be completely against the good design practices in c++. But was still wondering what might be the reasons of him to suggest the changes? If compile times were an issue, people used to use the optimisation recommended by Praetorian, originally recommened in Large Scale Software Design. However, most modern compilers automatically optimise for this case. For example, see the help from gcc I am looking for instructional materials on object-oriented software design that are framed as extended examples. In other words, over the course of several lessons or chapters, the author would develop a moderately large piece of software and explain the design approach step by step. Ideally, the material would address not only the design of the primary software being built but also offer useful advice on the rest of the development process -- testing, deployment, etc. This is indispensable for understanding large scale oo design. In though its implemented in c++ the concepts are completely general and can be used effectively on any platform: Large Scale OO Design Truly a classic!! I was wondering whether anyone had any good resources (papers/articles/book references) on compile/linking optimizations. I had worked in two companies that performed their linking operations differently. Both have their advantages/disadvantages and I was hoping on writing a paper for my school report on this subject and just looking for material. Thanks! Large Scale C++ Software Design is a good reference for this kind of stuff. My c++ program is using a separate header file (Let's call it myHeader.h) and therefore includes it ( #include "myHeader.h"). In my program I need to use another header file (Let's call it another.h). Does it make a difference whether I put the #include "another.h" directive in the cpp file or in myHeader.h? There is a difference - every time your h file is included, any files included in that h file are included as well - I haven't kept up-to-date with modern C++ compilers, but this used to really increase compile time. It also increases the physical dependency of the source - John Lakos' Large Scale C++ Software Design addresses this, and is well worth a read on structuring c++ programs. It's published in 1996, so it's not based around current practice, but the advise on structure is worth knowing. Should all c++ code in a project be encapsulated into a single class with main simply calling that class? Or should the main function declare variables and classes. If you are going to build a large project in C++, you should at the very least read Large Scale C++ Software Design by John Lakos about it. It's a little old but it sounds like you could benefit from the fundamentals in it. Keep in mind that building a large scale system in any language is a challenge and requires skill and discipline to prevent it falling to pieces very quickly. Don't take it lightly. That said, if your definition of "large" is different than mine than I may have alternative advice to give you. I'm assuming you're talking about a project where the word "million" will be mentioned in sentences that also contain the words "lines of code". We're creating very complex embedded system and «sources» contains few projects of Visual C++, IAR, Code Composer Studio and Altium Designer schemes and pcbs. All of that possibly could be in few versions. So, what practice could you advice me to arrange all that stuff? Thank you If your C++ source files are numerous and span multiple directories then the effort put into grokking Large Scale C++ Software Design by John Lakos may be very worth it. The main theme of the book is how your physical layout of the software, that is, the arrangement of source code files in directories, limit or extend your ability to modify the software. For many years, I have been re-reading John Lakos's classic Large-Scale C++ Software Design. Not only it was the first guidebook of this kind, but it also revolutionized how to develop a project in C++, in an efficient fashion to this day! Do you feel his ideas are outdated now? Some C++ techniques in the book are in fact old (don't forget that book has been written before the latest standard was published) . What's a good authority to guide building of a big system in C++ nowadays. Don't get me wrong, I am not giving up Lakos at all. It will always be referenced for me, and occupy a prime location on the bookshelf. Thanks Interestingly, his next book, Scalable C++: Component-Based Development, is anticipated in 2006. I don't think it has ever came to fruition... one day it may! Also, Agile Principles and patterns are widespread and effective software developing paradigm. I am shifting my gears in that directions. Check out this book: Agile Software Development, Principles, Patterns, and Practices How to effectively design a C++ modular program? How to learn? going to detail out a common hypothetical problem. Problem: I am provided with a static library say libX.a and the header files a.h and b.h. The header files a.h and b.h contain the APIs exported by the library. a.h includes a1.h and b.h includes b1.h. But a1.h and b1.h are not shipped by the owner of the library because a1.h and b1.h contain the data structures which are used privately by the library and the owner does not want to expose these data structures. I have to write an application invoking the APIs exported by the library. So I have to include a.h and b.h which contains the declaration for the APIs. Ok, fine. I write my application and include the header files a.h and b.h and invoke the APIs. But I will get a compiler error, because the compiler cannot find a1.h and b1.h which are internally included by a.h and b.h. Questions: Is there a solution to this problem? If yes, seeking earnestly to know the solution :) Is it necessary that the library owner expose all the private header files he internally uses in his library? 1) You could look at the nm tool, see SO: how to list symbols in a so-file. Perhaps it works for static-libraries as well, i'm not sure. 2) The library owner could have used the techniques in Large scale C++ software design by John Lakos to prevent exposing the internal structure. Perhaps you can use the techniques in there to create the required parts of a1.h and b1.h without relying on information you don't have. Especially declaring structures/classes without defining their contents. I keep running into problems the larger my program gets. For instance, I get the following error: In file included from WidgetText.h:8, from LCDText.h:17, from WidgetText.cpp:13: Generic.h:21: error: expected class-name before ',' token Here are those lines: #include "Generic.h" // WidgetText.h:8 #include "WidgetText.h" // LCDText.h:17 #include "LCDText.h" // WidgetText.cpp:13 class Generic: public virtual LCDText, public CFG, public virtual Evaluator { // Generic.h:21 Here are the contents of the various header files: //Generic.h #include "CFG.h" #include "Evaluator.h" #include "LCDText.h" #include "Widget.h" //WidgetText.h #include "Generic.h" #include "Property.h" #include "Widget.h" //LCDText.h class Generic; #include "LCDBase.h" #include "WidgetText.h" This isn't providing much; I know. I'm not sure what else to include. Each header defines a class named after its header, so LCDText.h has a class named LCDText. The one line declaring class 'Generic' in LCDText.h had to be placed there due to an earlier problem similar to this one. I'm assuming this current issue has a similar solution, but I've failed to find it thus far. Part of the solution is to add some forward declarations to get rid of these compiler errors (just like you did with your class Generic line). Google will turn up lots of suggestions on how exactly to do this. Using forward declarations will let you eliminate the cyclic / circular #includes described in this answer. A forward declaration lets you include references to and pointers to the forward-declared class, and it lets you pass the forward-declared class as a parameter, but it does not let you derive from or include an instance member of the forward-declared class. So your Generic class needs a way to #include (and not just forward-declare) the header files for LCDText, CFG, and Evaluator. If it can't do that because LCDText, CFG, or Evaluator need to #include (and not just forward-declare) Generic, then you need to rearrange your hierarchy to fix this (for example, by making a member variable a pointer or reference to a class instead of making it an instance of a class). However, using multiple inheritance like this (and especially using the diamond inheritance implied by two virtual inheritances) is a definite code smell. It suggests that you should be designing your class hierarchy differently. For example, maybe you need to be favoring composition over inheritance. That would make cleaning up your forward declarations and cyclic dependencies a lot easier. Edit: You mentioned that you've been running into this problem more as your code base gets larger. I'm told that John Lakos's Large-Scale C++ Software Design is a good reference for managing issues such as header file dependencies in large projects, although it may be overkill for where your project is right now. I'm a programmer for several years. I was always told (and told others) that you should include in your .c files only the .h files that you need. Nothing more, nothing less. But let me ask - WHY? Using today's compilers I can include the entire h files of the project, and it won't have a huge effect on compilation times. I'm not talking about including OS .h files, which include many definitions, macros, and preprocessing commands. Just including one "MyProjectIncludes.h". That will only say: #pragma once #include "module1.h" #include "module2.h" // and so on for all of the modules in the project What do you say? In general you don't want to have to re-compile modules unless headers that they actually depend on are changed. For smaller projects this may not matter and a global "include_everything.h" file might make your project simple. But in large projects, compile times can be very significant and it is preferable to minimize inter-module dependencies as much as possible. Minimizing includes of unnecessary headers is only one approach. Using forward declarations of types that are only referenced by pointers or references, using Pimpl patterns, interfaces and factories, etc., are all approaches aimed at reducing dependencies amongst modules. Not only do these steps decrease compile time, they can also make your system easier to test and easier to modify in general. An excellent, though somewhat dated reference on this subject, is John Lakos "Large Scale Software Design". In my spare time, I've been taking code I've written for various purposes and appropriating them into other languages just to have a look at what's out there. Currently I'm taking a genetic programming graph colouring algorithm, originally written in Java, and trying to coerce it into C++. The arbitrary data structure I'm using for the task has a few classes. In Java, it wasn't so much of an issue for me because I had been exposed to it for a while. The graph structure was only created once, and a Colouring was assigned to that. The Colouring (specifically finding a mostly optimal one) was the real point of the code. I could have a Graph class with inner classes like Node and Edge, for instance, or I could have a package graph with classes Graph, Node, Edge, etc. The first case above might lend itself well to my idea of C++. A main *.cpp file might have some classes Node, Graph, Edge, defined in it. But this seems to really be missing the point of C++, from what I can tell. I'm just taking what I wrote in Java and forcing it into C++, adding destructors where appropriate and turning object references to pointers. I'm not yet thinking in C++. Do these classes bear separating into separate *.cpp files? Should they be separated, and then compiled as a library to use in the main program? What I really need are some good resources or contrived examples (or even rules of thumb) to say, in C++ programming, what are the different options that exist and when is it a good idea to thinking about one over the other? EDIT: I've been asked by @Pawel Zubrycki to provide some example code. I'm not going to do this, because each component is fairly trivial - It generally has a reference to the next thing, and some get/set methods. I will, however, describe it. It's essentially an incidence list. There is some unnecessary use of classes termed ...Pointer - they were a product of a literal translation of a diagram first used to explain incidence lists to me. There is a container class, VertexList, which contains a head element VertexPointer, and methods to add new VertexPointer objects (Adding it to the graph, but not connecting it to any other nodes, allowing searches to search non-connected graphs), naive search for indices on Vertex objects, etc. Every VertexPointer has a Vertex object, as well as a VertexPointer next;, and all those handy hasNext() methods that you might expect. A Vertex also has an associated ConnectionList The same is duplicated for EdgeList, EdgePointer, and Edge, except that an Edge is associated with two Connection objects. ConnectionList and Connection: ConnectionList mimicking VertexList or EdgeList, having a Connection head; and all those handy methods you might expect, like addConnection(). A Connection has an Edge associated with it, as well as some Connection next; This allows us to easily get the connected components of any one point in the graph, and have an arbitrary number of connections. It seems pretty over-the-top complicated, but the same functionality could be duplicated with some LinkedList of Vertex objects, a LinkedList of Edge objects, and a number of LinkedList of Connection objects. The LinkedList of Vertex Objects allows us to iterate over all Vertices for exhaustive searches on Vertices, and the same applies for edges. The LinkedList objects of Connection allow us to quickly traverse to any connected Vertices and to arbitrarily add or connections in the graph. This step up in complexity was added to deal with the complexity of evaluating a certain colouring of a graph (weighted edges, quick traversal of local subgraphs, etc.) If you have classes like Node, Graph and Edge, and their implementation is not too large, it makes perfectly good sense to define them in one and the same .cpp file. After all, they are meant to be used together. In C++, a package like this is called a component. Usually it makes more sense to think in components than classes, since C++ is not only an OOP language and classes are not always the preferred way do things. If you want to learn more about the preferred way to organize code in C++, I recommend Large Scale C++ Software Design. BTW: Making a library out of these classes really seems overkill. I think this is a really newb question, but I never found out the answer. I don't know how exactly to phrase this question, but I often find that I have to access objects that are "far away" from the current object in terms of the current hierarchy. I just want to make sure that this is the right (only) way to do this. This goes along with passing parameters in from main also. I find that some objects far away from main need to be passed in with a parameter multiple times. How does an object far away from main get information from the command line? For example for the first case, for 4 classes... class A{ B b; //need to check status of D //choice 1 b.get_c().get_d().get_status(); //choice 2 const C& c = b.get_c(); const D& d = c.get_d(); d.get_status(); }; class B{ public: C c; const C& get_c() {return c;} }; class C{ public: D d; const D& get_d() {return d;} }; class D{ public: bool check_status(); }; Say something like, A is car, B is door assembly, C is door, D is lock. Then A has to check say, is lock on, otherwise prevent starting. Choice 3 is to directly call D's method from A, I'd have to make a few layers of check_status() in C, B, and A and return D, C, B.check_status(). Don't all these calls to subobjects (if the code was a bit more complicated) get a lot of overhead? Thanks. In addition to the answers above getting hold of a copy of Large Scale C++ Software Design may help in this regard. Don't worry that the first chapter is a bit irrelevant these days, the majority of the ideas presented are still applicable. I used to use the following code to make sure that the include file is not loaded more than once. #ifndef _STRING_ #include <string> #endif // use std::string here std::string str; ... This trick is illustrated in the book "API Design for C++". Now my co-work told me that this is not necessary in Visual Studio because if the implementation head file of string contains #pragma once, the include guard is not required to improve the compilation speed. Is that correct? Quote from original book: 7.2.3 Redundant #include Guards Another way to reduce the overhead of parsing too many include files is to add redundant preprocessor guards at the point of inclusion. For example, if you have an include file, bigfile.h, that looks like this #ifndef BIGFILE_H #define BIGFILE_H // lots and lots of code #endif then you might include this file from another header by doing the following: #ifndef BIGFILE_H #include "bigfile.h" #endif This saves the cost of pointlessly opening and parsing the entire include file if you’ve already included it. Redundant include guards are, by definition "redundant". They do not affect the binaries created through compilation. However, they do have a benefit. Redundant include guards can reduce compile times. Who cares about compile times? I care. I am just one developer is a project of hundreds of developers with millions of lines of source code in thousands of source files. A complete rebuild of the project takes me 45 minutes. Incremental builds from revision control pulls take me 20+ minutes. As my work depends on this big project, I cannot perform any testing while waiting on this prolonged build. If that build time were cut to under 5 minutes, our company would benefit greatly. Suppose the build time saving was 20 minutes. 1 year * 100 developers * 1 build/day, * 1/3 hour/build * 250 days/year * $50/hr = $416,667 savings per year. Someone should care about that. For Ed S, I have been using Redundant Include guards for 10 years. Occasionally you will find someone who uses the technique, but most shy from it because it can make ugly-looking code. "#pragma once" surely looks a lot cleaner. Percentage-wise, very few developers continually try to improve their talent by continuing their education and techniques. The redundant #include guards technique is a bit obscure, and its benefits are only realized when someone bothers to do an analysis on large-scale projects. How many develops do you know who go out of their way to buy C++ books on advanced techniques? Back to the original question about Redundant Include guards vs #pragma once in Visual Studio... According to the Wiki #pragma once, compilers which support "#pragma once" potentially can be more efficient that #include guards as they can analyze file names and path to prevent loading of files which were already loaded. Three compilers were mentioned by name as having this optimization. Conspicuously absent from this list, is Visual Studio. So, we are still left wondering if, in Visual Studio, should redundant #include guards be used, or #pragma once. For small to medium sized projects, #pragma once is certainly convenient. For large sized projects where compile time become a factor during development, redundant #include guards give a developer greater control over the compilation process. Anyone who is managing or architecting large-scale projects should have Large Scale C++ Design in their library--it talks about and recommends redundant #include guards. Possibly of greater benefit than redundant include guards is smart usage of #includes. With C++ templates and STL becoming more popular, method implementations are migrating from .cpp files to .h files. Any header dependencies the .cpp implementation would have had, is now necessarily having to migrate to the .h file. This increases compilation time. I have often seen developers stack lots of unnecessary #include's into their header files so they won't have to bother identifying the headers they actually need. This also increases compile time. Ok, may be this question have answer already but I don't know what keyword to search (most of my searched results are about include guard in .h only, but not in .cpp) Sometimes I saw in cpp each # include line have a extra include guard (sometimes even the included .h already have the own include guard) like this: SomeClass.cpp #ifndef__A__ #include A.h #endif #ifndef__B__ #include B.h #endif #ifndef__C__ #include C.h #endif instead of SomeClass.cpp #include A.h #include B.h #include C.h , what is the function of this include guard? The practice of using include guards in .cpp files was recommended by John Lakos in his book Large-Scale C++ Software Design. I don't know whether any one before him had recommended the practice. Say you have A.h: #ifndef __A__ #define __A__ #include "B.h" #include "C.h" // ... // ... // ... #endif B.h: #ifndef __B__ #define __B__ // ... // ... // ... #endif C.h: #ifndef __C__ #define __C__ // ... // ... // ... #endif SomeClass.cpp: #ifndef __A__ #include "A.h" #endif #ifndef __B__ #include "B.h" #endif #ifndef __C__ #include "C.h" #endif When SomeClass.cpp is compiled, the contents of A.h is included. As a by-product of including the contents of A.h, the contents of B.h and C.h are also included. Also, the pre-processor macros __A__, __B__ and __C__ are defined. When the line #ifndef __B__ is processed, since __B__ is already defined, the next line is skipped. If SomeClass.cpp had just: #include "A.h" #include "B.h" #include "C.h" the file B.h has to be opened and processed. The contents of the file will not be included again due to the include guards but the file has to be opened and closed. By using the first strategy, you avoid the cost of of opening and closing B.h and C.h. For large scale C++ project, John Lakos asserts, the cost is too much. Hence, the recommendation of using include guards even in .cpp files. Can I make the above statement? Is it right or not? does modularity and dependencies are different thing or are inter-related? Help... They're different things, but clearly they are related. For example, if you have two (alleged;-) components A and B, but A depends on B and B depends on A, then they're not really distinct components -- they're a weird split of what clearly remains a single component. To achieve real modularity, dependencies must indeed be kept in mind -- and Dependency Inversion is one of the crucial techniques to achieve clean, correct dependencies. I'd also strongly recommend this classic book -- while most relevant if your chosen language is C++, it does contain a wealth of advice that's also applicable to many other languages. I have been coding in java most of the time, and I also studied C and C++ at University. But I have never written a large C++ code from zero made of many files, as I have done in java with a file for each class. I'd like to know some book or reference with exercises and examples made of many files and classes en C++, so I can face big C++ projects in the future. Sorry if you feel this question is eternally repeated. Large-Scale C++ Software Design, by John Lakos. I think it's a spirit of C++ - you don't pay for what you don't want ( you explicitly pay for what you need ): // a.h #include <iosfwd> template< class T > class QVector; struct A { void process( QVector<int> ); void print( std::ostream& ); }; // some.cpp #include "a.h" #include <iostream> // I need only A::print() in this module, not full interface ... A().print( std::cout ); ... That's why I think that it's not fair to prohibit developer to work such way with STL ( Will C++11 STL have forward declaration's files? ). But also I see one bad thing: dependencies of module A will spread out in external context ( duplication of #include directives ) and it can lead to hard refactoring when interface will change ( e.g. replace QVector with QList - and now you need to replace all occurrences of <QVector> with <QList> ). Solution of this problem is: #include <iostream> #include <QVector> struct A { void process( QVector<int> ); void print( std::ostream& ); }; Should we call this an idiom "fundamental types of interface" - module interface's types should be like fundamentals types ( are always defined and available )? It also makes sense, but still isn't clear what way is better ( e.g. Qt mixes both approaches ). My personal decision - always provide both ways for better modularity ( when we have enough dependencies ): // a_decl.h #include <iosfwd> template< class T > class QVector; struct A { void process( QVector<int> ); void print( std::ostream& ); }; // a.h // Include this file if you want to use most interface methods // and don't want to write a lot of `#include` #include <iostream> #include <QVector> #include "a_decl.h" and let developer chooses what to include. What you can say about these approaches? What way is better for you and why? Do we have a one clear winner for all cases or it always will depend on context? From my correspondence with language creator ( I didn't receive an final answer ) UPDATE: With boost 1.48.0 comes Container library, which allow to define containers of undefined user types ( read more ). C++ is a language that leaves many degrees of freedom to the programmer, so it is somehow unavoidable that there are different ways to do the same thing. IMO, what you define as "the solution", i.e., including in any .h file all the necessary includes or forward declarations, is the way to go in order to avoid "incomplete header files", and I have always followed this rule. There is an interesting book with a thorough discussion of all the pros and cons of doing or not doing so: "Large-Scale C++ Software Design" by John Lakos, where the rule above comes from. Speaking specifically about forward declarations, Lakos distinguishes between "in-name-only" and "in-size" class usages; only in the second case it is legitimate (according to his opinion) the use of a forward declaration: Definition: A function f uses a type T in size if compiling the body of f requires having first seen the definition of T. Definition: A function f uses a type T in name only if compiling f and any of the components on which f may depend does not require having first seen the definition of T. Specifically, Lakos' reasoning revolves around the implications of certain styles of programming C++ for large scale systems, i.e. system of certain complexity, but I think that his suggestions are very well suited for any-scale systems also. Hope that his helps. I've read that it is better to have internal linkage (for variables, free functions, etc) because this will reduce number of symbols being "exported" from particular compilation unit. That way build times could be better. Is this true? Another advantage of using internal linkage is that there will not be any problems with names collision. reference: Large-Scale C++ Software Design In theory yes, but ... C++ evolved towards generic programming. And the introduction of namespaces limits the name collision problems. It is always more frequent to write programs in form of "headr only libraries" included hierarchically from a single cpp file containing just a main whose purpose is instantiate a "manager object" that takes care of all the orchestration, and supply a last resort "catch" for eventually escaped-out exceptions. Long symbol table can make faster by means of "precompiled headers". In this sense, all linkage is "internal", since there is nothing to "export". More in general, little external linkage result in faster linking time, little internal linkage result in faster compile time. The best minimum is most likely when the internal and external tables balance each other. But there are many other important factor to take care of. I wonder if a book like that can still be considered "good" for today standard: did you note that what it suggest -for example- about iterators is all but what the standard library today do? Ok so I was just thinking to myself why do programmers stress so much when it comes down to Access Modifiers within OOP. Lets take this code for example / PHP! class StackOverflow { private var $web_address; public function setWebAddress(){/*...*/} } Because web_address is private it cannot be changed by $object->web_address = 'w.e.', but the fact that that Variable will only ever change is if your programme does $object->web_address = 'w.e.'; If within my application I wanted a variable not to be changed, then I would make my application so that my programming does not have the code to change it, therefore it would never be changed ? So my question is: What are the major rules and reasons in using private / protected / non-public entities So my question is: What are the major rules and reasons in using private / protected / non-public entities In Python, there are no access modifiers. So the reasons are actually language-specific. You might want to update your question slightly to reflect this. It's a fairly common question about Python. Many programmers from Java or C++ (or other) backgrounds like to think deeply about this. When they learn Python, there's really no deep thinking. The operating principle is We're all adults here It's not clear who -- precisely -- the access modifiers help. In Lakos' book, Large-Scale Software Design, there's a long discussion of "protected", since the semantics of protected make subclasses and client interfaces a bit murky. How can I "hide" parts of a class so that whoever is using the libary does not have to include headers for all the types used in my class. Ie take the MainWindow class below, ho can I have it so when compiled in a static/dynamic libary, whoever is useing the libary does NOT have to include windows.h, ie HWND, CRITICAL_SECTION, LRESULT, etc do not have to be defined. I know I could split it into two classes, an abstract class with just the public interface, and an implementation class which is hidden that contains the members that require windows.h. The problem here is that the visible class can no longer be created itsself, and an additional create function (eg CreateMainWindow) is required. That is fine in this case since it is most likly that just a single instance created on the heap is wanted but for other classes this is not. class MainWindow { HWND hwnd; int width, height; std::string caption; bool started,exited; bool closeRequest; unsigned loopThread; CRITICAL_SECTION inputLock; Input *input; public: static void init_type(); Py::Object getattr(const char *name); MainWindow(int width, int height, std::string caption); ~MainWindow(); bool CloseRequest(const Py::Tuple &args); bool CloseRequestReset(const Py::Tuple &args); HWND GetHwnd(); int GetWidth(); int GetHeight(); Input* GetInput(); protected: unsigned static __stdcall loopThreadWrap(void *arg); unsigned LoopThreadMain(); LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam); LRESULT static CALLBACK WndProcWrapper(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); }; This book may give you some ideas: Large-Scale C++ Software Design by John Lakos I am having all sorts of problems with include-overload in my newbie C++ project, but I'm not sure how to avoid it. How do I avoid the problem of having to include dozens of classes, for example in a map-loading scenario: Here's a trivial example Map class, which will load a game-map from a file: // CMap.h #ifndef _CMAP_H_ #define _CMAP_H_ class CMap { public: CMap(); void OnLoad(); }; #endif // CMap.cpp #include "CMap.h" CMap::CMap() { } void CMap::OnLoad() { // read a big file with all the map definitions in it here } Now let's say I have a whole plethora of monsters to load into my map, so I might have a list or some other structure to hold all my monster definitions in the map std::list<CMonster*> MonsterList; Then I could simple forward-declare "CMonster" in my CMap.h, and add as many monsters as I like to that list // CMap.h class CMonster; // CMap.cpp void CMap::OnLoad() { // read a big file with all the map definitions in it here // ... // read in a bunch of mobs CMonster* monster; MonsterList.push_back(monster); } But what if I have lots of different types of monster? How do I create lots of different types of monster without including every CMonster_XXX.h? And also use methods on those? // CMap.cpp void CMap::OnLoad() { // read a big file with all the map definitions in it here // ... // read in a bunch of mobs CMonster_Kitten* kitty; kitty->OnLoad(); MonsterList.push_back(kitty); CMonster_Puppy *puppy; puppy->OnLoad(); puppy->SetPrey(kitty); MonsterList.push_back(puppy); CMonster_TRex *awesome; awesome->OnLoad(); awesome->SetPrey(puppy); MonsterList.push_back(awesome); } Here's the rule I use for including things. Edit: Additionally, you may want to read Large-Scale C++ Software Design. It talks about managing physical file dependencies. I have automatic generated code (around 18,000 lines, basically a wrap of data) and other about 2,000 lines code in a C++ project. The project turned on the link-time-optimization operation. /O2 and fast-code optimization. To compile the code, VC++ 2008 express takes incredibly long time (around 1.5 hours). After all, it has only 18,000 lines, why the compiler takes so much time? a little explanation to the 18,000 code. It is plain C, not even C++ which includes many unpacked for-loop, a sample would be: a[0].a1 = 0.1284; a[0].a2 = 0.32186; a[0].a3 = 0.48305; a[1].a1 = 0.543; .................. It basically fill a complex struct. But not so complex to compiler I guess. The Debug mode is fast, only the Relase mode has this issue. Before I have the 18,000 lines of code, they are all fine. (that time the data is in external location). However, the release mode does many work which reduce the size of exe from 1,800kb to 700kb. this issue does happen in link stage because all .obj files are generated. I have suspect on link-time-code-generation too but cannot figure out where is wrong. Historically, a common cause of slow C++ computation is excessive header file inclusion, usually a result of poor modularization. You can get a lot of redundant compilation by including the same big headers in lots of small source files. The usual reference in these cases is Lakos. You don't state whether you are using the pre-compiled header, which is the quick and dirty substitute for a header file refactoring. I have the following dilemma here: I have a few classes, let's say A, B, C and D. A has a public interface, and a has-a relationship with B (like A is having a member variable of type B) and one of the methods of A is returning this B object, B is just a class who exposes some methods, C is another class which exposes other methods, and D is a singleton object. The public interface of D has references (pointers if you like more) to objects of class C. So, obviously when I want to draw a relationship diagram at this step, I would have a relationship between A and B and C would be put on the diagram, without visible relationship to the other two. So, this is based on the header (.h) files, which contain the declaration of class A, B, C. I'm a little confused about D right now. On the other end: And here are my questions: Thanks a lot for your guidance. You should definitively read the book Large-Scale C++ Software Design. It particularly deals with the modeling of dependencies between interfaces and implementation, by introducing two new relationships uses-in-the-interface and uses-in-the-implementation, instead of just the traditional "has-a". Then, it goes on with design principles applied to such modeling (such as isolation, insulation, encapsulation, etc.). It is really a highly technical book, though. So be prepared! I organization is poorly designed? If so, what would be a way to arrange my "class diagram" and avoid this? I just want to know what would be the best practice in this scenario. Also, why doesn't the "#pragma once" directive solve this problem? Thanks in advance. There is a way to fix it, but it also means your class organization is broken. The way to fix it is called an 'include guard', though many compilers also support the #pragma once directive. I suppose it isn't working because #pragma once probably doesn't consider a header file included until the entire thing is parsed. And since the recursive inclusion happens in the middle of the header file, it isn't finished being parsed yet. An include guard is something like this: In ClassA.h: #pragma once // Just because. It really should help. #ifndef INCLUDED_CLASSA_H #define INCLUDED_CLASSA_H #include "ClassB.h" //... rest of header file #endif In ClassB.h: #pragma once // Just because. It really should help. #ifndef INCLUDED_CLASSB_H #define INCLUDED_CLASSB_H #include "ClassA.h" //... rest of header file #endif The organization problem is called a circular dependency, and circular dependencies are generally a bad idea. There are a number of different ways of breaking them, but which to use depends on the exact nature of and original reason for the dependency. Depending on the problem you can use one of a variety of techniques: There are other techniques. There is, in fact, a book that has a really wide variety of techniques to use in various situations because removing circular dependencies is a big theme of the book. That book is "Large-Scale C++ Software Design" by John Lakos. I need to finish others developer work but problem is that he started in different way... So now I found in situation to use existing code where he chooses to inherit a non-abstract class (very big class, without any virtual functions) that already implements bunch of interfaces or to dismiss that code (which shouldn't be to much work) and to write another class that implements interfaces I need. What are the pros and cons that would help me to choose the better approach. p.s. please note that I don't have to much experience Many Thanks What are the pros and cons that would help me to choose the better approach. It's legal to derive from a class with no virtual functions, but that doesn't make it a good idea. When you derive from a class with virtual functions, you often use that class through pointers (eg., a class Derived that inherits from Base is often manipulated through Base*s). That doesn't work when you don't use virtual functions. Also, if you have a pointer to the base class, delete-ing it can lead to a memory leak. However, it sounds more like these classes aren't being used through pointers-to-the-base. Instead the base class is simply used to get a lot of built in functionality, although the classes aren't related in the normal sense. Inversion of control (and has-a relationships) is a more common way to do that nowadays (split the functionality of the base class into a number of interfaces -- pure virtual base classes -- and then have the objects that currently derive from the base class instead have member variables of those interfaces). At the very least, you'll want to split the big base class into well-defined smaller classes and use those (like mixins), which sounds like your second option. However, that doesn't mean rewrite all the other code that uses the blob base class all in one go. That's a big undertaking and you're likely to make small typos and similar mistakes. Instead, buy yourself copies of Working Effectively With Legacy Code and Large-Scale C++ Software Design, and do the work piecemeal. I was wondering what methods of code organization stackoverflow users use. I have a sporadic thought process and as a result my code can start to look messy and over whelming. Any tips ? I would suggest looking at the principles of Large Scale C++ Software Design by John Lakos (ISBN-13: 978-0201633627) if not the book itself. They are summed up in these lecture notes. Another summary of ideas. Here's a brief outline of the headings of the principles, which while written about in the C++ context, the geist of which are language agnostic. I would like to reduce the link-time of my project, and to do that I want to understand, exactly, why it takes so long - is it a specific library? is it something else? How can I know what to change in order to improve the link time? Update There are many "generic" advices such as "reduce library dependencies" but they seem impractical in our case. Our code-base is large, there are many library dependencies, and finding out, by experimenting, which dependency affects the link time the most will take an enormous amount of time. A large portion of the code base was developed years ago without thinking that much about dependencies. We are looking for a way to find a concrete direction, such as "dependency of X on Y will benefit the link time", without exhaustively trying all possible directions.. Note that we are not using LTCG at all. For Visual C++, I think the first step in the linking time optimization is to turn off the 'Whole-Program Optimization (/GL)' option. I would like to recommend a book on this subject: Large-Scale C++ Software Design, by John Lakos. This book gives many good points on the large scale C++ development, but I think the main theme is 'how to design package relationship to minimize linking time'. It is about module(lib, dll) dependency minimization techniques. Because, linking a project consists of many small modules is tend to run faster than one big (many files) project. Also, check out this blog post: The “Large-Scale C++ Software Design” rules in practice Since I am not C++ ninja, as I see dependencies always creeps into my programs. Someone may have asked similar question before, but I want more direct responses. I ask C++ ninjas out there If they can suggest me good references for Idioms supported in C++ to minimize inter dependencies of code. Large-Scale C++ Software Design is a good resource. Some quick tips to reduce dependencies. Forward declaration when possible. Program 1: #include <iostream> std::string Hello(void){return "Hello";} std::string World(void){return "world!";} int main(){ std::cout << Hello() << " " << World() << std::endl; } The functions Hello() and World() exist in the global namespace. This means they can be called by any other function that comes after their declaration (or in this case, I provided the definition and did not need the declaration first). I have a problem with this, because as my project gets bigger, I include more header files that fill the global namespace with lots of functions, and I risk having function signature collisions, or worse, accidentally calling the wrong function that should only be called as a sub-task of another function. I am trying to follow the paradaim of functionally decomposing a task into sub-tasks, and thus it would not make sense for particular functions to ever be called outside the scope of another particular function. Here is a work-around, and apart from the code becoming unreadable due to the indentation depth, I want to know if there are any performance or implementation gotchas. lambda functions are a bit of magic for me at the moment, so I'm curious about the unforeseen dangers. Program 2: #include <iostream> int main(){ auto Hello = [](void) -> std::string{return "Hello";}; auto World = [](void) -> std::string{return "world!";}; std::cout << Hello() << " " << World() << std::endl; } Hello() and World() are encapsulated inside main() and can not be called from outside main()'s scope. Is that all that's different? I would not do it. In your case what you will end up is creating huge functions as to allow the definition of the lambdas inside, and you will end up with functions where the contents of the body are much harder to maintain. There have been very large projects before C++11 and lambdas, and the risk of collisions has been managed by different means, including namespaces as DeadMG already mentioned, but also classes and object oriented design and other forms of encapsulation (define local functions as static at namespace level in the implementation file, forcing internal linkage and avoiding conflicts with other translation units. Above that, if you carefully choose meaningful names for your identifiers, you should avoid 99% of the collisions. If you really are going to work on a large scale project consider reading John's Lakos Large Scale C++ Software Design To speed up the compilation of a large source file does it make more sense to prune back the sheer number of headers used in a translation unit, or does the cost of compiling code far outweigh the time it takes to process-out an include-guarded header? If the latter is true an engineering effort would be better spent creating more, lightweight headers instead of less. So how long does it take for a modern compiler to handle a header that is effectively include-guarded out? At what point would the inclusion of such headers become a hit on compilation performance? (related to this question) Assuming C/C++, simple recompilation of header files scales non-linearly for a large system (hundreds of files), so if compilation performance is an issue, it is very likely down to that. At least unless you are trying to compile a million line source file on a 1980s era PC... Pre-compiled headers are available for most compilers, but generally take specific configuration and management to work on non system-headers, which not every project does. See for example: 'Build time on my project is now 15% of what it was before!' Beyond that, you need to look at the techniques in: Or split the system into multiple parts with clean, non-header-based interfaces between them, say .NET components. access-modifiersapplication-structurearchitecturebit-manipulationbuild-automationbuild-processcc#c++c++-faqc++11c-preprocessorc99classclass-designcode-duplicationcode-organizationcode-reviewcoding-stylecompilationcompile-timecompiler-constructioncompiler-optimizationdelegationdependenciesdesigndesign-patternsdiagramdistributedembeddedenumsforward-declarationfunctionfunction-templatesgccheaderheader-fileshfileidiomsincludeinheritancelambdalanguage-agnosticlegacylexical-closureslinkerlogicmember-functionsmockingmodularmodularitynamespacesoopoptimizationpackage-designperformanceperlpimpl-idiompreprocessorprogramming-languagesproject-managementprojectspythonrefactoringrubyscalabilitysoftware-engineeringstatic-librariesstlstrategy-patterntddtestingumlunit-testingunixversion-controlvisual-c++visual-studiovisual-studio-2008vtablewarnings
http://www.dev-books.com/book/book?isbn=0201633620&name=Large-scale-C%2B%2B-Software-Design
CC-MAIN-2019-09
refinedweb
15,662
63.49
Results 1 to 2 of 2 Thread: update jlabel image - Join Date - Apr 2012 - 7 - Thanks - 2 - Thanked 0 Times in 0 Posts update jlabel image hi , i am doing a program which will display the image and update after x seconds. i have set the image name to be 1.jpeg , 2.jpeg .. till 100.jpeg. below is the code i have done so far import java.util.*; import java.awt.*; import java.io.*; import javax.swing.*; public class Tester extends JWindow { public static void main(String[]args) { int i = 1; ImageIcon ii=new ImageIcon(i + ".jpeg"); JLabel label=new JLabel(ii); JFrame frame=new JFrame("Show Image"); frame.add(label); while(i<6) { i++; label.setIcon(new ImageIcon( i + "jpeg")); } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); frame.setVisible(true); } } it can compile without error but when i run it, it only show the frame with empty gray background. can anyone tell me how to settle this problem. thanks in advance for helping me .. thanks a lot . - Join Date - Sep 2002 - Location - Saskatoon, Saskatchewan - 17,027 - Thanks - 4 - Thanked 2,668 Times in 2,637 Posts Label hasn't been specified a size, so it's likely trying to pack it as small as it can. Try setting the size to that of the maximum image. Make sure you repaint it as well. This isn't timed either. The while loop is irrelevant at this step since visibility hasn't been provided to the frame. You'll need to invoke the change in the label in a separate thread of its own, or call a loop after the frame is visible. To time it, you will want to use Thread.sleep or use a Timer to invoke a new Timertask. The while loop will also only update the label once, then complete before moving into the render of the JFrame itself. Just looking at it, this to me appears to toss runtime exceptions. ImageIcon will likely fail to find a file call Xjpeg, at minimum that should be looking for X.jpeg as an extension.
http://www.codingforums.com/java-and-jsp/257137-update-jlabel-image.html
CC-MAIN-2016-07
refinedweb
348
74.79
The project As the name suggest, we're gonna make a site with drum pads that play sound when triggered 🥁. The site was made with React and SASS. I figured I'll take 3 days to complete this, but circumstances pushed this to 4 days. Life always get in the way, so I should be more prepared about it 💪 What I learned - How to dynamically render components in React We can use array and its methods, such as Array.map(): render() { const soundArr = ["blip", "clan", "clap", "cymbal", "kclick", "piano1", "piano2", "snaps", "whoop"]; const keyArr = ["Q", "W", "E", "A", "S", "D", "Z", "X", "C"]; return ( <div id="drum-machine"> <p id="drum-title">Drum Machine</p> <Display /> {soundArr.map((soundClip, index) => <DrumPad audioName={soundClip} key={keyArr[index]} cap={keyArr[index]} />)} </div> ); } onkeydownevent on the document To detect key presses on the HTML document, we can use the onkeydown event: document.onkeydown = (e) => { let pressedSound = document.getElementById(e.key.toUpperCase()); if(pressedSound) { pressedSound.play(); document.getElementById("display").innerText = pressedSound.parentElement.id; } Note that there used to be onkeypress event, but it is now deprecated. - Add gradient overlay over background image We can use background-image CSS property for this: background-image: linear-gradient(180deg, rgba(0,255,233,0.0) 0%, rgba(0,0,0,1) 100%), url(''); Afterwords It's nearing the end of Ramadan, which means preparation for Eid is incoming. It will be a very busy week. Hope I can still continue doing this throughout Eid celebration. Anyway, happy Eid for Muslims around the world! ✨ Follow me on Github! Also on Twitter! Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/kemystra/day-20-24-drum-machine-4d27
CC-MAIN-2022-33
refinedweb
265
57.37
sandbox/wind_pool.c Constant wind over constant depth pool Example of a constant wind over a square constant depth pool A constant wind of 1 m/s blows in the x direction over a square pool of 1000 m side length with constant depth 2 m. We assume quadratic bottom friction with coefficient . Wind stress is defined by the formula where is taken from Wu (1982) JGRC So for a we have a wind stress of and thus . #include "grid/cartesian1D.h" #include "saint-venant_ss.h" #define MAXLEVEL 8 #define MINLEVEL 4 #define ETAE 1e-8 Here we can set standard parameters in Basilisk int main() { #if QUADTREE // 32^2 grid points to start with init_grid(1 << MINLEVEL); #else // Cartesian // 1024^2 grid points init_grid(1 << MAXLEVEL); #endif Here we setup the domain geometry. For the moment Basilisk only supports square domains. This case uses metres east and north. We set the size of the box L0 is 1000 m and the coordinates of the lower-left corner (X0,Y0) are (-500,-500). In this case we are assuming a square ‘pool’ of length 1000 m // the domain is size (1000.); origin(-L0/2.,-L0/2.); `G` is the acceleration of gravity required by the Saint-Venant solver. This is the only dimensional parameter.. // acceleration of gravity in m/s^2 G = 9.81; run(); } Adaptation Here we define an auxilliary function which we will use several times in what follows. Again we have two #if...#else branches selecting whether the simulation is being run on an (adaptive) quadtree but only for “wet” cells. If we used everywhere (i.e. the default provided by the Saint-Venant solver) we would also refine the dry topography, which is not useful. int adapt() { #if QUADTREE scalar η[]; foreach() η[] = h[] > dry ? h[] + zb[] : 0; boundary ({}, (double[]){ETAE}, MAXLEVEL, MINLEVEL); fprintf (stderr, "# refined %d cells, coarsened %d cells\n", s.nf, s.nc); return s.nf; #else // Cartesian return 0; #endif } Initiation event initiate(i=0) { The initial still water surface is at so that the water depth is… foreach() { zb[] = -2; h[] = max(0., - zb[]); ts.x[] = 0; ts.y[] = 0; } boundary ({h,zb}); } Stopping condition We want the simulation to stop when we are close to steady state. To do this we store the h field of the previous timestep in an auxilliary variable hn. scalar hn[]; event init_hn (i = 0) { foreach() { hn[] = h[]; } } Every 10 timesteps we check whether has changed by more than 10-8. If it has not, the event returns 1 which stops the simulation. We also output running statistics to the standard error. event logfile (i+= 10; i <= 10000000) { double dh = change (h, hn); if ( (i > 100 && dh < 1e-8) || i==10000000) { foreach() fprintf (stderr, "%g %g\n", x, h[]); return 1; /* stop */ } stats s = statsf (h); norm n = normf (u.x); if (i == 0) fprintf (stderr, "t i h.min h.max h.sum u.x.rms u.x.max dh dt\n"); fprintf (stderr, "%12.8g %d %12.8g %12.8g %12.8g %12.8g %12.8g %12.8g %12.8g\n", t, i, s.min, s.max, s.sum, n.rms, n.max, dh, dt); } Bottom Friction and Wind Forcing We also use a simple implicit scheme to implement quadratic bottom friction i.e. with . Also assume that we have a constant wind blowing in the x direction of event source (i++) { double ramp = t < 12000. ? t/12000. : 1.; struct { double x, y; } ts = {1.7e-4,0}; foreach() { ts.x[] = ramp*1.7e-4; ts.y[] = 0; double a_inv = h[] < dry ? 0. : h[]/(h[] + 2.5e-3*dt*norm(u)); //double a = h[] < dry ? HUGE : 1. + 2.5e-3*dt*norm(u)/h[]; foreach_dimension() u.x[] = u.x[] * a_inv; } boundary ({h,u}); } Output Every 5 minutes, the , and hmax fields are interpolated bilinearly onto a n x n regular grid and written on standard output. event snapshots (t += 300) { printf ("# file: t-%g\n", t); // output_field ({h, zb}, stdout, n = 1 << MAXLEVEL, linear = true); foreach() printf ("%10.4g %10.4g %10.8g %10.8g\n", x, y, h[], zb[]); printf ("\n"); } event movies (t+=60) { static FILE * fp = NULL; if (!fp) fp = popen ("ppm2mpeg > eta.mpg", "w"); scalar m[], etam[]; foreach() { etam[] = η[]*(h[] > dry); m[] = etam[] - zb[]; } boundary ({m, etam}); output_ppm (etam, fp, min = -0.005, max = 0.005 , n = 512, linear = true); // output_ppm (etam, fp, n = 512, linear = true); #if 0 static FILE * fp1 = NULL; if (!fp1) fp1 = popen ("ppm2mpeg > level.mpg", "w"); scalar l = etam; foreach() l[] = level; output_ppm (l, fp1, min = MINLEVEL, max = MAXLEVEL, n = 512); #endif } Adaptivity We apply our adapt() function at every timestep. event do_adapt (i++) adapt();
http://basilisk.fr/sandbox/wind_pool.c
CC-MAIN-2018-34
refinedweb
782
74.29
Copying an SVM I try the following code in C++ using OpenCV 2.42 and it fails when attempting to copy the svm include <opencv2/opencv.hpp> using namespace cv; int main(int argc, char *argv[]){ Mat trainData(100, 3, CV_32F); randu(trainData, 0.0f, 10.f); Mat classes = Mat::zeros(100, 1, CV_32F); for(int i = 50; i < classes.rows; i++) classes.at<float>(i) = 1.0f; Mat sample = Mat::ones(1, 3, CV_32F); SVM svm; svm.train_auto(trainData, classes, Mat(), Mat(), SVMParams(), 2); SVM svm2 = SVM(svm); } and gives the message (VS2010 Windows XP) OpenCV Error: Assertion failed (udata < (uchar*)ptr && ((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+16)) in unknown function, file ..\..\..\src\opencv\mod ules\core\src\alloc.cpp, line 78 Is this a bug, or is there something I am missing about copying an SVM? I expected it to copy the decision function, support vectors, and other parameters, but something seems to be going wrong. I had a look at the source in ml.hpp and it doesn't seem to define a copy constructor. I also meet the same case:" OpenCV Error: Assertion failed (udata < (uchar)ptr && ((uchar)ptr - udata) <=(ptrdiff_t)(sizeof(void*)+16)) in unknown function." If you fix it,please let me know how. I am also apparently having this problem. At first I got the same error, but after initializing the CvSVM outside of the loop where I tried to load and push SVMs into a vector, I only get a debug error saying R6010 - abort() has been called. (Microsoft Visual C++ 2010 Express)
https://answers.opencv.org/question/1005/copying-an-svm/?sort=oldest
CC-MAIN-2021-31
refinedweb
262
65.83
Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically. For Windows systems, make sure rshost is running under the same namespace as the attaching process. This error can also happen when the state manager failed to auto start with an invalid configuration file. The best practice is to use the administration tool to generate and deploy the configuration. If you are hand crafting the configuration file, it is useful to verify your configuration with the rshost utility as part of a verification step before the configuration file is put into use. The best practice to start the state manager is to set it up as a service in a production system.
http://dcx.sap.com/1200/en/saerrors/rserrors11031.html
CC-MAIN-2018-51
refinedweb
121
53.92
Java HW Help Arrays I am looking for a step by step how to do this. Not just solution. Thanks. Write a static method named findMin that returns the minimum value in an array of integers. For example, if a variable named list refers to an array containing the values {16, 12, 25, 44}, the call of findMin(list) should return 12 (the smallest value in the list). You may assume that the array has at least one element. Test your code with the following class: public class TestFindMin { public static void main(String[] args) { int[] a1 = {16, 12, 25, 44}; int[] a2 = {587, 23, 8975, 19}; int[] a3 = {42}; System.out.println(findMin(a1)); // 12 System.out.println(findMin(a2)); // 19 System.out.println(findMin(a3)); // 42 } // your code goes
https://www.studypool.com/discuss/1294037/Java-HW-Help-Arrays
CC-MAIN-2017-09
refinedweb
131
66.74
In analogy to filter effects that manipulate pixels in an image, PlotDevice provides the path mathematics to create filter effects that manipulate vector curves. Below are some demonstations of the kinds of effects you can achieve. A path filter that grows hair on each point in a contour. We measure the length of each contour and then calculate a number of points on it, based on the length (so longer segments will get more hairs and shorter segments will get less). On each point we draw some wiggly curves. size(550, 300) background("#3a3526") font("georgia", "bold", 175) path = textpath("hairs", 40, 200) for contour in path.contours: prev = None n = contour.length for pt in contour.points(int(n)): nofill() stroke(1, 0.75) pen(random(0.25, 0.5)) if prev != None: with bezier(prev.x, prev.y): curveto( pt.ctrl1.x - random(30), pt.ctrl1.y, pt.ctrl2.x, pt.ctrl2.y + random(30), pt.x, pt.y ) curveto( pt.ctrl1.x + random(10), pt.ctrl1.y, pt.ctrl2.x, pt.ctrl2.y - random(10), pt.x + random(-20, 20), pt.y + random(-10, 10) ) prev = pt A path filter that weaves a web between the points in each contour. Depending on the length of a contour, a number of points are calculated along the contour. Then points are connected randomly with straight lines (as long as the distance between them is smaller than some given number, fontsize() / 5 in this case). from math import sqrt size(550, 300) background("#3a3526") font("helvetica", "bold", 125) path = textpath("SPIDER", 20, 200) m = 2.0 for contour in path.contours: n = contour.length + 50 points = list(contour.points(n)) for i in range(int(n)): pt1 = choice(points) d = float("inf") while d > fontsize()/5: pt2 = choice(points) d = sqrt((pt2.x-pt1.x)**2 + (pt2.y-pt1.y)**2) with nofill(), stroke("white", 0.9), pen(0.35): line( pt1.x + random(-m, m), pt1.y + random(-m, m), pt2.x + random(-m, m), pt2.y + random(-m, m) ) A path filter that sketches a piece of text by drawing different layers of (gradually converging) paths on top of each other. For each contour a number of points are calculated. Two points are roughly connected by a straight line. The connection gets more accurate as more layers are drawn. size(550, 300) background("#3a3526") font("georgia", "bold", 175) path = textpath("draft", 40, 200) m = 15 for i in range(m): m -= 1 for contour in path.contours: prev = None n = contour.length for pt in contour.points(n/80*i): nofill() stroke(1, 0.75) pen(0.25) if prev != None: line( pt.x, pt.y, prev.x + random(-m, 0), prev.y + random(-m, 0) ) line( pt.x + random(-m, 0), pt.y + random(-m, 0), prev.x, prev.y ) prev = pt A path filter that draws perpendicular spikes along each contour. A spike is calculated from the angle between two consecutive points. Subtracting 90° from this angle gives us the perpendicular angle jutting outwards from the curve. We then find the point halfway between the starting and ending point and push it upwards. If we connect a curve from the starting point to this point, and a curve from this point to the ending point, we get a spike connecting the two. from math import degrees, atan2 from math import sqrt, pow from math import radians, sin, cos size(550, 300) background("#3a3526") font("helvetica", "bold", 125) path = textpath("SPIKED", 40, 200) m = 5 # spike length c = 0.8 # spike curvature # From the PlotDevice math tutorial: def angle(x0, y0, x1, y1): return degrees( atan2(y1-y0, x1-x0) ) def distance(x0, y0, x1, y1): return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2)) def coordinates(x0, y0, distance, angle): x1 = x0 + cos(radians(angle)) * distance y1 = y0 + sin(radians(angle)) * distance return x1, y1 # The "spike" function between two points. def perpendicular_curve(pt0, pt1, curvature=0.8): d = distance(pt0.x, pt0.y, pt1.x, pt1.y) a = angle(pt0.x, pt0.y, pt1.x, pt1.y) mid = Point( pt0.x + (pt1.x-pt0.x) * 0.5, pt0.y + (pt1.y-pt0.y) * 0.5 ) dx, dy = coordinates(mid.x, mid.y, m, a-90) vx = pt0.x + (mid.x-pt0.x) * curvature vy = pt0.y + (mid.y-pt0.y) * curvature curveto(vx, vy, dx, dy, dx, dy) vx = pt1.x + (mid.x-pt1.x) * curvature vy = pt1.y + (mid.y-pt1.y) * curvature curveto(dx, dy, vx, vy, pt1.x, pt1.y) for contour in path.contours: prev = None n = contour.length / 8 for pt in contour.points(n): nofill() stroke(1) strokewidth(0.75) if not prev: beginpath(pt.x, pt.y) elif pt.cmd == MOVETO: moveto(pt.x, pt.y) else: perpendicular_curve(prev, pt, c) prev = pt endpath() A path filter that trashes the path by inserting random line segments between two points. size(550, 300) background("#3a3526") font("georgia", "bold", 175) path = textpath("trash", 40, 200) def trash(path, pt0, pt1, m=0.2, n=20, d=3.0): # Add trash between two points. # m: controls how much of the path is trashed. # n: the number of lines to insert. # d: the maximum length of inserted lines. if random() < m: for i in range(random(n)): pt0.x += random(-d, d) pt0.y += random(-d, d) path.lineto(pt0.x, pt0.y) path.lineto(pt1.x, pt1.y) # Create a blot/speckle near the current point. # We have to add this to the path at the end. if random() < m*0.3: x = pt1.x - random(-d*4, d*4) y = pt1.y - random(-d*2, d*2) blot = Bezier() blot.moveto(x, y) for i in range(random(n)): x += random(-d, d) y += random(-d, d) blot.lineto(x, y) blot.closepath() return blot p = Bezier() extensions = [] for contour in path.contours: prev = None n = contour.length / 8 for pt in contour.points(n): if not prev: p.moveto(pt.x, pt.y) elif pt.cmd == MOVETO: p.moveto(pt.x, pt.y) else: blot = trash(p, prev, pt) if blot: extensions.append(blot) prev = pt for blot in extensions: p.extend(blot) fill(1) nostroke() drawpath(p)
https://plotdevice.io/tut/Path_Filters
CC-MAIN-2017-39
refinedweb
1,040
71.61
5. Built-in Types¶ The following sections describe the standard types that are built into the interpreter. Note Historically (until release 2.2), Python’s built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. This limitation no longer exists.. 5.1. Truth Value Testing¶ a __nonzero__()or __len__()method, when that method returns the integer zero or boolvalue.) 5.2. Boolean Operations — and, or, not¶ These are the Boolean operations, ordered by ascending priority: Notes: - This is a short-circuit operator, so it only evaluates the second argument if the first one is False. - This is a short-circuit operator, so it only evaluates the second argument if the first one is True. nothas a lower priority than non-Boolean operators, so not a == bis interpreted as not (a == b), and a == not bis a syntax error. 5.3. Comparisons¶: !=can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=..). 5.4. Numeric Types — int, float, long, complex¶to be 1, as is common for programming languages. All numbers.Real types ( int, long, and float) also include the following operations: 5.4.1. Bitwise Operations on Integer Types¶: Notes: - Negative shift counts are illegal and cause a ValueErrorto¶ The integer types implement the numbers.Integral abstract base class. In addition, they provide one more method: long. bit_length()¶ Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros: >>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6 More precisely, if xis nonzero, then x.bit_length()is the unique positive integer ksuch that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x)is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2)). If xis zero, then x.bit_length()returns 0. Equivalent to: def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 New in version 2.7. 5.4.3. Additional Methods on Float¶ The float type implements the numbers.Real abstract base class. float also has the following additional methods. float. as_integer_ratio()¶ Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowErroron infinities and a ValueErroron NaNs. New in version 2.6. float. is_integer()¶ Return Trueif the float instance is finite with integral value, and Falseotherwise: >>> (-2.0).is_integer() True >>> (3.2).is_integer() False New in version 2.6.. float. hex()¶ Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading 0xand a trailing pand exponent. New in version 2.6. float. fromhex(s)¶ Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace. New in version 2' 5.5. Iterator Types¶ New: container. __iter__()¶_iterslot of the type structure for Python objects in the Python/C API. The iterator objects themselves are required to support the following two methods, which together form the iterator protocol: iterator. __iter__()¶ Return the iterator object itself. This is required to allow both containers and iterators to be used with the forand instatements. This method corresponds to the tp_iterslot of the type structure for Python objects in the Python/C API. iterator. Return the next item from the container. If there are no further items, raise the StopIterationexception. This method corresponds to the tp_iternextslot of the type structure for Python objects in the Python/C API..) 5.5.1. Generator Types¶. 5.6. Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange¶ There are or Unicode string object the inand not inoperations act like a substring test. In Python versions before 2.3, x had to be a string of length 1. In Python 2.3 and beyond, x may be a string of any length. Values of n less than 0are treated as 0(which yields an empty sequence of the same type as s). Noteare references to this single empty list. Modifying any of the elements of listsmod?. If i or j is negative, the index is relative to the end of the string: len(s) + ior len(s) + jis substituted. But note that -0such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k + tor s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join()method which assures consistent linear concatenation performance across versions and implementations. Changed in version 2.4: Formerly, string concatenation never occurred in-place. 5.6.1. String Methods¶. str. capitalize()¶ Return a copy of the string with its first character capitalized and the rest lowercased. For 8-bit strings, this method is locale-dependent. str. center(width[, fillchar])¶ Return centered in a string of length width. Padding is done using the specified fillchar (default is a space). Changed in version 2.4: Support for the fillchar argument. str. count(sub[, start[, end]])¶ Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. str. decode([encoding[, errors]])¶. str. encode([encoding[, errors]])¶ Return an encoded version of the string.. New in version 2.0. Changed in version 2.3: Support for 'xmlcharrefreplace'and 'backslashreplace'and other error handling schemes added. Changed in version 2.7: Support for keyword arguments added. str. endswith(suffix[, start[, end]])¶ Return Trueif the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix. str. expandtabs([tabsize])¶' str. find(sub[, start[, end]])¶ Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1if sub is not found. str. format(*args, **kwargs)¶. This method of string formatting is the new standard in Python 3, and should be preferred to the %formatting described in String Formatting Operations in new code. New in version 2.6. str. index(sub[, start[, end]])¶ Like find(), but raise ValueErrorwhen the substring is not found. str. isalnum()¶ Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. str. isalpha()¶ Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. str. isdigit()¶ Return true if all characters in the string are digits and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. str. islower()¶ Return true if all cased characters [4] in the string are lowercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. str. isspace()¶ Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. str. istitle()¶. str. isupper()¶ Return true if all cased characters [4] in the string are uppercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. str. join(iterable)¶ Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method. str. ljust(width[, fillchar])¶()¶ Return a copy of the string with all the cased characters [4] converted to lowercase. For 8-bit strings, this method is locale-dependent. str. lstrip([chars])¶' Changed in version 2.2.2: Support for the chars argument. str. partition(sep)¶. New in version 2.5. str. replace(old, new[, count])¶ Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. str. rfind(sub[, start[, end]])¶ Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1on failure. str. rindex(sub[, start[, end]])¶ Like rfind()but raises ValueErrorwhen the substring sub is not found. str. rjust(width[, fillchar])¶)¶. str. rsplit([sep[, maxsplit]])¶. New in version 2.4. str. rstrip([chars])¶' Changed in version 2.2.2: Support for the chars argument. str. split([sep[, maxsplit]])¶ Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1elements). Noneseparator returns []. For example, ' 1 2 3 '.split()returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1)returns ['1', '2 3 ']. str. splitlines([keepends])¶ Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. Python recognizes "\r", "\n", and "\r\n"as line boundaries for 8-bit strings. For example: >>> 'ab c\n\nde fg\rkl\r\n'.splitlines() ['ab c', '', 'de fg', 'kl'] >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True) ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] Unlike split()when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> "".splitlines() [] >>> "One line\n".splitlines() ['One line'] For comparison, split('\n')gives: >>> ''.split('\n') [''] >>> 'Two lines\n'.split('\n') ['Two lines', ''] unicode. splitlines([keepends])¶ Return a list of the lines in the string, like str.splitlines(). However, the Unicode method splits on the following line boundaries, which are a superset of the universal newlines recognized for 8-bit strings. Changed in version 2.7: \vand \fadded to list of line boundaries. str. startswith(prefix[, start[, end]])¶ Return Trueif string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. Changed in version 2.5: Accept tuples as prefix. str. strip([chars])¶' Changed in version 2.2.2: Support for the chars argument. str. swapcase()¶ Return a copy of the string with uppercase characters converted to lowercase and vice versa. For 8-bit strings, this method is locale-dependent. str. title()¶." For 8-bit strings, this method is locale-dependent. str. translate(table[, deletechars])¶module to create a translation table. For string objects, set the table argument to Nonefor translations that only delete characters: >>> 'read this short text'.translate(None, 'aeiou') 'rd ths shrt txt' New in version 2.6: Support for a Nonetable argument. For Unicode objects, the translate()method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to Noneare deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecsmodule (see encodings.cp1251for an example). str. upper()¶ Return a copy of the string with all the cased characters [4] converted to uppercase. Note that str.upper().isupper()might be Falseif scontains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase). For 8-bit strings, this method is locale-dependent. str. zfill(width)¶: unicode. isnumeric()¶ Return Trueif there are only numeric characters in S, Falseotherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. 5.6.2. String Formatting Operations¶ String: - The '%'character, which marks the start of the specifier. - Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)). - Conversion flags (optional), which affect the result of some conversion types. - Minimum field width (optional). If specified as an '*'(asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision. - Precision (optional), given as a '.'(dot) followed by the precision. If specified as '*'(an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision. - Length modifier (optional). - Conversion type. %rconversion was added in Python 2.0. The precision determines the maximal number of characters used. If the object or format provided is a unicodestring,. 5.6.3. XRange Type¶ The. 5.6.4. Mutable Sequence Types¶: t must have the same length as the slice it is replacing. The C implementation of Python has historically accepted multiple parameters and implicitly joined them into a tuple; this no longer works in Python 2.0. Use of this misfeature has been deprecated since Python 1.4. t can be any iterable object. Raises ValueErrorwhenas an equivalent to omitting cmp was added. Changed in version 2.4: Support for key and reverse was added. Starting with Python 2.3, 2.3 and newer makes the list appear empty for the duration, and raises ValueErrorif it can detect that the list has been mutated during a sort. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * nunder Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. 5.7. Set Types — set, frozenset¶. As of Python 2.7, non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor. The constructors for both classes work the same: - class set([iterable])¶ - class frozenset([iterable])¶ Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozensetobjects. If iterable is not specified, a new empty set is returned. Instances of setand frozensetprovide the following operations: len(s) Return the number of elements in set s (cardinality of s). x in s Test x for membership in s. x not in s Test x for non-membership in s. isdisjoint(other)¶ Return Trueif the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. New in version 2.6. set < other Test whether the set is a proper subset of other, that is, set <= other and set != other. set > other Test whether the set is a proper superset of other, that is, set >= other and set != other. union(other, ...)¶ set | other | ... Return a new set with elements from the set and all others. Changed in version 2.6: Accepts multiple input iterables. intersection(other, ...)¶ set & other & ... Return a new set with elements common to the set and all others. Changed in version 2.6: Accepts multiple input iterables. difference(other, ...)¶ set - other - ... Return a new set with elements in the set that are not in the others. Changed in version 2.6: Accepts multiple input iterables. symmetric_difference(other)¶ set ^ other Return a new set with elements in either the set or other but not both.and frozensetsupportare compared to instances of frozensetbased on their members. For example, set('abc') == frozenset('abc')returns Trueand so does set('abc') in set([frozenset('abc')]). The subset and equality comparisons do not generalize to a total ordering function. For example, any two non-empty, like dictionary keys, must be hashable. Binary operations that mix setinstances with frozensetreturn the type of the first operand. For example: frozenset('ab') | set('bc')returns an instance of frozenset. The following table lists operations available for setthat do not apply to immutable instances of frozenset: update(other, ...)¶ set |= other | ... Update the set, adding elements from all others. Changed in version 2.6: Accepts multiple input iterables. intersection_update(other, ...)¶ set &= other & ... Update the set, keeping only elements found in it and all others. Changed in version 2.6: Accepts multiple input iterables. difference_update(other, ...)¶ set -= other | ... Update the set, removing elements found in others. Changed in version 2.6: Accepts multiple input iterables. symmetric_difference_update(other)¶ set ^= other Update the set, keeping only elements found in either set, but not in both. remove(elem)¶ Remove element elem from the set. Raises KeyErrorif elem is not contained. See also - Comparison to the built-in set types - Differences between the setsmodule and the built-in set types. 5.8. Mapping Types — dict¶. - class dict(**kwarg)¶ - class dict(mapping, **kwarg) - class dict(iterable, **kwarg) iterable object. Each item in the iterable must itself be an iterable.if. key in d Return Trueif d has a key key, else False. New in version 2.2. key not in d Equivalent to not key in d. New in version 2.2. iter(d) Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys(). fromkeys(seq[, value])¶ Create a new dictionary with keys from seq and values set to value. fromkeys()is a class method that returns a new dictionary. value defaults to None. New in version 2.3. get(key[, default])¶ Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. has_key(key)¶ Test for the presence of key in the dictionary. has_key()is deprecated in favor of key in d. items()¶()]. iteritems()¶ Return an iterator over the dictionary’s (key, value)pairs. See the note for dict.items(). Using iteritems()while adding or deleting entries in the dictionary may raise a RuntimeErroror fail to iterate over all entries. New in version 2.2. iterkeys()¶ Return an iterator over the dictionary’s keys. See the note for dict.items(). Using iterkeys()while adding or deleting entries in the dictionary may raise a RuntimeErroror fail to iterate over all entries. New in version 2.2. itervalues()¶ Return an iterator over the dictionary’s values. See the note for dict.items(). Using itervalues()while adding or deleting entries in the dictionary may raise a RuntimeErroror fail to iterate over all entries. New in version 2.2. keys()¶ Return a copy of the dictionary’s list of keys. See the note for dict.items(). pop(key[, default])¶ If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyErroris raised. New in version 2.3. popitem()¶ Remove and return an arbitrary (key, value)pair from the dictionary. popitem()is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem()raises a KeyError. setdefault(key[, default])¶ If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None. update([other])¶). Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments. values()¶ Return a copy of the dictionary’s list of values. See the note for dict.items(). viewitems()¶ Return a new view of the dictionary’s items ( (key, value)pairs). See below for documentation of view objects. New in version 2.7. viewkeys()¶ Return a new view of the dictionary’s keys. See below for documentation of view objects. New in version 2.7. viewvalues()¶ Return a new view of the dictionary’s values. See below for documentation of view objects. New in version 2.7. Dictionaries compare equal if and only if they have the same (key, value)pairs. 5.8.1. Dictionary view objects¶ The objects returned by dict.viewkeys(), dict.viewvalues() and dict.viewitems() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. Dictionary views can be iterated over to yield their respective data, and support membership tests: len(dictview) Return the number of entries in the dictionary. iter(dictview)or fail to iterate over all entries. x in dictview Return Trueif.) Then these set operations are available (“other” refers either to another view or a set):() >>> #'} 5.9. File Objects¶: file. Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueErrorafter the file has been closed. Calling close()more than once is allowed. As of Python 2.5, you can avoid having to call this method explicitly if you use the withstatement. For example, the following code will automatically close f when the withblockstatement. If your code is intended to work with any file-like object, you can use the function contextlib.closing()instead of using the object directly. file. flush()¶ Flush the internal buffer, like stdio‘s fflush(). This may be a no-op on some file-like objects. Note flush()does not necessarily write the file’s data to disk. Use flush()followed by os.fsync()to ensure this behavior. file. fileno()¶ Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntlmodule or os.read()and friends. Note File-like objects which do not have a real file descriptor should not provide this method! file. isatty()¶ Return Trueif the file is connected to a tty(-like) device, else False. Note If a file-like object is not associated with a real file, this method should not be implemented. file. A file object is its own iterator, for example iter(f)returns f (unless f is closed). When a file is used as an iterator, typically in a forloop (for example, for line in f: print line.strip()), the next()method is called repeatedly. This method returns the next input line, or raises StopIterationwhen EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order to make a forloop. file. read([size])¶ Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.). Note This function is simply a wrapper for the underlying fread()C function, and will behave the same in corner cases, such as whether the EOF value is cached. file. readline([size])¶. file. readlines([sizehint])¶. file. xreadlines()¶ This method returns the same thing as iter(f). New in version 2.1. Deprecated since version 2.3: Use for line in fileinstead. file. seek(offset[, whence])¶ Set the file’s current position, like stdio‘s fseek(). The whence argument is optional and defaults to os.SEEK_SETor 0(absolute file positioning); other values are os.SEEK_CURor 1(seek relative to the current position) and os.SEEK_ENDor 2(seek relative to the file’s end). There is no return value. For example, f.seek(2, os.SEEK_CUR)advances the position by two and f.seek(-3, os.SEEK_END)sets the position to the third to last. (without 'b'), only offsets returned by tell()are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. Changed in version 2.6: Passing float values as offset has been deprecated.. file. write(str)¶ Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush()or close()method is called. file. writelines(sequence)¶. file. closed¶ bool indicating the current state of the file object. This is a read-only attribute; the close()method changes the value. It may not be available on all file-like objects. file. encoding¶. file. mode¶ The I/O mode for the file. If the file was created using the open()built-in function, this will be the value of the mode parameter. This is a read-only attribute and may not be present on all file-like objects. file. name¶ If the file object was created using open(), the name of the file. Otherwise, some string that indicates the source of the file object, of the form <...>. This is a read-only attribute and may not be present on all file-like objects. file. newlines¶. file. softspace¶ Boolean that indicates whether a space character needs to be printed before another value when using the softspaceattribute, which should be initialized to zero. This will be automatic for most classes implemented in Python (care may be needed for objects that override attribute access); types implemented in C will have to provide a writable softspaceattribute. 5.10. memoryview type¶ New in version 2.7. memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying. Memory is generally interpreted as simple bytes. - class memoryview(obj)¶ Create a memoryviewthat references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include strand bytearray(but not unicode). A memoryviewhas the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such as strand bytearray, an element is a single byte, but other third-party types may expose larger elements. len(view)returns the total number of elements in the memoryview, view. The itemsizeattribute will give you the number of bytes in a single element. A memoryviewsupports slicing to expose its data. Taking a single index will return a single element as a strobject.has two methods: tobytes()¶ Return the data in the buffer as a bytestring (an object of class str). >>> m = memoryview("abc") >>> m.tobytes() 'abc' tolist()¶ Return the data in the buffer as a list of integers. >>> memoryview("abc").tolist() [97, 98, 99] There are also several readonly attributes available: format¶ A string containing the format (in structmodule style) for each element in the view. This defaults to 'B', a simple bytestring. shape¶ A tuple of integers the length of ndimgiving the shape of the memory as an N-dimensional array. strides¶ A tuple of integers the length of ndimgiving the size in bytes to access each element for each dimension of the array. 5.11. Context Manager Types¶ New: contextmanager. __enter__()¶ Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the asclause of withstatements using this context manager. An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow withstatement.statement without affecting code outside the withstatement. contextmanager. __exit__(exc_type, exc_val, exc_tb)¶ Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the withstatement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None. Returning a true value from this method will cause the withstatement to suppress the exception and continue execution with the statement immediately following the withstatement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the withstatement.. 5.12. Other Built-in Types¶ The interpreter supports several other kinds of objects. Most of these support only one or two operations. 5.12.1. Modules¶'>. 5.12.2. Classes and Class Instances¶ See Objects, values and types and Class definitions for these. 5.12.3. Functions¶. 5.12.4. Methods¶ Methods: 'instancemethod' object has no attribute 'whoami' >>> c.method.im_func.>> c.method.whoami 'my name is method' See The standard type hierarchy for more information. 5.12.5. Code Objects¶. See also the code module. A code object can be executed or evaluated by passing it (instead of a source string) to the exec statement or the built-in eval() function. See The standard type hierarchy for more information. 5.12.6. Type Objects¶ Type objects represent the various object types. An object’s type is accessed by the built-in function type(). There are no special operations on types. The standard module types defines names for all standard built-in types. Types are written like this: <type 'int'>. 5.12.7. The Null Object¶ This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name). It is written as None. 5.12.8. The Ellipsis Object¶[...]. 5.12.9. The NotImplemented Object¶ This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See Comparisons for more information. It is written as NotImplemented. 5.12.10. Boolean Values¶. 5.12.11. Internal Objects¶ See The standard type hierarchy for this information. It describes stack frame objects, traceback objects, and slice objects. 5.13. Special Attributes¶ The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the dir() built-in function. object. __dict__¶ A dictionary or other mapping object used to store an object’s (writable) attributes. definition. __name__¶ The name of the class, type, function, method, descriptor, or generator instance. The following attributes are only supported by new-style classes. class. __mro__¶ This attribute is a tuple of classes that are considered when looking for base classes during method resolution. class. mro()¶ This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__. class. __subclasses__()¶ Each new-style class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. Example: >>> int.__subclasses__() [<type 'bool'>] Footnotes
https://docs.python.org/2.7/library/stdtypes.html
CC-MAIN-2016-36
refinedweb
5,189
60.11
IRC log of rdfcore on 2002-10-04 Timestamps are in UTC. 14:01:05 [RRSAgent] RRSAgent has joined #rdfcore 14:01:14 [em] zakim, this is rdfcore 14:01:15 [Zakim] this was already SW_RDFCore()10:00AM 14:01:16 [Zakim] ok, em 14:01:23 [em] zakim, who is here? 14:01:24 [Zakim] On the phone I see FrankM, ??P10 (muted) 14:01:25 [Zakim] On IRC I see RRSAgent, em, Zakim, DanC, logger, Aa-latere, jang 14:01:34 [Zakim] +??P11 14:01:43 [DanC] anybody know what PatrickS means by "this proposal" in his recent message? 14:01:59 [Zakim] +??P13 14:02:04 [em] em has changed the topic to: rdfcore 2002-10-04 teleconference 14:02:32 [Zakim] +??P15 14:02:34 [DanC] "Of that the WG has had nearly unanimous agreement" <- as far as I know, the WG hasn't made any decisions about datatyping. We have no approved test cases. Or did I miss something? 14:02:41 [bwm] bwm has joined #rdfcore 14:02:50 [gk-scribe] gk-scribe has joined #rdfcore 14:02:54 [DanC] anybody know what PatrickS means by "this proposal" in his recent message? 14:02:56 [DanC] "Of that the WG has had nearly unanimous agreement" <- as far as I know, the WG hasn't made any decisions about datatyping. We have no approved test cases. Or did I miss something? 14:03:38 [DanC] Jermy writes "we had already agreed on with the 14:03:38 [DanC] rdf:datatype mechanism" 14:03:44 [DanC] ^where's the record of that agreement? 14:03:50 [DaveB] DaveB has joined #rdfcore 14:03:51 [JosD] JosD has joined #rdfcore 14:03:55 [DanC] when did the wg agree to rdf:datatype? 14:04:08 [jjc] jjc has joined #rdfcore 14:04:14 [jjc] jjc has joined #rdfcore 14:04:41 [Zakim] +??P14 14:04:43 [bwm] 3-4 weeks ago 14:04:44 [em] zakim, who is here? 14:04:45 [Zakim] On the phone I see FrankM, ??P10, ??P11, ??P13, ??P15, ??P14 14:04:46 [Zakim] On IRC I see jjc, JosD, DaveB, gk-scribe, bwm, RRSAgent, em, Zakim, DanC, logger, Aa-latere, jang 14:05:07 [Zakim] +EricM 14:05:22 [em] we seem to have a lot of unknowns... 14:05:52 [Zakim] +??P16 14:06:05 [em-scribe] zakim, ??P16 is MikeD 14:06:06 [Zakim] +MikeD; got it 14:06:06 [JosD] Zakim, ??p14 is JosD 14:06:08 [Zakim] +JosD; got it 14:06:24 [em-scribe] jjc to scribe next week 14:06:27 [em-scribe] role call... 14:06:30 [em-scribe] zakim, who is on the phone 14:06:31 [Zakim] I don't understand 'who is on the phone', em-scribe 14:06:33 [em-scribe] zakim, who is on the phone? 14:06:34 [Zakim] On the phone I see FrankM, ??P10, ??P11, ??P13, ??P15, JosD, EricM, MikeD 14:06:44 [danbri] danbri has joined #rdfcore 14:06:54 [Zakim] +??P17 14:07:01 [em-scribe] zakim, ??P17 is PatH. 14:07:02 [Zakim] +PatH.; got it 14:07:12 [em-scribe] zakim, ??P10 is bristol. 14:07:13 [Zakim] +Bristol.; got it 14:07:21 [em-scribe] zakim, ??P11 is PatrickS. 14:07:22 [Zakim] +PatrickS.; got it 14:07:29 [em-scribe] zakim, ??P13 is SteveP. 14:07:30 [Zakim] +SteveP.; got it 14:07:33 [em-scribe] zakim, ??P13 is GK. 14:07:34 [Zakim] sorry, em-scribe, I do not recognize a party named '??P13' 14:07:39 [em-scribe] zakim, ??P15 is GK. 14:07:40 [Zakim] +GK.; got it 14:07:48 [em-scribe] agenda discussion.... 14:07:54 [Zakim] +DanC 14:07:55 [em-scribe] patrick: sent item earlier 14:08:01 [DaveB] Zakim, bristol has bwm, jjc, daveb 14:08:02 [Zakim] +Bwm, Jjc, Daveb; got it 14:08:28 [em-scribe] DanC: rdfs:format agenda request? 14:08:34 [em-scribe] bwm: agenda item 9. 14:08:42 [em-scribe] minutes from last telecon are approved... 14:09:35 [Zakim] +EricP 14:09:36 [danbri] zakim, EricP is temporarily DanBri 14:09:37 [Zakim] +DanBri; got it 14:10:11 [em-scribe] minutes from last telecon are approved... 14:10:19 [em-scribe] todays agenda - 14:10:46 [em-scribe] brian: talking about voting structure 14:10:47 [DanC] how many members are there in good standing? 14:11:02 [em-scribe] brian: we're looking for 2/3 majority 14:11:04 [DaveB] that's a q for team contact 14:11:12 [DanC] yup; I'm asking em-scribe 14:11:27 [em-scribe] i missed the question? 14:11:38 [Zakim] +AaronSw 14:12:58 [em-scribe] ack DanC 14:13:17 [AaronSw] n-way questions sounds equivalent to condorcet 14:13:23 [AaronSw] is someone breathng heavily? 14:13:31 [DanC] Zakim, who's talking? 14:13:35 [mdean] mdean has joined #rdfcore 14:13:42 [Zakim] DanC, listening for 10 seconds I heard sound from the following: FrankM (55%), Bristol. (39%), PatrickS. (95%), PatH. (30%), DanBri (29%), DanC (5%) 14:14:07 [DanC] em-scribe, did you get the details of the voting procedure? or is there an action on bwm to mail out details? 14:14:21 [em-scribe] i'm going to ask for an action to the chair 14:15:52 [em-scribe] ACTION: Brian to send message to the list re the specifics of the voting procedure 14:16:43 [em-scribe] PS: agenda 7 ... (are we away from this) 14:18:20 [em-scribe] agenda 8.... HP Proposal - 14:18:43 [em-scribe] jjc: compromise between tidy and untidy proposal 14:19:56 [DanC] jjc, just say "yes". 14:20:25 [gk] jjc: Proposal is alternative, not replacement for typed literal 14:20:42 [em-scribe] mdean: does it have to be in the top? if so, how is this supported? 14:20:43 [DanC] again, jjc, the answer to mdean's question is "yes". 14:21:14 [em-scribe] jjc: if you round tripping, the order may not be preserved... literal by literal datatpye may be possible 14:22:06 [em-scribe] JosD: similar to namespace declarations 14:22:51 [DanC] mdean, consensus isn't at issue yet; jjc gets to say, unilaterally, what the proposal is. 14:22:51 [em-scribe] bwm: mike, is this a critical detail that is required to help explain (and decide) on this proposal? 14:24:55 [gk] q+ to say I think the proposal is fine in principle, but I'm concerned about some details and don't see why we need it at this time 14:24:58 [gk] q- 14:25:25 [danbri] q+ to suggest that XML entities give us a syntax hack for this already 14:25:36 [DanC] how so, danbri? 14:25:59 [DaveB] not for every property; only in generally shortening verboseness 14:26:14 [danbri] I read the HP proposal as a sort of macro expansion thingy... And that we could do same as people do now for taking up less room 14:26:18 [danbri] ...with uris etc 14:26:21 [jjc] correct 14:26:23 [danbri] hmm, can entities have whitespace in them? 14:26:26 [em-scribe] DaveB: changes to this proposal would only be in the syntax and primer documents 14:26:29 [danbri] q- 14:26:54 [DanC] jjc/danbri, has the WG decided to adopt the rdfd:datatype stuff? can somebody help me find the record of it? when was it? 14:27:03 [em-scribe] Patrick, i missed the querstion? can you repeat? 14:27:15 [DaveB] we did decide thiat danc, was called 'approving part1' i think 14:27:31 [em-scribe] pps; will there be some mechansism so that instance data would have to be mod to use this faciliyt? 14:27:37 [em-scribe] annswer: no 14:27:39 [danbri] I'm looking for such decisions too, for my RDFS editorial task list. 14:27:45 [em-scribe] arr... pps; -> PatrickS (sorry) 14:28:18 [em-scribe] DanC: the working group has approved rdfs:datatype? 14:28:21 [em-scribe] answer: yes 14:28:23 [em-scribe] (uri?) 14:28:40 [em-scribe] DanC: ok, i retrack the suggestion 14:28:41 [DaveB] getting it 14:28:49 [em-scribe] thanks DaveB 14:29:08 [DanC] no, I don't withdraw my proposal; I'm just not prepared to argue to re-open the rdfs:datatype decision. 14:29:16 [em-scribe] ok, thanks for clarification 14:29:17 [DanC] I withdraw my agenda request. 14:29:29 [DaveB] in msg .../2002/Sep/0178.html minutes of 2002-09-13 item 9 14:29:33 [jjc] q+ 14:29:35 [em-scribe] q+ 14:30:12 [DaveB] em-scribe: above url has the datatypes 1 decision recorded, i can't cut'n'paste urls here 14:30:30 [em-scribe] q? 14:30:42 [jjc] q- 14:31:22 [AaronSw] Zakim, who's talking? 14:31:28 [DanC] DaveB, item 9 on 13Sep was about splitting the document among the existing WDs; it wasn't a design decision, was it? 14:31:34 [Zakim] AaronSw, listening for 10 seconds I heard sound from the following: FrankM (39%), PatH. (15%), DanBri (68%), EricM (21%), DanC (5%) 14:31:52 [jjc] Zakim, who's talking? 14:32:03 [Zakim] jjc, listening for 10 seconds I heard sound from the following: FrankM (68%), PatrickS. (10%), PatH. (24%), DanBri (34%), EricM (76%), DanC (9%) 14:32:51 [jjc] q+ 14:32:54 [DaveB] DanC: it was, but by adding the docs secs to the WDs, it added rdf datatyping 14:33:55 [DanC] oh come on! the record doesn't say anything of the sort. 14:34:09 [Zakim] -SteveP. 14:34:33 [em-scribe] ack em 14:35:05 [DaveB] DanC: right, I see item 10 in 2002Sep/0081.html that is more explicit 14:35:22 [Zakim] +??P2 14:35:33 [gk] zakim, ??p2 is gk 14:35:35 [Zakim] +Gk; got it 14:35:41 [Zakim] -AaronSw 14:35:44 [DanC] ah, thx DaveB 14:35:53 [Zakim] +Guha 14:36:13 [em-scribe] ACTION: bwm, to help articulate a the tidy/untidy discussion (more statement.. 'can you live with this') and ask WebOnt at f2f 14:36:26 [Zakim] +AaronSw 14:37:04 [DanC] re my question on whether the WG has decided about rdf:datatype, yes, in item 10 on 6Sep 14:38:34 [em-scribe] ACTION: ericm, to contact the Adobe XMP folk and solicit input to tidy/untidy debate 14:39:30 [em-scribe] bwm to survey customers.... 14:39:49 [em-scribe] DaveB: (and aaron) say that DC is tidy('esq) 14:40:17 [em-scribe] ACTION: bwm, to contact Mark Butler (CCPP) about tidy/untidy issue 14:40:56 [DanC] note to self: suggest a technical way to address the conflict between cc/pp's current schema and tidy semantics. (specifically: change rdfs:range to rdfs:format, and the conflict goes away) 14:41:06 [em-scribe] action danc? 14:41:39 [DanC] ok by me, but it needs to be OK by the chair too, and I'm not sure he wants to go there. 14:41:49 [DanC] (i.e. to interrupt the discussion) 14:42:58 [em-scribe] bwm: is this propsal helpful? 14:43:03 [gk] q+ to the extent that verbosity is a concern, I think HP proposal helps 14:43:31 [em-scribe] stevep: i think this helps 14:43:50 [em-scribe] mdean: i think this helps some... need to think more (round tripping important0 14:44:01 [em-scribe] q? 14:44:06 [em-scribe] ack jjc 14:44:08 [em-scribe] ack Gk 14:44:08 [jjc] q- 14:44:08 [Zakim] Gk, you wanted to the extent that verbosity is a concern, I think HP proposal helps 14:44:36 [em-scribe] ack DanC 14:44:37 [Zakim] DanC, you wanted to say that the HP might help with verbosity, but it's too complex/messy 14:45:52 [em-scribe] DanC: new syntax is the core my concern 14:46:01 [em-scribe] (impact on testcases, parsers) 14:46:10 [em-scribe] implementation cost discussion.... 14:46:24 [em-scribe] DaveB: its new but i dont consider this large 14:46:31 [em-scribe] on the order of hours 14:46:42 [em-scribe] jjc: hours 14:46:46 [em-scribe] jjc: hours to implement 14:47:03 [em-scribe] q+ to ask frank 14:47:35 [em-scribe] q? 14:48:18 [em-scribe] ack em 14:48:19 [Zakim] Em, you wanted to ask frank 14:49:24 [Zakim] -AaronSw 14:49:27 [DaveB] i'd simplify this something like <rdf:DatatypingBlah rdf: 14:50:01 [Zakim] +AaronSw 14:50:07 [em-scribe] q? 14:50:11 [DanC] ah... I'm starting to remember why I didn't absorb the rdfd:datatype proposal... the spec is in a zip file that I never got around to unzipping; I should have objected to the record. 14:50:57 [DaveB] or <rdf:DatatypingRanges foo: 14:51:50 [DanC] yeah, but what about semantics? does it say that xsd:decimal is a class? a property? what's its extension? 14:52:04 [DanC] to me, it's a propoerty. 14:52:06 [DaveB] it's a syntax abbreviation 14:52:24 [DaveB] s/DatatypeingRanges/other term/ 14:52:40 [DanC] it (part1) doesn't specify any relationship between rdfs:range and that syntax? 14:54:50 [DanC] in section 6.1.2, I see <rdfs:range rdf:. sigh. 14:55:10 [Zakim] -AaronSw 14:55:48 [JosD] Zakim, mute JosD 14:55:50 [Zakim] JosD should now be muted 14:56:39 [DanC] Zakim, who's talking? 14:56:49 [Zakim] DanC, listening for 10 seconds I heard sound from the following: FrankM (60%), Bristol. (30%), PatrickS. (100%), PatH. (45%), DanBri (46%) 14:57:04 [gk] jjc, you mention datatyping being file-scoped -- do you mean that, or do you mean element-scoped? 14:57:12 [bwm] detail 14:57:16 [jjc] don't know 14:57:20 [JosD] Zakim, unmute JosD 14:57:22 [Zakim] JosD should no longer be muted 14:57:25 [jjc] I haven't really decided 14:58:26 [gk] (Yes, it's detail) 14:58:59 [em-scribe] frank: this prosal will require additinoal work on the primer 14:59:26 [DaveB] (DanC: sec 6 of that doc wasn't proposed to go in wds, if you looka t the split) 15:01:17 [em-scribe] DanC: <agr rdf: 15:02:40 [em-scribe] PatH: purely a lexical check?> 15:02:46 [em-scribe] DanC: yes per MT 15:02:51 [gk] q+ to ask DanC if his format check can be used with typed literals 15:03:13 [em-scribe] guha: there is actually history for this (CYC).. worked quite well 15:04:07 [em-scribe] PatH: is this propsal incompatable with typed literals? 15:04:09 [em-scribe] jjc: yes 15:04:19 [em-scribe] PatH: then i dont this is acceptable 15:04:55 [gk] q+ to object to withdrawal of typed literals 15:06:01 [em-scribe] guha: support danc's propsal 15:06:11 [em-scribe] JosD: agreed.. simple and straitforward 15:06:17 [em-scribe] miked: i support this as well 15:06:33 [em-scribe] guha: danc would go fine with the dmoz stuff 15:06:37 [gk] My position: the availability of typed literals is important to my view of accepting tidy literals in CC/PP ... see my message about redesigning CC/PP for tidy literals 15:06:39 [danbri] I like the sound of it too. 15:06:51 [DaveB] it=what? 15:06:52 [em-scribe] path: i'm amazed that you guys are supporting this... seems to rule out datatyping? 15:07:07 [danbri] it=danc's proposal. But I don't understand how it is incompatible with typed literals. 15:07:15 [DaveB] also limits to only XSD types, which isn't good 15:07:24 [DaveB] for e.g. DC can't use that limitation 15:08:05 [gk] I think DanC's proposal to withdraw typed literals is a bigger step back than any other we've considered today. 15:08:20 [em-scribe] PatrickS: i appose 15:08:38 [em-scribe] PatH: i disagree with this proposal as well 15:09:46 [em-scribe] PS: tidy/untidy debat as uncovered a divide... RDF as a markup model and others who want to represent knowledge... 15:09:47 [Zakim] -GK. 15:09:54 [Zakim] -PatH. 15:09:54 [Zakim] -JosD 15:09:54 [Zakim] -Guha 15:10:06 [Zakim] -MikeD 15:10:08 [gk] zamik, whos on the phone? 15:10:14 [gk] zakim, whos on the phone? 15:10:16 [Zakim] I don't understand your question, gk. 15:10:17 [em-scribe] zakim, who is on the phone? 15:10:18 [Zakim] On the phone I see FrankM, Bristol., PatrickS., EricM, DanC, DanBri, Gk 15:10:19 [Zakim] Bristol. has Bwm, Jjc, Daveb 15:10:33 [DaveB] Zakim: bristol has bwm, daveb 15:10:43 [DaveB] hmm 15:14:32 [Zakim] -DanBri 15:15:05 [danbri] danbri has left #rdfcore 15:20:49 [em-scribe] folks... i have to run ... thanks 15:21:12 [Zakim] -EricM 15:29:57 [Zakim] -Gk 15:35:17 [Zakim] -FrankM 15:35:22 [Zakim] -DanC 15:36:07 [DaveB] Zakim, who is on the phone? 15:36:09 [Zakim] On the phone I see Bristol., PatrickS. 15:36:09 [Zakim] Bristol. has Bwm, Jjc, Daveb 15:51:52 [Zakim] -PatrickS. 15:51:59 [Zakim] -Bristol. 15:52:01 [Zakim] SW_RDFCore()10:00AM has ended 17:50:50 [Zakim] Zakim has left #rdfcore 18:24:47 [DanC] DanC has left #rdfcore
http://www.w3.org/2002/10/04-rdfcore-irc
CC-MAIN-2014-52
refinedweb
3,003
72.76
An introduction to libROSA for working with audio Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Reading time: 35 minutes | Coding time: 20 minutes Librosa is powerful Python library built to work with audio and perform analysis on it. It is the starting point towards working with audio data at scale for a wide range of applications such as detecting voice from a person to finding personal characteristics from an audio. In this article, we will learn: - how to use Librosa and load an audio file into it - Get audio timeline, plot it for amplitude, find tempo and pitch - Compute mel-scaled spectrogram, time stretch an audio, remix an audio It help us to implement: - Audio signal analysis for music. - Reference implementation of common methods. - Building blocks for Music information retrieval (MIR). For a better understanding of libROSA it is said to have a knowledge about NumPy and SciPy. libROSA can be defined as a package which is structured as collection of submodules which further contains other functions. For installing the libROSA you just need to run the following command in your command line: pip install libROSA --user In your Python code, you can import it as: import librosa as lr We will use Matplotlib library for plotting the results and Numpy library to handle the data as array. The first step towards our analysis is to load an audio library into our code. This is done using librosa.core.load() function. Audio will be automatically resampled to the given rate (default = 22050). To preserve the native sampling rate of the file, use sr=None. librosa.core.load(path, sr=22050, mono=True, offset=0.0, duration=None, dtype=<class 'numpy.float32'>, res_type='kaiser_best') where - path: is the path to the audio file and is a string parameter is the sampling rate mono is the option (true/ false) to convert it into mono file. offset is a floating point number which is the starting time to read the file duration is a floating point number which signifies how much of the file to load. dtype is the numeric representation of data can be float32, float16, int8 and others. res_type is the type of resampling (one option is kaiser_best) Timeline for your audio In this code, we will print the timeline of the audio file. We will simply load the audio, convert it into a numpy array and print the output for one sample (by dividing by sampling rate). import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr audio='arabic6' # change with the name of your audio y, sr = lr.load('./{}.wav'.format(audio)) #you just need to make sure your audio is in the same folder in which you are coding or else you can change the path as per your requirement time = np.arange(0,len(y))/sr print(time) # prints timeline of arabic6 Output : [0.00000000e+00 4.53514739e-05 9.07029478e-05 ... 2.63027211e+01 2.63027664e+01 2.63028118e+01] Plotting the audio : Plotting the audio as Time v/s Sound amplitude import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) time = np.arange(0,len(y))/sr fig, ax = plt.subplots() ax.plot(time,y) ax.set(xlabel='Time(s)',ylabel='sound amplitude') plt.show() Output : Plotting and finding the estimating tempo Tempo was originally used to describe the timing of music, or the speed at which a piece of music is played or can be defined as beats per second. librosa.beat.tempo(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=<function mean at 0x7f3faa08a510>) It will return tempo as an array Parameters: - y: audio time series - sr: sampling rate of the time series - onset_envelope: pre-computed onset strength envelope - hop_length: hop length of the time series - start_bpm: initial guess of the BPM - std_bpm: standard deviation of tempo distribution - ac_size: length (in seconds) of the auto-correlation window - max_tempo: estimate tempo below this threshold - aggregate: for estimating global tempo. If None, then tempo is estimated independently for each frame. CODE import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) onset_env = lr.onset.onset_strength(y, sr=sr) tempo = lr.beat.tempo(onset_envelope=onset_env, sr=sr) print(tempo) tempo = np.asscalar(tempo) # Compute 2-second windowed autocorrelation hop_length = 512 ac = lr.autocorrelate(onset_env, 2 * sr // hop_length) freqs = lr.tempo_frequencies(len(ac), sr=sr,hop_length=hop_length) # Plot on a BPM axis. We skip the first (0-lag) bin. plt.figure(figsize=(8,4)) plt.semilogx(freqs[1:], lr.util.normalize(ac)[1:],label='Onset autocorrelation', basex=2) plt.axvline(tempo, 0, 1, color='r', alpha=0.75, linestyle='--',label='Tempo: {:.2f} BPM'.format(tempo)) plt.xlabel('Tempo (BPM)') plt.grid() plt.title('Static tempo estimation') plt.legend(frameon=True) plt.axis('tight') plt.show() Output : [112.34714674] Finding and plotting the pitch The sensation of a frequency is commonly referred to as the pitch of a sound. A high pitch sound corresponds to a high frequency sound wave and a low pitch sound corresponds to a low frequency sound wave. librosa.core.piptrack(y=None, sr=22050, S=None, n_fft=2048, hop_length=None, fmin=150.0, fmax=4000.0, threshold=0.1, win_length=None, window='hann', center=True, pad_mode='reflect', ref=None) Paramters : y: audio signal sr: audio sampling rate of y S: magnitude or power spectrogram n_fft: number of FFT bins to use, if y is provided. hop_length: number of samples to hop threshold: A bin in spectrum S is considered a pitch when it is greater than threshold * ref(S). fmin: lower frequency cutoff. fmax: upper frequency cutoff. win_length: Each frame of audio is windowed by window(). ref:scalar or callable for pitch It returns: - pitches:np.ndarray [shape=(d, t)] - magnitudes:np.ndarray [shape=(d,t)] Where d is the subset of FFT bins within fmin and fmax. pitches[f, t] contains instantaneous frequency at bin f, time t magnitudes[f, t] contains the corresponding magnitudes. Both pitches and magnitudes take value 0 at bins of non-maximal magnitude. CODE import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr from IPython.display import Audio audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) pitches, magnitudes = lr.piptrack(y=y, sr=sr) print(pitches) print('///') print(magnitudes) plt.subplot(212) plt.show() plt.plot(pitches) plt.show() Output : [.]] Compute a mel-scaled spectrogram An object of type MelSpectrogram represents an acoustic time-frequency representation of a sound librosa.feature.melspectrogram(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', power=2.0, **kwargs) Parammeters : y: audio time-series sr: sampling rate of y S: spectrogram n_fft: length of the FFT window hop_length: number of samples between successive frames. See librosa.core.stft win_length: Each frame of audio is windowed by window(). power: Exponent for the magnitude melspectrogram. e.g., 1 for energy, 2 for power, etc. kwargs:additional keyword arguments Mel filter bank parameters. See librosa.filters.mel for details. Returns: - S:np.ndarray [shape=(n_mels, t)] Mel spectrogram CODE import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr import librosa.display audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) lr.feature.melspectrogram(y=y, sr=sr) D = np.abs(lr.stft(y))**2 S = lr.feature.melspectrogram(S=D) S = lr.feature.melspectrogram(y=y, sr=sr, n_mels=128,fmax=8000) plt.figure(figsize=(10, 4)) lr.display.specshow(lr.power_to_db(S,ref=np.max),y_axis='mel', fmax=8000,x_axis='time') plt.colorbar(format='%+2.0f dB') plt.title('Mel spectrogram') plt.tight_layout() plt.show() Output : Modifying the audio : Time-stretch an audio series by a fixed rate librosa.effects.time_stretch(y, rate, **kwargs) Parameters: - y: audio time series - rate: Stretch factor. If rate > 1, then the signal is sped up. If rate < 1, then the signal is slowed down. - kwargs: additional keyword arguments. See librosa.decompose.stft for details. Returns: - y_stretch: audio time series stretched by the specified rate CODE import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) y_fast = lr.effects.time_stretch(y, 2.0) time = np.arange(0,len(y_fast))/sr fig, ax = plt.subplots() ax.plot(time,y_fast) ax.set(xlabel='Time(s)',ylabel='sound amplitude') plt.show()#compress to be twice as fast y_slow = lr.effects.time_stretch(y, 0.5) time = np.arange(0,len(y_slow))/sr fig, ax = plt.subplots() ax.plot(time,y_slow) ax.set(xlabel='Time(s)',ylabel='sound amplitude') plt.show()#half the original speed Output : Remix an audio signal by re-ordering time intervals new. librosa.effects.remix(y, intervals, align_zeros=True) Parameters : y: Audio time series intervals: iterable of tuples (start, end) An iterable (list-like or generator) where the i th itemintervals[i] indicates the start and end (in samples) of a slice of y. align_zeros: boolean If True, interval boundaries are mapped to the closest zero-crossing in y. If y is stereo, zero-crossings are computed after converting to mono. Returns: - y_remix:np.ndarray [shape=(d,) or (2, d)] - y remixed in the order specified by intervals CODE import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa as lr audio='arabic6' y, sr = lr.load('./{}.wav'.format(audio)) _, beat_frames = lr.beat.beat_track(y=y, sr=sr,hop_length=512) beat_samples = lr.frames_to_samples(beat_frames) intervals = lr.util.frame(beat_samples, frame_length=2,hop_length=1).T y_out = lr.effects.remix(y, intervals[::-1]) time = np.arange(0,len(y_out))/sr fig, ax = plt.subplots() ax.plot(time,y_out) ax.set(xlabel='Time(s)',ylabel='sound amplitude') plt.show() Output :
https://iq.opengenus.org/introduction-to-librosa/
CC-MAIN-2021-17
refinedweb
1,688
51.24
I put a bunch of scripts that generate variations of the same HDA in the TAB menu. So I have one tool and you can basically get a preset version of it straight from the TAB menu. And it can be looked up by the name of the preset. That's all good and it works. The issue arises, when I try to update the version of this HDA. I have the same HDA with the same script, name and namespace and incremented version suffix. But I get the old version from the TAB menu, when I use the generated labels. The TAB menu just keeps using the scripts from the older version. (I verified that by modifying the older version and observing the change.) When I delete the scripts in the older version, the TAB menu scripts use the newer version. Is this a bug, or am doing something wrong?
https://www.sidefx.com/forum/topic/75733/?page=1#post-324083
CC-MAIN-2022-40
refinedweb
151
83.05
. Note: If the first task run is not succeeded then on every retry task XComs will be cleared to make the task run idempotent. Custom XCom. You can also override the clear method and use it when clearing results for given dags and tasks. This allows the custom XCom backend to process the data lifecycle easier. Working with Custom XCom Backends in Containers¶ Depending on where Airflow is deployed i.e., local, Docker, K8s, etc. it can be useful to be assured that a custom XCom backend is actually being initialized. For example, the complexity of the container environment can make it more difficult to determine if your backend is being loaded correctly during container deployment. Luckily the following guidance can be used to assist you in building confidence in your custom XCom implementation. Firstly, if you can exec into a terminal in the container then you should be able to do: from airflow.models.xcom import XCom print(XCom.__name__) which will print the actual class that is being used. You can also examine Airflow’s configuration: from airflow.settings import conf conf.get("core", "xcom_backend") Working with Custom Backends in K8s via Helm¶ Running custom XCom backends in K8s will introduce even more complexity to you Airflow deployment. Put simply, sometimes things go wrong which can be difficult to debug. For example, if you define a custom XCom backend in the Chart values.yaml (via the xcom_backend configuration) and Airflow fails to load the class, the entire Chart deployment will fail with each pod container attempting to restart time and time again. When deploying in K8s your custom XCom backend needs to be reside in a config directory otherwise it cannot be located during Chart deployment. An observed problem is that it is very difficult to acquire logs from the container because there is a very small window of availability where the trace can be obtained. The only way you can determine the root cause is if you are fortunate enough to query and acquire the container logs at the right time. This in turn prevents the entire Helm chart from deploying successfully.
https://airflow.apache.org/docs/apache-airflow/2.2.4/concepts/xcoms.html
CC-MAIN-2022-33
refinedweb
355
54.83