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
Re: using of "@" before classname - From: Brian Gideon <briangideon@xxxxxxxxx> - Date: Wed, 28 May 2008 09:03:00 -0700 (PDT) On May 28, 5:47 am, Abhi <A...@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote: i was looking in some code in which i found that it is using @ keyword before class name and constructor like this public class @MyClass { public @MyClass { } } can anyone please help me to know that when and why we use this keyword before classname. Thanks Abhi It allows reserved words to be used as identifiers. It's use in C# is not that common. The reasoning behind that is that all keywords in C# begin with a lowercase character and if you follow the .NET naming guidelines you would make all public API identifiers begin with a capital letter. So even if your API was developed in another language it's still not going to be likely that you encounter an identifier- keyword collision in C#. It's a lot more likely that you would need to use VB.NET's equivalent [] characters to surround identifiers since VB is not case sensitive. For example, I could declare a class called Stop in C# not knowing that it was a keyword in VB.NET forcing developers of VB.NET to use []'s if they wanted to use my class. . - Prev by Date: TextBox with memory - Next by Date: Re: random sorting a collection - Previous by thread: Re: using of "@" before classname - Next by thread: problem with using CompareTo when having string - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2008-05/msg02892.html
crawl-002
refinedweb
252
69.72
MY_SOFTSPI in MySensors 2.0 clashes with built-in Arduino SD-Card Library Here is how to reproduce the problem: Use: - Latest (as of this write-up; SD Built-In by Arduino, Sparkfun 1.08) standard SD Card library from Arduino. - Latest MySensors libraries (2.0.0). Try to compile the following sketch: #include <SPI.h> #include <SD.h> #define MY_RADIO_NRF24 #define MY_SOFTSPI #include <MySensors.h> The following error is reported: DigitalPin.h:41:8: error: redefinition of 'struct pin_map_t' Maybe something should be conditionally included inside MySensors.h or thereafter within. Otherwise, most likely it will clash with other libraries that include the same thing(s). Cheers, Jordan
https://forum.mysensors.org/topic/4446/my_softspi-in-mysensors-2-0-clashes-with-built-in-arduino-sd-card-library/?page=1
CC-MAIN-2019-43
refinedweb
109
54.39
Aspect-oriented programming (AOP) is becoming increasingly popular on the Java™ platform. As AOP press and conference buzz grows, more tools and implementations of the technology are emerging. While it is clear that AOP is a complementary addition to object-oriented programming, it's less clear how Java developers should evaluate the current crop of AOP tools, particularly given the trade-offs inherent in any new technology implementation. In this two-part article, the first in a new developerWorks series devoted to AOP, I'll outline the state of the art in AOP tools and compare the most mature approaches to the technology -- AspectJ, AspectWerkz, JBoss AOP, and Spring AOP -- and contrast the adoption-related issues of each. I'll also address the implications of the recently announced merging of the AspectJ and AspectWerkz projects (see Resources). This article is not intended as an introduction to AOP or a primer on any one particular AOP implementation. Rather, it serves as an overview of the most commonly used AOP technologies available today. In-depth discussion of the trade-offs inherent in each tool's language mechanisms and tool support will help you choose the approach best suited to your projects. The criteria defined here should also make it easier for you to evaluate upcoming releases of AOP tools and features. For a listing of recent developerWorks articles introducing AOP, please refer to Resources. Note that this is a two-part article, with both parts published simultaneously for your convenience. Part 1 focuses on how each of the four leading tools handles the AOP language mechanisms. Topics include differences and similarities among the tools' aspect syntax and pointcut expressiveness, and the range of mechanisms for declaring aspects. Part 2 continues with a closer look at how the leading AOP implementations integrate with existing development environments, tools, and libraries. Topics include aspect weavers, IDE plug-ins, scalability, and upcoming directions for AOP tools, including a focus on the recent merging of the AspectJ and AspectWerkz projects. AOP is a new technology, and, as such, not all of the current crop of tools are mature enough for commercial development. One of the chief factors in determining maturity is user adoption. Before a new programming technology can be considered for commercial use, it must be hardened by feedback from an active user community. Table 1 shows the currently available AOP tools as listed on aosd.net (see Resources). The number of user-list posts for each tool gives us an idea of its user base. (The actual number of posts is omitted as statistics for a single month could be misleading.) Table 1. Number of posts to AOP tools user lists in November 2004 Note that the AOP portion of the Spring framework does not constitute a separate download or user community, so a percentage of the user base is likely posting about topics other than Spring AOP. Four additional tools are listed on aosd.net, but they either lack a user discussion forum or showed no posts in November. While the AOP tools that do not appear among the top four in the table may be technologically sophisticated, the lack of a strong user base suggests that they have not yet withstood the test of adoption. Although not suitable for commercial development at this writing, these tools are worth watching in the future. The table also indicates that non-Java platform AOP tools are less mature than Java platform ones, but it should be noted that the user communities for .NET and C++ tools are growing. Based on Table 1, you can see that AspectJ, AspectWerkz, JBoss AOP, and Spring AOP are the leading tools in terms of user adoption. All of these tools are open source projects suitable for use in commercial development. They are listed here in alphabetical order, along with V1.0 release dates: - AspectJ -- Released in 2001 from the AOP team at Xerox PARC. Currently hosted on eclipse.org and backed by IBM. Version reviewed is 1.2.1. - AspectWerkz -- Released in 2002 and backed by BEA Systems. Version reviewed is 2.0RC2. - JBoss AOP -- Released in 2004 as an addition to the JBoss application server framework. Version reviewed is 1.0. - Spring AOP -- Released in 2004 as an addition to the Spring framework. Version reviewed is 1.1.3. It's all about join points Each of the AOP tools reviewed in this article employs a join point model and mechanisms for explicitly declaring a program's crosscutting structure. While there is much similarity in how the tools implement this framework, it's important to understand the underlying mechanisms in order to appreciate the trade-offs of each approach. In this section, I'll review the AOP join point model and the language mechanisms that leverage it. AOP tools are designed to modularize crosscutting concerns, such as authentication and transaction management. When implemented with object-oriented programming alone, the code for these concerns becomes scattered across the system. Such scattering makes crosscutting structure needlessly hard to manage and evolve. Just as objects provide a language mechanism to cleanly capture inheritance structures, AOP enables the same benefits of good modularity for crosscutting concerns. At the heart of each of the AOP tools is a join point model, which provides a means of identifying where the crosscutting is happening. A join point is where the main program and the aspects meet. Static join points allow aspects to define new members on a class. Dynamic join points are where aspect execution meets the execution of the program. For example, plain Java programs execute join points such as method calls and field sets. Consider, for example, the concern of monitoring activity that alters the state of an Account, as discussed in Ramnivas Laddad's book AspectJ in Action (see Resources). The sequence diagram in Figure 1 highlights a few of the dynamic join points that result from operations on an Account. Figure 1. UML sequence diagram with selected dynamic join points highlighted Numbers below correspond to those in the figure: - Method execution join points correspond to the life cycle of a method until it returns. - Control flows capture the various join points that occur within a control flow sequence; in this case, the sequence below the debit()method call describes all the join points that occur within the debit()call. - Field access join points correspond to reads and writes of fields; in this case, an assignment of the namefield that is made on the Accountclass. Pointcuts, advice, and inter-type declarations AOP tools provide a mechanism for identifying sets of join points, called a pointcut. The advice mechanism specifies what action to take when a pointcut is matched in the execution of the program. In addition, inter-type declarations (also known as open classes or mixins) provide a means of declaring additional members on existing types. Together, pointcuts, advice, and inter-type declarations allow AOP languages to express crosscutting concerns explicitly. An aspect declaration can contain these three kinds of members in addition to the regular Java fields and methods. An aspect represents a unit of well-modularized crosscutting structure. As you will see below, the implementation of these mechanisms varies among the various AOP approaches. At the core of each approach, however, is the mechanism for accessing, composing, naming, and abstracting join points. Pointcuts can describe sets of join points by means of explicit enumeration. An example would be specifying the three method calls of interest on the Account shown in Figure 1. While enumeration can be useful, it is often more convenient to express join points by means of structural properties. Such property-based pointcuts can express a set of join points that matches "every call to a subtype of an Account" without forcing the programmer to enumerate those subtypes. Doing so ensures that when a new class that extends Account is added to the system, it will automatically be matched by the pointcut. Pointcut support for composition allows you to combine simple pointcuts into more complicated ones. For example, you can limit the pointcut of all Account calls to those made from a particular class or control flow. A mechanism for naming pointcuts facilitates readability and composition. Support for abstraction and concretization makes it easier to create generic libraries that can be defined independently of the application-specific pointcuts to which they will be applied. Finally, support for exposing join point state in pointcuts allows advice to access things like executing objects and method parameters. In the next section, we will see these mechanisms at work in each of the four tools. As previously mentioned, the underlying mechanism of all the AOP tools is the join point model and the concept of pointcuts, advice, and inter-type declarations. The major difference you'll notice among the tools is how aspect declarations are written and applied to the system. The tools approach aspect declaration in one of three ways: using Java-like code, annotations, or XML. For some developers, the familiarity of aspects written in the Java programming language will outweigh the trade-offs of a language extension approach, which are discussed in the next section. For others, the integration benefits of the annotation and XML approaches will outweigh the pain of working with pointcuts as strings. In this section, I'll use a common example to point out the differences in each tool's approach to aspect declaration. Consider the example of an authentication policy for the Account class shown in Figure 1. In an object-oriented implementation, you would most likely see calls to authentication scattered across methods in the Account class, as well as any other classes that required authentication. In an AOP implementation, you could capture this behavior explicitly with a single aspect and no modification to the code manipulating the accounts. Regardless of the tool used to declare it, this aspect would need the following characteristics: - A pointcut capturing the execution of all public methods on the banking.Accountclass - A means of referring to the Accountbeing authenticated - Advice invoking authentication for the Accountat the join points specified by the pointcut Now, let's see how each of the leading AOP tools would handle this aspect. Aspect declarations in AspectJ parallel class declaration in the Java language, as shown in Figure 2. Since AspectJ is an extension to the Java language syntax and semantics, it provides its own set of keywords for working with aspects. In addition to containing fields and methods, AspectJ's aspect declaration contains pointcut and advice members. The pointcut in the example uses a modifier and wildcard pattern to express "all public methods." Access to the account is provided by a pointcut parameter. The advice uses this parameter, and the pointcut binds it using this(account). This has the effect of capturing the Account object on which the method is executing. Otherwise, the body of an advice is similar to the body of a method. The advice can contain the authentication code or, as in this case, it can invoke another method. Figure 2. Aspect in AspectJ Building an AspectJ program is similar to building a Java program. It involves invoking the AspectJ incremental compiler, which builds all the project sources, including the plain Java sources. Running an AspectJ program is also identical to running a Java program, noting that the small aspectjrt.jar library needs to be appended to the classpath. To configure which aspects apply to the system, you must add or remove them from an inclusion list that is passed to the compiler, via the IDE support or a ".lst" inclusion file if you're working in the Ant environment or on the command line. Note that in Part 2, I'll discuss the details of building AOP programs, as well as the concept of weaving aspects. The key difference between AspectWerkz and AspectJ is that Authentication is now a plain Java class, not an aspect. AspectWerkz, JBoss AOP, and Spring AOP add aspect semantics without changing the Java language syntax. AspectWerkz provides two ways to make AOP declarations. The most commonly used are annotations, which can take the Java V5.0 style visible in Figure 3, or a Javadoc style for compatibility with J2SE V1.4. AspectWerkz also supports an alternate XML-based aspect declaration style. The XML style is similar to that of JBoss AOP described below and places the aspect declarations in a separate XML file. Note that the advice is a plain method declaration. By convention, it is considered to be a different kind of method declaration, since it should not be invoked explicitly, but instead run automatically when a particular pointcut matches. Pointcut declarations in AspectWerkz are string values attached to pointcut "methods," or stand-alone in XML. As a result, there is no import mechanism for pointcuts, and all type references must be fully qualified. Access to the executing Account object is identical to AspectJ's. Note that the planned @AspectJ syntax will look very similar to the AspectWerkz annotation syntax. Figure 3. Aspect in AspectWerkz Building an AspectWerkz program involves a standard Java build, followed by post-processing. To run the AspectWerkz program, you must place AspectWerkz libraries on your classpath. The aop.xml file configures the inclusion of aspects in the system, in the event that unpluggable aspects are used. JBoss AOP's XML-based aspect declaration style is visible in Figure 4. JBoss also supports an annotation style similar to the one in Figure 3. In the XML style, aspect, pointcut, and advice declarations are made in XML. Advice is implemented using plain Java methods that are invoked by the JBoss AOP framework. Both pointcuts and their bindings to advice are declared in the aspects using XML annotations. Rather than binding the Account parameter explicitly, JBoss provides reflective access to currently executing objects, requiring a cast to the corresponding type. Note that an upcoming release of JBoss will provide some static typing of pointcut parameters to address this issue. Figure 4. Aspect in JBoss AOP Building an aspect in JBoss involves only a plain Java build. JBoss AOP's run-time interception framework manages pointcut matching and advice invocation. Some configuration of the launch and classpath is required, but JBoss AOP's IDE plugin makes this transparent to the user. Aspects are configured in the jboss-aop.xml file. Looking at the Spring AOP example in Figure 5, you'll notice that there's more XML at work than in the previous one. Similar to JBoss AOP, Spring's advice implementation is a Java method with special parameters that will be invoked by the Spring framework. The XML declares the accountBean, which gives the Spring framework access to Account objects, including the interceptor used for the advice, the advisor and its matching pattern, and the before advice to apply to that pattern. Figure 5. Aspect in Spring AOP Although it presents more fine-grained configuration and wiring, Spring AOP's approach resembles that of JBoss AOP when used with XML. The process for building, running, and configuring Spring AOP aspects is the same as that of JBoss AOP, but relies on the convenient and minimal run-time configuration of the Spring framework, and does not require a separate launcher. Note that when used with JDK proxies, only objects retrieved from the proxies can be advised and the use of an interface is required. If the CGLIB proxy support is used an interface is not required. As shown by the figures above, one of the key differences among the AOP tools is how each one approaches aspect declaration. AspectJ is an extension of the Java language that lets you declare aspects entirely in code. AspectWerkz and JBoss AOP have you annotate your Java code with aspect metadata or declare the aspects in a separate XML file. In Spring AOP, you declare aspects entirely in XML. As a result, programming with aspects can feel quite different in each of the three approaches. Aspect and pointcut declarations in AspectJ's code style will feel just like Java code. In the annotation style of JBoss AOP or AspectWerkz, they'll feel like additional tags made on existing Java elements. And in Spring AOP, as well as the XML style of AspectWerkz and JBoss AOP, they'll feel like using a separate declarative XML language. Each approach has its advantages, and it's up to you to decide which will better suit your needs, so in this section, I'll briefly discuss some of the fine points that could help you make your decision. Regardless of which AOP tool you choose, working with advice bodies simply involves working with Java code. The differences become apparent when it's time to modify a pointcut. When working in the XML style, as in Spring AOP, changing a pointcut involves navigating from the advice to the corresponding pointcut declaration in the XML file. On the plus side, this approach localizes all of your pointcuts and aspect configurations, but it can become tedious if you find yourself frequently editing many advice and pointcuts, and repeatedly flipping back and forth between the Java and the XML files. If you go with the annotation style offered by AspectWerkz or JBoss AOP, you'll have the option of moving the pointcut expression value from XML to an annotation on a Java member. This makes it much easier to work on the advice body and the pointcut concurrently. If you choose the code style of AspectJ, you'll find that working with a pointcut feels like working with code, rather than an unstructured string value. Everything you expect from Java code (such as "import" statements) will also work for pointcuts. By contrast, you'll always need to qualify the type references in pointcuts when using the XML and annotation styles of AspectWerkz, JBoss AOP, and Spring AOP. Aspect declaration style has a broad impact on what it feels like to work with aspects in each tool. For example, the tools that support declaring aspects in XML also allow you to configure how aspects apply to the system in the same XML file. In the previous section, I showed only pointcut and aspect declarations, but inter-type declarations are similarly affected by the choice of style. In AspectJ, an inter-type method declaration looks almost identical to a normal method declaration and is referred to in the same way. In the other approaches, new methods are added via annotations or XML by specifying that a class extends an additional mixin class and inherits those additional members. Note that at this time, AspectJ is the only tool that provides a static enforcement mechanism that employs pointcuts. Table 2 compares the tools' handling of the key elements of AOP syntax. Table 2. Comparing syntax among the leading AOP tools It's clear from the aspect declarations in figures 2-5 that the code style is the most concise approach to working with AOP declarations. It doesn't require naming advice, as advice isn't intended to be invoked explicitly. The code style doesn't require explicitly binding advice to pointcuts, as found in the XML styles, or the return statement required in AspectWerkz's pointcut "method." AspectJ's syntactic extensions to the Java language also let you directly express the verbose wiring you can see in the XML of Figure 3 and Figure 4. Writing aspects in AspectJ feels more like writing Java code, avoids redundant typing, and results in less potential for error. On the downside, Java syntax extension comes at a big price, and the annotation and XML styles yield their own unique benefits. Most notably, the XML styles let you control the binding of pointcuts and advice. This can be beneficial to extending and configuring aspects, which I'll discuss in the next section, along with other trade-offs that result from the various styles. Code style vs. annotations and XML So, should you go with the code style, or declare aspects using annotations or XML? Here's a summary of the trade-offs of AspectJ's Java code-based approach: +Concise syntax leverages familiarity with Java code and results in less typing and fewer errors. +Pointcuts are first-class entities, which makes them much easier to work with. -For many developers, declarative programming in XML is more familiar than Java language extensions. -Advice to pointcut bindings cannot be controlled by the developer. If this summary doesn't narrow down your decision, don't worry. There's a lot more to be considered than what it feels like to write aspects in each style. Syntactic decisions will come up again when we take a look at semantics in the next section, and also affect tool support, which I'll discuss in Part 2. While there are major syntactic differences among the tools' aspect declaration style, the core AOP semantics are similar. Each tool has the exact same notion of a join point model, treating join points as principled points in a Java program, pointcuts as a mechanism for matching join points, and advice as a mechanism for specifying what to execute when a pointcut is matched. Table 3 and Table 4 summarize the semantics of each approach. You'll note numerous small differences and slight variations in the naming conventions, but the approaches have converged on the same core concepts. This convergence is a huge benefit because it means that the learning curve is easily transferred from one AOP approach to another. What's left to consider is the trade-offs imposed by the differences in each approach. The expressiveness of an AOP tool's join point model determines the granularity of the join points available, and how those join points are matched. Each AOP tool offers a number of primitive pointcuts for matching join points. Some primitive pointcuts match only join points of a specific kind (for example, method executions). Other pointcuts can match any kind of join point, based on a common property of those points (for example, all join points in a certain control flow). The kinds of join points, and their specific pointcuts, can be grouped as follows: - Invocation -- Points when methods and other code elements are called or executed - Initialization -- Points in the initialization of classes and objects - Access -- Points when fields are read or written - Exception handling -- Points when exceptions and errors are thrown and handled In addition, the following categories of kindless pointcuts are supported: - Control flow -- Join points within certain program control flows - Containment -- Join points that correspond to places in the code contained within certain classes or methods - Conditional -- Join points at which a specified predicate is true As Table 3 indicates, each of the tools has a slightly different implementation of the join point model and the primitive pointcuts used to match join points. Note that in some cases (indicated in parentheses) join points are not identified with pointcuts. Table 3. Join points and the primitive pointcuts used to match them The main trade-off here is in expressiveness vs. simplicity. A more complete and fine-grained set of pointcuts allows more of the interesting points of program execution to be accessible to aspects. For example, an aspect related to persistence might need access to an object's initialization join points. But such completeness brings with it additional complexity and a steeper learning curve. Many Java programmers do not distinguish between calls and execution, and even fewer need to understand the subtleties of initialization. Also, many commonly used aspects are termed auxiliary, in that they are not tightly coupled to the application functionality. Common auxiliary aspects, such as monitoring and logging, typically make use of only coarse-grained pointcuts like method executions. On the flipside, a broader set of pointcuts does have a pay-as-you-go property, as pointcuts can be learned as needed. And attempting to make do without pointcuts can result in forced refactoring of the object-oriented code, for example to expose class initialization in the form of init() methods. The join point models of AspectJ and AspectWerkz have converged almost completely, and this has been one of the key enablers of the recent merger. The JBoss AOP model is nearly as expressive and only omits some of the less commonly used join points for the benefit of simplicity. One notable difference is that control flows cannot be expressed as "all of the join points under the execution of this pointcut" in JBoss AOP. Instead, the programmer needs to manually list each call in the call stack of interest. Spring AOP takes a different approach and purposely limits the expressiveness of its join point model. This makes it particularly easy to adopt and useful for coarse-grained crosscutting. An upcoming release will integrate with AspectJ to provide interoperability with fine-grained crosscutting mechanisms. Join point model expressiveness vs. simplicity Will your project benefit from a more expressive join point model like the ones offered by AspectWerkz, AspectJ, and JBoss AOP, or would you be better off going with the coarse-grained expedience of Spring AOP? Here's a summary of the trade-offs inherent in the more expressive models, to help you think it over: -More to learn. -Only a few pointcuts are required for coarse-grained crosscutting and auxiliary aspects. +Many aspects cannot be expressed without fine-grained pointcuts. +The learning curve for using new pointcuts is pay as you go. I'll close the discussion in this first part of the AOP tools comparison with a more detailed contrast of each approach's language mechanisms. Table 4 is an overview of the AOP semantics of the four tools. The most notable differences are discussed below. Table 4. Semantics overview of the leading AOP tools Pointcut matching and composition: AspectJ, AspectWerkz, and JBoss AOP offer similar support for type patterns. All three allow matching on signatures, which for the Java 5 application includes annotations and generics. AspectJ and AspectWerkz offer a concise way of referring to multiple types (for example, Account+ indicates all subtypes of an account). All of the tools support wildcard matching. Spring AOP also offers support for regular expressions. While this may seem like a powerful advantage, it should be noted that the other approaches have chosen to forgo regular expressions in order to discourage pointcuts that are hard to read and potentially brittle. The pointcut composition operators are almost identical across the board. Spring AOP does not provide negation, which is typically used in conjunction with containment join points that are not exposed in the Spring AOP join point model. Advice forms: AspectJ supports more forms of advice than the other approaches, and, conversely, JBoss AOP only supports one. Each form of advice can be expressed as around advice, so JBoss' approach is not limiting, and it does offer added simplicity. The downside is loss of conciseness, as can be seen from the additional call to proceed with the original method invocation visible in Figure 4, which would not be necessary with a before advice. Also note that forcing advice to adhere to plain Java rules, as the annotation and XML styles do, is problematic in a few cases, since those rules were designed for methods. AspectJ's ability to "soften" exceptions for advised methods can be useful, and does not adhere to the standard method exception-checking semantics. Join point context: In AspectJ and AspectWerkz, dynamic join point state is accessed by specifying and binding pointcut parameters, similar to how method parameters are declared in the Java language (see Figure 2 and Figure 3). This gives the benefit of static typing for join point context. JBoss AOP and Spring AOP access join point state reflectively, which removes the complexity of parameter binding from pointcut expressions, but at the cost of static typing of the parameters. Java programmers are accustomed to the benefits of static typing for method parameters and get the same benefits from static typing of pointcut parameters. As a result, there are plans to provide statically typed "args" in an upcoming release of JBoss AOP. Instantiation: In all of the tools, aspect instantiation is controlled by per clauses. As expected, Spring AOP's instantiation model is more simple. Support for additional instantiation mechanisms means that aspects can be written to apply only in a particular dynamic context without the need to write code that stores that context and tests whether the aspect should apply. The main differentiators are that AspectJ supports aspect instantiation per control flow, while AspectWerkz supports instantiation per thread, and JBoss per individual join point. Which is most useful depends on your needs. Extensibility: Aspect extensibility enables the deployment of library aspects that can later be concretized for a particular application. For example, an aspect library could provide all the logic and infrastructure required for application monitoring. However, to adopt the library for a particular project, the pointcuts used by the library must be extended to the join points specific to the application. AspectJ supports extensibility with abstract aspects, which contain abstract pointcuts and concrete advice. Sub-aspects that extend these must concretize the pointcuts. AspectWerkz and JBoss AOP use a considerably different approach and do not employ the mechanism of abstract pointcuts. Extension is done by subclassing the aspect and defining a new advice binding in XML or via annotations. The explicit binding of pointcuts to advice give AspectWerkz and JBoss AOP the compelling benefit of allowing aspects to be easily extended to a new system without the need to subclass. More usage data from the aspect libraries becoming increasingly available will determine whether AspectJ's special AOP form of inheritance is better or worse than the other approaches' use of Java-style inheritance and pointcut bindings. Each of the approaches offers a unique set of trade-offs when it comes to the handling of AOP language mechanisms. Summarizing these trade-offs in a simple list is not possible since the benefits of each will vary for different projects. However, the above information provides a guideline for selecting a tool, or for finding an alternative when you encounter a critical limitation. The challenge of choosing an AOP tool for your project is in comparing the trade-offs of each approach without getting lost in them. This first part of the AOP tools comparison has highlighted the core mechanisms of the four leading AOP approaches, and contrasted their similarities and differences. If this article were reporting on a new modularity technology 10 years ago, we could have stopped here, and you would be ready to begin writing an aspect in the style of your choice -- probably built on the command line using Emacs or another text editor. Today, however, you can't consider adopting a new technology without a close look at how it integrates with existing development environments and other tools. So, the second half of this article will focus on how integration factors impact your choice of AOP tool. Among other things, I'll discuss how each tool handles aspect compilation and weaving, as well as how they all stack up in terms of IDE integration and tool support. I'll also compare the basic features of the tools and give you a glimpse of what's around the corner for them, including a further discussion of what you can expect from the merging of the AspectJ and AspectWerkz projects. - AOP@Work is a year-long series dedicated to helping you incorporate AOP into your day-to-day Java programming. Don't miss a single article in the series. See the complete series listing. - See the AOP tools comparison, Part 2: Development environments (developerWorks, February 2005), where the author focuses on the tools' integration with the development environment and build process. - Read Develop aspect-oriented development with Eclipse and AJDT (developerWorks, September 2004) to get a jump on Part 2, which examines IDE integration. - Eclipse.org hosts the recent press release on AspectJ and AspectWerkz joining forces. - See the Eclipse Projects to learn more about AspectJ. - Codehaus hosts information about AspectWerkz. - To learn more about JBoss AOP, visit JBoss. - The Spring framework Web site includes information about Spring AOP. - Want to learn more about the basics of AOP on the Java platform? Start with Nicholas Lesiecki's Improve modularity with aspect-oriented programming (developerWorks, January 2002). - Gary Pollice uses a logging example to introduce the basic concepts of AOP in A look at aspect-oriented programming (The Rational Edge, January 2004). - The Accountexample used in this article originally appeared in Ramnivas Laddad's AspectJ in Action (Manning, 2003). - The user-base survey in Table 1 was based on information that originally appeared on aosd.net, home to the annual Aspect-Oriented Software Development conference. - For more AOP articles, papers, and presentations by the author, visit his Web site. - You'll find articles about every aspect of Java programming in the developerWorks Java technology zone. - Browse for books on these and other technical topics. - Also see the Java technology zone for a complete listing of free Java-focused tutorials from developerWorks. Mik Kersten is a leading aspect-oriented programming expert and a committer on the AspectJ and AJDT eclipse.org projects. As a research scientist at Xerox PARC, he built the IDE support for AspectJ. He is completing his Ph.D. at the University of British Columbia, where he is working on making IDEs more aspect-oriented. He also consults for companies that build development tools to help them leverage and support aspect-oriented programming technology
http://www.ibm.com/developerworks/java/library/j-aopwork1/
crawl-002
refinedweb
5,578
52.19
A BeerXML Parser Project description pybeerxml A simple BeerXML parser for Python Parses all recipes within a BeerXML file and returns Recipe objects containing all ingredients, style information and metadata. OG, FG, ABV and IBU are calculated from the ingredient list. (your milage may vary) Installation pip install pybeerxml Usage from pybeerxml import Parser path_to_beerxml_file = "/tmp/SimcoeIPA.beerxml" parser = Parser() recipes = parser.parse(path_to_beerxml_file) for recipe in recipes: # some general recipe properties print(recipe.name) print(recipe.brewer) # calculated properties print(recipe.og) print(recipe.fg) print(recipe.ibu) print(recipe.abv) # iterate over the ingredients for hop in recipe.hops: print(hop.name) for fermentable in recipe.fermentables: print(fermentable.name) for yeast in recipe.yeasts: print(yeast.name) for misc in recipe.miscs: print(misc.name) Testing Unit test can be run with PyTest: python setup.py test License MIT Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pybeerxml/
CC-MAIN-2020-24
refinedweb
171
52.05
A Windows user has a problem with opening a connection using port "imaps", which doesn't exist in that user's service file (or wherever Windows stashes these things). So I'm wondering whether there's any nice way to determine that that's the situation and work around it. (open-network-stream "hello" nil "gmail.com" "hello") => Debugger entered--Lisp error: (error "gmail.com/hello Servname not supported for ai_socktype") Possibilities are: 1) Don't use "imaps", but just say "993". This would work, and it's simple. But is it rude to use port numbers instead of service names? Are users supposed to be able to edit /etc/services and have "imaps" go off somewhere else entirely? 2) Somehow determine that the OS doesn't know what "imaps" is, and use "993" as a fallback. I have no idea whether that's easy to do. 3) Make `open-network-stream' "know" about these mappings (a variable), and if we get the right error message (i.e. the one above), we try again using that mapping. This would probably mean propagating RET meaningfully (somehow) from `make-network-process' here: ret = getaddrinfo (SSDATA (host), portstring, &hints, &res); if (ret) #ifdef HAVE_GAI_STRERROR error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret)); #else error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret); #endif immediate_quit = 0; Thoughts? -- (domestic pets only, the antidote for overdose, milk.) bloggy blog
https://lists.gnu.org/archive/html/emacs-devel/2011-09/msg00414.html
CC-MAIN-2015-22
refinedweb
235
64.61
Is there a way to store a single word as a variable so i can access it later? What i want to do: Have variables for 'hotbar1', 'hotbar2', 'hotbar3' ... etc (each representing the designated slot in the hotbar) Have it so an external script (an inventory manager) modifies the values of each hotbar variable is (for example, hotbar1 will become 'handgun' if the player equips a handgun in slot 1) Have it so that when buttons 1, 2, 3 (etc) are pressed, the item currently in 'hotbar1' becomes the 'held item', which is the item that will display and be active. I haven't really worked with variables before, so it is confusing me somewhat. Currently the line 'public string hotbar1 = knife;' (and the one after it) does not work, because knife hasnt been declared. Is there a way to just store the variable as a single word? My bad example code: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Hotbarmanager : MonoBehaviour { public string helditem; public string hotbar1 = knife; public string hotbar2 = rifle; void Update () { if (Input.GetKeyUp(KeyCode.1)) { helditem = hotbar1; } if (Input.GetKeyUp(KeyCode.2)) { helditem = hotbar2; } } } Thanks :p Use enum will make your code should be better, instead of use a string. Answer by SteenPetersen · Aug 08, 2017 at 03:13 PM Hi, your not really passing it a string value in your example you would maybe want to do this: public string hotbar1 = "knife"; Unsure if this would be the most efficient way of doing this setup. Enum filter for Item system 1 Answer Is it possible to do Vuforia AR (pattern-based recognition) on top of Mapbox AR (location-based spawns)? 0 Answers slide the item left -right sides in inventory? 0 Answers Void being called 4 times, no apparent reason 1 Answer NullReferenceException: Object reference not set to an instance of an object 1 Answer
https://answers.unity.com/questions/1390896/is-there-a-variable-that-simply-stores-a-word-so-i.html
CC-MAIN-2020-05
refinedweb
314
59.53
When you change view.sel() in a sublime_plugin.WindowCommand, the selection is not visually updated until you do something else in the view (move cursor, scroll, change view, ...)If you put your caret somewhere in a file and run this command using a keybindings: class ExampleCommand(sublime_plugin.WindowCommand): def run(self): self.window.active_view().sel().clear() self.window.active_view().sel().add(0) the caret stay where it was until you try to move it, then it jump to the first char.IMO it's a bug. I resolved this issue using a begin/end_edit: class ExampleCommand(sublime_plugin.WindowCommand): def run(self): edit = self.window.active_view().begin_edit() self.window.active_view().sel().clear() self.window.active_view().sel().add(0) self.window.active_view().end_edit(edit) Now it works fine.I think that it make sense to create an edit if you change something to the view, including the selections.I suppose that this is the way ST2 know if a view need to be refreshed. But I like to have a confirmation that this is the way it must work, and that is not a bug. (Jon?)
https://forum.sublimetext.com/t/bug-changing-view-sel-in-a-windowcommand/7713/2
CC-MAIN-2016-30
refinedweb
184
51.65
Modern Apps - Understanding Your Language Choices for Developing Modern Apps By Rachel Appel | September 2013 Developing modern software using a single language just doesn’t happen in 2013. Programming has evolved to a polyglot model with domain-specific languages (DSLs) for each tier of development. For example, a popular scenario is to use SQL and C# on the back end and HTML, JavaScript and CSS as the UI languages. As a developer, you want to be able to add skills to your skill set, but working in too many languages spreads your skills thin in each. You also want to put products out to market quickly, which often leaves little room for learning a new language and all its quirks, so optimally you want to build on top of skills you already have. When creating Windows Store and Windows Phone apps, you have a variety of choices in languages for every project scenario, and at least one will nicely complement your experience. In this article, I’ll show you what languages go with different development scenarios. In addition, I’ll look at the options you need to weigh and how factors such as data access or porting an app affect the language you need to use. The Landscape of Modern App Languages Here are the available language sets for Windows Store app development: - HTML, JavaScript and CSS - XAML and C#, or XAML and Visual Basic .NET - XAML and C++, or DirectX and C++ If you develop on the Microsoft stack, at least some of these languages should be familiar and, of course, Web developers know HTML and friends quite well. It makes sense that many of the same language sets are available for Windows Phone development: XAML with C#, Visual Basic .NET, and C++. What about HTML, JavaScript and CSS for Windows Phone? At the time of this writing, the only way you can write HTML in a Windows Phone app is by using a WebView control, a technique normally seen in hybrid apps (these are half-Web, half-native app mutants). If you’re creating a cross-platform native app (not a Web site) outside of the Microsoft ecosystem, the language landscape changes to these two options: - Java for Android - Objective-C for iOS (technically there are more options, but I’ll discuss only Objective-C here) Fortunately, Xamarin has come to the rescue for .NET and Windows developers who want to write cross-platform apps. There’s no need to learn Java (although it’s quite similar to C#) or Objective-C, the language of iOS development (more on this later). Now that you have a solid idea of what languages are available to use, I’ll look at how easy or difficult each one is to learn. The Language Learning Curve The path of least resistance is often the best path to take, and it’s certainly the fastest. The languages you and your team are familiar with are an important consideration when moving into new territory. Not everyone seamlessly transitions from one language to another, particularly with languages that behave completely different. It’s more difficult for some junior developers because they usually lack experience with different language paradigms and therefore more frequently make mistakes or are unaware of common pitfalls. Even seasoned developers who move from a compiled language such as C# to interpreted JavaScript can experience a lot of pain because they don’t realize tiny quirks of the language such as the this keyword behaving differently, that hoisting occurs, or the myriad other JavaScript oddities. Fortunately, Web developers continue to enjoy working with the same HTML, CSS and JavaScript as they would in any client Web project, but the difference when writing for Windows 8 is the addition of the Windows Library for JavaScript (WinJS). WinJS makes it easy to write native apps on Windows 8 with Web languages. You continue to use the same open standard APIs as in Web development, but you also work with Windows-specific libraries to access the native experience. Developers who are accustomed to Web languages will find that the trick to HTML controls in Windows Store apps is that they’re simply elements marked with data-win* attributes. Using these attributes allows the core WinJS code and some CSS to transform those elements into beautiful UI widgets that make a rich native experience. The WinJS code that renders the controls contains CSS rules that apply the look and feel of the Windows 8 modern UI. The core WinJS code also creates the more complex controls such as date pickers and grids at run time, and can add data-binding HTML elements to JavaScript arrays or objects. XAML developers from both the Windows Presentation Foundation (WPF) and Silverlight camps continue to write the same declarative XAML for the UI layout alongside C#, Visual Basic .NET or C++ as its compiled companion. As you might expect, in XAML there are new libraries and namespaces dedicated to the Windows 8 modern experience. There’s a great amount of parity among the declarative languages—that is, any “ML” language—concerning the amount and quality of UI controls. In general, if you find a control in XAML, it likely exists in HTML or the WinJS library and vice versa; however, there are one or two differences between the two. XAML developers will hardly notice a change except for some namespaces and other trivial changes. Expression Blend is still a great tool to do UI design in XAML, while Visual Studio is best for the compiled language behind the scenes. A widespread third-party ecosystem exists around XAML UI controls, such as grids for XAML on the WPF platform, and many of these controls work the same way or similarly between Windows Store and Windows Phone apps. Finally, if you’re a Windows Forms developer, it’s time to learn XAML, as you practically have no other choice. There’s no comparable UI language that you can use, because Windows Forms doesn’t have one—it’s all C# or Visual Basic .NET behind a design palette. While you can carry your general .NET and language skills over, you must learn the DSL of the UI: XAML. You could learn HTML, but that would require the addition of both CSS and JavaScript, so you’d then have three languages to learn, and that’s no small undertaking. Data Access Affects Language Choice How you access data varies—sometimes greatly—between languages, and the kind of data you’re dealing with determines how you access that data, as well. To start, some techniques are available only to one set of technologies or another, as is the case with Web Storage (also known as DOM Storage, which you can learn more about in my blog post, “Managing Data in Web Applications with HTML5 Web Storage,” at bit.ly/lml0Ul) and IndexedDB, both of which you may only use with browser-based languages such as JavaScript. Windows Azure Mobile services (which you can learn more about in another blog post, “Use Windows Azure Mobile Services to Power Windows Store and Windows Phone Apps,” at bit.ly/15nhO8d) and the Windows Azure platform offer several native APIs for all the popular platforms as well as REST APIs that are inherently cross-platform. Because REST is an open standard, you can access its data from any language, anywhere, at any time, via a consistent interface. REST interfaces make it easy to develop across platforms because—despite language syntax and quirks—the code has a general consistency, or pattern. Public APIs, such as those provided by Twitter, Facebook, weather services and so on, usually return JSON or XML (or both) that you can consume via REST or XMLHttpRequest (XHR). SQLite is a local database option available across all platforms and languages. SQLite is available as a NuGet package for Windows Store and Windows Phone apps in Visual Studio 2012. You can also access it through a Xamarin toolset and use its libraries to access SQLite databases on iOS and Android. SQLite is easier to use with XAML apps than HTML apps. File access and file I/O on the Windows platform are at par level between Windows Store XAML and HTML apps, so the language doesn’t really matter when your app requires reading and writing to the file system. Although normal HTML and JavaScript in the browser have many restrictions on file I/O operations and accessing system resources, the Windows Store app development model allows more than sufficient access to the file system while maintaining security. For complete details on data-access technologies for Windows Store and Windows Phone apps, see my March 2013 column, “Data Access and Storage Options in Windows Store Apps,” at msdn.microsoft.com/magazine/jj991982. Cross-Platform Considerations Objective-C is syntactically and operationally different from the other languages, as Java and C# behave similarly because they’re managed languages. However, if you’re writing cross-platform apps, you aren’t doomed to separate codebases such as Objective-C for iOS, Java for Android and C# for Windows platforms, because the aforementioned Xamarin tools make it easy to write in C# and generate Java and Objective-C. Xamarin provides a native code-generation toolset for cross-platform device development (that is, mobile and tablet devices), and it’s the lowest common denominator for doing cross-platform native development. As a result, developers from just about any platform can easily move their skills to the Windows platform or cross-platform via Xamarin and C#. Developers from the iOS and Android platforms would do well to pick C# as their language of choice if they want to publish on the Windows platform as well as the others. Note, however, that some developers in Redmond disagree, advocating that it’s more convenient to develop libraries in C++ and C because they can be accessed by iOS (directly) and Windows apps (via Windows Runtime, or WinRT, components). They point out that this approach is “free” (most Xamarin tools cost money) and more performant than third-party tools. I favor just creating and sharing Xamarin components, as time to market is more important than the negligible performance benefits—and I don’t particularly like using C++. Porting from Legacy Codebases Affects Language Choice Not all apps are greenfield apps (that is, new or rewritten). Most, in fact, are brownfield—or legacy programs—especially if the code you’re writing is for the enterprise. Many apps are really parts of a larger ecosystem of software made of multiple apps or multiple UIs that interact with business logic, service layers, public APIs or libraries. Migrating Web apps in particular can be tricky, as you often need to keep the content of an existing Web site intact yet integrate that same content into the client app and make it feel like a native experience. This is because business requirements frequently dictate that the original Web site or architecture must remain unchanged. This can cause the look and feel of the app to be different from its host OS, making usability difficult, and it can block the user’s natural workflow. Fortunately, if you’re porting an existing Web site or app, you often have the choice to integrate instead. If this is the case, then the Apache Cordova framework (formerly PhoneGap) can help. Cordova enables you to create hybrid, Web-native apps by integrating Web content and native UI components and publishing across platforms. Conversely, integrating Web content with a native WinJS Windows Store app isn’t difficult to do using WinJS, and the experience is usually smoother for the user. Native apps enjoy a closer integration experience with the OS than client Web apps do, because native apps have access to modern hardware resources such as the camera, microphone, device settings, accelerometers, geolocation and so on. In addition to this, native apps have a distinct lifecycle and contain state, whereas Web apps are lightweight and stateless. The Purpose of the App Matters The type and purpose of your app determine the language you use, to an extent. High-intensity games and graphics apps lend themselves to languages such as C++ and DirectX (now part of the Windows SDK) because you can get closer to the machine and gain performance and better device control. DirectX is a complete collection of close-to-the-metal APIs you can access via C++ to create stunning games and apps. The downside of C++/DirectX is complex code that makes it easy to get yourself into trouble. C++ isn’t the only option for games, either. JavaScript—yes, JavaScript—apps are top performers, especially for canvas games. The Windows Store app execution container offloads script processing to the GPU so JavaScript can run in parallel yet independent of the layout done by the Trident layout engine. This notion of offloading makes JavaScript a really fast language that can perform just as well as native code. If performance is a big deal for you but you don’t want to learn C++, using the HTML canvas means you might not have to. If you write business and productivity apps, you usually have your choice of any language that suits you, because things such as performance and UI controls are so similar. These apps tend to be common forms-over-data apps. The current set of technologies is what normally drives language and technology choices for these kinds of apps. What About F#? Wondering what happened to F#? While F# isn’t one of the basic templates for Windows Store and Windows Phone app development, you can reference and consume components created in F#. It’s also a great language for processing analytics and running code on the back end—and all apps need a back end. Web developers often use a mix of CSS for styling HTML and JavaScript that together build modern UIs. Native developers also have a set of concurrent languages for the same, so it’s up to you to consider all the factors that might affect your app when choosing a language. Microsoft technical experts for reviewing this article: Eric Schmidt (erschmid@microsoft.com) and John Kennedy (jken@microsoft.com) Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/magazine/dn385713.aspx
CC-MAIN-2018-43
refinedweb
2,392
56.69
Settings¶ Mach can read settings in from a set of configuration files. These configuration files are either named machrc or .machrc and are specified by the bootstrap script. In mozilla-central, these files can live in ~/.mozbuild and/or topsrcdir. Settings can be specified anywhere, and used both by mach core or individual commands. Core Settings¶ These settings are implemented by mach core. alias - Create a command alias. This is useful if you want to alias a command to something else, optionally including some defaults. It can either be used to create an entire new command, or provide defaults for an existing one. For example: [alias] mochitest = mochitest -f browser browser-test = mochitest -f browser Defining Settings¶ Settings need to be explicitly defined, along with their type, otherwise mach will throw when trying to access them. To define settings, use the SettingsProvider() decorator in an existing mach command module. E.g: from mach.decorators import SettingsProvider @SettingsProvider class ArbitraryClassName(object): config_settings = [ ('foo.bar', 'string', "A helpful description"), ('foo.baz', 'int', "Another description", 0, {'choices': set([0,1,2])}), ] @SettingsProvider’s must specify a variable called config_settings that returns a list of tuples. Alternatively, it can specify a function called config_settings that returns a list of tuples. Each tuple is of the form: ('<section>.<option>', '<type>', '<description>', default, extra) type is a string and can be one of: string, boolean, int, pos_int, path description is a string explaining how to define the settings and where they get used. Descriptions should ideally be multi-line paragraphs where the first line acts as a short description. default is optional, and provides a default value in case none was specified by any of the configuration files. extra is also optional and is a dict containing additional key/value pairs to add to the setting’s metadata. The following keys may be specified in the extra dict: - choices- A set of allowed values for the setting. Wildcards¶ Sometimes a section should allow arbitrarily defined options from the user, such as the alias section mentioned above. To define a section like this, use * as the option name. For example: ('foo.*', 'string', 'desc') This allows configuration files like this: [foo] arbitrary1 = some string arbitrary2 = some other string Finding Settings¶ You can see which settings are available as well as their description and expected values by running: ./mach settings # or ./mach settings --list Accessing Settings¶ Now that the settings are defined and documented, they’re accessible from individual mach commands if the command receives a context in its constructor. For example: from mach.decorators import ( Command, CommandProvider, SettingsProvider, ) @SettingsProvider class ExampleSettings(object): config_settings = [ ('a.b', 'string', 'desc', 'default'), ('foo.bar', 'string', 'desc',), ('foo.baz', 'int', 'desc', 0, {'choices': set([0,1,2])}), ] @CommandProvider class Commands(object): def __init__(self, context): self.settings = context.settings @Command('command', category='misc', description='Prints a setting') def command(self): print(self.settings.a.b) for option in self.settings.foo: print(self.settings.foo[option])
http://firefox-source-docs.mozilla.org/mach/settings.html
CC-MAIN-2020-10
refinedweb
493
50.33
Unclutter your Downloads folder in Windows with this extremely useful file classifier which is written in Python. After running this script, you will be able to manage your downloads with ease. Internet users download several files to the Downloads folder of Windows OS. If you examine the contents of your Downloads folder (C:\Users\<user-name>\Downloads) you might find various files in diverse formats like MP3, PDF, docs, srt, Zip, MP4, etc. These files populate your C drive, and then you start moving the files from the Downloads folder to other folders, which can be a very tiresome and monotonous task. In this article, I am going to show you how to shift your files from the Downloads folder to their respective folders automatically, by using a simple Python program. The structure of the program The complete program contains a Python code and one txt file. The txt file supplies the necessary parameters and rules for moving the files. First, let’s write a text file called rules.txt, as shown below: C:\Users\<user-name>\Downloads R mp3:D:\music pdf:D:\all_pdf exe:D:\software doc:D:\all_docs docx:D:\all_docs srt:D:\all_srts mp4:D:\all_mp4 The first line indicates the complete path of the Downloads folder; so it is user-specific. The second line states the mode. I used ‘R’ for recursive mode and ‘S’ for simple mode. In recursive mode, the interpreter checks folders inside Downloads. In simple mode, the interpreter checks the files only in the Downloads folder. The remaining lines show the file extensions with paths. This means that MP3 files must be moved to D:\music folder and so on. Let us look at the program class1.py, and try and understand it: # program created by mohit # official website L4wisdom.com # email-id [email protected] Import the mandatory files: import os import shutil The following lines indicate the path of the rules.txt file. In your Windows folder, this should be C:\Users\<user-name>\. file_path= os.path.expanduser(‘~’) file_name = file_path+”//” +”rules.txt” Get the path and mode from rules.txt: file_t = open(file_name,’r’) path=file_t.readline() mode = file_t.readline() mode = mode.strip(“\n”).lower() path1 = path.strip(“\n”) The following function returns a dictionary that contains the rules. The dictionary’s keys behave as extensions of the files, and values act as moved paths, respectively. def rules(): dict1 = {} for each in file_t: each = each.strip(“\n”) if each.split(“:”,1)[0]: file_ext,dest_path = each.split(“:”,1) file_ext = file_ext.strip() dest_path = dest_path.strip() dict1[file_ext]=dest_path return dict1 The following function takes a list of files, and moves the files to their respective folders: def file_move(files_list): for file in files_list : if “.” in file: ext = file.rsplit(“.”,1)[1] ext= ext.strip() if ext in dict1: dst = dict1[ext] try: print file shutil.move(file, dst) except Exception as e : print e The following function is used when a simple mode is selected: def single_dir(path1): os.chdir(path1) files = os.listdir(“.”) file_move(files) The following function is used when a recursive mode is selected: def rec_dirs(path1): for root, dirs, files in os.walk(path1, topdown=True, onerror=None, followlinks=False): #print files os.chdir(root) file_move(files) print “files are moved” dict1 = rules() if mode ==’r’: rec_dirs(path1) else: single_dir(path1) Running the program So, the program is ready. Now let us convert the Python program into an .exe file. In order to do this, use the installer shown in Figure 1. After conversion, it will make a directory called class1\dist, as shown in Figure 2. Get the class1.exe files from the directory class1\dist and put them in the Windows folder. Before doing that, you can rename the exe file. I am calling it cfr.exe. In this way, cfr.exe is added to the system path. cfr.exe works like a DOS command. In order to run the program, use Windows’ run facility, as shown in Figure 3. After a successful run, check the folders as specified in the rules.txt. If the folders do not exist, then the program automatically creates the folders.
https://opensourceforu.com/2018/03/automate-file-classification-python-program/
CC-MAIN-2018-17
refinedweb
690
68.87
On Sat, 05 Sep 2009 04:57:21 -0700, Adam Skutt wrote: >> >: Yes, you're right, my bad. Globals are shared, but not all shared variables are global. >> What do you mean by "variables"? Do you mean names? > > In the case of python I mean the name and the value, since all variables > in Python are pointers. Let me see if I understand you... You say that by "variable" you mean the name and the value. Then you say that all variables are pointers. In other words... "all names and values in Python are pointers". Either you're not explaining yourself correctly, or you're badly confused about Python. In Python, names are keys in namespaces, and values are objects. Possibly some Python implementations use pointers in some way to implement namespaces, or objects, but Python the language doesn't have pointers, and the Python virtual machine that executes Python byte code doesn't have pointers either. > (Worrying about the difference though, is semantics) Semantics are important. If we can't agree on what things mean, how can we possibly communicate? >>). I can *guess* what you mean by all that, but it's just a guess. You say "assignment to the variable", but earlier you said that to you, variables are names and values, so I'm left wondering if you mean assignment to the name, assignment to the value, or both. Likewise for copying the variable. Here is my guess... you're pointing out the similarities between Python name binding and C pointers: * when you bind a name to a new object, you cause the name be associated with the new object rather than mutating the existing object to become equal to the new object; * assigning two names to a single object causes both names to be associated with the same object, rather than each name being associated with independent copies of the object; while ignoring the differences between Python name binding and C pointers: * Python names are keys, not numeric addresses, hence you can't perform anything like pointer arithmetic on them; * objects in Python have no idea what, if any, names are associated with them, unlike C pointers, where you can always ask for the address of a variable. Okay, I accept that if you focus only on the similarities and completely ignore the differences, Python name binding is just like pointer semantics. >>? I don't understand what you mean. Python lacks the ability to do what altogether? If you mean that Python threads lack the ability to have local variables, that's not true at all. -- Steven
https://mail.python.org/pipermail/python-list/2009-September/550703.html
CC-MAIN-2017-04
refinedweb
431
70.73
Unity 2019.4.28_Release Notes (.PDF) New to Unity? Get started Release notes Known Issues in 2019.4.28f1 AI: Crash with ComputeTileMeshJob when generating Navmesh (1329346)) Metal: [iOS 14] Application stucks on splash screen and 'XPC_ERROR_CONNECTION_INTERRUPTED' error is thrown (1282747)) Scripting: [Android][Mono][IL2CPP] "Unable to find libc" error thrown when executing certain SslStream constructor (1022228).28f1 Release Notes Improvements 2D: Tilemap.GetSprite now returns the currently animated Sprite for an animated Tile instead of the initially set Sprite. IL2CPP: Correctly provide the source file hash so that a managed debugger can determine when a source file has changed and provide a proper warning. Package Manager: Corrected provide the source file hash so that a managed debugger can determine when a source file has changed and provide a proper warning. Changes Android: Updated Android Logcat package to version 1.2.2. Package: Updated Addressables package to version 1.16.19. Package: Updated com.unity.ide.visualstudio package to version 2.0.8. Package: Updated com.unity.purchasing package to version 3.0.1. XR: Updated Oculus XR Plugin package to version 1.9.1. crash on startup on Android 4.4 devices. (1331290) Animation: Fixed an issue where the animator parameter values would truncate float values to 1 decimal. (1308930) Asset Import: Fixed infinite asset import loop during InitializeOnLoad when Editor script uses CreateAsset and importParameters change during import. (1323499) Burst: Fixed a crash that was caused by member function debug information on tvOS. Burst: Fixed an UnauthorizedAccessException that could occur when using Burst in players built for the macOS App Sandbox. Editor: Added System.IO.Compression to reference assemblies when targeting .NET 4.7.1 (editor only contexts). (1275859) Editor: Fixed items in right click menu doing nothing on arrays in scriptable object with custom editors. (1307389) Graphics: Fixed a crash when loading old asset bundles that contain Vulkan shader binaries. (1308947) Graphics: Fixed mip streaming for static batched meshes and use of CombineMesh API. (1329555) IL2CPP: Corrected the behavior of Mathf.RoundToInt with Mathf.Infinity on ARM architectures. (1323419) IL2CPP: Fixed "Use of undeclared identifier 'BoxNullable'" error. (1328819) IL2CPP: Fixed crash due to race condition allocating memory in MetadataCache::GetGenericInst. (1323462)) Kernel: Fixed an issue with Atomic 64-bit Load/Store on Win32/UWP x86. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. incorrect error check in SetParticles that would cause an exception to be thrown when the offset value was equal or greater than the particles array length. (13134: Fixed changing the GUID of a Prefab in Prefab Mode in isolation triggers different issues. Profiler: Fixed Profiler Window CPU Usage chart highlighting selected sample in all frames. Scene Manager: Fixed an issue to prevent loading scene where multiple objects have same identifier. (1249893) Scene/Game View: Fixed SceneView.rotation value incorrectly affecting camera rotation in 2D mode. (1314928) Serialization: Fixed Property Diff after clearing array w/refs. (1266303) Services: Fixed bug where Accelerator namespace was not added when opening project with -cacheServerNamespacePrefix argument. (1294806) Shaders: Fixed a crash when PrimitiveID is the only input to a stage. (1289378) UI Elements: Fixed problem with inspector redrawing unnecessarily. Universal Windows Platform: Fixed word suggestion not appearing in the Windows On Screen Keyboard when editing an InputField or TextMeshPro control. (1332468) Windows: Fixed an issue whereby X86_64 is now the default Windows architecture. (1283651) XR: Fixed screenspace shadows with XR multiview. (1168315) XR: Fixed World space UI to render in secondary cameras. (1326167): 1381962e9d08
https://unity3d.com/unity/whats-new/2019.4.28
CC-MAIN-2021-39
refinedweb
584
51.04
As shown earlier, Morningstar computes its version of the Sharpe Ratio using substantially different procedures from those typically used in academic studies. Here, we contrast the Morningstar version (msSR) with ERSR, the annualized version of the traditional measure. Morningstar and excess return Sharpe ratios Clearly, the two measures are highly correlated across funds. While some curvature appears in the relationship, within the range in which most fund ratios lie (0 to 2.0 in this period), the points fall very close to a 45-degree line, since the results are very similar in magnitude. To compare rankings based on two measures we cross-plot the corresponding percentiles for the funds. Percentiles are computed as follows. First the funds are ranked on the basis of the value in question (for example, the Morningstar Sharpe ratio). The fund with the highest value is assigned rank 1286, the fund with the smallest value is assigned rank 1, and all other funds are assigned ranks between 1 and 1286, in order. Then the ranks are converted to percentiles, with rank 1 assigned percentile 1/1286, rank 2 assigned percentile 2/1286, and so on up to rank 1286, which is assigned percentile 1.0 (100%). Below we plot the percentiles based on the two Sharpe ratios. Not surprisingly, they are very similar. Morningstar and excess return Sharpe ratio percentiles The relationships we have shown graphically can also be summarized numerically in terms of correlation coefficients. Broadly, a correlation coefficient of 0 indicates no (linear) relationship between the variables, while a coefficient of 1.0 indicates a perfectly positive linear relationship. In this case, the correlation coefficient for the Sharpe ratios themselves was 0.995, while that for the percentiles was 0.997. Whatever the merits or demerits of one of these measures vis-a-vis the other, the choice between them seems to make little difference in practice. As indicated earlier, it is useful to consider any performance measure as a statistic designed to help answer a specific investment question (or questions). The evaluate the relevance of a measure for a given task one must know the question that it is designed to help answer. What, then, is the question for which the Excess Return Sharpe Ratio may be at least a partial answer? As described in William F. Sharpe, The Sharpe Ratio, (The Journal of Portfolio Management, Fall 1994), a Sharpe Ratio is a measure of the expected return per unit of standard deviation of return for a zero-investment strategy. Such a strategy involves taking a short position in one asset or set of assets and an equal and offsetting long position in another asset or set of assets. As such it can, in principle, be undertaken at any desired scale. While the expected return and standard deviation of such a strategy will depend on the chosen scale, their ratio will not. Hence, the Sharpe ratio is unaffected by scale. More importantly, for any given desired level of risk, a strategy based on, say, fund X will provide higher expected return than one based on fund Y if and only if the Sharpe Ratio of X exceeds that of Y. When the Excess Return Sharpe Ratio is used, the strategy being considered involves borrowing at a short-term interest rate and using the proceeds to purchase a risky investment such as a mutual fund. In the present context, the Sharpe ratio of any strategy involving a combination of treasury bills and a given mutual fund will be the same. This is illustrated in the figure below, in which X and Y are two mutual funds. Excess Return Sharpe Ratios for Two Funds Consider an investor who plans to put all her money in either fund X or fund Y. Moreover, assume that the graph plots the best possible predictions of future expected return and future risk, measured by the standard deviation of return. She might choose X, based on its higher expected return, despite its greater risk. Or, she might choose Y, based on its lower risk, despite its lower expected return. Her choice should depend on her tolerance for accepting risk in pursuit of higher expected return. Absent some knowledge of her preferences, an outside analyst cannot argue that X is better than Y or the converse. But what if the investor can choose to put some money in one of these funds and the rest in treasury bills which offer the certain return shown at point B? Say that she has decided that she would prefer a risk (standard deviation) of 10%. She could get this by putting all her money in fund Y, thereby obtaining an expected return or 11%. Alternatively, she could put 2/3 of her money in fund X and 1/3 in Treasury Bills. This would give her the prospects plotted at point X' -- the same risk (10%) and a higher expected return (12%). Thus a Fund/Bill strategy using fund X would dominate a Fund/Bill strategy using fund Y. This would also be true for an investor who desired, say, a risk of 5%. And, if it were possible to borrow at the same rate of interest, it would be true for an investor who desired, say, a risk of 15%. In the latter case, fund X (by itself) would dominate a strategy in which fund Y is levered up to obtain the same level of overall risk. Note that in this comparison it is assumed that only one risky investment is to be undertaken. The reason that the Excess Return Sharpe Ratio is, in principle, designed to deal with this situation is not difficult to see -- the measure of risk is the total risk of the fund in question. But in a multi-fund portfolio, both the total risk of a fund and its correlation with movements in other funds is relevant. Since the Excess Return Sharpe Ratio deals only with the former, it is best suited to investors who wish to choose only one risky mutual fund. Prospectively, the Excess Return Sharpe Ratio is best suited to an investor who wishes to answer the question: If I can invest in only one fund and engage in borrowing or lending, if desired, which is the single best fund? Retrospectively, an historic Excess Return Sharpe Ratio can provide an answer for an investor with the question: If I had invested in only one fund and engaged in borrowing or lending, as desired, which would have been the single best fund? Of course, Excess Return Sharpe Ratio may prove to be useful for answering other questions to the extent that it can serve as an adequate proxy for a measure that is, in principle, more applicable. Such possibilities will be explored subsequently. In practice, there are situations in which funds underperform treasury bills on average and hence have negative average excess returns. In such cases it is often considered paradoxical that a fund with greater standard deviation and worse average performance may nonetheless have a higher (less negative) Excess Return Sharpe Ratio and thus be considered to have been "better". Given the basis for the use of the measure, however, this is not a paradox. Consider the case shown below. Excess Return Sharpe Ratios for Two Funds Here X by itself was clearly inferior to Y (and both were inferior to Treasury Bills). But, for an investor who had planned for a standard deviation of 10%, the combination of 2/3 X and 1/3 Bills would have broken even, while investment in fund Y would have lost money. Thus a Fund/Bills strategy using the fund with the higher (or less negative) Excess Return Sharpe Ratio would have been better. Of course, one would never invest in funds such as X or Y if their prospects involved risk with negative expected excess returns. But, after the fact, the Sharpe Ratio comparison remains valid, even in this case, if the preconditions for its use were in effect. Whatever the relevance of the Excess Return Sharpe Ratio may be, it is useful to investigate the relationship between fund performance, so measured, and fund characteristics.. We investigate three such characteristics: expense ratios, turnover ratios and total assets. Since all our measures of performance are based on net returns, higher costs would lead to lower net returns and hence poorer performance unless more than offset by higher gross performance. Moreover, since larger funds tend to have lower proportional expenses, they would provide better net performance unless their gross performance were commensurately lower. We choose the traditional annualized excess return Sharpe ratio (ERSR) for this analysis, since it is more familiar and has somewhat better statistical and economic properties. However, results using the Morningstar measure would have differed little from those shown here. Here (and later) we first consider each of the three variables in isolation, following the method used earlier. We group the funds into deciles of 129 funds each (except that there are 125 funds in the tenth decile) based on the variable of interest (for example, expense ratio). We then compute the average Sharpe ratio for the funds in each decile and graph the average values for each of the ten deciles. If the variable has explanatory power, the deciles will vary in average performance by economically meaningful amounts. We begin with expense ratios, the results for which are shown below: Average Sharpe ratios for ten deciles based on expense ratios While by no means uniform, the bars become considerably shorter as one goes from left to right. The average Sharpe ratio for the funds with the smallest expense ratios was over 75% greater than that of the funds with the greatest expense ratios. This is evidence in support of the thesis that higher expenses add far more to expense than they add to performance. A similar result is obtained when turnover ratios are considered: Average Sharpe ratios for ten deciles based on turnover ratios While the magnitude of the difference between the largest and smallest decile is somewhat smaller than that obtained when funds were grouped based on expense ratios, the greater uniformity of the decline in bar height from left to right is impressive. This is evidence that the greater costs incurred by funds with high turnover are not offset by commensurate performance gains. Since large funds tend to have lower expenses and somewhat lower turnover, we would expect performance to increase with asset size, given the two previous results. As the next graph shows, such is the case. Average Sharpe ratios for ten deciles based on total assets While bigger funds tend to have had better performance, this may be due entirely to their tendency to have lower expenses and turnover. To try to separate out the influences of these three fund characteristics, we perform a multiple regression analysis with all three characteristics as independent variables and the Sharpe ratios as the dependent variable. For each variable, two statistics are reported below -- one measuring the variable's statistical significance, the other its economic significance. Multiple regression, dependent variable: Sharpe ratio From a statistical standpoint, both expense ratios and turnover ratios are highly significantly related to Sharpe ratios. A standard rule of thumb considers a variable statistically significant if the t-value from a multiple regression has an absolute value greater than 2.0. In this sense, the two cost measures are highly significant while the size of the fund, per se, is not. Statistical significance is important, but economic significance measures the effect of a variable on an investor's overall wealth. To capture the latter we compute the impact of a change in each variable equal to one cross-sectional standard deviation of that variable for the funds in the analysis. For example, let the average expense ratio for the funds be aE and the standard deviation of expense ratios for the funds be sdE. In this case, aE=1.3047 and sdE = 0.6552. In the multiple regression equation the coefficient for the expense ratio was -0.2039. This indicates that moving from a fund with an expense ratio equal to aE to one with an expense ratio of aE+sdE would, on average, reduce the fund's Sharpe ratio by 0.2039*0.6552, or 0.1336. Roughly, going from a typical fund to one in the 84'th percentile in terms of expense ratios would, on average, lower performance measured by the Sharpe ratio by 0.1336. As the figures in the final column of the table indicate, expense ratio was the most economically important determinant of performance in this analysis, with turnover ratio a fairly close second, and assets, per se, a distant third. Evidence that fund net performance tends to be lower when expenses are high than when they are low is not new. Nor is evidence that higher turnover tends to lower net performance. However, our results may overstate the importance of each of these factors. Consider, for example, two funds with equal dollar expenses, each of which is fixed and unaffected by assets under management. If one fund does well while the other does poorly, the expense ratios at the end of the measurement period will differ, with the ratio of dollar costs to asset value lower for the fund that provided the better performance, even though the performance was unrelated to its expenses. In practice, fund expense ratios do not decline as rapidly with size as our example would suggest. Nonetheless, it is likely that our results overstate the relationship between expenses (and possibly turnover) measured before the fact and subsequent performance. To provide at least some measure of the latter, we examine the relationship between expenses ratios at the end of 1993 and Sharpe Ratios for the 1994-1996 period for the 540 funds in our 6-year sample. The figures below show average Sharpe Ratios for fund deciles based on prior measures of , respectively, expense ratios, turnover ratios and fund size. Note that the differences in performance are somewhat smaller than in the prior analyses, but they are still substantial and in the same directions. The table below shows the results of a multiple regression in which the Sharpe Ratio for 1994-1996 was the dependent variable and the three measures determined in 1993 were the independent variables. Multiple regression, dependent variable: Sharpe ratio All the numbers in the table are smaller in absolute value than their counterparts in the prior analysis, again suggesting that the earlier analysis was in fact biased as expected. This being said, the coefficients for expenses and turnover are both statistically and economically highly significant. One final comment about these results is in order. Note that the sample does not include all the funds for which expense ratios and turnover data were available in later 1993. Most of the missing funds are likely to have performed poorly between 1994 and 1996. If they tended to have had high expenses and/or turnovers, our results may well understate the negative impact of such characteristics. This seems more likely than the alternative hypothesis that our results understate the impact of expenses and turnover. However, lacking complete data on the missing ("dead") funds, no definitive statement regarding the sign or size of the bias can be made. Go to Table of Contents for this Paper
https://web.stanford.edu/~wfsharpe/art/stars/stars6.htm
CC-MAIN-2019-35
refinedweb
2,556
57.91
Initialization oddities: Aggregate initializationPosted: May 10, 2016 Filed under: C++ Leave a comment Do you know the quickest way to create a constructor that initializes the elements in this struct? #include <string> struct MyStruct { int x; std::string y; const char *z; }; If you answered “by typing really fast”, you may be interested in knowing that the fastest way to create this constructor is to not write it at all! MyStruct a = {42, "Hello", "World"}; Yes, the line above works and it’s perfectly legal C++. It’s event C++ 98! This language feature is called aggregate initialization and it says the compiler should be smart enough to initialize MyStruct using each value successively. Of course C++11 has made this syntax somewhat simpler and a lot more uniform: MyStruct a{42, "Hello", "World"}; There are some caveats when using this initialization, namely that the initialized type must be an aggregate. An aggregate, in standard lingo, is a type that has some restrictions. No virtuals, no privates, etc. You can say it’s a POD and in most cases you’d be right. Now, is this also legal? MyStruct a = {42, "Hello"}; You’d be tempted to say that’s a syntax error. It’s not, now z will just be default-initialized. What about this, then? MyStruct a = {42, "Hello", "World", "Extra!"}; According to the standard, that’s an error. Or… is it? Let’s try out this example: struct A { int x; }; struct B { A a; std::string y; }; struct C { B b; const char *z; }; C o = {42, "Hello", "World"}; Yes. Believe it or not, the object o will now contain three members: o.b.a.x, o.b.y and o.z. All three will be properly initialized with their respective value. Aggregate initializations should, according to the standard, be smart enough to initialize aggregate objects and use any “spill over” to continue initializing other values/aggregate objects recursively. Bonus I: Aggregate initialization is also what makes this idiom valid: char x[] = {1, 2, 3} In this case, x will be of length 3 because that’s the length of its aggregate initializer. Bonus II: I’m sure anyone trying to get up to date with C++11 will have played around with variadic templates. One of the first exercises I’d recommend for this would be a compile-time list of different types. Knowing about aggregate initializations now, how would you write a constructor for this type? template <typename H, typename... T> struct Multilist<H, T...> { H x; Multilist<T...> next; }; Multilist<int, string, float> foo{42, "XXX", 1.23};
https://monoinfinito.wordpress.com/2016/05/10/initialization-oddities-aggregate-initialization/
CC-MAIN-2017-39
refinedweb
435
65.83
This chapter provides a set of design guidelines and techniques you can use to ensure that your Swing GUIs perform well and provide fast, sensible responses to user input. Many of these guidelines imply the need for threads, and sections 11.2, 11.3, and 11.4 review the rules for using threads in Swing GUIs and the situations that warrant them. Section 11.5 describes a web-search application that illustrates how to apply these guidelines. Note: Sections 11.2 and 11.3 are adapted from articles that were originally published on The Swing Connection. For more information about programming with Swing, visit The Swing Connection online at. Design work tends to be time-consuming and expensive, while building software that implements a good design is relatively easy. To economize on the design part of the process, you need to have a good feel for how much refinement is really necessary. For example, if you want to build a small program that displays the results of a simple fixed database query as a graph and in tabular form, there's probably no point in spending a week working out the best threading and painting strategies. To make this sort of judgment, you need to understand your program's scope and have a feel for how much it pushes the limits of the underlying technology. To build a responsive GUI, you'll generally need to spend a little more time on certain aspects of your design: The following sections describe four key guidelines for keeping your distributed applications in check: In a distributed application, it's often not possible to provide results instantaneously. However, a well-designed GUI acknowledges the user's input immediately and shows results incrementally whenever possible. Your interface should never be unresponsive to user input. Users should always be able to interrupt time-consuming tasks and get immediate feedback from the GUI. Interrupting pending tasks safely and quickly can be a challenging design problem. In distributed systems, aborting a complex task can sometimes be as time-consuming as completing the task. In these cases, it's better to let the task complete and discard the results. The important thing is to immediately return the GUI to the state it was in before the task was started. If necessary, the program can continue the cleanup process in the background. One way to do this is to use explicit notifications. For example, if the information is part of the state of an Enterprise JavaBeans component, the program might add property change listeners for each of the properties being displayed. When one of the properties is changed, the program receives a notification and triggers a GUI update. However, this approach has scalability issues: You might receive more notifications than can be processed efficiently. To avoid having to handle too many updates, you can insert a notification concentrator object between the GUI and the bean. The concentrator limits the number of updates that are actually sent to the GUI to one every 100 milliseconds or more. Another solution is to explicitly poll the state periodically-for example, once every 100 milliseconds. Imagine a program that displays the results of a database query each time the user presses a button. If the results don't change, the user might think that the program isn't working correctly. Although the program isn't idle (it is in fact performing the query), it looks idle. To fix this problem, you could display a status bar that contains the latest query and the time it was submitted, or display a transient highlight over the fields that are being updated even if the values don't change. Event processing in Swing is effectively single-threaded, so you don't have to be well-versed in writing threaded applications to write basic Swing programs. The following sections describe the three rules you need to keep in mind when using threads in Swing: repaintand revalidatemethods on JComponent.) invokeLaterand invokeAndWaitfor doing work if you need to access the GUI from outside event-handling or drawing code. SwingWorkeror Timer.For example, you might want to create a thread to handle a job that's computationally expensive or I/O bound. Realized means that the component's paint method has been or might be called. A Swing component that's a top-level window is realized by having setVisible(true), show, or (this might surprise you) pack called on it. Once a window is realized, all of the components that it contains are realized. Another way to realize a Component is to add it to a Container that's already realized. The event-dispatching thread is the thread that executes the drawing and event-handling code. For example, the paint and actionPerformed methods are automatically executed in the event-dispatching thread. Another way to execute code in the event-dispatching thread is to use the AWT EventQueue.invokeLater method. There are a few exceptions to the single-thread rule: initmethod. Existing browsers don't render an applet until after its initand startmethods have been called, so constructing the GUI in the applet's initmethod is safe as long as you never call showor setVisible(true)on the actual applet object. JComponentmethods can be called from any thread: repaint, revalidate, and invalidate. The repaintand revalidatemethods queue requests for the event-dispatching thread to call paintand validate, respectively. The invalidatemethod just marks a component and all of its direct ancestors as requiring validation. add<ListenerType >Listenerand remove<ListenerType >Listenermethods. These operations have no effect on event dispatches that might be under way. mainthread. For example, the code in Listing 11-1 is safe, as long as no Componentobjects (Swing or otherwise) have been realized. public class MyApplication { public static void main(String[] args) { JPanel mainAppPanel = new JPanel(); JFrame f = new JFrame("MyApplication"); f.getContentPane().add(mainAppPanel, BorderLayout.CENTER); f.pack(); f.setVisible(true); // No more GUI work here } } Constructing a GUI in the mainthread In this example, the f.pack call realizes the components in the JFrame. According to the single-thread rule, the f.setVisible(true) call is unsafe and should be executed in the event-dispatching thread. However, as long as the program doesn't already have a visible GUI, it's exceedingly unlikely that the JFrame or its contents will receive a paint call before f.setVisible(true) returns. Because there's no GUI code after the f.setVisible(true) call, all GUI processing moves from the main thread to the event-dispatching thread, and the preceding code is thread-safe. invokeLaterand invokeAndWaitmethods to cause a Runnableobject to be run on the event-dispatching thread. These methods were originally provided in the SwingUtilities class, but are part of the EventQueue class in the java.awt package in J2SE v. 1.2 and later. The SwingUtilties methods are now just wrappers for the AWT versions. invokeLaterrequests that some code be executed in the event-dispatching thread. This method returns immediately, without waiting for the code to execute. invokeAndWaitacts like invokeLater, except that it waits for the code to execute. Generally, you should use invokeLaterinstead., it doesn't wait for the event- dispatching thread to execute the code. Listing 11-2 shows how to use invokeLater. Runnable doWork = new Runnable() { public void run() { // do some GUI work here } }; SwingUtilities.invokeLater(doWork); Using invokeLater invokeAndWaitmethod is just like the invokeLatermethod, invoked code is running. Listing 11-3 shows how to use invokeAndWait. Listing 11-4 shows how a thread that needs access to GUI state, such as the contents of a pair of JTextFields, can use invokeAndWait to access the necessary information. void showHelloThereDialog() throws Exception { Runnable doShowModalDialog = new Runnable() { public void run() { JOptionPane.showMessageDialog(myMainFrame, "HelloThere"); } }; SwingUtilities.invokeAndWait(doShowModalDialog); } Using invokeAndWait void printTextField() throws Exception { final String[] myStrings = new String[2]; Runnable doGetTextFieldText = new Runnable() { public void run() { myStrings[0] = textField0.getText(); myStrings[1] = textField1.getText(); } }; SwingUtilities.invokeAndWait(doGetTextFieldText); System.out.println(myStrings[0] + " " + myStrings[1]); } Using invokeAndWaitto access GUI state Remember that you only need to use these methods if you want to update the GUI from a worker thread that you created. If you haven't created any threads, then you don't need to use invokeLater or invokeAndWait. Timerclasses: one in the javax.swingpackage and the other in java.util. Nearly every computer platform has a timer facility of some kind. For example, UNIX programs can use the alarm function to schedule a SIGALRM signal; a signal handler can then perform the task. The Win32 API has functions, such as SetTimer, that let you schedule and manage timer callbacks. The Java platform's timer facility includes the same basic functionality as other platforms, and it's relatively easy to configure and extend. //DON'T DO THIS! while (isCursorBlinking()) { drawCursor(); for (int i = 0; i < 300000; i++) { Math.sqrt((double)i); // this should chew up time } eraseCursor(); for (int i = 0; i < 300000; i++) { Math.sqrt((double)i); // likewise } }Busy wait loop A more practical solution for implementing delays or timed loops is to create a new thread that sleeps before executing its task. Using thefinal Runnable doUpdateCursor = new Runnable() { boolean shouldDraw = false; public void run() { if (shouldDraw = !shouldDraw) { drawCursor(); } else { eraseCursor(); } } }; Runnable doBlinkCursor = new Runnable() { public void run() { while (isCursorBlinking()) { try { EventQueue.invokeLater(doUpdateCursor); Thread.sleep(300); } catch (InterruptedException e) { return; } } } }; new Thread(doBlinkCursor).start(); Thread sleepmethod to time a delay works well with Swing components as long as you follow the rules for thread usage outlined in Section 11.4 on page 176. The blinking cursor example could be rewritten using Thread.sleep, as shown in Listing 11-6. As you can see, the invokeLatermethod is used to ensure that the drawand erasemethods execute on the event-dispatching thread. Using the Thread sleepmethod The main problem with this approach is that it doesn't scale well. Threads and thread scheduling aren't free or even as cheap as one might hope, so in a system where there might be many busy threads it's unwise to allocate a thread for every delay or timing loop. javax.swing.Timerclass allows you to schedule an arbitrary number of periodic or delayed actions with just one thread. This Timerclass is used by Swing components for things like blinking the text cursor and for timing the display of tool-tips. The Swing timer implementation fires an action event whenever the specified interval or delay time passes. You need to provide an Action object to the timer. Implement the Action actionPerformed method to perform the desired task. For example, the blinking cursor example above could be written as shown in Listing 11-7. In this example, a timer is used to blink the cursor every 300 milliseconds. Action updateCursorAction = new AbstractAction() { boolean shouldDraw = false; public void actionPerformed(ActionEvent e) { if (shouldDraw = !shouldDraw) { drawCursor(); } else { eraseCursor(); } } }; new Timer(300, updateCursorAction).start(); Blinking cursor The important difference between using the Swing Timer class and creating your own Thread is that the Swing Timer class uses just one thread for all timers. It deals with scheduling actions and putting its thread to sleep internally in a way that scales to large numbers of timers. The other important feature of this timer class is that the Action actionPerformed method runs on the event-dispatching thread. As a result, you don't have to bother with an explicit invokeLater call. java.utilpackage. Like the Swing Timerclass, the main java.utiltimer class is called Timer. (We'll call it the "utility Timerclass" to differentiate from the Swing Timerclass.) Instead of scheduling Actionobjects, the utility Timerclass schedules instances of a class called TimerTask. The utility timer facility has a different division of labor from the Swing version. For example, you control the utility timer facility by invoking methods on TimerTask rather than on Timer. Still, both timer facilities have the same basic support for delayed and periodic execution. The most important difference between javax.Swing.Timer and java.util.Timer is that the latter doesn't run its tasks on the event-dispatching thread. The utility timer facility provides more flexibility over scheduling timers. For example, the utility timer lets you specify whether a timer task is to run at a fixed rate or repeatedly after a fixed delay. The latter scheme, which is the only one supported by Swing timers, means that a timer's frequency can drift because of extra delays introduced by the garbage collector or by long-running timer tasks. This drift is acceptable for animations or auto-repeating a keyboard key, but it's not appropriate for driving a clock or in situations where multiple timers must effectively be kept in lockstep. The blinking cursor example can easily be implemented using the java.util.Timer class, as shown in Listing 11-8. final Runnable doUpdateCursor = new Runnable() { private boolean shouldDraw = false; public void run() { if (shouldDraw = !shouldDraw) { drawCursor(); } else { eraseCursor(); } } }; TimerTask updateCursorTask = new TimerTask() { public void run() { EventQueue.invokeLater(doUpdateCursor); } }; myGlobalTimer.schedule(updateCursorTask, 0, 300); Blinking the cursor with java.util.Timer An important difference to note when using the utility Timer class is that each java.util.Timer instance, such as myGlobalTimer, corresponds to a single thread. It's up to the program to manage the Timer objects. Timerclass is preferred if you're building a new Swing component or module that doesn't require large numbers of timers (where "large" means dozens or more). The new utility timer classes give you control over how many timer threads are created; each java.util.Timer object creates one thread. If your program requires large numbers of timers you might want to create several java.util.Timer objects and have each one schedule related TimerTasks. In a typical program you'll share just one global Timer object, for which you'll need to create one statically scoped Timer field or property. The Swing Timer class uses a single private thread to schedule timers. A typical GUI component or program uses at most a handful of timers to control various animation and pop-up effects. The single thread is more than sufficient for this. The other important difference between the two facilities is that Swing timers run their task on the event-dispatching thread, while utility timers do not. You can hide this difference with a TimerTask subclass that takes care of calling invokeLater. Listing 11-9 shows a TimerTask subclass, SwingTimerTask, that does this. To implement the task, you would then subclass SwingTimerTask and override its doRun method (instead of run). abstract class SwingTimerTask extends java.util.TimerTask { public abstract void doRun(); public void run() { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater(this); } else { doRun(); } } } Extending TimerTask Cross-fade animation This animation is implemented using the java.util.Timer and SwingTimerTask classes. The cross-fade is implemented using the Graphics and Image classes. Complete code for this sample is available online,1 but this discussion concentrates on how the timers are used. A SwingTimerTask is used to schedule the repaints for the animation. The actual fade operation is handled in the paintComponent method, which computes how far along the fade is supposed to be based on the current time, and paints accordingly. The user interface provides a slider that lets the user control how long the fade takes-the shorter the time, the faster the fade. When the user clicks the Fade button, the setting from the slider is passed to the startFade method, shown in Listing 11-10. This method creates an anonymous subclass of SwingTimerTask (Listing 11-9) that repeatedly calls repaint. When the task has run for the allotted time, the task cancels itself. public void startFade(long totalFadeTime) { SwingTimerTask updatePanTask = new SwingTimerTask() { public void doRun() { /* If we've used up the available time then cancel * the timer. */ if ((System.currentTimeMillis()-startTime) >= totalTime) { endFade(); cancel(); } repaint(); } }; totalTime = totalFadeTime; startTime = System.currentTimeMillis(); timer.schedule(updatePanTask, 0, frameRate); } Starting the animation The last thing the startFade method does is schedule the task. The schedule method takes three arguments: the task to be scheduled, the delay before starting, and the number of milliseconds between calls to the task. It's usually easy to determine what value to use for the task delay. For example, if you want the cursor to blink five times every second, you set the delay to 200 milliseconds. In this case, however, we want to call repaint as often as possible so that the animation runs smoothly. If repaint is called too often, though, it's possible to swamp the CPU and fill the event queue with repaint requests faster than the requests can be processed. To avoid this problem, we calculate a reasonable frame rate and pass it to the schedule method as the task delay. This frame rate is calculated in the initFrameRate method shown in Listing 11-11. public void initFrameRate() { Graphics g = createImage(imageWidth, imageHeight).getGraphics(); long dt = 0; for (int i = 0; i < 20; i++) { long startTime = System.currentTimeMillis(); paintComponent(g); dt += System.currentTimeMillis() - startTime; } setFrameRate((long)((float)(dt / 20) * 1.1f)); } Initializing the frame rate The frame rate is calculated using the average time that it takes the paintComponent method to render the component to an offscreen image. The average time is multiplied by a factor of 1.1 to slow the frame rate by 10 percent to prevent minor fluctuations in drawing time from affecting the smoothness of the animation. For additional information about using Swing timers, see How to Use Timers in The Java Tutorial.2 If it might take a long time or it might block, use a thread. If it can occur later or it should occur periodically, use a timer. Occasionally, it makes sense to create and start a thread directly; however, it's usually simpler and safer to use a robust thread-based utility class. A thread-based utility class is a more specialized, higher-level abstraction that manages a worker thread. The timer classes described in Section 11.3 are good examples of this type of utility class. Concurrent Programming in Java3 by Doug Lea describes many other useful thread-based abstractions. Swing provides a simple utility class called SwingWorker that can be used to perform work on a new thread and then update the GUI on the event-dispatching thread. SwingWorker is an abstract class. To use it, override the construct method to perform the work on a new thread. The SwingWorker finished method runs on the event-dispatching thread. Typically, you override finished to update the GUI based on the value produced by the construct method. (You can read more about the SwingWorker class on The Swing Connection.4) The example in Listing 11-12 shows how SwingWorker can be used to check the modified date of a file on an HTTP server. This is a sensible task to delegate to a worker thread because it can take a while and usually spends most of its time blocked on network I/O. final JLabel label = new JLabel("Working ..."); SwingWorker worker = new SwingWorker() { public Object construct() { try { URL url = new URL(""); return new Date(url.openConnection().getLastModified()); } catch (Exception e) { return ""; } } public void finished() { label.setText(get().toString()); } }; worker.start(); // start the worker thread Checking the state of a remote file using a worker thread In this example, the construct method returns the last-modified date for java.sun.com, or an error string if something goes wrong. The finished method uses SwingWorker.get, which returns the value computed by the construct method, to update the label's text. Using a worker thread to handle a task like the one in the previous example does keep the event-dispatching thread free to handle user events; however, it doesn't magically transform your computer into a multi-CPU parallel-processing machine. If the task keeps the worker thread moderately busy, it's likely that the thread will absorb cycles that would otherwise be used by the event-dispatching thread and your program's on-screen performance will suffer. There are several ways to mitigate this effect: The example in the next section illustrates as many of these guidelines and techniques as possible. It's a front end for web search engines that resembles Apple's Sherlock 2 application5 or (to a lesser extent) Infoseek's Express Search application.6 These types of user interfaces push the limit of what works well in the HTML-based, thin-client application model. Many of the operations that you might expect to find in a search program, such as sorting and filtering, can't easily be provided under this dumb-terminal-style application model. On the other hand, the Java platform is uniquely suited for creating user interfaces for web services like search engines. The combination of networking libraries, HTTP libraries, language-level support for threads, and a comprehensive graphics and GUI toolkit make it possible to quickly create full-featured web-based applications. Search Party application The Search Party application, shown in Figure 11-2, provides this kind of Java technology-based user interface for a set of web search engines. It illustrates how to apply the guidelines and techniques described in this chapter to create a responsive GUI. You can download the complete source code for the Search Party application from. Search Party allows the user to enter a simple query that's delivered to a list of popular search engines. The results are collected in a single table that can be sorted, filtered, and searched. The GUI keeps the user up-to-date on the search tasks that are running and lets the user interrupt a search at any time. Worker threads are used to connect to the search engines and parse their results. Each worker thread delivers updates to the GUI at regular intervals. After collecting a couple hundred search hits, the worker thread exits. If the user interrupts the search, the worker threads are terminated. The following sections take a closer look at how the worker threads operate. Thread.MIN_PRIORITY.The thread-priority property allows you to advise the underlying system about the importance of scheduling the thread. How the thread- priority property is used depends on the JVM implementation. Some implementations make rather limited use of the priority property and small changes in thread priority have little or no effect. In other JVM implementations, a thread with a low priority might starve (never be scheduled) if there are always higher-priority threads that are ready to run. In the Search Party application, the only thread we're concerned about competing with is the event-dispatching thread. Making the worker threads' priorities low is reasonable because we're always willing to suspend the worker threads while the user is interacting with the program. When the Thread.interrupt method is called, it just sets the thread's interrupted boolean property. If the interrupted thread is sleeping or waiting, an InterruptedException is thrown. If the interrupted thread is blocked on I/O, an InterruptedIOException might be thrown, but throwing the exception isn't required by the JVM specification and most implementations don't. Search Party's SwingWorker subclass, SearchWorker, checks to see if it's been interrupted each time it reads a character from the buffered input stream. Although the obvious way to implement this would be to call Thread.isInterrupted before reading a character, this approach isn't reliable. The isInterrupted flag is cleared when an InterruptedException is caught or when the special "interrupted" test and reset method is called. If some code that we've implicitly called happens to catch the InterruptedException (because it was waiting or sleeping) or if it clears the isInterrupted flag by calling Thread.interrupted, Search Party wouldn't realize that it's been interrupted! To make sure that Search Party detects interruptions, the SwingWorker interrupt method interrupts the worker thread and permanently sets the boolean flag that is returned by the SwingWorker method isInterrupted. What happens if the interrupted worker thread is blocked on I/O while waiting for data from the HTTP server it's reading from? It's unlikely that the I/O code will throw an InterruptedIOException, which means there's a potential thread leak. To avoid this problem, SearchWorker class overloads the interrupt method. When the worker is interrupted, the input stream it's reading from is immediately closed. This has the nice side effect of immediately aborting any pending I/O. The SearchWorker implementation catches and ignores the I/O exception that results from closing the thread's input stream while a read was pending. You can download the code for this and other examples from Mary Campione and Kathy Walrath, The Java Tutorial: Object-Oriented Programming for the Internet, Second Edition. Addison-Wesley, 1998.3 Doug Lea, Concurrent Programming in Java: Design Principles and Patterns, Second Edition. Addison-Wesley, 1999.4 Visit The Swing Connection online at For more information about Sherlock, see For more information about Express Search, see © 2001, Sun Microsystems,Inc.. All rights reserved.
http://java.sun.com/docs/books/performance/1st_edition/html/JPSwingThreads.fm.html
crawl-001
refinedweb
4,159
55.54
In a September item, Martin Kleppmann says: Scala in 2009 has the place which Python had in 2004. I bookmarked Scala (the language; not the band ;-) back in June 2007, but I didn't find a good excuse to try it out until Alexandre Bertails, the new W3C webmaster, suggested adding scala to the php/perl/python/java mix that powers w3.org. He gave a great PreparedKata on scala. I have now built a couple little projects using Scala. The experience brings me back to a June 1996 Usenet posting, where I wrote: Modula-3 was more fun to learn than I had had in years. The precision, simplicity, and discipline employed in the design of the language and libraries is refreshing and results in a system with amazing complexity management characteristics. I have high hopes for Java. I will miss a few of Modula-3's really novel features. The way interfaces, generics, exceptions, partial revelations, structural typing + brands come together is fantastic. But Java has threads, exceptions, and garbage collection, combined with more hype than C++ ever had. I'm afraid that the portion of the space of problems for which I might have looked to python and Modula-3 has been covered -- by perl for quick-and-dirty tasks, and by Java for more engineered stuff. And both perl and Java seem more economical than python and Modula-3. I'm happy to say that I was wrong; python matured quickly enough that I use it for most of the spectrum. The libraries matured quickly enough to allow me to get away from perl. And I'm pretty happy that I avoided Java long enough for scala to come along and fill in the bits of Modula-3 that Java lacks. The main reason I never did pick up Java is that the main part of my job was project management, i.e. on the manager's schedule, and an hour isn't enough to do any software engineering. It is enough time to write, test, and document some python code! I'm doing more software development these days; working on the UI part of a Science Commons project last summer finally gave me several days in a row to dig in and learn JavaScript development. And I had to interface to a Java API in JMOL, so I dipped my toe in the Java waters using Jython. I got it working, but since I largely depend on doctest mode for emacs and never got jython working there, it's only manually tested. I can now write, test, and document scala code, though it's about equal parts fun and frustration at this point. The first frustration was finding that there's nothing like the python tutorial on the scala web site. The tour of scala was very tasty, but didn't teach me enough to read scala code and be confident about what's going on. I tried reading the language spec, but got lost in abstractions (that's one thing Java has over scala; GJS's Java spec is a joy to read). Alexander eventually got me to read the ebook, which is quite good, though not freely available. Shortly after that I discovered the video of Martin Odersky's FODEM talk; I think that one pleasant hour could have substituted for several earlier frustrating hours on the scala web site. And I discovered the O'Reilly scala book; people say it's nowhere near as good, but I'm going to try to migrate to it for reference purposes, since I can more easily share what I find there. The next frustration I feared was giving up emacs in favor of a modern Java IDE. But the friendly folks in the #scala channel assured me it wasn't necessary: <DanC> I'm an emacs addict, but I gather the way to do scala is with Eclipse <paulp> DanC: don't know where you gathered that but I would bet eclipse user a minority. <DanC> oh. <DanC> what do you use? <paulp> textmate. <dcsobral> jEdit here. I did give up make for simple build tool (sbt); I only miss it a little; sbt emacs integration is pretty raw and next-error gets out of sync about which line to go to (workaround: restart sbt-shell). Flymake looks cool, but I haven't managed to get it working. Giving up doctest is much harder. I learned to use scalatest, but it's no it's tedious and using the 1.0 version requires using unreleased versions of sbt (which worked fine for me). ScalaCheck is even more bothersome, as it uses level 12 scala type inference magic while I'm only a level 4 apprentice, but at least it rewards you by generating zillions of test cases for you. None of the scala test frameworks are integrated with scaladoc, the documentation framework. Every time I had to fill in a test name or description I'd think "Why is this not integrated with docs? An interpreter and REPL are as much a part of the scala culture as the python culture; surely there's a doctest for scala out there" and go searching. No joy. I did find a couple starts at doctest for Java (they use JavaScript for the REPL; Java itself just doesn't work that way). I eventually got fed up enough to start my own doctest.scala, though it's not feature complete enough to use yet. "Beautiful is better than ugly." says the Zen of Python, and scala feels pretty elegant. But the next aphorism is "Explicit is better than implicit." Java clearly takes this too far with FileInputStream x = new FileInputStream(file); Telling the compiler type type of x once should be enough, and with scala, it is. But scala has lots more magic that, all together, can make it hard to read. The complexity shows up in the compiler diagnostics, which I find misleading more often than not. Scala has parallel namespaces for types and values; it's kinda cute, but consider this diagnostic: [error] /home/connolly/projects/rdfsem/src/test/scala/rdfstdtest.scala:137: not found: value Graph [error] val manifest = Graph(WebData.loadRDFXML(args(0))) [error] ^ I sit there pulling my hair out, saying "Graph is imported 10 lines up; are you blind?!?!?!" But what I imported was the type, not the value. The real problem in that line of code is that scala is like java in using a new keyword for instantiating (most) classes, but python habits die hard. And that's just the beginning when it comes to mystifying compiler diagnostics. Be very afraid of "Missing closing brace `}' assumed here." The missing brace may be very, very far away. The ScalaCheck docs really need a special decoder ring due to its use of higher order magic; check this out: [error] /home/connolly/projects/rdfsem/src/test/scala/strquot1.scala:33: missing parameter type for expanded function ((x0$1) => x0$1 match { [error] case (s @ (_: String)) => dequote(quote(quote(s))).$eq$eq(quote(s)) [error] }) [error] Prop.forAll((genQuotEsc) { [error] ^ That "case (s @ ..." stuff isn't in my code; the compiler magically conjured it up. I only know from monkey-see-monkey-do reading of the ScalaCheck docs that the right answer is: Prop.forAll(genQuotEsc) { Here the compiler is being sadistically misleading: [error] /home/connolly/projects/rdfsem/src/test/scala/rdfstdtest.scala:103: not enough arguments for method apply: (n: Int)org.w3.swap.logic.Term in trait LinearSeqLike. [error] Unspecified value parameter n. [error] println(manifest.each(u, rdf_type, what).mkString()) [error] ^ My sin in this case was to break the rules for methods without parentheses. Many thanks to RSchulz and company in #scala for taking my side in several battles against the compiler's disinformation campaign. Once that battle is over, life is much more fun. That is, after all, much of the value proposition of statically typed languages, though the global consistency guarantee in the language and build tools comes with a downside that when you change a type, you can't just test a few modules without getting everything in sync. My debugging tool so far is the trusty println(). When my code hangs, I'm used to hitting ctrl-c and getting a python backtrace. The java runtime, and hence scala runtime, just quits with no backtrace when you hit ctrl-c. Ouch. When I asked about debugging and profiling tools in #scala, the suggestions I got were about various GUI tools, many of them commercial. I managed to get IDEA with the scala plugin configured to navigate my code, but it took 20x longer than sbt to build, and before I managed to learn to use its debugger, I spotted the bug myself. For profiling, java -Xprof worked just fine for my needs, though jvisualvm is free and packaged by Ubuntu and I did get it to attach to my running code; I'm still stumped about how to get it to tell me which methods are taking the most time, though. I like the idea that scala is now where python was a few years ago, i.e. that the frustrations that I'm running into are rough edges that will get smoothed out soonish. The cascade that started with scalatest 1.0 requiring using an unreleased version of sbt continued thru using version 2.8.0.Beta1-RC5 of the compiler and libraries. I still love python, but I'm happy to restore an elegant statically typed languge to my toolset after Modula-3 went fallow, especially one that interoperates with the java platform everywhere from android mobile devices to Google App Engine. tags: programming
http://www.advogato.org/person/connolly/diary/71.html
CC-MAIN-2015-32
refinedweb
1,621
70.53
How to check whether a number is in the range[low, high] using one comparison ? This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range. A simple solution is compare x with low and high #include <iostream> using namespace std; // Returns true if x is in range [low..high], else false bool inRange(unsigned low, unsigned high, unsigned x) { return (low <= x && x <= high); } int main() { inRange(10, 100, 30)? cout << "Yes\n": cout <<"No\n"; inRange(10, 100, 5)? cout << "Yes\n": cout <<"No\n"; } Output: Yes No The above solution does two comparisons, Can we do the same task using one comparison? We strongly recommend you to minimize your browser and try this yourself first. The idea is to compare “x-low” with “high-x”. x is in range [low, high] if and only if x is greater than or equal to low and smaller than or equal to high. Output: Yes No How does this work for [10, 100] and x = 5? When we subtract 10 from 5, we get -5 which is considered as UNIT_MAX-4 in unsigned int form. UNIT_MAX is maximum possible unsigned int value. The assumption here is, numbers are stored in 2’s complement form. In 2’s complement form, -1 represents UINT_MAX, -2 represets UINT_MAX-1,..etc. Thanks to Utkarsh for suggesting this solution. A Solution that works for negative numbers also The idea is to multiply (x-low) and (x-high). If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range. Else not. Thanks to eva for suggesting this method. Output: Yes No Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Recommended Posts: - Measure execution time with high precision in C/C++ - Comparison of a float with a value in C - Ratio Manipulations in C++ | Set 2 (Comparison) - Results of comparison operations in C and C++ - Comparison of Exception Handling in C++ and Java - Comparison of Java with other programming languages - Assigning an integer to float and comparison in C/C++ - Comparison of static keyword in C++ and Java - Comparison of boolean data type in C++ and Java - C program to Check Whether a Number is Positive or Negative or Zero - NaN in C++ - What is it and how to check for it? - Check if a given graph is Bipartite using DFS - Program to check if two strings are same or not - Check if a key is present in a C++ map or unordered_map - Quickly check if two STL vectors contain same elements or not
https://www.geeksforgeeks.org/how-to-check-whether-a-number-is-in-the-rangea-b-using-one-comparison/
CC-MAIN-2019-35
refinedweb
520
69.01
Java Program to Print Odd Numbers From 1 to 99 In this tutorial, we will be going to Solve and tackle the problem Java Program to Print Odd Numbers From 1 to 99. If You Don’t Have an idea on how to Filter out the odd numbers between a given range, then you are at the perfect place to learn. In this tutorial, we will be focusing on odd numbers concept. We will see how to tackle the above problem. Java Program to Print Odd Numbers From 1 to 99 As we know that odd numbers are the ones which when divided by 2, it leaves a remainder 1. In this problem, we will be going to Filter out the odd numbers between the given range. Here, it is between 1 to 99. So, after every iteration, the counter I moves from 1 to 2 and checks the condition and if it gets satisfied, it Prints else moves to other next iteration. Initially, we will be looping from 1 to 100, in which we will be making a condition check after each iteration of the loop, whether the present number when divided by 2, leaves a remainder 1, then we will be displaying them from the right first iteration. As we know, looping can be done anyway, either with a while loop, for loop, or do while any would work here. In the Below case, I implemented Iteration through for loop. As we know, the remainder is calculated using the modulus operator, and if condition checks for the odd number condition to successfully print them. System.out.print displays in a single line, whereas System.out.println displays into a new line after each iteration. Below is the code to Display odd numbers between 1 to 99: public class Main { public static void main(String[] args) { for (int i = 1; i < 100; i++) { if (i % 2 != 0) { System.out.print(i+" "); } } } } As we see that, after Successfully compilation of the above code, we get the output as 1 3 5 7 ….. till 99. Below is the output of the above program: You may also learn:
https://www.codespeedy.com/java-program-to-print-odd-numbers-from-1-to-99/
CC-MAIN-2020-40
refinedweb
356
67.69
Hi interwebz. I just want to share this short poor man’s fix when migrating TypeScript to filter out some particular errors in TypeScript build. Why the hell you (might) need it? So what would be the common use case , why to bother mask/mute errors on build? Compile is the first test our code need to undergo, like first pass of “unit tests”. Our situation : currently we have a lot of .js files that let’s say most of the time worked and we need to iterate on way to migrate fully from JavaScript only to TypeScript only. So we rename .js to .ts and then we ran into errors like (among others) : - error TS2365 Operator ‘>=’ cannot be applied to types ‘string’ and ‘number’. - error TS2365 Operator ‘==’ cannot be applied to types ‘string’ and ‘number’. - error TS2345 Argument of type ‘number’ is not assignable to parameter of type ‘string’. Yes indeed these are against the “logic” of TypeScript – bring types to JavaScript. But I know I want it there for some short timespan. Just to test. I don’t want to wade through 1500 same errors I know I will have to fix, but among them TypeScript also tells me big and real problems, but buried under many same errors about types. We are not alone in this, more ppl write about it here : and also here Solution : So the solutions vary from custom branch of TypeScript as such to stupid grep on the command line output. And since I am on Windows 10 (my dev box) , I chose to stick with PowerShell so this is snippet that should do the job. Lets say we want to mute TS2365 and TS2345 errors and your TS build gulp task has name someTSBuildTaskName. PS script – output to some file : node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345" | Out-File "grepts.txt" PS script – output just to console (just drop the last part after pipe) : node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345" PS: I am calling here the gulp task without gulp installed with -g flag (global) so you can just call gulp someTSBuildTaskName with globally installed gulp and you are also good to go. Found any better solution? Pls let us know in comments! 🙂 AD: you can also use this console log parser on Jenkins: Regular Expression : ([\w\\\.]+)\((\d+),\d+\):\s+\w+\s+((?!TS2365|TS2345)\w+):\s+(.*)$ Mapping Script : import hudson.plugins.warnings.parser.Warning String fileName = matcher.group(1) String line = matcher.group(2) String category = matcher.group(3) String message = matcher.group(4) return new Warning(fileName, Integer.parseInt(line), "TS Error", category, message); and plug this into your build pipeline.
http://rostacik.net/2016/11/10/how-to-filter-particular-typescript-errors-in-build-result/
CC-MAIN-2017-30
refinedweb
459
74.69
. On Interoperability> . SVG in the IE9 Platform Preview: >>IMAGE> . SVG in Internet Explorer 9 The following: - Methods of embedding: <embed>, <iframe>, <img>, css image, .svgz - Gradients and Patterns - Clipping, Masking, and Compositing - Cursor, Marker - Remainder of Text, Transforms, Events We encourage you to download the Platform Preview and try out its SVG functionality! The Windows Internet Explorer Test Drive site contains a few demos and is a good starting point. Jennifer Yu Program Manager Update 3/19 - updated the second code sample to remove the xmlns and version attributes from the SVG tag since these aren't necessary and could be confusing in the context of the other samples. I suggest: Internet Explorer 10=IE9+virtual pc) SVG… looks rignt. BUT WHERE IS THE CANVAS? IMPLEMENTING CANVAS USING C++ IS NOT DIFFICULT!!! AND IT’S IMPLEMENTABLE USING DIRECTX/WPF. And WPF(Using DirectX) can be implemented in XP, Why not IE9? re: infinite re: canvas support: canvas is patented by apple. As they are in the w3c working group, they have an obligation to license it royalty-free… but ONLY WHILE IT’S A W3C RECCOMENDATION. even css2.1 is only a candidate at the moment… legally, MS cannot begin implementing canvas until html5 is a proper standard Thanks for the informative post and great news on SVG. Your link to the test drive site is, perhaps, an internal one. I think you meant to all those XP users, just move on, and upgrade. XP is the IE6 of the OS landscape, it’s old, full of security problems, and just obsolete already. Just kill XP, like how we kill IE6. You have declared that "One code, One markup, One script, Runs everywhere" , but, how can we implement this using a canvas-unsupported ie? And here is an UI design done by me for IE9: Very happy about this! Microsoft gets it right eventually, in this case at least. "Patrick Dengler, a member of the SVG Working Group and Senior Program Manager at Microsoft, is working closely with the SVG Working Group to help define the future of SVG…" That made me laugh. Patrick’s been a member for 4 weeks now? Or is it eight? But the SVG group has been around for 10 years? And now he’s giving the SVG group advice? I love how Chrome (WebKit) handles it! "Most of SVG that is currently supported in the Platform Preview is fully implemented." Putting it in real terms: "The parts of SVG we support we fully implement." iow, "We don’t fully implement SVG". So this level of SVG support (28% according to) is all we can expect in IE9? I was expecting at least 80% up and that might take the IE team 4-5 more releases to catch up. While accelerated graphics are certainly the best way moving forward, Windows XP users should be given the rendering engine of IE9 to keep up with web standards. Just my two cents. ignore winxp let’s software steps further faster Jose, as the article describes, SVG support in IE9 is not feature complete in the IE Platform Preview. Rob, the statement you quote refers mainly to the methodical approach we’re taking in implementing SVG and not to the level of support the team is committed to. Jose, Microsoft has stated they will have a great deal more SVG ready in subsequent IE9 previews. This is only a start. foreignObject support for HTML content is an important aspect of SVG – does IE9 support it? @Jose, "I was expecting at least 80% up and that might take the IE team 4-5 more releases to catch up." I think Microsoft will release 4-5 more IE9 preview/alpha/beta within 5-6 months, so they’ll catch up very soon. @wechrome "Q. How often will be you be updating this? A. We hope to release a new version of Internet Explorer Platform Preview approximately every 8 weeks." I hate you microsoft and IE team. Will have push chrome frame plugin on IE forever!!!!!! HTML5 with full canvas and CSS3 is indeed just a far away dream. Don’t think you can handle criticism, being dictatoring this blog deleting comments at will. You’re doing IE6 again, for the 4th time. @Rob: they could go the Webkit way and implement all objects and methods in a way that’d work on test cases (that’s how Webkit scored 100/100 at Acid3 at first), or go the Mozilla way and enable a spec only once the entire engine is finished, road tested, tried and true (see how long it took Gecko to switch from CSS 2.0 to CSS 2.1, and the status of SMIL support). Instead, if Trident doesn’t support SVG in its entirety (that’s a difficult scope to define), what SVG objects Trident supports, is fully supported: all properties and methods. Or something. If I read that properly, current engines run the test case this way: – Presto ignores the negative value (it is seen as erroneous) – Gecko doesn’t support rectangles with negative radius (the object’s declaration is wrong) – Webkit implements negative radius. Of all, Webkit is the ‘most wrong’: in 1.1, a negative value is defined as an error, and the UA should switch into error mode – which, in all cases, includes stopping the parsing – and this is what Gecko does (Gecko’s SVG implementation predates Tiny 1.2). In Tiny 1.2, negative values should be ignored: that’s what Presto does. For those of you that say ‘Webkit is t3h 1337", proof is made: Webkit ain’t standards-perfect either. Personally, I also regret the lack of IE 9 for WinXP, eventhough I can understand it. It would be nice though, to have the rendering and script engines backported, even in software mode – as in, a Trident 5.0 Frame "à la" Chrome Frame. As an aside: the IE team may have been the first to think about using Direct2D for rendering in IE, but Mozilla may beat you to the first shipping final version: current Firefox 3.7 nightlies can use Direct2D, eventhough it’s not enabled by default -yet. You’d better hurry… SVG support looks nice so far. Though it still needs a lot to be done. I semi-regularly contribute to Wikimedia Commons with flag images and usually I’m using the viewBox and preserveAsspectRatio attributes to control the coordinate system for and ensure proper scaling without having to hassle with floating-point values which might be inaccurate in some cases. IE doesn’t support viewBox yet (or the upscaling to the SVG’s size), I’d hope that will come. Otherwise I’d have to rely on Firefox again to test my images 🙂 If anyone there is interested in some test cases. I put one rendering test here: A recursive markup approach on the Sierpinski carpet also serves well as a performance measurement: and – the 6th iteration already takes quite a while to render in IE and other renderers (and due to the lack of viewBox support doesn’t display right in IE yet). I’ve not read this blog since November when the first early preview of IE9 was posted. I was disappointed back then and angry that the topics covered didn’t feature enough about compliance. However reading the recent updates I’m pleasantly surprised by the IE teams progress. It all looks positive, I just hope it continues this way. I’d rather see them get IE9 right, than ship it sooner. Most developers know the pain of a new IE coming too early before it’s standards compliance is up to scratch. SVG support is nice but it divides developers again – if Webkit browsers, FF and Opera go the Canvas route and MS goes SVG where does that leave us? @Greg K All other browsers support both SVG and Canvas, all "to a degree" (with Opera’s SVG degree being the highest), so it’s not that other browsers are going the "Canvas route". So where does that leave us? Use SVG, or rather, the consistently supported parts, and the same markup will work everywhere. Lest we forget, SVG’s first name is ‘SCALABLE’. IE9 has the opportunity to present Zoom and Pan as intuitive and responsive even for the largest of SVG files. (Other browsers seem to have dis-remembered this.) Please provide various options, and get solid feedback for this very,very important feature. I personally think, that IE9 in first not alpha/beta/RC release will support approx. 50% of SVG 1.1 specification, but it is good enough for me, for you not? Although SMIL support would be very welcome, yes, but that will come, in my opinion, in some later versions… But all in all => good work and go on, don’t slow down in your implementation… No canvas mentioned, son I am disappoint I know this is off topic, but please <Canvas> tag support and CSS Transitions. You guys must add these things, for further relevancy to me. I was going to post requesting various methods of implementing such as via the img element and CSS background-images. I’m not a graphics person so SVG isn’t something I’ve spent much time. I presume that DOML2 Core and SVGDOM cover JavaScript / SVG combined so that if I wanted to replace a .style.backgroundImage via JavaScript/CSS that I could do this with an SVG image? If so I’ll be completely happy with the current set of implementation of methods to implement SVG in to (X)HTML. Also while I wouldn’t expect hardware acceleration in IE9 on XP I do expect IE9 to be released for XP. If Microsoft wants people like me to buy Windows 7 or use my copy of Vista then put back all the stuff you took out or just make Windows 8 XP with Aero and the networking and security improvements otherwise I’m sticking with XP until I find a viable Linux alternative. XP fulfills the P in PC, Vista and 7 do not. This is fantastic! I understand the commenters looking for canvas, but please.. let’s appreciate the steps as they come. Having SVG support in IE is a major win for the web. Thanks for this, MS. Keep it up ! I think that you should look at adding EventSource too. This blog was supposed to be communication with developers, but all I can see is talking to developers after decisions have been made. Where is the roadmap of features so that we don’t constantly have to ask for the same features with no response? My name is billybob and IE9 was NOT my idea. I bet xmlns:xlink="" is missing somewhere in your 3rd example Hmm, no filters or SVG Animation in IE9? @Innovimax: That example is using inline HTML, not XHTML. The XLink namespace is implied and does not to be explicitly defined. The same goes for the SVG namespace which I’ve included unnecessarily. Thanks for calling attention to that; I’ll remove the extraneous attributes. So pleased to see what’s going to be supported in SVG, especially XHTML and SVG. And I understand the company’s concerns about Canvas, and the patent issues while the API is still only a working draft. Just a note: HTML5 support for SVG had nothing to do with CSS working with SVG. We had this before HTML5. Also, for those who tell we who have XP machines to just upgrade: not all of us have the bucks to buy newer machines. I could really wish that IE9 worked on XP, not just so that I can test it, but so that we can eliminate IE6-IE8 that much more quickly. Anyway, thanks again for the SVG/XHTML support, Microsoft. I find it humorous that IE9 won’t implement Canvas simply because Apple invented it. C’mon softies, copying Apple is what put you on the map! Finally – been waiting for this for nine years. But what are the implication Will 90% of generated SVG use the namespace ? Will roundtripping of SVG files work between different vendor tools? Will Visio, Word, PowerPoint etc. use SVG as their native graphic format and when? Jens: Take a look at IE 8 which renamed the proprietary CSS attributes to the correct “-ms-” variants. What Office does is an entirely different matter, telling that the IE team is the wrong address; they likely didn’t write a single line of code in Office. Visio had SVG export for years now, by the way.; Graphviz does that right, at least. Sorry for the tangent here. @Johannes: You can save as Optimized SVG which strips out all the inkscape/sodipodi elements and attributes. Alternatively you can use the standalone scour script which does the same thing. ohannes " There is a free tool specifically designed for IE users who want to create lean W3C SVG for IE9 source and other apps. The tool require the Adobe SVG Viewer Add-on for IE8. See: The IE Team has a lot on its plate to bring SVG1.1 standards into IE9. I’d like to suggest the desert course :)… IE9 will substantially move ahead of other browsers in SVG if it were to also include applicable SVG1.2 and some of the SVG2.0 standards and DOM API’s that will surely be adopted. The cherry-on-top would be inclusion of features that Microsoft has available in XAML and Silverlight that could be applied to SVG. So there is a moment after all, when the IE may actually get some praise even from me. This may represent nice move forward fore the web. The achieved greater interoperability on scalable graphics would be very very helpful… I have a testcase of somee CSS-3, HTML5, and SVG here: While there is browser-sniffing to deliver the right SVG embed codes, the platform preview seems to be having trouble. It also is putting the SVG images in a giant white box when put in with an object tag. It also doesn’t respect the video element, nor multiple backgrounds in CSS. It does, at least, accept the XML delivery. If I’ve done something wrong in the code (though it validates), I’d love it if someone gave me a heads-up; otherwise, I suppose I leave it to you guys as a test-case! As long-time user of XP pro I heard great things about Windows 7. So, in order to particate in the IE9 SVG testing stage, I moved to a Windows 7 machine. I think the only folks who gave Windows 7 a glowing report were Vista users…so far, I’m not impressed for its SVG support. Anyway, the first challange was to get Windows 7 and IE8 to recognize .svg and .svgz files. These file extensions must be added. Then, the Adobe SVG Viewer, a so-called IE Add-on, does not load as an addon, but must be SAVED to the Downloads folder as a separate program. It then must be run from there, as Administrator. I think Windows 7 must address these issues soonest, to assure IE9 seamlessly accepts SVG. "The use of the more interoperable SVG over VML is highly encouraged." Wow, that was unexpected in a microsoft blog. (and also awesome)! Please implement SMIL as well! It goes along perfectly with SVG. 10 years ago(!) I did a "by hand" SVG test site for the Adobe Viewer with SMIL animation. ( ) I still think it’s one of the coolest (simple/dumb) websites I’ve ever seen. Nope, no humility on that one… Thanks, – Ron I want to test SVG and report bugs for IE9. This roadmap helped me somewhat to understand which areas had been substantially completed so I could do some testing in those areas, and not waste time in areas that had not yet been included. However, I find that I need a more detailed list of current implementations and those under construction. This is a suggestion to include a more specific list of SVG implemented vs ‘to do’ in the next Platfom Preview version. Now that Internet Explorer has embraced SVG, I think it is time to look at IE8 users and their transition into IE9. This is a suggestion that should make the process of viewing SVG seamless in both browser versions. The key is the <EMBED> element. This provides very solid svg viewing in IE8 if the Adobe SVG Viewer ActiveX is installed in the user’s computer. The <EMBED> call in IE9 could include a default flag that used the Adobe ActiveX if it were available. This would then allow IE9 to view the many 1000’s of svg apps created by svg developers during the past 10 years. Furthermore, in the best of SVG worlds, the Adobe ActiveX could be a resident ActiveX in IE9. @Francis: Adobe discontinued support for their SVG Viewer ActiveX control 14 months ago. Ref: Does the current version support svgz (compressed svg)? @Esveegee: As noted in response to your comment on the other post, no IE9PP1 does not support the compressed SVG format known as SVGZ. (You can use HTTP compression however, that will work fine).
https://blogs.msdn.microsoft.com/ie/2010/03/18/svg-in-ie9-roadmap/?replytocom=364591
CC-MAIN-2017-43
refinedweb
2,886
72.56
Android ExpandableListView BaseExpandableListAdapter Custom adapter This component can be used when we have a long item list and it can be divided in groups to organize them and make things less confused. When user clicks on the group it gets expanded and we have: As it is shown above, we need two different layout: one for the group and another one for items. So it is a little bit more complex than a listView even if the concept behind this component it is the same. We need to develop an adapter and two layouts. Let’s suppose we have two classes that represent our model: one is the Category class and another one is the ItemDetail. Category holds a list of ItemDetail so Category class is like a Group (see above) and ItemDetail is an item. Here there’s a code snippet: public class Category implements Serializable { private long id; private String name; private String descr; private List<ItemDetail> itemList = new ArrayList<ItemDetail>(); ... } public class ItemDetail implements Serializable { private long id; private int imgId; private String name; private String descr; .... } Now it is time to create our group layout. We will make it really simple: just two lines one for the Category name and the other for its description, so we have: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: <TextView android: </RelativeLayout> Now we need another layout for items so we have: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: <TextView android: </RelativeLayout> We made things really simple. Now we have our layouts we need to create an adapter to handle items and groups and bind them together. ExpandableListView Adapter To create a suitable adapter we have to extend BaseExpandableListAdapter. If you read the documentation about this abstract class you can notice we have to implement some methods. We could use SimpleExpandableListAdapter that implements some methods already, but we want to have a deeper control about our adapter. There are two methods that are used to create the View corresponding to our layout, one for the items (childs) and one for the groups. These methods are: View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) used when we need to create a child View View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) used when we need to create our group View. So we have to override these two methods so that we can use our layouts. There are other “helper” methods that we need to implement in order to know the total number of childs (items in our case), the child ids, the total group (category) number and the group ids. Let’s focus our attention on the getChildView first, here there’s the code @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater inflater = (LayoutInflater)ctx.getSystemService (Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.item_layout, parent, false); } TextView itemName = (TextView) v.findViewById(R.id.itemName); TextView itemDescr = (TextView) v.findViewById(R.id.itemDescr); ItemDetail det = catList.get(groupPosition).getItemList().get(childPosition); itemName.setText(det.getName()); itemDescr.setText(det.getDescr()); return v; } As you can notice in the method we receive the groupPosition and the childPosition this one specify the the child position inside the category (group). The code is quite trivial we simply inflate our item_layout and then we retrieve first the group inside the category list at groupPosition and then the child (ItemDetail class) inside the list held by Category class. ItemDetail det = catList.get(groupPosition).getItemList().get(childPosition); When we have to create a group View corresponding to our Category class we simply do the same thing, like shown below: @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater inflater = (LayoutInflater)ctx.getSystemService (Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.group_layout, parent, false); } TextView groupName = (TextView) v.findViewById(R.id.groupName); TextView groupDescr = (TextView) v.findViewById(R.id.groupDescr); Category cat = catList.get(groupPosition); groupName.setText(cat.getName()); groupDescr.setText(cat.getDescr()); return v; } What about other methods?…Well they’re really trivial and we don’t need to explain them. In the main activity the one that create our ExpandableListView we have: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initData(); setContentView(R.layout.activity_main); ExpandableListView exList = (ExpandableListView) findViewById(R.id.expandableListView1); ExpandableAdapter exAdpt = new ExpandableAdapter(catList, this); exList.setIndicatorBounds(0, 20); exList.setAdapter(exAdpt); } In the code above we simply get the ExpandableListView widget reference in our main layout and create the Adapter. One thing you should notice is exList.setIndicatorBounds(0, 20); Using this method we set the indicator bounds. The indicator is the icon that is drawn near the group that change if the group is open or close. Here some images: Image of a list of category Image of items inside each category Source code availabe @ github Nice post.Give it up. Thanks for share this article. For more visit:android development thanks , nice article! how to add sliding animation? what kind of animation would you like to add? Can't thank you enough. It was useful. I wanted to see the customization for group and Item separately. This is what i wanted exactly. how load bd in function initdata()? What's bd? If you mean data you can download the source code at github and you can find how data is initialized. Let me know if the answer is what you are looking for. tenxs, I need load the ExpandableListView with my BD. But i see function initdata() load records. Are you example o idea load records in the function initdata?. sorry for my bad english write. Regards how to delete the item from the list after I clicked it? it really something new for me, i have to try this. so tips facebook want to say thanks so much i want to expand row using simple adpter on expandable ?help please i want to expand row by clicking buttton and using simple base adapter not expandable?can any body help me ? You've not defined catList and you also defined itemList in the class for Category properties not Item properties. Where did you define "catList" and why is itemList defined in the Category class? Can't you find it in the source code? Most interesting part is missing...
http://www.survivingwithandroid.com/2013/01/android-expandablelistview-baseexpandablelistadapter.html
CC-MAIN-2015-35
refinedweb
1,063
57.47
How to connect a bool flag with a widget enable bool - vasu_gupta last edited by I have a button save as and i want it to active if and only if a bool edit is true ,in case this bool edit is again resetted save as option again becomes disable. How to do this - raven-worx Moderators last edited by raven-worx @vasu_gupta see Qt's signals/slots concept QObject::connect( checkBox, &QCheckBox::toggled, saveBtn, &QPushButton::setEnabled ); - vasu_gupta last edited by @raven-worx i m not using a checkbox but a simple boolean variable - mrjj Lifetime Qt Champion last edited by You can do button->setEnabled(Mybool); You cannot bind a variable to widget as such. Not with connect. How is this "bool edit" altered ? - J.Hilk Moderators last edited by J.Hilk #include <QObject> class booleanWithSignal : public QObject { Q_OBJECT public: void setTrue(){ if(b != true) emit changed(true); b = true; } void setFalse(){ if(b != false) emit changed(false); b = true; } const bool &state(){return b;} signals: void changed(bool state); private: bool b = false; } // in your ui-class booleanWithSignal allowSave; connect(&allowSave, &booleanWithSignal::changed,mySaveBtn, &QPushButton::setEnabled); @vasu_gupta said in How to connect a bool flag with a widget enable bool: @raven-worx i m not using a checkbox but a simple boolean variable and what are you using? - dheerendra Qt Champions 2017 last edited by as it already suggested by other in the group, please go through signals/slots. Try few examples with how signals/slots work. This should give good info to achieve your use case.
https://forum.qt.io/topic/83059/how-to-connect-a-bool-flag-with-a-widget-enable-bool
CC-MAIN-2020-05
refinedweb
259
58.42
Back to: Python Tutorials For Beginners and Professionals Decorators and Generators in Python In this article, I am going to discuss Decorators and Generators in Python with examples. Please read our previous article where we discussed Recursive and Lambda Functions in Python with examples. As part of this article, we are going to discuss the following pointers which are related to Decorators and Generators in Python. - Decorators in Python - @ symbol in python - Generators in Python - next function in Python Decorators in Python: We have already discussed nested functions and function as first class object concepts already. Clear understanding of these concepts is important in understanding decorators. A decorator is a special function which adds some extra functionality to an existing function. The meaning of the statement can be understood clearly by the end of this topic. For now let’s understand a decorator as: - A decorator is a function that accepts a function as a parameter and returns a function. - Decorators are useful to perform some additional processing required by a function. Steps to create decorator: Step1: Decorator takes a function as an argument Step2: Decorator body should have an inner function Step3: Decorator should return a function Step4: The extra functionality which you want to add to a function can be added in the body of the inner_function. Let’s create a function which takes two arguments and prints the sum of them. Example: Add Function (Demo40.py) def add(a,b): res = a + b return res print(add(20,30)) print(add(-10,5)) Output: Now, I wish to add some extra functionality of adding the two numbers only if they are positive. If any number is negative, then I wish to take it as 0 during adding. For adding this extra functionality let create a decorator. def decor(func): #Here ‘func’ is the the argument/parameter which receives the function def inner_function(x,y): if x<0: x = 0 if y<0: y = 0 return func(x,y) return inner_function #Decor returns the func passed to it. We have created our decorator and now let’s use it with our add function from demo40.py add = decor(add) With the above statement, we are passing the add function as parameter to the decorator function, which is returning inner_function. Now, the inner_function object or address will be overridden in the ‘add’ because we are capturing the returned function in it. After this, whenever we call add, the execution goes to inner_function in the decorator. add(-10,20) In inner_function, we are doing the extra logic for checking whether the arguments are positive or not. If not positive we are assigning them with zero. And we are passing the processed values to the original add function which was sent to the decorator. Our final code will be Example: Decorator Function (Demo41.py) def decor(func): def inner_function(x,y): if x<0: x = 0 if y<0: y = 0 return func(x,y) return inner_function def add(a,b): res = a + b return res add = decor(add) print(add(20,30)) print(add(-10,5)) Output: @ symbol in python: In the above example, in order to use the decorator, we have used the ‘add = decor(add)’ line. Rather than using this we can just use the ‘@decor’ symbol on top of the function for which we want to add this extra functionality. The decorator once created can also be used for other functions as well. Example: Subtract Function using decorator (Demo40.py) def decor(func): def inner_function(x,y): if x<0: x = 0 if y<0: y = 0 return func(x,y) return inner_function @decor def sub(a,b): res = a - b return res print(sub(30,20)) print(sub(10,-5)) Output: Generators in Python: Generators are just like functions which give us a sequence of values one as an iterable (which can be iterated upon using loops). Generators contain yield statements just as functions contain return statements. Example: Generators (Demo41.py) def m(): yield 'Mahesh' yield 'Suresh' g = m() print(g) print(type(g)) for y in g: print(y) Output: Example: Generators (Demo42.py) def m(x, y): while x<=y: yield x x+=1 g = m(5, 10) for y in g: print(y) Output: next function in Python: If we want to retrieve elements from a generator, we can use the next function on the iterator returned by the generator. This is the other way of getting the elements from the generator. (The first way is looping in through it as in the examples above). Example: Generators with next function (Demo43.py) def m(): yield 'Mahesh' yield 'Suresh' g = m() print(type(g)) print(next(g)) print(next(g)) Output: In the next article, I am going to discuss Modules and Packages in Python. Here, in this article, I try to explain Decorators and Generators in Python. I hope you enjoy this Decorators and Generators in Python article. I would like to have your feedback. Please post your feedback, question, or comments about this article.
https://dotnettutorials.net/lesson/decorators-and-generators-in-python/
CC-MAIN-2020-29
refinedweb
842
52.49
On 9/8/06, Joshua Zucker <joshua.zucker at gmail.com> wrote: > On 9/8/06, kirby urner <kirby.urner at gmail.com> wrote: > > I think the model today is "a person writing code for him or herself" > > i.e. "self as client" -- at least in an early context. We're not > > guiding the unknowing through a menu tree. We're computer literate, > > fluent. > > > > Why would we ask ourselves for raw_input, when it's much easier to > > just pass arguments to functions? > > As someone who has taught a lot of functional programming (Scheme), I > have a lot of sympathy for this argument. It wouldn't occur to me to > teach raw_input or its equivalent anywhere early in the course, > because designing functions is what it's all about! I don't think it's an accident that the Scheme community seems more prepared to teach in a functional style, and treat .py namespaces as fish tanks full of mouthy functions and class type initializers -- both callables. Top-to-bottom executable scripting, with maybe forks in the road, as in: dumb_user_says = raw_input("yes or no?: ") and likely no going back if you answer it wrong: confirm = raw_input("are you sure??") Not that we don't like being asked a 2nd time, but there are other ways to build in security. You might have to actually go into the source and uncomment something (standard in POSIX environments: cut and paste a commented example, tweak and uncomment). You might have to tweak a permission. Very likely, a program with consequences will log its activities. A big part of a sysop's job: know where programs leave audit trails ( /var/syslog or whatever). Companies sometimes have manuals of style. Code that's potentially dangerous should be flagged as such. Various conventions. Often there's a "no anonymous users" policy i.e. you can't run this code if you're not willing to have your real name in the log as the user. But of course hackers are always looking for ways to bypass such restrictions (sometimes to hack into their own systems, when they've been a little too clever, and now can't remember the stupid passphrase or whatever it was). Very often, companies resort to physical dongles, swipe cards, other hardware, to prevent unauthorized access. Anyway, the most primitive module or namespace is the current session, a kind of temporary scratch pad, where we cut and paste the "keepers" to a "final draft" version. Smalltalk has less of this sense of "saving out to permanent storage" and keeps the current scratch pad as the image (unless you don't save it). I wonder about that workflow, but realize you can internalize any file structure you like in an image: Smalltalk tends to seek the outer frame, and provide everything internally (the tablet itself was the "smalltalk machine" with "lid closed hibernation" -- since the 1960s at least). > But the Scheme course I taught also came with a lot of teachpacks > (read: modules to import) that did things like provide an interactive > session with your function (prompting, like raw_input but with more > error handling built in, or GUI). Without those, I might have been > tempted to teach those input functions after all. People have different motives for getting into programming, which need to be taken into account. Some want to impress their mom's with "look mom, no hands" GUI programs, others want to sit in a back office fine tuning statistical analysis programs that will never see the light of day, but which make the company tons of money and adds quality of life to its customers as well. I'm not saying any of these ways is "wrong". But I think we should acknowledge each language brings forward a sense of an interface. Python's is most naturally a shell. That's how it was designed. And that goes will with today's "unit testing" and "extreme programming" best practices. Work interactively at a work bench, debugging, reloading, while saving out "keeper quality" work to intelligently designed modules, properly populated with docstrings etc. Kirby
https://mail.python.org/pipermail/edu-sig/2006-September/007119.html
CC-MAIN-2017-04
refinedweb
683
71.55
>> Function overloading and return type in C++ C in Depth: The Complete C Programming Guide for Beginners 45 Lectures 4.5 hours Practical C++: Learn C++ Basics Step by Step 50 Lectures 4.5 hours Master C and Embedded C Programming- Learn as you go 66 Lectures 5.5 hours You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.. Same function signature with different return type will not be overloaded. Following is the example where same function print() is being used to print different data types Example Code #include <iostream> using namespace std; class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; int main(void) { printData pd; pd.print(5); // Call print to print integer pd.print(500.263); // Call print to print float pd.print("Hello C++"); // Call print to print character return 0; } Output Printing int: 5 Printing float: 500.263 Printing character: Hello C++ - Related Questions & Answers - method overloading and type promotion in Java - Function Overloading and Overriding in PHP - Function overloading and const keyword in C++ - Difference Between Function Overloading and Overriding in C++ - What is function overloading in JavaScript? - Why is method overloading not possible by changing the return type of the method only in java? - Covariant return type in Java - Return type of getchar(), fgetc() and getc() in C - C function argument and return values - Implicit return type int in C - Importance of return type in Java? - Increment ++ and Decrement -- Operator Overloading in C++ - Method Overloading and null error in Java - What are the best practices for function overloading in JavaScript? - What is covariant return type in Java?
https://www.tutorialspoint.com/function-overloading-and-return-type-in-cplusplus
CC-MAIN-2022-40
refinedweb
313
51.38
Dec 11, 2018 12:05 PM|rtaVix|LINK I am trying to use TryPar, but it did not solve my problem. Follow the code below: private void populatesLineValueIRF (StringBuilder str, List <ProcessInterest> ListProcInter) { // listProcInter.RemoveAll(o => o.ValueIR == 0 || o.ValueIR == null); List <ProcessInterest> aux = new List <ProcessInterest> (); decimal summation = 0; List <int> months = new List <int> (); if (ListProcInter.Count! = 0) { str.Append ("\ r \ nRTIRF |"); for (int i = 0; i <listProcInter.Count; i ++) { sDate = listProcInter [i].DataPayment.ToString (); datevalue = Convert.ToDateTime (sDate); months.Add (datevalue.Month); } if (! months.Contains (9)) str.Append ("|"); else { sum = 0; aux = listProcInter.FindAll (o => (Convert.ToDateTime (the.DataPath.ToString ())).Month == 9); if (Count> 1) { foreach (var j in aux) { sum = sum + decimal.Parse (j.ValorIR.ToString ()); } } else summation = decimal.Parse (aux [0] .ValorIR.ToString ()); //The error bursts in this line if (summation == 0) str.Append ("|"); else { if (sum.ToString (). Contains (',')) str.Append (sum.ToString (). Replace (",", "") + "|"); else str.Append (sum.ToString (). Replace (",", "") + "00" + "|"); } } I do not know what can be causing this. All-Star 46250 Points Dec 11, 2018 12:29 PM|PatriceSc|LINK Hi, When it happens you need to : - have a look at the string value you are trying to parse - ie here what is the value for aux[0].ValorIR.ToString() ? - check which System.Threading.Thread.CurrentThread.CurrentCulture is used. For example "12.3" could be invalid for a culture which doesn't use . as the "decimal point" symbol All-Star 46250 Points Dec 11, 2018 01:25 PM|PatriceSc|LINK I mean that as parsing aux[0].ValorIR.ToString() to a decimal fails, it make sense to just look at which string value is returned by this expression to better understand why it fails . A common error is to misuse ToString() returning then for example a type name. Also parsing a string to a decimal (or to a date etc...) always depends on which country convention (ie "culture") is used. For example "1,234" can be 1.234 for some countries or 1234 for others because in some countries, the "," character is the decimal point while for others it is the thousand separator. It could likely fails for some countries when "," is none of that. Technically speaking your code is correct. The problem is likely which value you are trying to parse and/or with which country convention. So what if you look at the value shown by aux[0].ValorIR.ToString() ? Edit: TryParse may or may not help depending on the value you are trying to parse and why it fails. It is used most often for user input. Contributor 3460 Points Dec 12, 2018 05:45 AM|Ackerly Xu|LINK Hi rtaVix, You could use TryParse as follows. decimal.TryParse(list[0].ValorIR.ToString(), out summation) will return false if it fails in parsing and it will return true and set the second parameter's value to the parsed decimal. Please don't forget to add out keyword to your second parameter. protected void Page_Load(object sender, EventArgs e) { List<MyModel> list = new List<MyModel>(); MyModel model = new MyModel() { ValorIR = 5.7 }; list.Add(model); Response.Write( myMethod(list)); } private decimal myMethod(List<MyModel> list) { decimal summation; if (decimal.TryParse(list[0].ValorIR.ToString(), out summation)) { return summation; } else { // fail in parsing // please write your own logic } } public class MyModel { public double ValorIR { get; set; } } To see the value of list[0].ValorIR.ToString(), you could set a breakpoint and in debug mode move your mouse to the variable list.(in your case is aux) and see what the value of its first element's property ValorIR. Best regards, Ackerly Xu 6 replies Last post Dec 18, 2018 11:53 AM by rtaVix
https://forums.asp.net/t/2150274.aspx?+System+FormatException+The+input+string+was+not+in+a+correct+format+
CC-MAIN-2020-10
refinedweb
613
59.7
Question: I've setup a std map to map some numbers, at this point I know what numbers I'm mapping from an to, eg: std::map<int, int> myMap; map[1] = 2; map[2] = 4; map[3] = 6; Later however, I want to map some numbers to the lowest number possilbe that is not in the map, eg: map[4] = getLowestFreeNumberToMapTo(map); // I'd like this to return 1 map[5] = getLowestFreeNumberToMapTo(map); // I'd like this to return 3 Any easy way of doing this? I considered building an ordered list of numbers as I added them to the map so I could just look for 1, not find it, use it, add it etc. Solution:1 Something like typedef std::set<int> SetType; SetType used; // The already used numbers int freeCounter = 1; // The first available free number void AddToMap(int i) { used.insert(i); // Actually add the value to map } void GetNewNumber() { SetType::iterator iter = used.lower_bound(freeCounter); while (iter != used.end() && *iter == freeCounter) { ++iter; ++freeCounter; } return freeCounter++; } If your map is quite big but sparse, this will work like o(log(N)), where N is the number of items in the map - in most cases you won't have to iterate through the set, or just make a few steps. Otherwise, if there are few gaps in the map, then you would better have a set of free items in the range [1..maxValueInTheMap]. Solution:2 Finding the lowest unused number is a very common operation in UNIX kernels, as every open/ socket/etc. syscall is supposed to bind to the lowest unused FD number. On Linux, the algorithm in fs/file.cÂ# alloc_fd is: - keep track of next_fd, a low water mark -- it is not necessarily 100% accurate - whenever a FD is freed, next_fd = min(fd, next_fd) - to allocate a FD, start searching the bitmap starting from next_fd-- lib/find_next_bit.cÂ# find_next_zero_bitis linear but still very fast, because it takes BITS_PER_LONGstrides at a time - after a FD is allocated, next_fd = fd + 1 FreeBSD's sys/kern/kern_descrip.cÂ# fdalloc follows the same idea: start with int fd_freefile; /* approx. next free file */, and search the bitmap upwards. However, these are all operating under the assumption that most processes have few FDs open, and very, very few have thousands. If the numbers will go much higher, with sparse holes, the common solution (as far as I've seen) is #include <algorithm> #include <functional> #include <vector> using namespace std; int high_water_mark = 0; vector<int> unused_numbers = vector<int>(); int get_new_number() { if (used_numbers.empty()) return high_water_mark++; pop_heap(unused_numbers.begin(), unused_numbers.end(), greater<int>()); return unused_numbers.pop_back(); } void recycle_number(int number) { unused_numbers.push_back(number); push_heap(unused_numbers.begin(), unused_numbers.end(), greater<int>()); } (untested code... idea is: keep a high water mark; try to steal from unused below the high water mark, or up the high water mark otherwise; return freed to unused) and if your assumption is that the used numbers will be sparse, then Dmitry's solution makes more sense. Solution:3 I'd use a bidirectional map class for this problem. That way you can simply check if value 1 exists etc. Edit The benefits of using a bimap is that there already exist robust implementations of it and even if searching for the next free number is O(n) it is only an issue if n is large (or possibly if n is moderate and this is called very frequently). Overall making for a simple implementation that is unlikely to be error prone and easily maintainable. If n is large or this operation is performed very frequently than investing the effort of implementing a more advanced solution is merited. IMHO. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/06/tutorial-find-lowest-unused-number.html
CC-MAIN-2018-34
refinedweb
631
58.52
In this tutorial you will learn how to write to InputStream in java. Write to file from InputStream in java you may use the InputStream class of java.io package. This class reads the streams of bytes. And to write these streams of bytes FileOutputStream can be used that writes data to a file. To give the example there a file will be required from where contents can be read and rewritten to the another file. So at first I have created a file and write some text into it. In the example given below I have created the InputStream object and passed the existing file name into its instance to read the contents, and created a new file using File into which the contents of an existing file will be rewritten to it. Then passed the object of this file in FileOutputStream instance to write the contents that are read from the existing file. Example : WriteToInputStream.java import java.io.*; class WriteToInputStream { public static void main(String args[]) { InputStream is = null; OutputStream os = null; int i= 0; try { File file = new File("writeToInputStream.txt"); is = new FileInputStream("..\\WriteFileFromString\\writeToFileFromString.txt"); os = new FileOutputStream(file); byte[] data = new byte[1024]; while((i=is.read(data))>0) { os.write(data); } is.close(); os.close(); } catch(Exception e) { System.out.println(e); } } } How to Execute this example : After doing the basic process to execute a java program write simply on command prompt as : javac WriteToFileFromInputStream.java to compile the program And after successfully compilation to run simply type as : java WriteToFileFromInputStream.java Output : When you will execute this example, contents of an existing file will be first read by FileInputStream and a new file will be created and then read contents will be rewritten to it using the FileOutputStream : 1. An existing file that contains some text. 2. A newly created file into which an existing file contents will be rewritten. InputStream Post your Comment
http://www.roseindia.net/java/examples/io/writeToInputStream.shtml
CC-MAIN-2015-18
refinedweb
323
55.64
0 Members and 1 Guest are viewing this topic. There is an even stranger division later on. The formula you presented is not the whole thing. obj=goodname=KohleMapColor=128metric=tonnencatg=2value=210speed_bonus=2weight_per_unit=1000 Revenue: 0.70% Bonus: = 2%Weight: 1000kg (Revenue) * x = (value)0.70 * x = 210x = 210 / 0.70x = 300 waren[i]->value = (uint16)((long_base_value*multiplier)/1000l); const sint32 kmh_base = (100 * speedkmh) / ref_kmh - 100; 0 : -100 -> -11 : 0 -> 02 : 100 -> 1 const sint32 grundwert_bonus = 1000+kmh_base*besch->get_speed_bonus(); // speed bonus factor 0 : -200 -> -21 : 0 -> 02 : 200 -> 2 0 : 800 -> 0.81 : 1000 -> 1.02 : 1200 -> 1.2 return besch->get_preis() * (grundwert128 > grundwert_bonus ? grundwert128 : grundwert_bonus); # lowest possible income with speedbonus (1000=1) default 125bonus_basefactor = 125 0 : 168000 -> 0.561 : 210000 -> 0.702 : 252000 -> 0.84 // calculate freight revenue incl. speed-bonus if (ware.get_besch() != last_freight) { freight_revenue = ware_t::calc_revenue(ware.get_besch(), get_besch()->get_waytype(), cnv_kmh); last_freight = ware.get_besch(); } const sint64 price = freight_revenue * (sint64)dist * (sint64)ware.menge; // sum up new price value += price; // Hajo: Rounded value, in cents return (value+1500ll)/3000ll; 0 : 56 -> 0.561 : 70 -> 0.702 : 84 -> 0.84 Code: [Select] const sint32 kmh_base = (100 * speedkmh) / ref_kmh - 100;The multiply by 100 here is clearly some scaling factor. Without it the integer division will produce nonsense results. Why 100 was chosen instead of some binary value (which should be faster) is unclear and probably down to not knowing about fixed point numbers in computers. [...]why cargo values are in 1/3 of a simucent I do not know. It's percent, plain and simple. If speedkmh is 101 and ref_kmh is 100, kmh_base is 1. Which means speed is 1% above the reference speed. Simutrans can't store it as 0.01, as it's doing integer math only at these depths. % Bonus: The percent change in cargo revenue per 10% of current speedbonus speed change to convoy average maximum speed. However it could have been a fixed point. Potentially more precision and retains its fractional value (from a human understanding point of view) so in theory should be more readable.
https://forum.simutrans.com/index.php?topic=15025.0
CC-MAIN-2020-40
refinedweb
345
70.9
SunPy | Plotting a Solar Image in Python SunPy is a package for solar data analysis using Python. We will be using this package for analysis of solar data Installation On the command line type: pip install sunpy Downloading Sample Data The SunPy package contains a number of data files which are solar data of proton/electron fluxes from various solar observatory and solar labs. They are stored under the module sunpy.data. To download the sample data simply run the following command: import sunpy.data sunpy.data.download_sample_data() In this small project, we will see a very simple way to plot a sample AIA image. AIA =. First we try to explore. Maps: Maps are the primary data type in SunPy they are spatially and / or temporally aware data arrays. There are types of maps for a 2D image, a time series of 2D images or 1D spectra or 2D spectrograms. Making a map of your data is the normally the first step in using SunPy to work with your data. Creating a Map SunPy supports many different data products from various sources ‘out of the box’ we shall use SDO’s AIA instrument as an example in this tutorial. The general way to create a map from one of the supported data products is with the sunpy.Map() command. sunpy.Map() takes either a filename, list of filenames data array and header. We can test map with: import sunpy aia = sunpy.Map(sunpy.AIA_171_IMAGE) This returns a map named aia. Plotting a sample solar data file Let’s begin by creating a simple plot of an AIA image. To make things easy, SunPy includes several example files. These files have names like sunpy.AIA_171_IMAGE and sunpy.RHESSI_IMAGE. Output If everything has been configured properly you should see an AIA image with a red colormap, a colorbar on the right-hand side and a title and some labels. Solar data plotting is a crucial aspect in order to detect future solar flares and solar storms. Also it is important to note the variation of the proton and electron flux at various intervals of time. This article is contributed by Prateek Ch
https://www.geeksforgeeks.org/sunpy-plotting-solar-image-python/?ref=rp
CC-MAIN-2021-31
refinedweb
360
55.54
Routing and Action Selection in ASP.NET Web API by Mike Wasson This article describes how ASP.NET Web API routes an HTTP request to a particular action on a controller. Note. - Selecting an action. You can replace some parts of the process with your own custom behaviors. In this article, I describe the default behavior. At the end, I note the places where you can customize the behavior. Route Templates A route template looks similar to a URI path, but it can have placeholder values, indicated with curly braces: "api/{controller}/public/{category}/{id}" When you create a route, you can provide default values for some or all of the placeholders: defaults: new { category = "all" } You can also provide constraints, which restrict how a URI segment can match a placeholder: constraints: new { id = @"\d+" } // Only matches if "id" is one or more digits. The framework tries to match the segments in the URI path to the template. Literals in the template must match exactly. A placeholder matches any value, unless you specify constraints. The framework does not match other parts of the URI, such as the host name or the query parameters. The framework selects the first route in the route table that matches the URI. There are two special placeholders: "{controller}" and "{action}". - "{controller}" provides the name of the controller. - "{action}" provides the name of the action. In Web API, the usual convention is to omit "{action}". Defaults If you provide defaults, the route will match a URI that is missing those segments. For example: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{category}", defaults: new { category = "all" } ); The URI "" matches this route. The "{category}" segment is assigned the default value "all". Route Dictionary If the framework finds a match for a URI, it creates a dictionary that contains the value for each placeholder. The keys are the placeholder names, not including the curly braces. The values are taken from the URI path or from the defaults. The dictionary is stored in the IHttpRouteData object. During this route-matching phase, the special "{controller}" and "{action}" placeholders are treated just like the other placeholders. They are simply stored in the dictionary with the other values. A default can have the special value RouteParameter.Optional. If a placeholder gets assigned this value, the value is not added to the route dictionary. For example: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{category}/{id}", defaults: new { category = "all", id = RouteParameter.Optional } ); For the URI path "api/products", the route dictionary will contain: - controller: "products" - category: "all" For "api/products/toys/123", however, the route dictionary will contain: - controller: "products" - category: "toys" - id: "123" The defaults can also include a value that does not appear anywhere in the route template. If the route matches, that value is stored in the dictionary. For example: routes.MapHttpRoute( name: "Root", routeTemplate: "api/root/{id}", defaults: new { controller = "customers", id = RouteParameter.Optional } ); If the URI path is "api/root/8", the dictionary will contain two values: - controller: "customers" - id: "8" Selecting a Controller Controller selection is handled by the IHttpControllerSelector.SelectController method. This method takes an HttpRequestMessage instance and returns an HttpControllerDescriptor. The default implementation is provided by the DefaultHttpControllerSelector class. This class uses a straightforward algorithm: - Look in the route dictionary for the key "controller". - Take the value for this key and append the string "Controller" to get the controller type name. - Look for a Web API controller with this type name. For example, if the route dictionary contains the key-value pair "controller" = "products", then the controller type is "ProductsController". If there is no matching type, or multiple matches, the framework returns an error to the client. For step 3, DefaultHttpControllerSelector uses the IHttpControllerTypeResolver interface to get the list of Web API controller types. The default implementation of IHttpControllerTypeResolver returns all public classes that (a) implement IHttpController, (b) are not abstract, and (c) have a name that ends in "Controller". Action Selection After selecting the controller, the framework selects the action by calling the IHttpActionSelector.SelectAction method. This method takes an HttpControllerContext and returns an HttpActionDescriptor. The default implementation is provided by the ApiControllerActionSelector class. To select an action, it looks at the following: - The HTTP method of the request. - The "{action}" placeholder in the route template, if present. - The parameters of the actions on the controller. Before looking at the selection algorithm, we need to understand some things about controller actions. Which methods on the controller are considered "actions"? When selecting an action, the framework only looks at public instance methods on the controller. Also, it excludes "special name" methods (constructors, events, operator overloads, and so forth), and methods inherited from the ApiController class. HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows: -. Note. Ignore actions with the [NonAction] attribute. Step #3 is probably the most confusing. The basic idea is that a parameter can get its value either from the URI, from the request body, or from a custom binding. For parameters that come from the URI, we want to ensure that the URI actually contains a value for that parameter, either in the path (via the route dictionary) or in the query string. For example, consider the following action: public void Get(int id) The id parameter binds to the URI. Therefore, this action can only match a URI that contains a value for "id", either in the route dictionary or in the query string. Optional parameters are an exception, because they are optional. For an optional parameter, it's OK if the binding can't get the value from the URI. Complex types are an exception for a different reason. A complex type can only bind to the URI through a custom binding. But in that case, the framework cannot know in advance whether the parameter would bind to a particular URI. To find out, it would need to invoke the binding. The goal of the selection algorithm is to select an action from the static description, before invoking any bindings. Therefore, complex types are excluded from the matching algorithm. After the action is selected, all parameter bindings are invoked. Summary: -.) - Try to match the most number of parameters. The best match might be a method with no parameters. Extended Example Routes: routes.MapHttpRoute( name: "ApiRoot", routeTemplate: "api/root/{id}", defaults: new { controller = "products", id = RouteParameter.Optional } ); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); Controller: public class ProductsController : ApiController { public IEnumerable<Product> GetAll() {} public Product GetById(int id, double version = 1.0) {} [HttpGet] public void FindProductsByName(string name) {} public void Post(Product value) {} public void Put(int id, Product value) {} } HTTP request: GET Route Matching The URI matches the route named "DefaultApi". The route dictionary contains the following entries: - controller: "products" - id: "1" The route dictionary does not contain the query string parameters, "version" and "details", but these will still be considered during action selection. Controller Selection From the "controller" entry in the route dictionary, the controller type is ProductsController. Action Selection The HTTP request is a GET request. The controller actions that support GET are GetAll, GetById, and FindProductsByName. The route dictionary does not contain an entry for "action", so we don't need to match the action name. Next, we try to match parameter names for the actions, looking only at the GET actions. Notice that the version parameter of GetById is not considered, because it is an optional parameter. The GetAll method matches trivially. The GetById method also matches, because the route dictionary contains "id". The FindProductsByName method does not match. The GetById method wins, because it matches one parameter, versus no parameters for GetAll. The method is invoked with the following parameter values: - id = 1 -));
https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
CC-MAIN-2018-47
refinedweb
1,292
57.47
1. Introduction QLearn: A Haskell library for iterative Q-learning. Reinforcement learning is a quickly growing field that’s centered around teaching agents how to operate optimally in environments with states, actions and rewards associated with state and action pairs. QLearn is a library that allows you to easily implement Q-learning-based agents in Haskell. You can get it through Cabal: cabal install qlearn You can include it in your code with: import Data.QLearn There are lots of good explanations of Q-learning so we won’t go into much detail about the technique here. Basically, we have an agent that’s moving around in an environment where the agent can end up in particular states and transition between these states using actions. Each state and action pair has a reward associated with it. The agent doesn’t know exactly how the state and action pairs turn into new states and also doesn’t know how much of a reward each state and action pair gives. It does, however, know which state it is in at a a given time. Given this information, the Q-learning algorithm tries to have the agent figure out the optimal strategy. There are two numerical parameters we can control: alpha and gamma. Both have values between 0 and 1. The former represents how much new observations should affect our current understanding of the environment in comparison to old observations in terms of learning (i.e. a learning rate) and the latter describes how much rewards in the future should be discounted. In addition to these, there’s also an epsilon function. If our agent were to just always follow the policy it has "learned" right from the start, it might get stuck on some really bad policy. So, we want to sometimes take a random action. Given the number of time steps remaining, the epsilon function returns the probability of taking this random action. 2. Example QLearn is incredibly easy to use. There’s only a little bit of setup needed to create an agent and an environment for the agent to operate in. For a simple agent moving about on a grid, we have the following code: import QLearn import System.Random main = do let alpha = 0.4 gamma = 1 totalTime = 1000 numStates = 16 -- we are operating in a 4x4 grid numActions = 4 -- up, down, left and right epsilon = (/timeRemaining -> 1.0/(fromIntegral $ totalTime - timeRemaining)) execute = executeGrid testGrid possible = possibleGrid testGrid qLearner = initQLearner alpha gamma epsilon numStates numActions environment = initEnvironment execute possible g <- newStdGen moveLearnerPrintRepeat totalTime g environment qLearner (State 0) Notice that we’re using the testGrid , which is a 4×4 multidimensional array of doubles with each point within the grid representing a state and the value of each point representing the reward associated with the state. All actions are deterministic within this grid. We’re able to get the state transition behavior using executeGrid and possibleGrid from QLearn. If you run the code snippet, you should see the value table for the agent update as it performs 1000 iterations on the grid. » QLearn – reinforcement learning in Haskell 评论 抢沙发
http://www.shellsec.com/news/15719.html
CC-MAIN-2016-50
refinedweb
521
53.31
PyObjC Type Conversion Introduction If you have ever worked with the PyObjC bridge on the macOS platform you might have noticed that data is often returned as a Objective-C class object (NSArray, NSDictionary, etc.) Thanks to the effort put into PyObjC, python can seamlessly use python type methods with their Objective-C class equivalents. But, what do you do when you are required to use a pure python object? Use case I ran into this issue when using the Boto3 python library for my s3Repo plugin for munki. The boto3.session.Session method does a type check on one of the input parameters to make sure you are passing a python dictionary object. If I attempted to pass a NSDictionary object I would crash the boto3 library. So I needed to convert it. If this object was a simple dictionary, I could have used a loop with a dict.update(my_ns_dictionary) but my object was a nested NSDictionary. After a bit of searching online I found the proper solution. However, it is a bit hidden inside the pyobjc code and my search results were less than helpful. Conversion process To see the conversion you will need a few NS objects: from Foundation import NSDictionary, NSArray d = NSDictionary.dictionaryWithDictionary_({"foo": "bar", "more": {"level1": 10, "level2": 20}}) type(d) print(d) a = NSArray.alloc().initWithObjects_(1,2,3,4) type(a) print(a) Now we have verified the type and content, lets convert: from PyObjCTools import Conversion new_d = Conversion.pythonCollectionFromPropertyList(d) type(new_d) print(new_d) new_a = Conversion.pythonCollectionFromPropertyList(a) type(new_a) print(new_a) Fin Such an easy to use solution and it is built-in to the PyObjC module. Credits - Thanks to Michael Lynn for corrections.
https://clburlison.com/pyobjc-type-conversion/
CC-MAIN-2017-34
refinedweb
285
56.05
"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > En Mon, 05 Jan 2009 02:03:26 -0200, Roy Smith <roy at panix.com> escribió: > > >> The other day, I came upon this gem. It's a bit of perl embedded in a >> Makefile; this makes it even more gnarly because all the $'s get >> doubled to >> hide them from make: >> >> define absmondir >> $(shell perl -e ' \ >> sub absmon { my $$a = $$_[0]; \ >> if ( $$^O =~ m/cygwin|MSWin32/i ) { >> $$prefix = `/bin/mount -p|awk "NR==2{print >> \\\$$1}"`; >> chomp($$prefix); \ >> $$a = ($$_[1]||"$(PWD)") . "/$$a" \ >> unless ( $$a =~ m !^(:?$$prefix|/|[A-Za-z]:)! ); \ >> } else { $$a = ($$_[1]||"$(PWD)") . "/$$a" unless ( $$a =~ m !^/! >> ); } \ >> return unslash(undot(undotdot($$a))); }; \ >> sub unslash ($$) { $$_[0] =~ s://+:/:g; $$_[0] =~ s:/$$::; >> return($$_[0]); >> }; \ >> sub undot ($$) { $$_[0]=~s:/\./:/:g; return ($$_[0]); }; \ >> sub undotdot ($$) { my $$in = $$_[0]; \ >> return ( $$in =~ s:/[^/.][^/]*/\.\.::g )?undotdot($$in):$$in; }; \ >> print absmon("$(1)","$(2)"); \ >> ' ) >> endef >> >> Barf-o-rama. I know what it's supposed to do, and I still can't >> figure it out. > > Ouch! Me too, when I come to some piece of Perl code I've written some > years ago, I invariably think "what's all this noise?". Never happens > with other languages I've used in the past. I still occassion upon the chance to write some Perl, and even as a full-time developer who works with Python for a living, I relish every opportunity. The funny thing is that I've never had the problem of writing code like this in Perl. The example is a very poor use-case and doesn't reflect on the useful/useless-ness of the language itself but more on the choices of the implementor. Perl is a very useful language overall and when used properly, very powerful.
https://mail.python.org/pipermail/python-list/2009-January/518645.html
CC-MAIN-2014-15
refinedweb
297
73.88
Create the app class Let's take a minute to summarize what we've done so far. We created the main app UI, which displays a list of quote authors. This main screen also includes an Add action that lets users create a new quote and add it to the list. We created the add page, which includes text fields for the new quote, first name, and last name, as well as a title bar. Finally, we created the quote page, which displays an individual quote and lets users edit or delete the quote. In each of these components, we handled important signals that provide the fundamental behavior of our app. For example, we handled signals that GroupDataModel emits when items are added to, removed from, or updated in the data model. We also handled custom signals that our custom QML components emit, such as update() and cancel() from our EditControls component. Now, we're ready to implement the C++ classes and functions that support our app's behavior. Specifically, we need a way to interact with the SQL database that contains our quote data. We handle this interaction in several C++ files to keep it separate from the visual aspects of the app (which we created in QML). It's usually a good idea to separate the business logic code (in our case, functions that interact with the database) from the UI-related code in your apps. This approach makes it easy to change one aspect (for example, using a different database type, or changing the appearance of list items) without affecting the other. Change the main.cpp file Let's start by changing some code in the main.cpp file in our project. The main.cpp file is created automatically when you create a new project, and it contains quite a bit of prepopulated code. This code is useful for getting a sample app running quickly, and also provides support for translation. To keep things simple, our Quotes app won't provide translation support, and we'll separate some of the existing code and place it in different source files. Open the main.cpp file, located in your project's src folder, and remove the prepopulated code in the main() function. Our main() function needs just four lines of code that do the following: - Create an instance of the main Application class. - Create an instance of the class that represents our app, QuotesApp. - Call the onStart() function, which is part of QuotesApp, to initialize our app. - Start the event loop by calling Application::exec(). Application app(argc, argv); QuotesApp mainApp; mainApp.onStart(); return Application::exec(); If you need any additional information about these lines and what they do, see Create your first app. You can also remove the prepopulated statements at the top of the file. Instead, add the following: #include "quotesapp.h" using ::bb::cascades::Application; Create the QuotesApp class The first class that we create is the QuotesApp class, which includes most of our app's functionality. In the src folder in your project, create a class called QuotesApp. Make sure that you create both an .h file and a .cpp file (if you click New > Class to create the class, both of these files are created for you). Don't worry about creating method stubs; we'll provide you with all of the code you need to put in each file. You can also remove any other .h or .cpp files that are present in the src folder (except main.cpp, of course). Open the QuotesApp.cpp file first. We need to include a few classes at the start of this file. We also need to include the corresponding QuotesApp.h header, as well as a header called QuotesDbHelper.h (which we'll talk about a bit later). We make sure to use the bb::cascades namespace so we don't have to use fully qualified names for the Cascades controls we use. #include "QuotesApp.h" #include "QuotesDbHelper.h" #include <bb/cascades/GroupDataModel> #include <bb/cascades/ListView> #include <bb/cascades/NavigationPane> #include <bb/cascades/QmlDocument> using namespace bb::cascades; Our class constructor is empty, and our class destructor contains only one line. In the destructor, we delete an object called mQuotesDbHelper. This object is an instance of the QuotesDbHelper class, which we'll create later in the tutorial. This helper class takes care of all of the SQL database operations that our app needs, such as inserting and removing entries. When our app needs to manipulate data in the database, we simply call the corresponding functions of our QuotesDbHelper object. When we're done with this object, we need to free the memory that we allocated for it. QuotesApp::QuotesApp() { } QuotesApp::~QuotesApp() { delete mQuotesDbHelper; } Implement the setup functions Next, we implement the onStart() function. Remember that we called this function in main.cpp to perform some initial setup operations for our app. The onStart() function creates the instance of the QuotesDbHelper class, mQuotesDbHelper, that we discussed above. It also calls loadQMLScene() to load our main.qml file and set up our data model. void QuotesApp::onStart() { // Instantiate the database helper object mQuotesDbHelper = new QuotesDbHelper(); if (!loadQMLScene()) { qWarning("Failed to load QML scene."); } } Let's implement the loadQMLScene() function, which contains most of the initialization operations. We create a QML document from our main.qml file, then test to see whether the creation was successful. If so, we set the context property for the document to _quoteApp. By setting the context property, we can call functions from this class in QML (specifically, functions that we mark as Q_INVOKABLE). If you recall, we called some of these C++ functions from our QML code, such as addNewRecord() in AddPage.qml. bool QuotesApp::loadQMLScene() { QmlDocument *qmlDocument = QmlDocument::create("asset:///main.qml"); if (!qmlDocument->hasErrors()) { qmlDocument->setContextProperty("_quoteApp", this); We create a NavigationPane object from the root NavigationPane control in our QML document, and we test to see whether it was created successfully. If so, we call the loadDataBase() function of our helper object mQuotesDbHelper. This function takes two arguments: the name of the database file (which is located in the assets/sql folder in our project) and the name of the SQL table inside the database file. NavigationPane* navigationPane = qmlDocument-> createRootObject<NavigationPane>(); if (navigationPane) { QVariantList sqlData = mQuotesDbHelper->loadDataBase("quotes.db", "quotes"); If the database loaded successfully, we locate the GroupDataModel in our QML document and insert the data into the GroupDataModel. We also locate the ListView that represents our list of quote authors; we'll need to refer to this ListView later when we implement the deleteRecord() function. if (!sqlData.isEmpty()) { mDataModel = navigationPane->findChild<GroupDataModel*>("quotesModel"); mDataModel->insertList(sqlData); mListView = navigationPane->findChild<ListView*>("quotesList"); } To finish the loadQMLScene() function, we set the main scene of the application and return true to indicate that loading was successful. If any of our tests above failed, we return false. Application::instance()->setScene(navigationPane); return true; } } return false; } Implement the add and update functions In our QML code, we called a function called addNewRecord() when we wanted to add a new quote to the database, so let's implement that function now. We add all of the function parameters (first name, last name, and quote) to a QVariantMap, which makes it easy to insert the data into our database and data model. We call the insert() function of our helper object mQuotesDbHelper, and if the insertion is successful, we receive a unique primary key for the entry as a return value. We'll use this key later when we want to edit or delete the entry, so we store the key in our QVariantMap and insert the map into our data model. void QuotesApp::addNewRecord(const QString &firstName, const QString &lastName, const QString "e) { QVariantMap map; map["firstname"] = QString(firstName); map["lastname"] = QString(lastName); map["quote"] = QString(quote); QVariant insertId = mQuotesDbHelper->insert(map); if (!insertId.isNull()) { map["id"] = insertId; mDataModel->insert(map); } } We need a function that updates a particular quote with new information, so we create the updateSelectedRecord() function for this purpose. To determine which quote item we need to update, we call the selected() function of our ListView, which returns the index path of the selected item. If the index path is valid, we retrieve the data that's located at that index path in the data model and convert the data to a QVariantMap. We use the function parameters to update this map, and then we call update() and updateItem() to save the changes to the database and data model, respectively. void QuotesApp::updateSelectedRecord(const QString &firstName, const QString &lastName, const QString "e) { QVariantList indexPath = mListView->selected(); if (!indexPath.isEmpty()) { QVariantMap itemMapAtIndex = mDataModel->data(indexPath).toMap(); itemMapAtIndex["firstname"] = QString(firstName); itemMapAtIndex["lastname"] = QString(lastName); itemMapAtIndex["quote"] = QString(quote); mQuotesDbHelper->update(itemMapAtIndex); mDataModel->updateItem(indexPath, itemMapAtIndex); } } Implement the delete function Finally, we implement the deleteRecord() function, which removes a quote from the database and data model. Similar to updateSelectedRecord(), we start by retrieving the index path of the selected quote item. Then, we retrieve the data at that location as a QVariantMap and call deleteById() to delete the quote from the database. void QuotesApp::deleteRecord() { QVariantList indexPath = mListView->selected(); if (!indexPath.isEmpty()) { QVariantMap map = mDataModel->data(indexPath).toMap(); if (mQuotesDbHelper->deleteById(map["id"])) { After a quote is deleted, we want another quote to be displayed automatically. When we created our QML code, it was mentioned that determining the new quote item to select was a tricky task. There are several steps to determine the correct item to select. First, we store the number of items that are located in the category from which the item was removed. For our purposes, a category refers to a set of quote authors whose last names start with the same letter. In our ListView, these authors all appear under a heading with that letter. For example, in the initial data model for our app, the "L" category contains three entries: "Steven Levy", "Staffan Lincoln", and "Ada Lovelace". After we store this number, we remove the selected item from the data model. QVariantList categoryIndexPath; categoryIndexPath.append(indexPath.first()); int childrenInCategory = mDataModel->childCount(categoryIndexPath); mDataModel->remove(map); Next, we select another item relative to the one that was removed. After we remove the item, if the item's category still contains items (that is, the number of items that we stored above is greater than 1), we select an item within that same category. Either we select the next item in the category (relative to the removed item) or, if the last item in the category was the item that was removed, we select the previous item. if (childrenInCategory > 1) { int itemInCategory = indexPath.last().toInt(); if (itemInCategory < childrenInCategory - 1) { mListView->select(indexPath); } else { indexPath.replace(1, QVariant(itemInCategory - 1)); mListView->select(indexPath); } If the item's category doesn't contain any more items (that is, the removed item was the only item in its category), we move to the next category and select an item from there. If there are no more categories below the one with the removed item, we move to the previous category instead. If there are no items left at all (the removed item was the last item in the entire list), we navigate back to the (empty) list of quote authors. } else { QVariantList lastIndexPath = mDataModel->last(); if (!lastIndexPath.isEmpty()) { if (indexPath.first().toInt() <= lastIndexPath.first() .toInt()) { mListView->select(indexPath); } else { mListView->select(mDataModel->last()); } } } } //end of inner if statement } // end of outer if statement } // end of deleteRecord() Complete the QuotesApp header file We've completed the implementation of our QuotesApp class. We need to complete the associated header file. Open the QuotesApp.h file in the src folder of your project. The contents of this file are straightforward. We include several supporting classes, use forward declarations for other classes that we need, and then declare each function that we defined in our QuotesApp.cpp file above. We use the Q_INVOKABLE macro for the functions that we call from QML. #ifndef QUOTESAPP_H #define QUOTESAPP_H #include <bb/cascades/Application> #include <bb/cascades/DataModel> #include <bb/data/SqlDataAccess> #include <QObject> using namespace bb::cascades; using namespace bb::data; namespace bb { namespace cascades { class GroupDataModel; class ListView; class NavigationPane; } } class QuotesDbHelper; class QuotesApp: public QObject { Q_OBJECT public: QuotesApp(); ~QuotesApp(); void onStart(); Q_INVOKABLE void addNewRecord(const QString &firstName, const QString &lastName, const QString "e); Q_INVOKABLE void updateSelectedRecord(const QString &firstName, const QString &lastName, const QString "e); Q_INVOKABLE void deleteRecord(); private: bool loadQMLScene(); QuotesDbHelper *mQuotesDbHelper; GroupDataModel *mDataModel; ListView *mListView; }; #endif Our Quotes app is almost complete. In the final section of this tutorial, we'll create the helper class QuotesDbHelper that we use to interact with the SQL database. Last modified: 2015-03-31 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/documentation/ui/lists/lists_create_app_class.html
CC-MAIN-2018-13
refinedweb
2,132
55.24
Hello all, I'm a student who just began a course in Java programming and I'm trying to create a program which generates a random number between 0-99 and then asks the user to guess the number. If the guess was close to the correct answer, the program informs the user. I have tried to get the code to compile and run for several hours now (using NetBeans), and I keep getting various error messages like the one in the title of this thread. Here is the code: /*This is a number guessing game*/ package labfirst; import java.util.Random; import java.util.Scanner; public class Guess { public static void main(String[] args) { //Here the program should create a random number generator Random random = new Random(); //The program asks the user to input a number and generates a random number Scanner scanner = new Scanner(System.in); System.out.print("Guess a number between 0-99: "); int ranInt = random.nextInt(100); int userInt = -1; } while (userInt!=ranInt) { System.out.print("Incorrect! Guess again: "); userInt = scanner.nextInt(); } /*The program compares the user's input with the randomly generated number and comments on whether the number is correct, incorrect or close*/ if (userInt==ranInt - 5) { System.out.print("The number I was thinking of was " + ranInt + " , you were close."); } else if (userInt==ranInt + 5) { System.out.print("The number I was thinking of was ") + ranInt + (" , you were close."); } else if (userInt==ranInt) { System.out.print("Congratulations, the number was ") + ranInt + (" , you win!"); System.exit(0); } } Please forgive my ignorance, I'm really new at this. I've edited and re-edited the code so many times (searching online for help) that I'm sure there are more errors now than there were to begin with . This is the exact error message:. This is the exact error message: Exception in thread "main" java.lang.ClassFormatError: Duplicate field name&signature in class file labfirst/Guess at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java :792) at java.security.SecureClassLoader.defineClass(Secure Class.j ava:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:4 24) at sun.misc.Launcher$AppClassLoader.loadClass(Launche r.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:3 57) at sun.launcher.LauncherHelper.checkAndLoadMain(Launc herHelper.java:482) Java Result: 1
http://www.javaprogrammingforums.com/whats-wrong-my-code/30970-newbie-coder-needs-help-number-guessing-game-exception-thread-main-java-lang-classformaterror-duplicate-field-name-signature-class-file.html
CC-MAIN-2015-18
refinedweb
387
51.65
Mort Learns How To Use Monitoring in a WebApp By ByronNevins on Dec 02, 2009 This blog is a follow-up of my earlier monitoring blog, and I recommend reading that one first. This time we will setup probes inside of a user application. We will not be in the internal GlassFish environment. We need to use the Monitoring tools available from GlassFish OSGi. But -- we will be in a plain vanilla web module, not an OSGi module. Oh no! How can we access the Habitat inside GlassFish? JavaEE 6 comes to the rescue with the @Resource annotation! @Resource private ProbeProviderFactory probeProviderFactory; @Resource private ProbeClientMediator listenerRegistrar; These 2 variables are what we need to register a probe and hook up the probe with a listener. The web app consists of the usual boilerplate song and dance needed for any web app. The business end of this web app is in two classes: - The Servlet class -- ProbeServlet.java - The Probe Listener class -- MyProbeListener.java The servlet class has this method: @Probe(name="myProbe") public void myProbeMethod(String s) { System.out.println("inside myProbeMethod " + "called with this arg: " + s); } and it has this annotation at the class level: @ProbeProvider( moduleProviderName="fooblog", moduleName="samples", probeProviderName="ProbeServlet") That's all you need to do to turn this servlet class into an official GlassFish V3 Probe! To get the Probe registered with GlassFish you need to add one line of code that needs to run before you use the probe (I added it to the init method): probeProviderFactory.getProbeProvider(getClass()); I made the servlet painfully simple. Whenever you load or reload the servlet it calls myProbeMethod(). Of course all of this would be pointless without a listener class that is hooked-up to the probe. The init code in the servlet hooks up the listener with this one line of code: listenerRegistrar.registerListener( new MyProbeListener()); But wait! How in the world is that listener class going to be connected to the probe class?!? This is where the magic of annotation processing comes in. The listener class is super-simple. Here it is in it's entirety: public class MyProbeListener { @ProbeListener("fooblog:samples:ProbeServlet:myProbe") public void probe1(String s) { System.out.println("PROBE LISTENER HERE!!!!"); } } Note how the strings in the ProbeProvider annotation are used in the listener to identify the correct probe. This is a very simple example but you can see how you can create listeners in their own separate apps and have probes in many apps. To see the output simply tail the server log. When you write to System.out from a Listener - it will appear in the server log. The app is available in open source as a maven web-app. It can be checked out using this URL:: If you make changes to the Listener class you should restart the server after redeploying. Sample output from loading the app in a browser: ....|PROBE LISTENER HERE. Called with this arg: Hello #1|#] ....|inside myProbeMethod called with this arg: Hello #1|#]
https://blogs.oracle.com/foo/tags/javaee
CC-MAIN-2014-15
refinedweb
500
66.23
CPSC 124, Winter 1998 Sample Answers to Lab 7 This page contains sample answers to some of the exercises from Lab #7 in CPSC 124: Introductory Programming, Winter 1998. See the information page for that course for more information. Exercise 1: Here is a completed "histogram" program, with the added code shown in blue./* This file defines a "histogram" program. The user is asked to enter some numbers. The numbers are stored in an array. Then the data in the array are displayed in the form of a histogram. (For each number in the array, the histogram shows a line of stars. The number of stars in the i-th line is equal to the number in the i-th spot in the array.) NOTE: Your assignemnt is to complete the missing parts of of the program. You can use the stars() subroutine, given below, to output each line of stars. */ public class Histogram { static Console console = new Console(); // console for input/output public static void main(String[] args) { int numberOfLines; // The number of lines in the histogram. // This is also, therefore, the size of the array. int[] data; // The array of data, containing numbers entered by the user. console.putln("This program will display a histogram based on data"); console.putln("you enter. You will be asked to enter the numbers"); console.putln("that specify how many *'s there are in each row of"); console.putln("the histogram. The numbers must be between 0 and 50."); console.putln(""); // Find out how many numbers the user wants to enter. // This number is restricted to be in the range 1 to 25. do { console.put("How many numbers do you want to enter? "); numberOfLines = console.getlnInt(); if (numberOfLines < 1 || numberOfLines > 25) console.putln("Please specify a number between 1 and 25."); } while (numberOfLines < 1 || numberOfLines > 25); // Create an array to hold the user's numbers. The size of the // array is given by the number of numbers the user wants to enter. data = new int[numberOfLines]; // Use a for loop to read the user's numbers, one at a time, and // store them in the array: console.putln(); console.putln("Please enter your data:"); console.putln(); for (int i = 0; i < numberOfLines; i++) { // get next number from user do { console.put("Item #" + i + "? "); data[i] = console.getlnInt(); if (data[i] < 0 || data[i] > 50) console.putln("Please specify a number between 0 and 50."); } while (data[i] < 0 || data[i] > 50); } // Output the histogram, using a for loop. Call the "stars()" method // once for each number in the array: console.putln(); console.putln("Here's a histogram of your data:"); console.putln(); console.putln(" 10 20 30 40 50"); console.putln("|---------|---------|---------|---------|---------|-----"); for (int i = 0; i < numberOfLines; i++) { console.put("|"); stars(data[i]); } console.putln("|---------|---------|---------|---------|---------|-----"); console.close(); } // end main(); static void stars(int starCount) { // Outputs a line of *'s, where starCount gives the // number of *'s on the line. There is a carriage // return at the end of the line. for (int i = 0; i < starCount; i++) { console.put('*'); } console.putln(); } } // end of class Histogram Exercise 2: Here is the version of BBCanvas that I wrote for the enhanced version of the bouncing balls applet. Note the use of an array to store the color of each ball. The mouseDown() and mouseDrag() methods were added to tell the balls how to respond when the user clicks, or clicks-and-drags, the mouse.import java.awt.*; class BBCanvasEnhanced extends Canvas implements Runnable { int threadDelay = 40; // Time, in milliseconds, inserted between frames. Image OSC = null; // An "off-screen canvas", used for double buffering. Graphics OSG; // A graphics object that can be used for drawing to OSC. int width, height; // The width and height of the canvas. boolean running = true; // This state variable is "true" when the ball // should be moving, and "false" when it is // standing still. double[] x; // The left edge of the ball. double[] y; // The right edge of the ball. double[] dx; // The amount by which x changes from one frame to the next. double[] dy; // The amount by which y changed from one frame to the next. Color[] ballColor; // The color used for the ball. int ballSize = 10; // The diameter of the ball. int ballCount = 30; BBCanvasEnhanced() { // Constructor merely sets the background color // (Note: The Canvas's width and height are not // established when the constructor is called, // so the "off-screen canvas" can't be created here. setBackground(Color.black); } synchronized void initialize() { // initialize() is called from the run() method, defined below, // AFTER the off-screen canvas has been created ans the values // of width and height have already been determined x = new double[ballCount]; // create arrays y = new double[ballCount]; dx = new double[ballCount]; dy = new double[ballCount]; ballColor = new Color[ballCount]; for (int i=0; i < ballCount; i++ ) { x[i] = width / 2; // Put the ball at the middle of the canvas. y[i] = height / 2; do { // Choose random velocity, not too small. dx[i] = 20*Math.random() - 10; dy[i] = 20*Math.random() - 10; } while (Math.abs(dx[i]) < 2 && Math.abs(dy[i]) < 2); if (i % 3 == 0) // Assign one of three colors to each ball ballColor[i] = Color.red; else if (i % 3 == 1) ballColor[i] = Color.blue; else ballColor[i] = Color.green; } } synchronized void doTimeStep() { // doTimeStep() is called over and over by the run() method // It updates variables, redraws the offscreen canvas, and // calls repaint() to make the changes visible on the screen. if (running == false) // If the "running" state variable is false, return; // then don't do anything. OSG.setColor(Color.black); // fill off-screen canvas with black OSG.fillRect(0,0,width,height); for (int i = 0; i < ballCount; i++) { // First, move the ball by adding dx to x and adding dy to y: x[i] += dx[i]; y[i] += dy[i]; // Next check whether the ball has hit one of the edges: if (x[i] <= 0) // Ball has hit left edge. dx[i] = Math.abs(dx[i]); // Make sure ball is moving right (with dx > 0) else if (x[i] + ballSize >= width) // Ball has hit right edge. dx[i] = -Math.abs(dx[i]); // Make sure ball is moving left. if (y[i] <= 0) // Ball has hit top edge. dy[i] = Math.abs(dy[i]); // Make sure ball is moving down (dy > 0). else if (y[i] + ballSize >= height) // Ball has hit bottom edge. dy[i] = -Math.abs(dy[i]); // Make sure ball is moving up. OSG.setColor(ballColor[i]); // draw the ball (in its current location) OSG.fillOval((int)x[i], (int)y[i], ballSize, ballSize); } repaint(); // Call repaint() to tell system to redraw screen } // end doTimeStep() // -- Methods called from the applet in response to user actions, -- // -- such as clicking on a button or checkbox. -- synchronized void faster() { // This method makes the ball go faster by multiplying its // speed by 1.25. (This is called from the applet.) for (int i=0; i < ballCount; i++) { dx[i] = 1.25 * dx[i]; dy[i] = 1.25 * dy[i]; } } synchronized void slower() { // This method makes the ball go slower by multiplying its // speed by 0.8. (This is called from the applet.) for (int i=0; i < ballCount; i++) { dx[i] = 0.8 * dx[i]; dy[i] = 0.8 * dy[i]; } } synchronized void setRunning(boolean newRunning) { // Set the state variable "running" to the specified new value. // The ball stops moving when running is false. // This method is called from the applet. running = newRunning; } synchronized public boolean mouseDown(Event evt, int a, int b) { // Called when the user presses the mouse button at // the point (a,b). Here, I adjust the velocities of // all the balls so that they head towards (a,b). // The speed of the ball does not change; it just // changes direction. for (int i = 0; i < ballCount; i++ ) { double v = Math.sqrt(dx[i]*dx[i] + dy[i]*dy[i]); // speed of ball if (v > 0 && (x[i] != a || y[i] != b) ) { dx[i] = (a - x[i]); // set velocity to point to (a,b) dy[i] = (b - y[i]); double d = Math.sqrt(dx[i]*dx[i] + dy[i]*dy[i]); // length of (dx,dy) dx[i] = (dx[i]/d)*v; // adjust speed to be v, the same as it was before dy[i] = (dy[i]/d)*v; } } return true; } public boolean mouseDrag(Event evt, int a, int b) { // Called when mouse is moved to a new position, while // the user is holding down the mouse button. Here, I // just want to do the same thing as in mouseDown, so I // call that method. mouseDown(evt,a,b); return true; } //------------------------ painting ------------------------------ // // This should not have to be changed. synchronized public void paint(Graphics g) { // Copies OSC to the screen. if (OSC != null) g.drawImage(OSC,0,0,this); else { g.setColor(getBackground()); g.fillRect(0,0,size().width,size().height); } } public void update(Graphics g) { // Simplified update method. paint(g); // (Default method erases the screen } // before calling paint().) //-------------------- thread stuff and run method ----------------- // // It shoud not be necessary to change this. private Thread runner; void startCanvas() { // This is called when the applet starts. if (OSC == null) { // Off-screen canvas must be created before starting the thread. width = size().width; height = size().height; OSC = createImage(width,height); OSG = OSC.getGraphics(); OSG.setColor(getBackground()); OSG.fillRect(0,0,width,height); } if (runner == null || !runner.isAlive()) { // create and start a thread runner = new Thread(this); runner.start(); } } void stopCanvas() { // This is called when the applet is stopped if (runner != null && runner.isAlive()) runner.stop(); } void destroyCanvas() { // This is called when the applet is destroyed. if (runner != null && runner.isAlive()) runner.stop(); runner = null; } public void run() { // The run method to be executed by the runner thread. initialize(); while (true) { try { Thread.sleep(threadDelay); } catch (InterruptedException e) { } doTimeStep(); } } // end run() } Exercise 3: Arrays make it possible to deal with many items, without declaring a variable for each individual item. Since an array can be processed with a for loop, a few lines of code can easily be written to apply the same operation to each item. For example, where it took two lines of code to increase the speed of a ball in the original BouncingBalls applet:dx = 0.8*dx; dy = 0.8*dy; it takes only one more line of code to handle all the balls in the version that uses arrays:for (int i = 0; i < ballCount; i++) { dx = 0.8*dx; dy = 0.8*dy; } Arrays are useful in cases where many items are input and must be remembered individually for processing later in the program. If you want to input a bunch of numbers from the user and add them up or find the maximum, you don't need arrays, since the numbers can be processed one-by-one as they are read. However, in the histogram example from this lab, the numbers input by the user are read into an array and saved. There is no other easy way to write this program. David Eck, 3 March 1998
http://math.hws.edu/eck/cs124/labs98/lab7/answers.html
crawl-001
refinedweb
1,831
74.9
Tree views Use a tree view to display objects, such as folders, in a hierarchical manner. Objects in the tree view are nodes. The highest node is the root node. A node in the tree can have child nodes under it. A node that has a child is a parent node. Users can perform the following action in a tree view: Best practice: Implementing tree views - Use the TreeField class to create tree views. - Provide a pop-up menu if users can perform multiple actions when they click a parent node. - Include a root node only if users need the ability to perform actions on the entire tree. Otherwise, exclude the root node. Create a field to display a tree view Use a tree view to display objects, such as a folder structure, in a hierarchical manner. A TreeField contains nodes. The highest node is the root node. A node in the tree can have child nodes under it. A node that has a child is a parent node. - Import the required classes and interfaces. import net.rim.device.api.ui.component.TreeField; import net.rim.device.api.ui.component.TreeFieldCallback; import net.rim.device.api.ui.container.MainScreen; import java.lang.String; - Implement the TreeFieldCallback interface. - Invoke TreeField.setExpanded() on the TreeField object to specify whether a folder is collapsible. Create a TreeField object and multiple child nodes to the TreeField object. Invoke TreeField.setExpanded() using node4 as a parameter to collapse the folder. String fieldOne = new String("Main folder"); ... TreeCallback myCallback = new TreeCallback(); TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE); int node1 = myTree.addChildNode(0, fieldOne); int node2 = myTree.addChildNode(0, fieldTwo); int node3 = myTree.addChildNode(node2, fieldThree); int node4 = myTree.addChildNode(node3, fieldFour); ... int node10 = myTree.addChildNode(node1, fieldTen); myTree.setExpanded(node4, false); ... mainScreen.add(myTree); - To repaint a TreeField when a node changes, create a class that implements the TreeFieldCallback interface and implement the TreeFieldCallback.drawTreeItem method. The TreeFieldCallback.drawTreeItem method uses the cookie for a tree node to draw a String in the location of a node. The TreeFieldCallback.drawTreeItem method invokes Graphics.drawText() to draw the String. private class TreeCallback implements TreeFieldCallback { public void drawTreeItem( TreeField _tree, Graphics g, int node, int y, int width, int indent) { String text = (String)_tree.getCookie(node); g.drawText(text, indent, y); } }
https://developer.blackberry.com/bbos/java/documentation/tree_views_1970223_11.html
CC-MAIN-2016-40
refinedweb
384
62.04
This document is meant to provide some simple, straightforward steps to illustrate how to create a JSR 181 web service that you can then mediate in the ESB. - In the JBT/JBDS tooling, open the JBoss AS Perspective. In the Package Explorer view, right-click and select New->Dynamic Web Project or use the File menu and select File->New->Dynamic Web Project. - Type "MyWebServiceProject" as the Project name. - If the Target Runtime is set correctly, just click Finish. Otherwise, specify an appropriate Target Runtime. The "Open Associated Perspective?" dialog will appear if you are in the JBoss AS perspective. You can switch to the Java EE perspective if you want, but for now we'll stay in the Java AS perspective for these steps, so click "No." - Now we want to create our web service java class in our project. In the "src" folder of your new project, right-click and select New->Class. Give the class an appropriate package, such as "org.jboss.lab" and the name "MyWebService". Then click Finish. - The code for the class is pretty simple: package org.jboss.lab; import javax.jws.WebMethod; import javax.jws.WebService; @WebService() public class MyWebService() { @WebMethod() public String sayHello ( String name ) { return "Hello " + name + "!"; } } - Save your class and go to the "WebContent/WEB-INF" folder in your project. Double-click on web.xml. In the navigator on the left of the Web XML Editor, find and select Servlets. Click "Add..." in the Servlets section and in the dialog that appears, give it the name "MyWebServiceServlet" and give it the fully-qualified class name for our web service class - org.jboss.lab.MyWebService. Click Finish. Now click "Add..." in the Servlet Mappings section. In that dialog, give it the name "MyWebServiceServlet" and the URL-pattern "/MyWebService". - Make sure everything is saved (go to the File menu and select Save All if it's enabled) and now we'll deploy our web service to the server. In the Servers view or JBoss Server View (deprecated in JBT 3.1/JBDS 3), right-click on your runtime server and select "Add and Remove Projects..." - In the dialog that appears, select your web service project and click "Add>" to move it to the "Configured Projects" list. Then click Finish. - If everything goes well, we should see in the console that our web service was deployed and a WSDL was created in the file system. To verify that it deployed properly, open your web browser and direct it to URL -. (You may need to log in.) Once it comes up, you can see all the web services deployed on the server. Look for your web service "MyWebService" in the list. - Now you can use a separate tool such as soapUI to try invoking your web service or the Web Services Explorer from WTP. - To use the Web Services Explorer... Make sure you are in the J2EE perspective, in the menubar, select "Run -> Launch the Web Services Explorer" The Web Services Explorer opens. There is a small toolbar in the upper right corner of the window. Click the "WSDL Page" button. - When the WSDL Page opens, you will see a tree on the left with "WSDL Main" at the root. When you select the "WSDL Main" item in the tree, you will see a panel with "Open WSDL" to the right. Here you can provide a WSDL URL or WSDL file location. When you are finished, click on the 'Go' button. Now on the left, you will get a web service tree under the "WSDL Main" root. When you drill in and select your web service operation, you will see "Invoke a WSDL Operation." In the Body section, you'll see a list of arguments where you can provide values. Click Add to provide a value, input the value, and click the "Go" button when you are complete. (If your web service operation needs to input many arguments, you can click the 'Source' menu on the right-top of the right. Then you can give a soap message to the web service.) In the "Status" pane, you will see the reply message from the web service.
https://developer.jboss.org/wiki/CreatingAJSR181WebServiceUsingJBTJBDSTooling
CC-MAIN-2017-43
refinedweb
692
75.3
How to get data on how fast the wake word detection on Amazon Alexa/Google Home is? I am building a wake word(ww) detector using Tensorflow's Simple audio recognition tutorial. The model generated takes approximately 5 seconds to detect if the input audio file is a wake word or not. It has to be sped up. I want to know if there is any way to obtain metrics/data on how long Alexa/Google Home take to detect their ww. There doesn't seem to be any documentation as such out there. Does anyone have this measure already so that I know how much more faster my own detector can perform? See also questions close to this topic - How to have predictions AND labels returned with tf.estimator (either with predict or eval method)? I am working with Tensorflow 1.4. I created a custom tf.estimator in order to do classification, like this: def model_fn(): # Some operations here [...] return tf.estimator.EstimatorSpec(mode=mode, predictions={"Preds": predictions}, loss=cost, train_op=loss, eval_metric_ops=eval_metric_ops, training_hooks=[summary_hook]) my_estimator = tf.estimator.Estimator(model_fn=model_fn, params=model_params, model_dir='/my/directory') I can train it easily: input_fn = create_train_input_fn(path=train_files) my_estimator.train(input_fn=input_fn) where input_fn is a function that reads data from tfrecords files, with the tf.data.Dataset API. As I am reading from tfrecords files, I don't have labels in memory when I am making predictions. My question is, how can I have predictions AND labels returned, either by the predict() method or the evaluate() method? It seems there is no way to have both. predict() does not have access (?) to labels, and it is not possible to access the predictions dictionary with the evaluate() method. - Immense error in regression exercise Hej, I am currently trying to understand how to solve regression problems with the help of tensorflow. Unfortunately, as soon as I try to introduce a second dimension for my input-data, the error or loss gets insanely large. The dataset I am using is selfmade and quite simple. The values are all sorted and X2 is just every value from x1 + 1 X1 = [2.167,3.1,3.3,4.168,4.4,5.313,5.5,5.654,6.182,6.71,6.93,7.042,7.59,7.997,9.27,9.779,10.791] X2 = [3.167,4.1,4.3,5.168,5.4,6.313,6.5,6.654,7.182,7.71,7.93,8.042,8.59,8.997,10.27,10.779,11.791] y = [1.221,1.3,1.573,1.65,1.694,1.7,2.09,2.42,2.53,2.596,2.76,2.827,2.904,2.94,3.19,3.366,3.465] I tried to approximate the values using linear regression: numbers = pd.DataFrame({'x1': X1, 'x2':X2}) X_train, X_test, y_train, y_test = train_test_split(numbers,y,test_size=0.3,random_state=101) X_data = tf.placeholder(shape=[None,2], dtype=tf.float32) y_target = tf.placeholder(shape=[None], dtype=tf.float32) w1 = tf.Variable(tf.random_normal(shape=[2,1])) b1 = tf.Variable(tf.random_normal(shape=[1])) final_output = tf.add(tf.matmul(X_data, w1), b1) loss = tf.reduce_sum(tf.square(final_output-y_target)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) train = optimizer.minimize(loss) init = tf.global_variables_initializer() steps = 5000 with tf.Session() as sess: sess.run(init) for i in range(steps): sess.run(train,feed_dict={X_data:X_train,y_target:y_train}) # PRINT OUT A MESSAGE EVERY 100 STEPS if i%500 == 0: print('Currently on step {}'.format(i)) training_cost = sess.run(loss, feed_dict={X_data:X_test,y_target:y_test}) print("Training cost=", training_cost/5) training_cost = sess.run(loss, feed_dict={X_data:X_test,y_target:y_test}) print("Training cost=", training_cost) This gives me the output Currently on step 0 Training cost= 12376958566.4 Currently on step 500 Training cost= nan Currently on step 1000 Training cost= nan Currently on step 1500 Training cost= nan Currently on step 2000 Training cost= nan Currently on step 2500 Training cost= nan Currently on step 3000 Training cost= nan Currently on step 3500 Training cost= nan Currently on step 4000 Training cost= nan Currently on step 4500 Training cost= nan Training cost= nan I received a little better results with the Adagrad optimizer which gave me an error of 5, but I still think there should be a lot more possible. Would it maybe be an option here to add a hidden layer? I tried also this previously, but while using relu as my activation function in the layer and just f(x)=x on my output layer, I received similar high nan-errors. Cheers! - Tensorflow, map Standard Scale column In my DF I have a column based on ZSCORE/Standard Score values: Index ColA 216 -0.757 217 -0.861 218 -0.918 219 -0.975 220 -0.991 221 -1.049 222 -0.930 223 -0.568 224 -0.067 225 0.922 226 1.225 227 1.253 228 1.316 229 1.041 230 1.276 231 1.099 232 0.965 233 0.803 234 0.265 235 -0.006 236 -0.174 237 -0.316 238 -0.408 239 -0.567 Due to negative float nature of ColA I could not map it to with: colA = tf.contrib.layers.real_valued_column('colA'). Any ideas how I can 'feature column' and map this feature to my DNN Regressor. I'm using high-level Contrlib Tensorflow API. - Path is null error I have this speech recognition program in Visual Studio but one of the very last lines is throwing "Object reference not set to an instance of an object." private string GetResponse(string query) { Request request = new Request(query, user, bot); Result result = bot.Chat(request); return result.Output; } - Android Speech recognition Blocked offensive words I am just using the speech recognition. Is there any way to show the censored words from code in android? When I say "fuck" I get this "fu.." - Converting Speech to text and then text to speech on the fly I am working on a program that interacts with human using speech recognition and speech synthesis (it is a virtual avatar). The user can talk with the avatar. Further, the program has a remote module using which the user can talk with a remote operator. The remote operator talks through the avatar. When user talks with remote operator what we currently do is convert speech to text in the remote module, then send the text to main module and then again convert the text to speech and vice versa. But when the message in lengthy this causes a huge latency (only after recognizing all the speech we can send the text and convert to speech). Therefore this does not allow a good conversation between user and remote operator (the user should not realize that someone else is talking, it should appear like the avatar is talking with the user, therefore there should not be a huge latency) Is it possible to implement this in c#.NET. Anyone has a idea how to achieve this? - i want to send receive and receive data from Alexa lambda node JS Alexa should ask for use strict'; const Alexa = require('alexa-sdk'); exports.handler = (event, context) => { const alexa = Alexa.handler(event, context); var APP_ID = "amzn1.ask.skill.[XXXXX-45cc-9558-3c284b72148f]"; alexa.APP_ID = APP_ID; alexa.dynamoDBTableName = 'LongFormAudioSample'; // creates new table for session.attributes alexa.registerHandlers(handlers); alexa.execute(); }; const handlers = { 'LaunchRequest': function() { }, 'NewSession': function() { this.attributes['eventType'] = ""; }, 'SessionEndedRequest': function() { //this.attributesp["crash:emergency"] = null; this.emit(':tell', "Thank you"); }, 'WishingWelcomeIntent': function( ) { // here I want to send username var username = ''; // should get from request var json = { place : "USA"; } // this.emit(":tell", "Hi", +username, "you'r welcome", json should send along with the audio response from Alexa ); }, }; How can we send data to Alexa? POST data Alexa to the app. Actually, I want to send data to the lambda function along with the audio. I want to send some JSON data from Alexa to my application. I am developing the mobile app. with Alexa voice service. Is there any way to send and receive data using Alexa? - Processing Custom Alexa Skill Cards in AVS-SDK I am building some simple custom skills with card like this: this.response.cardRenderer(skillName,textCard); this.emit(':responseReady'); I have AVS SDK installed on a Raspberry Pi, but I can't see where the card info ends up. The service simulator has the following info in the service response: "card": { "content": "hum, I can't sense any fan here.", "title": "FanControlIntent on" }, Is there anyway I can extract the card info so I can process it in the SDK on my raspberry pi? My first guess is this will be in the payload of the directive but is not. - Alexa Voice Services Data Retention/Deletion/Privacy When my users record their voice using Alexa Voice Services, how can I give them the option to delete them later? I tried to search everywhere but haven't any APIs yet. Alexa seems to allow this within their companion app, but what about developers building something similar? Similarly, what is the retention policy for these recordings? - Webhook Service for Dialogflow does not recieve any requests (Status 206) I host a nodejs webservice to handle my Dialogflow Webhook requests. I am using Express and I handle any POST-Requests (and first thing I do is loggin incoming POST-Requests to the console). 'use strict'; var express = require('express'); var bodyParser = require('body-parser'); const http = require('http'); var app = express(); app.use(bodyParser.json()); app.post('*', function(req, res) { console.log(JSON.stringify(req.body)); [...] My NodeJS service is exposed to my domain through a Apache ReverseProxy (.htaccess) and I have a valid Let'sEncrypt SSL Certificate for my domain. RewriteRule ^(.*) [P] When I test my Service through Postman I see the request being logged on the node console and the correct response being sent. But when I want to use it in Dialogflow as Webhook Fulfillment, Dialogflow shows me this status and I don't even see a POST-Request coming into my Nodejs App / Console: [...] "status": { "code": 206, "errorType": "partial_content", "errorDetails": "Webhook call failed. Error: Webhook response was empty.", "webhookTimedOut": false } [...] In my opinion at least a request should come to my Server? Can somebody help me with this? Thanks a lot. - How to design stateful conversation with Dialogflow I'm trying to make an app to reserve meeting rooms in my office by Google Home and Dialogflow. Here's my plan: Me: "OK Google, is there any available room now?" Google Home: "Room 1 is available until 16:00." Me: "Book it." Google Home: "Booked Room 1." The current problem is how to make Google Home's response stateful. In my plan, when I say "Book it", Google Home has to remember Room 1. But I don't know how to make it happen. I read documents of conversation API, but I haven't understand it's possible to preserve variables or states within the same conversation Id. Does anyone know about that? - Can I Use Google Home To Automatically Chromecast My Own Content I have a working "Action On Google" that we programmed. I separately created a website that Chromecasts video (based on Google's sample code). However, what I would REALLY like to have is speak to my Google Home, then automatically have content (ideally an image + audio, then a video right after) cast to the Chromecast. Is this technically possible exclusively through the Google Home interaction? Alternately, is there a way to cast image + audio at the same time through a website (and what code do I need to do so)?
http://quabr.com/46685611/how-to-get-data-on-how-fast-the-wake-word-detection-on-amazon-alexa-google-home
CC-MAIN-2017-47
refinedweb
1,944
59.8
I am always looking for better ways to write parallel programs. In chapter 7 of our book “Cloud Computing for Science and Engineering” we looked at various scalable parallel programming models that are used in the cloud. We broke these down into five models: (1) HPC-style “Single Program Multiple Data” (SPMD) in which a single program communicates data with copies of itself running in parallel across a cluster of machines, (2) many task parallelism that uses many nearly identical workers processing independent data sets, (3) map-reduce and bulk synchronous parallelism in which computation is applied in parallel to parts of a data set and intermediate results of a final solution are shared at well defined, synchronization points, (4) graph dataflow transforms a task workflow graph into sets of parallel operators communicating according to the workflow data dependencies and (5) agents and microservices in which a set of small stateless services process incoming data messages and generate messages for other microservices to consume. While some applications that run in the cloud are very similar to the batch style of HPC workloads, parallel computing in the cloud is often driven by different classes application requirements. More specifically, many cloud applications require massive parallelism to respond external events in real time. This includes thousands of users that are using apps that are back-ended by cloud compute and data. It also includes applications that are analyzing streams of data from remote sensors and other instruments. Rather than running in batch-mode with a start and end, these applications tend to run continuously. A second class of workload is interactive data analysis. In these cases, a user is exploring a large collection of cloud resident data. The parallelism is required because the size of the data: it is too big to download and if you could the analysis would be too slow for interactive use. We have powerful programming tools that can be used for each of the parallel computing models described above but we don’t have a single programming tool that support them all. In our book we have used Python to illustrate many of the features and services available in the commercial clouds. We have taken this approach because Python and Jupyter are so widely used in the science and data analytics community. In 2014 the folks at Continuum (now just called Anaconda, Inc) and a several others released a Python tool called Dask which supports a form of parallelism similar to at least three of the five models described above. The design objective for Dask is really to support parallel data analytics and exploration on data that was too big to keep in memory. Dask was not on our radar when we wrote the drafts for our book, but it certainly worth discussing now. Dask in Action This is not intended as a full Dask tutorial. The best tutorial material is the on-line YouTube videos of talks by Mathew Rocklin from Anaconda. The official tutorials from Anaconda are also available. In the examples we will discuss here we used three different Dask deployments. The most trivial (and the most reliable) deployment was a laptop installation. This worked on a Windows 10 PC and a Mac without problem. As Dask is installed with the most recent release of Anaconda, simply update your Anaconda deployment and bring up a Jupyter notebook and “import dask”. We also used the same deployment on a massive Ubuntu linux VM on a 48 core server on AWS. Finally, we deployed Dask on Kubernetes clusters on Azure and AWS. Our goal here is to illustrate how we can use Dask to illustrate several of the cloud programming models described above. We begin with many task parallelism, then explore bulk synchronous and a version of graph parallelism and finally computing on streams. We say a few words about SPMD computing at the end, but the role Dask plays there is very limited. Many Task Parallelism and Distributed Parallel Data Structures Data parallel computing is an old important concept in parallel computing. It describes a programming style where a single operation is applied to collections of data as a single parallel step. A number of important computer architectures supported data parallelism by providing machine instructions that can be applied to entire vectors or arrays of data in parallel. Called Single instruction, multiple data (SIMD) computers, these machines were the first supercomputers and included the Illiac IV and the early Cray vector machines. And the idea lives on as the core functionality of modern GPUs. In the case of clusters computers without a single instruction stream we traditionally get data parallelism by distributed data structures over the memories of each node in the cluster and then coordinating the application of the operation in a thread on each node in parallel. This is an old idea and it is central to Hadoop, Spark and many other parallel data analysis tools. Python already has a good numerical array library called numpy, but it only supports sequential operations for array in the memory of a single node. Dask Concepts Dask computations are carried out in two phases. In the first phase the computation is rendered into a graph where the nodes are actual computations and the arcs represent data movements. In the second phase the graph is scheduled to run on a set of resources. This is illustrated below. We will return to the details in this picture later. Figure 1. Basic Dask operations: compile graph and then schedule on cluster There are three different sets of “resources” that can be used. One is a set of threads on the host machine. Another is a set of process and the third is a cluster of machines. In the case of threads and local processes the scheduling is done by the “Single machine scheduler”. In the case of a cluster it called the distributed cluster. Each scheduler consumes a task graph and executes it on the corresponding host or cluster. In our experiments we used a 48 core VM on AWS for the single machine scheduler. In the cluster case the preferred host is a set of containers managed by Kubernetes. We deployed two Kubernetes clusters: a three node cluster on Azure and a 6 node cluster on AWS. Dask Arrays, Frames and Bags Python programmers are used to numpy arrays, so Dask takes the approach to distributing arrays by maintaining as much of the semantics of numpy as possible. To illustrate this idea consider the following numpy computation that creates a random 4 by 4 array, then zeros out all elements lest than 0.5 and computes the sum of the array with it’s transpose. x = np.random.random((4,4)) x[x<0.5] = 0 y = x+x.T We can use Dask to make a distributed version of the same matrix and perform the same computations in parallel. Import dask.array as da x = da.random.random(size = (4,4), chunks =(4,1)) x[x<0.5] = 0 y = x+x.T The important new detail here is that we give explicit instructions on how we want the array to be distributed by specifying the shape of the chunks on each node. In this case we have said we want each “chunk” to be a 4×1 slice of the 4×4 array. We could have partitioned it into square blocks of size 2×2. Dask takes care of managing each chunk and the needed communication between the processes that handle each chunk. The individual chunks are managed on each thread/process/worker as numpy arrays. As stated above, there are two parts to a dask computation. The first phase is the construction of a graph representing the computation involving each chunk. We can actually take a look at the graph. For example, in the computation above we can use the “visualize()” method as follows. y = x+x.T y.visualize() Figure 2. Sample Dask Graph for x+x.T The nodes represent data or operations and the lines are data movements from one node to another. As can be seen this is a rather communication intensive graph. This is becase the transpose operation requires element on the rows (which are distributed) must be moved to columns on the appropriate node to do the addition. The way we chunck the array can have a huge impact on the complexity of the distributed computation. For example, 2×2 chuncking makes this one very easy. There are 4 chunks and doing the transpose involves only a simple swap of the “off diagonal” chunks. In this case the graph is much simpler (and easier to read!) Figure 3. Task graph for x+x.T with 2×2 chunking of data The second step for Dask is to send the graph to the scheduler to schedule the subtasks and execute them on the available resources. That step is accomplished with a call to the compute method. y.compute() Dask arrays support almost all the standard numpy array operations except those that involve complex communications such as sorting. In addition to numpy-style arrays, Dask also has a feature called Dask dataframes that are distributed versions of Pandas dataframes. In this case each Dask dataframe is partitioned by blocks of rows where each block is an actual Pandas dataframe. In other words, Dask dataframes operators are wrappers around the corresponding Pandas wrappers in the same way that Dask array operators are wrappers around the corresponding numpy array operators. The parallel work is done primarily by the local Pandas and Numpy operators working simultaneously on the local blocks and this is followed by the necessary data movement and computation required to knit the partial results together. For example, suppose we have a dataframe, df, where each row is a record consisting of a name and a value and we would like to compute the sum of the values associated with each name. We assume that names are repeated so we need to group all records with the same name and then apply a sum operator. We set this up on a system with three workers. To see this computational graph we write the following. df.groupby(['names']).sum().visualize() Figure 4. Dataframe groupby reduction As stated earlier, one of the motivations of Dask is the ability to work with data collections that are far too large to load on to your local machine. For example, consider the problem of loading the New York City taxi data for an entire year. It won’t fit on my laptop. The data for is for 245 million passenger rides and contains a wealth of information about each ride. Though we can’t load this into our laptop we can ask dask to load it from a remote repository into our cloud and automatically partition it using the read_csv function on the distrusted dataframe object as shown below. Figure 5. Processing Yellow Cab data for New York City The persist method moves the dataframe into memory as a persistent object that can be reused without being recomputed. (Note: the read_cvs method did not work on our kubernetes clusters because of a missing module s3fs in the dask container, but it did work on our massive shared memory VM which has 200 GB of memory.) Having loaded the data we can now follow the dask demo example and compute the best hour to be a taxi driver based on the fraction of tip received for the ride. Figure 6. New York City cab data analysis. As you can see, it is best to be a taxi driver about 4 in the morning. A more general distributed data structure is the Dask Bag that can hold items of less structured type than array and dataframes. A nice example illustrates using Dask bags to explore the Enron public email archive. Dask Futures and Delayed One of the more interesting Dask operators is one that implements a version of the old programming language concept of a future A related concept is that of lazy evaluation and this is implemented with the dask.delayed function. If you invoke a function with the delayed operator it simply builds the graph but does not execute it. Futures are different. A future is a promise to deliver the result of a computation later. The future computation begins executing but the calling thread is handed a future object which can be passed around as a proxy for the result before the computation is finished. The following example is a slightly modified version of one of the demo programs. Suppose you have four functions def foo(x): return result def bar(x): return result def linear(x, y): return result def three(x, y, z): return result We will use the distributed scheduler to illustrate this example. We first must create a client for the scheduler. Running this on our Azure Kubernetes cluster we get the following. from dask.distributed import Client c = Client() c To illustrate the delayed interface, let us build a graph that composes our example functions from dask import visualize, delayed i = 3 x = delayed(foo)( I ) y = delayed(bar)( x ) z = delayed(linear)(x, y) q = delayed(three)( x, y, z) q.visualize(rankdir='LR') In this example q is now a placeholder for the graph of a delated computation. As with the dask array examples, we can visualize the graph (plotting it from Left to Right). Figure 7. Graph of a delayed computation. A call to compute will evaluate our graph. Note that we have implemented the four functions each with about 1 second of useless computational math (computing the sum of a geometric series) so that we can measure some execution times. Invoking compute on our delayed computation gives us which shows us that there is no parallelism exploited here because the graph has serial dependences. To create a future, we “submit” the function and its argument to the scheduler client. This immediately returns a reference to future value and starts the computation. When you need the result of the computation the future has a method “result()” that can be invoked and cause the calling thread to wait until the computation is done. Now let us consider the case where the we need to evaluate this graph on 200 different values and then sum the results. We can use futures to kick off a computation for each instance and wait for them to finish and sum the results. Again, following the example in the Dask demos, we ran the following on our Azure Kubernetes cluster: Ignore the result of the computation (it is correct). The important result is the time. Calculating the time to run this sequentially (200*4.19 = 838 seconds) and dividing by the parallel execution time we get a parallel speed-up of about 2, which is not very impressive. Running the same computation on the AWS Kubernetes cluster we get a speed-up of 4. The Azure cluster has 6 cores and the AWS cluster has 12, so it is not surprising that it is twice as fast. The disappointment is that the speed-ups are not closer to 6 and 12 respectively. Results with AWS Kubernetes Cluster However, the results are much more impressive on our 48 core AWS virtual machine. Results with AWS 48-core VM In this case we see a speed-up of 24. The difference is the fact that the scheduling is using shared memory and threads. Dask futures are a very powerful tool when used correctly. In the example above, we spawned off 200 computations in less than a second. If the work in the individual tasks is large, that execution time can mask much of the overhead of scheduler communication and the speed-ups can be much greater. Dask Streams Dask has a module called streamz that implements a basic streaming interface that allows you to compose graphs for stream processing. We will just give the basic concepts here. For a full tour look at. Streamz graphs have sources, operators and sinks. We can start by defining some simple functions as we did for the futures case: def inc(x): return x+13 def double(x): return 2*x def fxy(x): #expects a tuple return x[0]+ x[1] def add(x,y): return x+y from streamz import Stream source = Stream() The next step will be to create a stream object and compose our graph. We will describe the input to the stream later. We use four special stream operators here. Map is how we can attach a function to the stream. We can also merge two streams with a zip operator. Zip waits until there is an available object on each stream and then creates a tuple that combines both into one object. Our function fxy(x) above takes a tuple and adds them. We can direct the output of a stream to a file, database, console output or another stream with the sink operator. Shown below our graph has two sink operators. Figure 8. Streamz stream processing pipeline. Visualizing the graph makes this clear. Notice there is also an accumulate operator. This allows state flowing through the stream to be captured and retained. In this case we use it to create a running total. To push something into the stream we can use the emit() operator as shown below. The emit() operator is not the only way to send data into a stream. You can create the stream so that it takes events from kafka, or reads lines from a file or it can monitor a file system directory looking for new items. To illustrate that we created another stream to look at the home director of our kubernetes cluster on Azure. Then we started this file monitor. The names of the that are there are printed. Next, we added another file “xx” and it picked it up. Next, we invoked the stream from above and then added another file “xxx”. Handling Streams of Big Tasks Of the five types of parallel programming Dask covers 2 and a half: many task parallelism, map-reduce and bulk synchronous parallelism and part of graph dataflow. Persistent microservices are not part of the picture. However, Dask and Streamz can be used together to handle one of the use cases for microservices. For example, suppose you have a stream of tasks and you need to do some processing on each task but the arrival rate of tasks exceed the rate at which you can process them. We treated this case with Microservices while processing image recognition with MxNet and the resnet-152 deep learning model (see this article.) One can use the Streams sink operation to invoke a future to spawn the task on the Kubernetes cluster. As the tasks finish the results can be pushed to other processes for further work or to a table or other storage as illustrated below. Figure 9 Extracting parallelism from a stream. In the picture we have a stream called Source which gathers the events from external sources. We then map it to a function f() for initial processing. The result of that step is sent to a function called spawn_work which creates a future around a function that does some deep processing and sends a final result to an AWS DynamoDB table. (The function putintable(n) below shows an example. It works by invoking a slow computation then create the appropriate DynamoDB metadata and put the item in the table “dasktale”.) def putintable(n): import boto3 e = doexp(n*1000000) dyndb = boto3.resource('dynamodb', … , region_name='us-west-2' ) item ={'daskstream':'str'+str(n),'data': str(n), 'value': str(e)} table = dyndb.Table("dasktale") table.put_item(Item= item ) return e def spawn_work(n): x = cl.submit(putintable, n) This example worked very well. Using futures allowed the input stream to work at full speed by exploiting the parallelism. (The only problem is that boto3 needs to be installed on all the kubernetes cluster processes. Using the 48 core shared memory machine worked perfectly.) Dask also has a queue mechanism so that results from futures can be pushed to a queue and another thread can pull these results out. We tried as well, but the results were somewhat unreliable. Conclusion There are many more stream, futures, dataframe and bag operators that are described in the documents. While it is not clear if this stream processing tool will be robust enough to replace any of the other systems current available, it is certainly a great, easy-to-use teaching tool. In fact, this statement can be made about the entire collection of Dask related tools. I would not hesitate to use it in an undergraduate course on parallel programming. And I believe that Dask Dataframes technology is very well suited to the challenge of big data analytics as is Spark. The example above that uses futures to extract parallelism from a stream challenge is interesting because it is completely adaptive. However, it is essential to be able to launch arbitrary application containers from futures to make the system more widely applicable. Some interesting initial work has been done on this at the San Diego Supercomputer center using singularity to launch jobs on their resources using Dask. In addition the UK Met Office is doing interesting things with autoscaling dask clusters. Dask and StreamZ are still young. I expect them to continue to evolve and mature in the year ahead.
https://esciencegroup.com/category/python/
CC-MAIN-2021-39
refinedweb
3,585
61.87
, ListView, iOS, HasUnevenRows don't work. I query data from a webservice. The result is stored in a list with 1-n entrys from type object. In the list, there are some textfields and image-fields. I show the result in a listview. The length of data in the testfields is variable (some contains more, some less text) For the image I have set HeightRequest = 200 and WidthRequest = 200, As the length in the text-fields is variable, I want to set HasUnevenRows to true to the Listview (so that the needed high is settled automatically at runtime. Problem description: HasUnevenRows to the ListView works as expected on Android (HW) and with WP-Emulator. HasUnevenRows to the ListView don’t work with iOS. => On iOS all elements are showed "stacked" on the same space Code-snipped: lvErgebnisAnzeige = new ListView { HasUnevenRows = true, // DON’T WORK WITH IOS, works with Android (HW) and WP-Emulator //RowHeight = 600, // to display the ListView in iOS, the RowHeight has to set to a value (what in don’t want to do) }; // lvErgebnisAnzeige.ItemSelected += (sender, e) => { var eq = (Empfehlung)e.SelectedItem; string cAnzeige = "Selektiert: " + eq.cAdresse.Trim() + " / Key: " + eq.iAnbieterKey; DisplayAlert("Empfehlung info", cAnzeige, "OK"); }; Content = new StackLayout { Padding = new Thickness(0, 20, 0, 0), Children = { indicator, lStatusAbfrage, piServerAuswahl, piGuide, btEmpfehlungenLaden, lvErgebnisAnzeige,} }; // Cellendefinition class EmpfehlungenCell : ViewCell { public EmpfehlungenCell() { var image = new Image { HorizontalOptions = LayoutOptions.Start, HeightRequest = 200, WidthRequest = 200, VerticalOptions = LayoutOptions.Start, }; image.SetBinding(Image.SourceProperty, "bAnbieterFoto"); image.BindingContextChanged += (sender, e) => { base.OnBindingContextChanged(); var c = BindingContext as Empfehlung; string cFotoBase64 = c.bAnbieterFoto; Byte[] ImageFotoBase64 = System.Convert.FromBase64String(cFotoBase64); image.Source = ImageSource.FromStream(() => new MemoryStream(ImageFotoBase64)); }; var EmpfehlungLayout = CreateEmpfehlungenLayout(); // Viewlayout-Grunddefinition var viewLayout = new StackLayout() { Orientation = StackOrientation.Horizontal, Children = { image, EmpfehlungLayout } }; // Ausrichtung anpassen für Phone / Tablet if (Device.Idiom == TargetIdiom.Phone) { viewLayout.Orientation = StackOrientation.Vertical; } else { viewLayout.Orientation = StackOrientation.Horizontal; } View = viewLayout; } static StackLayout CreateEmpfehlungenLayout() // Labels var AdressLabel = new Label { HorizontalOptions = LayoutOptions.FillAndExpand}; AdressLabel.SetBinding(Label.TextProperty, "cAdresse"); // var SloganLabel = new Label { HorizontalOptions = LayoutOptions.FillAndExpand }; SloganLabel.SetBinding(Label.TextProperty, "cAnbieterSlogan"); // var AngeboteLabel = new Label { HorizontalOptions = LayoutOptions.FillAndExpand }; AngeboteLabel.SetBinding(Label.TextProperty, "cAngebote"); // var TitelAngeboteLabel = new Label { Text = "Angebote:", HorizontalOptions = LayoutOptions.FillAndExpand, Font = Font.SystemFontOfSize(14, FontAttributes.Bold ),}; // var nameLayout = new StackLayout() { HorizontalOptions = LayoutOptions.StartAndExpand, Orientation = StackOrientation.Vertical, Children = { AdressLabel, SloganLabel, TitelAngeboteLabel, AngeboteLabel } }; return nameLayout; } I have checked this issue but unable to reproduce it. I have tried following steps. 1.Create a Xamarin forms Application. 2.Add a class UnevenRowsCell.cs and did Some code. 3.Add a class UnevenRowsPage.cs and Did Some Code. 4. Set listView.HasUnevenRows = true; 4.Call UnevenRowsPage.cs in App.cs 5. Set .ios project as Start tup project 6.Run the application. I observed that listView.HasUnevenRows property is working fine. // UnevenRowsCell.cs class public class UnevenRowsCell : ViewCell { public UnevenRowsCell () { var label1 = new Label { Text = "Label 1", Font = Font.SystemFontOfSize(NamedSize.Small) }; label1.SetBinding(Label.TextProperty, new Binding(".")); View = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.StartAndExpand, Padding = new Thickness (15, 5, 5, 5), Children = { label1 } }; } const int avgCharsInRow = 35; const int defaultHeight = 44; const int extraLineHeight = 20; protected override void OnBindingContextChanged () { base.OnBindingContextChanged (); if (Device.OS == TargetPlatform.iOS) { var text = (string)BindingContext; var len = text.Length; if (len < (avgCharsInRow * 2)) { // fits in one cell Height = defaultHeight; } else { len = len - (avgCharsInRow * 2); var extraRows = len / 35; Height = defaultHeight + extraRows * extraLineHeight; } } } } // UnevenRowsPage.cs public class UnevenRowsPage : ContentPage { public UnevenRowsPage () { var listView = new ListView (); listView.HasUnevenRows = true; // listView. " }; listView.ItemTemplate = new DataTemplate(typeof(UnevenRowsCell)); listView.ItemTapped += (sender, e) => { if (e == null) return; // has been set to null, do not 'process' tapped event Debug.WriteLine("Tapped: " + e.Item); ((ListView)sender).SelectedItem = null; // de-select the row }; Padding = new Thickness (0,20,0,0); Content = listView; } } //App.cs public class App { /// <summary> /// This sample includes both C# and XAML versions of the user interface. /// UNCOMMENT the version below that you wish to try /// </summary> public static Page GetMainPage () { return new UnevenRowsPage(); } } Let me know if i have to follow other steps to reproduce it. Screencast: Environment Info: VS 2013 Update 3 XVS 3.3.47.0 Xamarin.forms 1.2.2.6243 Hi Arpit Thanks for Feedback As this bug is elementar (it is a "killer"), I have created a documentation for you with screenshots. I also upload the .cs file with the page for you (sorry.. as I am in testing, there are much commented lines). If (really) needed, I also can submit you my whole project (if you handle it confidential). With the whole project you also should ne able to query data from our webservice. Let me know, if you need the whole project. Please give this problem a high priority, as it is a real "killer". If the Height cannot is not calculates correct automatically, it's simple not usable for iOS (it's not clever and smart to set a fix height). Thanks Fredy Created attachment 7883 [details] Description with Screenshots Description with Screenshots -> See my last posting I have checked this issue and Now able to reproduce it. I have tried following steps to reproduce it. 1.Create Xamarin form application. 2.Add a class(.cs) and did some code in it. 3.Call .cs class in App.cs 4.Set ios as startup project. 5.Run the application. I observed that content of listview overlaps but when we set row height then Listview looks as expected. I can reproduce the reported behavior HasUnevenRows don't work in Listview with iOS . I’ll need confirmation from the developer if this is a bug. Leaving as NEW for now. public class MyPage : ContentPage { ListView lvErgebnisAnzeige; Label lStatusAbfrage; public MyPage() { lvErgebnisAnzeige = new ListView { HasUnevenRows = true, }; lvErgebnisAnzeige. " }; lvErgebnisAnzeige.ItemTemplate = new DataTemplate(typeof(UnevenRowsCell)); lvErgebnisAnzeige.ItemSelected += (sender, e) => { //var eq = (Empfehlung)e.SelectedItem; // aktuell selektiertes Objekt übernehmen -> als Parameter auf die Detailseite übergeben //string cAnzeige = "Selektiert: " + eq.cAdresse.Trim() + " / Key: " + eq.iAnbieterKey; //DisplayAlert("Empfehlung info", cAnzeige, "OK"); //this.Navigation.PushAsync(new SucheDetails(eq)); // Detailseite mit Objekt aufrufenh }; Content = new StackLayout { Padding = new Thickness(0, 20, 0, 0), Children = { lvErgebnisAnzeige, } }; } } Screencast: Environment Info: VS 2013 Update 3 XVS 3.3.47.0 Xamarin.forms 1.2.2.6243 Hi Arpit Thanks for confirm the bug. Please help, that the bug will be fixed soon, as it blocks development for iOS. Greetings from Switzerland. Fredy See also (new) bug: I think the bugs are related... *** Bug 22597 has been marked as a duplicate of this bug. *** Created attachment 8032 [details] Additional description See las message Sadik: You have marked my second bug-entry as duplicate and ALSO HAVE DELETED MY ADDITIONAL SECOND description specially to the text-cut-bug. I have added the attachment once again to this bug. Can you (or somebody else) give me a Feedback, until when the bug will be fixed as this is a show stopper for me)? Thanks Fredy iOS does not support automatically sizing row cells, you must set a ListView.RowHeight or a Cell.Height. Unfortunately, we did not specifically disable this from working on Android or Windows Phone (where it just works without our intervention), and it has lead some to believe that iOS is broken in this respect. Unfortunately this is a limitation of the iOS platform and therefore is the intended behavior. Sorry, but I can't accept that. There is a special property (hasunevenrows), that works as expected in Android and WP. It can't be, that this don't work in iOS. My Input ist dynamic and bindet - so I have no idea how to calculate it myself and I don't want to calculate it myself. .Forms is specially for multiplatform (write once, run on ALL platforms. So... I expect, that XAMARIN implements something, that this also works with iOS, otherwise the property (hasunvenerows) don't work and can't be used! Fredy Actually I'm on the same boat, how are we suppose to compute the height of the row for iOS based only on the text length? What would be the solution to not have stacked content? (except setting the row height to a "big" number) Can you provide an example of this? I think Fredy has made a good point, either the feature is supported by all three platform or shouldn't be included in Xamarin.Forms at all... Greetings from Switzerland too ;) I agree that the calculation should be inside Xamarin framework. But until it gets implemented it should throw a NotSupportedException when the HasUnevenRows property is set on iOS, otherwise this will definitely be regarded as a bug. There is documentation on what can be used for all platforms, including what is required for iOS here: @John Miller: This Link is well known (old) - BUT NO SOLUTION (not usable in the real world). @Fredy Wenger: Yes! In real world it's necessary to measure strings size exactly. I don't know if there's a cleaner way, but I found one that works. I just use native calls to get string size for specified font name and size: That's really not perfect, but works for me :)
https://xamarin.github.io/bugzilla-archives/22/22535/bug.html
CC-MAIN-2019-43
refinedweb
1,502
51.14
<?php $client = new SoapClient('', array('soap_version' => SOAP_1_2, 'trace' => 1, 'use' => SOAP_LITERALL, 'style' => SOAP_DOCUMENT, 'encoding'=>' UTF-8')); $typedVar = new SoapVar("mystring", XSD_STRING, "string", ""); $params = '<RemittanceRequest><RequestType>BranchListRequest</RequestType><agent>BWS</agent><userid>wbsuser</userid><password>pass@wbs</password></RemittanceRequest>'; $params = new SoapVar($params, XSD_ANYXML); $result = $client->GetBranchListXML($params); echo "REQUEST:\n" . $client->__getLastRequest() . "\n"; echo "Response:\n" . $client->__getLastResponse() . "\n"; print_r($result);.[]=SOAP+related One such bug involves namespaces. Variables with the same name, but in different namespaces, collide. WTF you might say, what's the point of namespaces? Well, that is exactly what I said when I hit the bug. It caused a failed project for me after an investment of more than a week of my life. Hopefully you won't have that experience with your project. If there is any way at all to get the client to expose a RESTful interface to the API, choose that instead. If you have to continue to use SOAP, consider NuSOAP (Google it). It may be better at getting around the vagaries of PHP SOAP support. Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
https://www.experts-exchange.com/questions/28515293/Change-Namespace-SOAP.html
CC-MAIN-2018-30
refinedweb
212
59.19
Seven Languages In Seven Weeks: Ruby - Day 2 I just finished Ruby - Day 2 in my Seven Languages in Seven Weeks book. Day 2 definitely kicked it up a notch from day 1. I love how much the author - Bruce Tate - is really pushing us to look things up. He gives us problems that aren't too difficult, but they definitely require a lot of independent study in order to solve. And, while this is frustrating at times, having to open up a dozen browser tabs really gives a sense of just how robust a language can be. Ruby in particular, seems to provide a half-dozen ways to solve every problem, each of which uses fewer lines of code and less syntax than the approach before it. HW1: Print the contents of an array of sixteen numbers, four numbers at a time, using just each. Now, do the same with each_slice in Enumerable. - #(); - # Now, we're going to loop over the values using each. However, in - # order to output 4 values at a time, we're gonna only do so on - # certain indexes. - # - # Since we don't have any insight into which value we are looking - # at (index-wise), we're going to keep an internal stack of - # values which we will output only when it reaches a length of 4. - # However, I can't figure out how to do this with *just* each. As - # such, I am creating an external stack. - valueStack = []; - # Now, loop over each element in the array. - values.each{ |value| - # Push the current iteration value onto the stack. - valueStack.push( value ); - # Check to see if the value stack has reached a length of 4. If - # so, we are going to output it. - if (valueStack.length == 4) - # Output the stack of 4 values as a list. - puts( valueStack.join( ", " ) ); - # Reset the value stack to prepare it to collect the next - # four values in the array. - valueStack = []; - end - }; I don't think I fully knew how to solve this problem. I tried a few attempts that only used the each() method; but, they all failed do to the local scoping of variables within the code block. Finally, I had to compromise and define a local variable outside of the each() method which I could then use as a stack within the iteration. I'd love to see how this can be sovled with only each(). When we run the above code, we get the following console output: 1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12 13, 14, 15, 16 Once I had that done, I then tried to solve the problem with each_slice(), which was extremely easy: - #(); - # This time, we are going to iterate over the array, four elements - # at a time, using the each_slice() method. This allows us to look - # at sections of an array as sub-arrays. - values.each_slice( 4 ){ |valueStack| - # Output the sub-section of the array as a list. - puts( valueStack.join( ", " ) ); - }; This was much much easier. As you can see, when you use each_slice(), the sub-elements of the array are packaged up and passed to the code block - no grouping logic is required on our end. And, when we run the above code, we get the same exact console output, so I won't bother showing it. HW2: The Tree class was interesting, but it did not allow you to specify a new tree with a clean interface. Let the initializer accept a nested structure with hashes and arrays. You should be able to specify a tree like this: { "grandpa" => { "dad" => { "child1" => {}, "child2" => {} }, "uncle" => { "child3" => {}, "child4" => {} } } }. - # The Tree class was interesting, but it did not allow you to - # specify a new tree with a clean user interface. Let the initailizer - # accept a nested structure with hashes and arrays. You should be - # able to specific a tree like this: ..... - # The Tree Class - class Tree - attr_accessor :childNodes; - attr_accessor :name; - # I return an initialized Tree instance. - def initialize( treeData ) - # Initialize the node variables. By default, we are going - # to treat this node as the root node (unless the incoming - # tree data only has one top-level key, in which case that - # will be the root node). - @name = "root"; - @childNodes = []; - # Check to see how many top-level keys the tree data has. - # If it only has one, we can use it to define this tree - # node; if it has more than one, will have to treat it as - # the child data of a the "root" node. - if (treeData.size() == 1) - # We only have one top-level key. We can use that to - # define this tree node. - @name = treeData.keys()[ 0 ]; - # Convert the sub-level tree data into the chile nodes - # of this tree node. - treeData[ @name ].each{ |key, value| - @childNodes.push( - Tree.new( { key => value } ) - ); - }; - else - # We have more than one top-level key. We need to - # create a root node to house multiple nodes. - treeData.each{ |key, value| - @childNodes.push( - Tree.new( { key => value } ) - ); - }; - end - end - # I visit all decendant nodes in a depth-first traversal. - def visitAll( &block ) - # Visit this node. - visit( &block ); - # Visit all of this node's children. - childNodes.each{ |c| - c.visitAll( &block ); - } - end - # I visit just this node. - def visit( &block ) - block.call( self ); - end - end - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # Create our new Tree. - tree = Tree.new( - { - "grandpa" => { - "dad" => { - "child1" => {}, - "child2" => {} - }, - "uncle" => { - "child3" => {}, - "child4" => {} - } - } - } - ); - # Visit all nodes in the tree, starting with the root. - tree.visitAll{ |node| - puts( "Visiting #{node.name}" ); - }; This problem was particularly hard because we had to build a tree based on a flexible data structure. The biggest problem that this presented was the fact that there's nothing about a hash that says it has to have one key. Normally, this isn't a problem; but, when you're dealing with a tree that necessarily has to start with one node, fitting one into the other can require some trickery. To deal with this, I check for the number of top-level keys that are in the hash - if there is only one, I treat it as the root node. If there are multiple, I create a new root node to house all of the top-level keys. In my Tree class methods, you'll notice that the code block arguments are preceded by an ampersand. This apparently turns the code block into a Proc object which can then be treated like a variable. I don't fully understand what that means, but it appears to be necessary. When we run the above code, we get the following console output: Visiting grandpa Visiting uncle Visiting child3 Visiting child4 Visiting dad Visiting child1 Visiting child2 HW3: Write a simple grep that will print the lines of a file having any occurrences of a phrase anywhere in that line. You will need to do a simple regular expression match and read lines from a file. (This is surprisingly simple in Ruby.) If you want, include line numbers. - # The first thing we are going to do is build up the file content - # we are going to be searching. In this case, we are going to be - # building up the content using Ruby's "Here Document" notation. - content = <<END_CONTENT_BUFFER.strip().gsub( /^\t*/m, "" ) - I definitely think that Helena Bonham Carter is hot. I - know people will disagree with me here... and maybe she's - not hot in the most mundane sense; but, there's something just - absolutely stunning about her. Plus, she's a wonderful actress - which makes her seem all that much hotter. If you haven't seen - "Conversations With Other Women," I'd recommend it. She plays - qutie well opposite Aaron Eckhart. Plus, it was the first - movie I've ever seen her in knickers - it's refreshing to see a - woman who can be hot without feeling like she has to be a twig. - END_CONTENT_BUFFER - # Create a connection to the relative-path file (relative to the - # current directory of execution). - contentFile = File.new( "./data.txt", "w" ); - # Write the content to the file. - contentFile.puts( content ); - # Since we opened this file as "writing", we need to close it - - # we can't use it for reading. - contentFile.close(); - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # ------------------------------------------------------------ # - # Set the phrase that we're going to be searching for within the - # file. This could also be gotten from the standard IO (command - # line), but we'll hard-code it for now. - targetPhrase = "hot"; - # Open the data file for searching. Notice that we are opening - # the file with a code block; in doing it this way, we don't - # have to explicitly close the file when we're done - Ruby will - # take care of that for us. - File.open( "./data.txt", "r" ){ |fileStream| - # Read the file in, one line at a time, until we reach the - # end of the file. Gets() will return the line or return nil - # when it hits the end of the file. - while ( line = fileStream.gets()) - # When Ruby uses a file, it appears to create meta data - # about the line that's been read in and the line number. - # I'm defining both here for reference, but am not using - # all of it (since we assinged line above). - lineContent = $_; - lineNumber = $.; - # Check the current line to see if it contains the given - # phrase. To make the search a bit more flexible, we are - # going to use a case-insensitive regular expression. Notice - # that a regular expression literal can use variable - # subistitution via the #{var} notation. The "o" pattern - # modifier indicates that this subsitution only takes place - # the first time the pattern is evaluated (I don't fully - # understand what that means). - # - # NOTE: This assumes no reg-ex special charactrers are within - # our pattern. - if (line =~ /#{targetPhrase}/io) - # Output the current line with the line number. When - # you open a file, - puts( "Line #{lineNumber}: #{line}" ); - end - end - } In this problem, I am first writing content to a file and then reading the file back in, line by line, looking for a given phrase. The content is defined by a Ruby "Here Document," or "heredoc." This is somewhat like the CFSaveContent tag in ColdFusion. The cool part about it, however, is that you can perform actions on the buffered content by attaching methods to the heredoc delimiter (in this case, I am stripping white space before saving the value). When we run the above code, we get the following console output: Line 1: I definitely think that Helena Bonham Carter is hot. I Line 3: not hot in the most mundane sense; but, there's something just Line 5: which makes her seem all that much hotter. If you haven't seen Line 9: woman who can be hot without feeling like she has to be a twig. This homework took a good amount of time to figure out. Like I said, the book is really pushing us to learn independently. I still have some issues with the extreme amount of syntactic sugar that Ruby provides; but, I suppose that once you get used to it, it does make programming faster. Another Perlism: Heredocs. Nice. Another resource for you, if you find yourself really enjoying Ruby: (One of our graduates worked on that project. That's the second language I've seen with an interactive console where you can test out language features -- the first I saw was MongoDB. It's pretty slick, and would be awesome for CFML/CFScript.) use each on a range: a = (1..16).to_a (0...4).each {|i| puts a[4*i...4*(i+1)].join(',') } We can then generalize this to print any length array in groups of four: def print_quads(a) (0...a.size/4+1).each {|i| puts a[4*i...4*(i+1)].join(',') } end print_quads((1..7).to_a) print_quads((1..16).to_a) And we can generalize again and implement each_slice def each_slice(a, n) return if a.empty? (0...a.size/n+1).each {|i| yield a[n*i...n*(i+1)] } end # print groups of 3 each_slice((1..7).to_a, 3) { |slice| puts slice.join(',') } Your other examples could also be simplified if written more ruby like: You may want to check out a ruby style guide. It'll explain when to use certain features, naming conventions, and tips for writing simpler code. Cool to see you checking out ruby. The only downside is that once you really get the hang of a language like ruby or python, CF code looks so bloated. It does change your perspective about how to write simple code though! :) @Rick, Thanks for the link. The book hasn't touched on Rails at all (beyond mentioning that it is very popular). It is definitely something I'd be interested in exploring. @Elliott, Very cool solutions! I think the key to being able to write such concise code is, in part, changing the mindset, and in part, simply knowing the vast amount of methods that are available! I know my style is way off :) Ruby really loves the "_" approach to naming and *no* semi-colons (oh the humanity) which just kind of feels weird to me. I would assume that as I got more comfortable with the language, I would probably adapt the conventions more readily. I have to say, though, Ranges are simply badass! As is the ability to bring back a portion of an array using a range selection. Elliott- Sorry, I was unclear. I was referring to a web-based interactive console. So that people completely new to the language can try it out without having to install anything. Viz: Here's another possible solution for the first example (just using each): >> a = (1..16).to_a >> a.each {|i| print "#{i} "; puts if i % 4 == 0} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Stephen, Pretty good, my friend. I see this leverages the fact that some outputs don't append a newLine character. Slick. Just going through the book myself, and new to all seven languages as well (though my background is much more C/C++). My attempt at grep used foreach: @Jody, I remember seeing something about foreach() and I could have sworn that there was a reason that I didn't use it. Although, I have so many languages floating around in my head that I can't remember what language I remember doing what in. Your example looks way more concise than mine, though. But, what I can say for fact is that I am IN LOVE with any kind of regular expression operator :) When I saw that languages like Groovy and Ruby can use "=~" for regular expression actions, my heart just melted :) provided by Elliott Sprehn but looks to me like it only handles hashes. That's a question really as perhaps I'm misunderstanding the code, I'm definitely still getting the hang of Ruby. I just got this book for Christmas, and I had a lot of fun/trouble with #2 as well. I'm still terrible at Ruby, so I'm not sure how Rubythonic (or whatever people say) this is, but here's my solution: @Nat, Looks pretty cool to me. I especially like your use of pattern matching (in the non-regex sense). As I have gotten through the first 5 languages, I am definitely getting a bit of a better handle on the concept of data-type pattern matching. At first it was super confusing. But now, I am starting to see some of its power. @Boatzart, Congrats on getting the book. I've been having a blast with it. It is, at the same time, thrilling, frustrating, demeaning, and inspiring. It's very interesting to go from something like ColdFusion, where I know so much about the language, to these others where I know pretty much nothing. Just an FYI for people using Ruby < 1.8.7 (like me :( ) ... to use each_slice you need to first run <code>require 'enumerator'<code> hat-tip to SO for that because it was driving me mad () Matt d'oh bad end tag I don't know if you'd seen this yet, but you can print the array using each_slice with only one line of code like so: It's short and sexy and amazing that this is built into Ruby. @Matt, I don't know what type of machine you're on but if it's Mac or Linux, you can use RVM to have different Ruby versions installed. If you're on Windows, you can use Pik to do the same type of thing. @Boatzart, One thing in Ruby that you probably wouldn't want to do is using the word 'spec' for naming, especially if you end up using Rspec to write tests. Rubyists tend to opt for more descriptive_naming_conventions_using_underscores. I'm relieved to see that the second tree exercise was somewhat of a challenge to others as well. Below is what i came up with after staring at the screen for 30 minutes. Ruby is definitely fun. #day2_tree2.rb The most concise code that I saw for this is in the pragprog forum:: which outputs: the mental switch, imho, is to forget about the array, and start to think about the range instead. Nice switch btw. Way dated but since I'm just now getting into this book I'd like to contribute :) My answer was close to Stephen's original... (1..16).each {|i| i % 4 == 0 ? (puts i) : (print i, ", ")} My first solution for the problem #3. I'd be curious to better implementations though.... # readFile.rb filename = ARGV[0] word = ARGV[1] f = File.open(filename, 'r') f.each_line { |line| /#{word}/.match(line) ? (puts "#{f.lineno}: #{line}") : next} # From Command Line ruby readFile.rb lorem.txt lorem Why Not?
http://www.bennadel.com/blog/2062-seven-languages-in-seven-weeks-ruby-day-2.htm?_rewrite
CC-MAIN-2015-32
refinedweb
2,945
72.46
Hi Stepan, Thank you for the notes. I am curently contructing a new linux system, hopfully with enough power to run a modern web brouser. When I have finished that (maybe be the end of next week), I will have another go at texinfo-4.7 cross compilation. I will let you know how I get on. On Wed, 6 Oct 2004, Stepan Kasal wrote: > Hi again, > > On Wed, Oct 06, 2004 at 10:33:24AM +0200, Stepan Kasal wrote: > > > > of course, I meant: > > if TOOLS_ONLY > SUBDIRS = lib info makeinfo util > else > SUBDIRS = $(build_tools) intl m4 lib info makeinfo po util doc > endif > > Stepan >
http://lists.gnu.org/archive/html/bug-texinfo/2004-10/msg00020.html
CC-MAIN-2015-18
refinedweb
104
79.9
Peter Donald wrote: > > I finally got around to looking at action framework to see if it fitted all > my needs. I tested it against the following applications I have developed > in past. > <snip/> > Guess what C2 + proposed actions == 100% success :P <snip/> >> > > And probably the best way to define actions is just like you do with other > components - ie > > <map:action > <map:action > > <map:action > <identity-manager > > </map:action> > > <map:action > <schema>my-path-to-schema-resource.xsd</schema> > </map:action> > > <map:action > <database> ....... </database> > </map:action> > > </map:action> > > Cocoon is not (or better will not) parse any cookies/post/get things. This is delegated to the sitemap components because it is environment specific. > build an action chain out of them. However we don't want the user to be > able to submit arbitary actions - we want control over this for security > reasons - so this leads us to the next step: Action chains in sitemap > > <map:action-chains No default. I think it goes at the level like <map:resources> and <map:views> > <map:action-chain > <map:perform > <map:perform > </map:action-chain> > > <map:action-chain > <map:perform > <map:perform > <map:perform > <map:perform > </map:action-chain> > > <map:action-chain > <map:perform > <map:perform > </map:action-chain> > > <map:action-chain > <map:perform > <map:perform > </map:action-chain> > > </map:action-chains> To be consistent with the rest of the sitemap syntax I suggest using: <map:action-chains> <map:action-chain <!-- The type= attribute references a action defined in the components actions section --> <map:perform <map:perform </map:action-chain> <map:action-chain <!-- The chain= attribute references an action-chain --> <map:perform <map:perform </map:action-chain> <map:action-chain <map:perform <map:perform </map:action-chain> </map:action-chains> > The one last requirement is that remainin explicit actions in chain can be > saved and deferred by some means programmatically. I suggest leave this for later and concentrate on actions and action-chains. > So in conclusion this is what C2 needs: > > * building implict action chain (as per Giacomo's proposal) > * building explicitly requested action chain (as per above or another method) > * some way to push explicitly submitted actions onto stack and then pop and > execute them later Ok, let me summarize to see if I grasped it: Explicit actions are those presented to the user in kinda control panels or alike (do that, check this, etc.). From the sitemap point of view they can be collected into action-chains. In the pipeline section of the sitemap explicit Actions and especially action-chains do not have a way to control sitemap evaluation flow by means of the List object an Action may return and thus cannot have nested elements from the sitemap namespace (Parameters should be allowed). Of course they can communicate with other sitemap component ddduring pipeline evaluation time through the objectModel Map. Implicit actions are those which do processings like data validation and signal the sitemap engine if nested elements are to be evaluated or not by means of returning a List object or null. The List object is used to substitute occurences of {n} in src attributes of nested sitemap components (Generators, Transformers, Readers). The n in {n} is a number representing the index into the last List returned by a component to the sitemap engine. An expression like {../2} means the 2. element of the List returned by the parent component of the last components returning a List (and so on). The sitemap engine is only able to distinguish action-chains from actions but not explicit actions from implicit action. The sitemap engine will call ations in an action-chain in the order they are defined. It's the responsability of the action itself to determine what processing it should be doing. > Yes, there is the <map:mount> element exactly for this purpose. For further reduction off verbosity we plan to make subsitemaps inherit components from their parent sitemaps. But for this we need some kind of ComponentManagers able to be hierarchicaly structured and also able to handle pools of components because most of them are not ThreadSafe (Sharable) but Poolable. But this is a question I've put on the avalon list. Any comments?:
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200009.mbox/%3C39C36C21.4123DEF0@pwr.ch%3E
CC-MAIN-2015-11
refinedweb
696
50.06
The Cloud Development Kit for Terraform (CDKTF) allows you to define your infrastructure in a familiar programming language such as TypeScript, Python, Go, C#, or Java. CDKTF generates Terraform configuration in JSON, then automatically applies that configuration via Terraform to provision your infrastructure. In this tutorial, you will provision an EC2 instance on AWS using your preferred programming language. If you do not have CDKTF installed on your system, follow the steps in the install CDKTF tutorial to install it before you continue with this tutorial. »Prerequisites To follow this tutorial, you need the following installed locally: - Terraform v1.0+ - A Terraform Cloud account, with CLI authentication configured - CDK for Terraform v0.12+ - an AWS account - AWS Credentials configured for use with Terraform Terraform and CDKTF will use credentials set in your environment or through other means as described in the Terraform documentation. You will also need to install a recent version of the programming language you will use for this tutorial. We have verified this tutorial works with the following language versions. Typescript v4.4 and Node.js v16.13 »Initialize a new CDK for Terraform application Start by creating a directory named learn-cdktf for your project. $ mkdir learn-cdktf Then navigate into it. $ cd learn-cdktf Inside the directory, run cdktf init, specifying the template for your preferred language. Tip: If you would prefer to keep your state locally, use the --local flag with cdktf init. $ cdktf init --template="typescript" ? Project Name learn-cdktf ? Project Description A simple getting started project for cdktf. Detected Terraform Cloud token. We will now set up Terraform Cloud for your project. ? Terraform Cloud Organization Name <YOUR_ORG> We are going to create a new Terraform Cloud Workspace for your project. ? Terraform Cloud Workspace Name learn-cdktf ? Do you want to start from a Terraform project? No Setting up remote state backend and workspace in Terraform Cloud. ? Do you want to send crash reports to the CDKTF team? See -reporting-for-the-cli for more information Yes Generating Terraform Cloud configuration for '<YOUR_ORG>' organization and 'learn-cdktf' workspace..... added 2 packages, and audited 54 packages in 825ms 5 packages are looking for funding run `npm fund` for details found 0 vulnerabilities added 297 packages, and audited 351 packages in 8s 35 packages are looking for funding run `npm fund` for details found 0 vulnerabilities ======================================================================================================== Your cdktf typescript project is ready! ##... Use Providers: You can add prebuilt providers (if available) or locally generated ones using the add command: cdktf provider add "aws@~>3.0" null kreuzwerker/docker You can find all prebuilt providers on npm: You can also install these providers directly through npm: npm install @cdktf/provider-aws npm install @cdktf/provider-google npm install @cdktf/provider-azurerm npm install @cdktf/provider-docker npm install @cdktf/provider-github npm install @cdktf/provider-null You can also build any module or provider locally. Learn more ======================================================================================================== This initializes a new CDK for Terraform project using an interactive command. Accept the defaults for Project Name and Project Description. Select your Terraform Cloud Organization, and choose the name learn-cdktf for the Terraform Cloud Workspace. »Install AWS provider CDKTF provides packages with prebuilt classes for several common Terraform providers that you can use in your TypeScript projects. For other Terraform providers and modules, CDKTF automatically generates the appropriate TypeScript classes. Install the AWS provider. $ cdktf provider add "aws@~>4.0" Checking whether pre-built provider exists for the following constraints: provider: aws version : ~>4.0 language: typescript cdktf : 0.12.0 Found pre-built provider. Adding package @cdktf/provider-aws @ 9.0.0 Installing package @cdktf/provider-aws @ 9.0.0 using npm. Package installed. »Define your CDK for Terraform Application Open the main.ts file to view your application code. The template creates a scaffold with no functionality. Replace the contents of main.ts with the following code for a new TypeScript application, which uses the CDK to provision an AWS EC2 instance in us-west-1, and stores its state in Terraform Cloud. import { Construct } from "constructs"; import { App, TerraformStack, TerraformOutput, RemoteBackend } from "cdktf"; import { AwsProvider, ec2 } from "@cdktf/provider-aws"; class MyStack extends TerraformStack { constructor(scope: Construct, id: string) { super(scope, id); new AwsProvider(this, "AWS", { region: "us-west-1", }); const instance = new ec2.Instance(this, "compute", { ami: "ami-01456a894f71116f2", instanceType: "t2.micro", }); new TerraformOutput(this, "public_ip", { value: instance.publicIp, }); } } const app = new App(); const stack = new MyStack(app, "aws_instance"); new RemoteBackend(stack, { hostname: "app.terraform.io", organization: "<YOUR_ORG>", workspaces: { name: "learn-cdktf", }, }); app.synth(); Replace <YOUR_ORG> with the Terraform Cloud organization name you chose when you ran terraform init earier. Tip: If you would prefer to store your project's state locally, remove or comment out new RemoteBackend(stack, { [...] }); and remove RemoteBackend from the import { [...] } from "cdktf"; line near the top of the file. »Examine the code Most of the code is similar to concepts found in a traditional Terraform configuration written in HCL, but there are a few notable differences. Review the code for the programming language you have selected. You must explicitly import any classes your TypeScript code uses. For example, you will use TerraformOutput to create a Terraform output value for your EC2 instance's public IP address. import { Construct } from "constructs"; import { App, TerraformStack, TerraformOutput, RemoteBackend } from "cdktf"; The code imports the AwsProvider and ec2 classes from the provider you installed earlier. import { AwsProvider, ec2 } from "@cdktf/provider-aws"; The MyStack class defines a new stack, which contains the code to define your provider and all of your resources. class MyStack extends TerraformStack { constructor(scope: Construct, id: string) { super(scope, id); The code configures the AWS provider to use the us-west-1 region. new AwsProvider(this, "AWS", { region: "us-west-1", }); The AwsProvider accepts an object with keys and values that map to Terraform arguments as listed in the AWS provider documentation. The ec2.Instance class creates a t2.micro EC2 instance with an AWS ami. const instance = new ec2.Instance(this, "compute", { ami: "ami-01456a894f71116f2", instanceType: "t2.micro", }); The ec2.instance class also accepts object, using camel case for properties that correspond to the AWS provider documentation. The code stores the instance as a variable so that the TerraformOutput below can reference the instance's publicIp attribute. new TerraformOutput(this, "public_ip", { value: instance.publicIp, }); When you write CDKTF code with an IDE, use it view the properties and functions of the classes, variables, and packages in your code. This example uses the publicIp attribute from the instance variable. Finally, your application uses the stack you have defined, configures a remote backend to store your project's state in Terraform Cloud, and calls app.synth() to generate Terraform configuration. const app = new App(); new MyStack(app, "aws_instance"); new RemoteBackend(stack, { hostname: "app.terraform.io", organization: "<YOUR_ORG>", workspaces: { name: "learn-cdktf" } }); app.synth(); »Provision infrastructure Now that you have initialized the project with the AWS provider and written code to provision an instance, it's time to deploy it by running cdktf deploy. When CDKTF asks you to confirm the deploy, respond with a yes. $ cdktf deploy Deploying Stack: aws_instance Resources ✔ AWS_INSTANCE compute aws_instance.compute Summary: 1 created, 0 updated, 0 destroyed. Output: public_ip = 50.18.17.102 The cdktf deploy command runs terraform apply in the background. After the instance is created, visit the AWS EC2 Dashboard. Notice that the CDK deploy command printed out the public_ip output value, which matches the instance's public IPv4 address. »Change infrastructure by adding the Name tag Add a tag to the EC2 instance. Update the ec2.Instance in main.ts to add a Name tag. const instance = new ec2.Instance(this, "compute", { ami: "ami-01456a894f71116f2", instanceType: "t2.micro", + tags: { + Name: "CDKTF-Demo", + }, }); Deploy your updated application. Confirm your deploy by choosing Approve. $ cdktf deploy aws_instance Initializing the backend... aws_instance Successfully configured the backend "remote"! Terraform will automatically use this backend unless the backend configuration changes. aws_instance Initializing provider plugins... aws_instance - Finding hashicorp/aws versions matching "4.23.0"... aws_instance - Using hashicorp/aws v4.23.0 from the shared cache directory ##... Plan: 1 to add, 0 to change, 0 to destroy. Changes to Outputs: + public_ip = (known after apply) ##... Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: aws_instance public_ip = "54.219.167.18" aws_instance public_ip = 54.219.167.18 »Clean up your infrastructure Destroy the application by running cdktf destroy. Confirm your destroy by choosing Approve. $ cdktf destroy aws_instance Initializing the backend... aws_instance Initializing provider plugins... - Reusing previous version of hashicorp/aws from the dependency lock file aws_instance - Using previously-installed hashicorp/aws v4.23.0 ##... Plan: 0 to add, 0 to change, 1 to destroy. Changes to Outputs: - public_ip = "54.219.167.18" -> null ##... Plan: 0 to add, 0 to change, 1 to destroy. Changes to Outputs: - public_ip = "54.219.167.18" -> null aws_instance aws_instance.compute (compute): Destroying... [id=i-0fc8d2e3931b28db3] aws_instance aws_instance.compute (compute): Still destroying... [id=i-0fc8d2e3931b28db3, 10s elapsed] aws_instance aws_instance.compute (compute): Still destroying... [id=i-0fc8d2e3931b28db3, 20s elapsed] aws_instance aws_instance.compute (compute): Still destroying... [id=i-0fc8d2e3931b28db3, 30s elapsed] aws_instance aws_instance.compute (compute): Destruction complete after 30s aws_instance Destroy complete! Resources: 1 destroyed. Destroying your CDKTF application will not remove the Terraform Cloud workspace that stores your project's state. Log into the Terraform Cloud application and delete the workspace. »Next steps Now you have deployed, modified, and deleted an AWS EC2 instance using CDKTF! CDKTF is capable of much more. For example, you can: - Use the cdktf synthcommand to generate JSON which can be used by the Terraform executable to provision infrastructure using terraform applyand other Terraform commands. - Use Terraform providers and modules. - Use programming language features (like class inheritance) or data from other sources to augment your Terraform configuration. - Use CDKTF with Terraform Cloud for persistent storage of your state file and for team collaboration. For other examples, refer to the CDKTF documentation repository. In particular, check out the: - CDKTF Architecture documentation for an overview of CDKTF's architecture. - Community documentation to learn how to engage with the CDKTF developer community. - Review Example code in several programming languages.
https://learn.hashicorp.com/tutorials/terraform/cdktf-build?in=terraform/1-0
CC-MAIN-2022-40
refinedweb
1,676
51.75
Issue Type: New Feature Created: 2007-01-31T18:46:02.000+0000 Last Updated: 2009-01-09T12:36:18.000+0000 Status: Resolved Fix version(s): - 1.8.0 (30/Apr/09) Reporter: Philipp Führer (flipkick) Assignee: Ralph Schindler (ralph) Tags: - Zend_Db_Table Related issues: - ZF-1335 Attachments: i've wanted to count row results to build a nice helper which organizes my index-views more comfortable. so i've added .. <pre class="highlight"> /** * Fetches the number of row results. * * @return int The number of row results */ public function fetchCount($where = null) { return (int)$this->_fetch('Count', $where); } .. and changed .. <pre class="highlight"> // the FROM clause $select->from($this->_name, array_keys($this->_cols)); .. to .. <pre class="highlight"> //:
https://framework.zend.com/issues/browse/ZF-836
CC-MAIN-2017-22
refinedweb
116
60.92
Testing infrastructure for Zope and Plone projects. Project description Introduction Table of contents - Introduction - Installation and usage - Layers - Writing tests - Zope testing tools - Layer reference - Zope Component Architecture - Zope Security - Zope Publisher - ZODB - Zope 2 - Changelog - 5.1.1 (2017-04-19) - 5.1 (2017-04-13) - 5.0.0 (2016-02-19) - 4.2.0 (2016-02-18) - 4.1.0 (2016-01-08) - 4.0.15 (2015-08-14) - 4.0.14 (2015-07-29) - 4.0.13 (2015-03-13) - 4.0.12 (2014-09-07) - 4.0.11 (2014-02-22) - 4.0.10 (2014-02-11) - 4.0.9 (2014-01-28) - 4.0.8 (2013-03-05) - 4.0.7 (2012-12-09) - 4.0.6 (2012-10-15) - 4.0.5 (2012-10-15) - 4.0.4 (2012-08-04) - 4.0.3 (2011-11-24) - 4.0.2 (2011-08-31) - 4.0.1 - 2011-05-20 - 4.0 - 2011-05-13 - 4.0a6 - 2011-04-06 - 4.0a5 - 2011-03-02 - 4.0a4 - 2011-01-11 - 4.0a3 - 2010-12-14 - 1.0a2 - 2010-09-05 - 1.0a1 - 2010-08-01 - Detailed documentation - Layer base class - Zope Component Architecture layers - Security - Zope Publisher layers - Zope Object Database layers - Zope 2 layers: Bear in mind that different Python frameworks have slightly different takes on how to approach testing. Therefore, you may find examples that are different to those shown below. The core concepts should be consistent, however. Compatibility plone.testing 4.x has only been tested with Python 2.6 and 2 test case sets up, executes and makes assertions against a single scenario that bears testing. Test fixture The state used as a baseline for one or more tests. The test fixture is set up before each test is executed, and torn down afterwards. This is a pre-requisite for test isolation - the principle that tests should be independent of one another. Layer The configuration of a test fixture shared by a number of tests. All test cases that belong to a particular layer will be executed together. The layer is set up once before the tests are executed, and torn down once after. Layers may depend on one another. Any base layers are set up before and torn down after a particular child layer is used. The test runner will order test execution to minimise layer setup and tear-down. Test suite A collection of test cases (and layers) that are executed together. Test runner The program which executes tests. This is responsible for calling layer and test fixture set-up and tear-down methods. It also reports on the test run, usually by printing output to the console. Coverage To have confidence in your code, you should ensure it is adequately covered by tests. That is, each line of code, and each possible branching point (loops, if statements) should be executed by a test. This is known as coverage, and is normally measured as a percentage of lines of non-test code covered by tests. Coverage can be measured by the test runner, which keeps track of which lines of code were executed in a given test run. Doctest A style of testing where tests are written as examples that could be typed into the interactive Python interpreter. The test runner executes each example and checks the actual output against the expected output. Doctests can either be placed in the docstring of a method, or in a separate file. The use of doctests is largely a personal preference. Some developers like to write documentation as doctests, which has the advantage that code samples can be automatically tested for correctness. You can read more about doctests on Wikipedia. Installation and usage To use plone.testing', ] }, You can add other test-only dependencies to that list as well, of course. To run tests, you need a test runner. If you are using zc.buildout, you can install a test runner using the zc.recipe.testrunner recipe. For example, you could add the following to your buildout.cfg:: [test] recipe = zc.recipe.testrunner eggs = my.package [test] defaults = ['--auto-color', '--auto-progress'] You’ll also need to add this part to the parts list, of course:: [buildout] parts = ... test In this example, have listed a single package to test, called my.package, and asked for it to be installed with the [test] extra. This will install any regular dependencies (listed in the install_requires option in setup.py), as well as those in the list associated with the test key in the extras_require option. Note that it becomes important to properly list your dependencies here, because the test runner will only be aware of the packages explicitly listed, and their dependencies. For example, if your package depends on Zope 2, you need to list Zope2 in the install_requires list in setup.py; ditto for Plone, or indeed any other package you import from. Once you have re-run buildout, the test runner will be installed as bin/test (the executable name is taken from the name of the buildout part). You can execute it without arguments to run all tests of each egg listed in the eggs list: $ bin/test If you have listed several eggs, and you want to run the tests for a particular one, you can do: $ bin/test -s my.package If you want to run only a particular test within this package, use the -t option. This can be passed a regular expression matching either a doctest file name or a test method name.: $ bin/test -s my.package -t test_spaceship There are other command line options, which you can find by running: $ bin/test --help Also note the defaults option in the buildout configuration. This can be used to set default command line options. Some commonly useful options are shown above. Coverage reporting When writing tests, it is useful to know how well your tests cover your code. You can create coverage reports via the excellent coverage library. In order to use it, we need to install it and a reporting script: [buildout] parts = ... test coverage report [coverage] recipe = zc.recipe.egg eggs = coverage initialization = include = '--source=${buildout:directory}/src' sys.argv = sys.argv[:] + ['run', include, 'bin/test', '--all'] [report] recipe = zc.recipe.egg eggs = coverage scripts = coverage=report initialization = sys.argv = sys.argv[:] + ['html', '-i'] This will run the bin/test script with arguments like –all to run all layers. You can also specify no or some other arguments. It will place coverage reporting information in a .coverage file inside your buildout root. Via the --source argument you specify the directories containing code you want to cover. The coverage script would otherwise generate coverage information for all executed code, including other packages and even the standard library. Running the bin/report script will generate a human readable HTML representation of the run in the htmlcov directory. Open the contained index.html in a browser to see the result. If you want to generate an XML representation suitable for the Cobertura plugin of Hudson, you can add another part: [buildout] parts = ... report-xml [report-xml] recipe = zc.recipe.egg eggs = coverage scripts = coverage=report-xml initialization = sys.argv = sys.argv[:] + ['xml', '-i'] This will generate a coverage.xml file in the buildout root. Optional dependencies plone.testing comes with a core set of tools for managing layers, which depends only on zope.testing and (for Python < 2.7) unittest2. In addition, there are several layers and helper functions which can be used in your own tests (or as bases for your own layers). Some of these have deeper dependencies. However, these dependencies are optional and not installed by default. If you don’t use the relevant layers, you can safely ignore them. plone.testing does specify these dependencies, however, using the setuptools “extras” feature. You can depend on one or more extras in your own setup.py install_requires or extras_require option using the same square bracket notation shown for the [test] buildout part above. For example, if you need both the zca and publisher extras, you can have the following in your setup.py: extras_require = { 'test': [ 'plone.testing [zca, publisher]', ] }, The available extras are: zodb ZODB testing. Depends on ZODB3. The relevant layers and helpers are in the module plone.testing.zodb. zca Zope Component Architecture testing. Depends on core Zope Component Architecture packages such as zope.component and zope.event. The relevant layers and helpers are in the module plone.testing.zca. security Security testing. Depends on zope.security. The relevant layers and helpers are in the module plone.testing.security. publisher Zope Publisher testing. Depends on zope.publisher, zope.browsermenu, zope.browserpage, zope.browserresource and zope.security and sets up ZCML directives. The relevant layers and helpers are in the module plone.testing.publisher. z2 Zope 2 testing. Depends on the Zope2 egg, which includes all the dependencies of the Zope 2 application server. The relevant layers and helpers are in the module plone.testing.z2 Adding a test buildout to your package When creating re-usable, mostly stand-alone packages, it is often useful to be able to include a buildout with the package sources itself that can be used to create a test runner. This is a popular approach for many Zope packages, for example. In fact, plone.testing itself uses this kind of layout. To have a self-contained buildout in your package, the following is required: - You need a buildout.cfg at the root of the package. - In most cases, you always want a bootstrap.py file to make it easier for people to set up a fresh buildout. - Your package sources need to be inside a src directory. If you’re using namespace packages, that means the top level package should be in the src directory. - The src directory must be referenced in setup.py. For example, plone.testing has the following layout: plone.testing/ plone.testing/setup.py plone.testing/bootstrap.py plone.testing/buildout.cfg plone.testing/README.rst plone.testing/src/ plone.testing/src/plone plone.testing/src/plone/__init__.py plone.testing/src/plone/testing/ plone.testing/src/plone/testing/* In setup.py, the following arguments are required: packages=find_packages('src'), package_dir={'': 'src'}, This tells setuptools where to find the source code. The buildout.cfg for plone.testing looks like this: [buildout] extends = parts = coverage test report report-xml develop = . [test] recipe = collective.xmltestreport eggs = plone.testing [test] defaults = ['--auto-color', '--auto-progress'] [coverage] recipe = zc.recipe.egg eggs = coverage initialization = include = '--source=${buildout:directory}/src' sys.argv = sys.argv[:] + ['run', include, 'bin/test', '--all', '--xml'] [report] recipe = zc.recipe.egg eggs = coverage scripts = coverage=report initialization = sys.argv = sys.argv[:] + ['html', '-i'] [report-xml] recipe = zc.recipe.egg eggs = coverage scripts = coverage=report-xml initialization = sys.argv = sys.argv[:] + ['xml', '-i'] Obviously, you should adjust the package name in the eggs list and the version set in the extends line as appropriate. You can of course also add additional buildout parts, for example to include some development/debugging tools, or even a running application server for testing purposes. Hint: If you use this package layout, you should avoid checking any files or directories generated by buildout into your version control repository. You want to ignore: - .coverage - .installed.cfg - bin - coverage.xml - develop-eggs - htmlcov - parts - src/*.egg-info Layers In large part, plone.testing is about layers. It provides: - A set of layers (outlined below), which you can use or extend. - A set of tools for working with layers - A mini-framework to make it easy to write layers and manage shared resources associated with layers. We’ll discuss the last two items here, before showing how to write tests that use layers. Layer basics Layers are used to create test fixtures that are shared by multiple test cases. For example, if you are writing a set of integration tests, you may need to set up a database and configure various components to access that database. This type of test fixture setup can be resource-intensive and time-consuming. If it is possible to only perform the setup and tear-down once for a set of tests without losing isolation between those tests, test runs can often be sped up significantly. Layers also allow re-use of test fixtures and set-up/tear-down code. plone.testing provides a number of useful (but optional) layers that manage test fixtures for common Zope testing scenarios, letting you focus on the actual test authoring. At the most basic, a layer is an object with the following methods and attributes: setUp() Called by the test runner when the layer is to be set up. This is called exactly once for each layer used during a test run. tearDown() Called by the test runner when the layer is to be torn down. As with setUp(), this is called exactly once for each layer. testSetUp() Called immediately before each test case that uses the layer is executed. This is useful for setting up aspects of the fixture that are managed on a per-test basis, as opposed to fixture shared among all tests. testTearDown() Called immediately after each test case that uses the layer is executed. This is a chance to perform any post-test cleanup to ensure the fixture is ready for the next test. __bases__ A tuple of base layers. Each test case is associated with zero or one layer. (The syntax for specifying the layer is shown in the section “Writing tests” below.) All the tests associated with a given layer will be executed together. Layers can depend on one another (as indicated in the __bases__ tuple), allowing one layer to build on the fixture created by another. Base layers are set up before and torn down after their dependants. For example, if the test runner is executing some tests that belong to layer A, and some other tests that belong to layer B, both of which depend on layer C, the order of execution might be: 1. C.setUp() 1.1. A.setUp() 1.1.1. C.testSetUp() 1.1.2. A.testSetUp() 1.1.3. [One test using layer A] 1.1.4. A.testTearDown() 1.1.5. C.testTearDown() 1.1.6. C.testSetUp() 1.1.7. A.testSetUp() 1.1.8. [Another test using layer A] 1.1.9. A.testTearDown() 1.1.10. C.testTearDown() 1.2. A.tearDown() 1.3. B.setUp() 1.3.1. C.testSetUp() 1.3.2. B.testSetUp() 1.3.3. [One test using layer B] 1.3.4. B.testTearDown() 1.3.5. C.testTearDown() 1.3.6. C.testSetUp() 1.3.7. B.testSetUp() 1.3.8. [Another test using layer B] 1.3.9. B.testTearDown() 1.3.10. C.testTearDown() 1.4. B.tearDown() 2. C.tearDown() A base layer may of course depend on other base layers. In the case of nested dependencies like this, the order of set up and tear-down as calculated by the test runner is similar to the way in which Python searches for the method to invoke in the case of multiple inheritance. Writing layers The easiest way to create a new layer is to use the Layer base class and implement the setUp(), tearDown(), testSetUp() and testTearDown() methods as needed. All four are optional. The default implementation of each does nothing. By convention, layers are created in a module called testing.py at the top level of your package. The idea is that other packages that extend your package can re-use your layers for their own testing. A simple layer may look like this: >>> from plone.testing import Layer >>> class SpaceShip(Layer): ... ... def setUp(self): ... print "Assembling space ship" ... ... def tearDown(self): ... print "Disasembling space ship" ... ... def testSetUp(self): ... print "Fuelling space ship in preparation for test" ... ... def testTearDown(self): ... print "Emptying the fuel tank" Before this layer can be used, it must be instantiated. Layers are normally instantiated exactly once, since by nature they are shared between tests. This becomes important when you start to manage resources (such as persistent data, database connections, or other shared resources) in layers. The layer instance is conventionally also found in testing.py, just after the layer class definition.: >>> SPACE_SHIP = SpaceShip() Note Since the layer is instantiated in module scope, it will be created as soon as the testing module is imported. It is therefore very important that the layer class is inexpensive and safe to create. In general, you should avoid doing anything non-trivial in the __init__() method of your layer class. All setup should happen in the setUp() method. If you do implement __init__(), be sure to call the super version as well. The layer shown above did not have any base layers (dependencies). Here is an example of another layer that depends on it:: >>> class ZIGSpaceShip(Layer): ... defaultBases = (SPACE_SHIP,) ... ... def setUp(self): ... print "Installing main canon" >>> ZIG = ZIGSpaceShip() Here, we have explicitly listed the base layers on which ZIGSpaceShip depends, in the defaultBases attribute. This is used by the Layer base class to set the layer bases in a way that can also be overridden: see below. Note that we use the layer instance in the defaultBases tuple, not the class. Layer dependencies always pertain to specific layer instances. Above, we are really saying that instances of ZIGSpaceShip will, by default, require the SPACE_SHIP layer to be set up first. Note You may find it useful to create other layer base/mix-in classes that extend plone.testing.Layer and provide helper methods for use in your own layers. This is perfectly acceptable, but please do not confuse a layer base class used in this manner with the concept of a base layer as described above: - A class deriving from plone.testing.Layer is known as a layer class. It defines the behaviour of the layer by implementing the lifecycle methods setUp(), tearDown(), testSetUp() and/or testTearDown(). - A layer class can be instantiated into an actual layer. When a layer is associated with a test, it is the layer instance that is used. - The instance is usually a shared, module-global object, although in some cases it is useful to create copies of layers by instantiating the class more than once. - Subclassing an existing layer class is just straightforward OOP re-use: the test runner is not aware of the subclassing relationship. - A layer instance can be associated with any number of layer bases, via its __bases__ property (which is usually via the defaultBases variable in the class body and/or overridden using the bases argument to the Layer constructor). These bases are layer instances, not classes. The test runner will inspect the __bases__ attribute of each layer instance it sets up to calculate layer pre-requisites and dependencies. Also note that the zope.testing documentation contains examples of layers that are “old-style” classes where the setUp() and tearDown() methods are classmethod methods and class inheritance syntax is used to specify base layers. Whilst this pattern works, we discourage its use, because the classes created using this pattern are not really used as classes. The concept of layer bases is slightly different from class inheritance, and using the class keyword to create layers with base layers leads to a number of “gotchas” that are best avoided. Advanced - overriding bases In some cases, it may be useful to create a copy of a layer, but change its bases. One reason to do this may if you are re-using a layer from another module, and you need to change the order in which layers are set up and torn down. Normally, of course, you would just re-use the layer instance, either directly in a test, or in the defaultBases tuple of another layer, but if you need to change the bases, you can pass a new list of bases to the layer instance constructor:: >>> class CATSMessage(Layer): ... ... def setUp(self): ... print "All your base are belong to us" ... ... def tearDown(self): ... print "For great justice" >>> CATS_MESSAGE = CATSMessage() >>> ZERO_WING = ZIGSpaceShip(bases=(SPACE_SHIP, CATS_MESSAGE,), name="ZIGSpaceShip:CATSMessage") Please note that when overriding bases like this, the name argument is required. This is because each layer (using in a given test run) must have a unique name. The default is to use the layer class name, but this obviously only works for one instantiation. Therefore, plone.testing requires a name when setting bases explicitly. Please take great care when changing layer bases like this. The layer implementation may make assumptions about the test fixture that was set up by its bases. If you change the order in which the bases are listed, or remove a base altogether, the layer may fail to set up correctly. Also, bear in mind that the new layer instance is independent of the original layer instance, so any resources defined in the layer are likely to be duplicated. Layer combinations Sometimes, it is useful to be able to combine several layers into one, without adding any new fixture. One way to do this is to use the Layer class directly and instantiate it with new bases:: >>> COMBI_LAYER = Layer(bases=(CATS_MESSAGE, SPACE_SHIP,), name="Combi") Here, we have created a “no-op” layer with two bases: CATS_MESSAGE and SPACE_SHIP, named Combi. Please note that when using Layer directly like this, the name argument is required. This is to allow the test runner to identify the layer correctly. Normally, the class name of the layer is used as a basis for the name, but when using the Layer base class directly, this is unlikely to be unique or descriptive. Layer resources Many layers will manage one or more resources that are used either by other layers, or by tests themselves. Examples may include database connections, thread-local objects, or configuration data. plone.testing contains a simple resource storage abstraction that makes it easy to access resources from dependant layers or tests. The resource storage uses dictionary notation:: >>> class WarpDrive(object): ... """A shared resource""" ... ... def __init__(self, maxSpeed): ... self.maxSpeed = maxSpeed ... self.running = False ... ... def start(self, speed): ... if speed > self.maxSpeed: ... print "We need more power!" ... else: ... print "Going to warp at speed", speed ... self.running = True ... ... def stop(self): ... self.running = False >>> class ConstitutionClassSpaceShip(Layer): ... defaultBases = (SPACE_SHIP,) ... ... def setUp(self): ... self['warpDrive'] = WarpDrive(8.0) ... ... def tearDown(self): ... del self['warpDrive'] >>> CONSTITUTION_CLASS_SPACE_SHIP = ConstitutionClassSpaceShip() >>> class GalaxyClassSpaceShip(Layer): ... defaultBases = (CONSTITUTION_CLASS_SPACE_SHIP,) ... ... def setUp(self): ... # Upgrade the warp drive ... self.previousMaxSpeed = self['warpDrive'].maxSpeed ... self['warpDrive'].maxSpeed = 9.5 ... ... def tearDown(self): ... # Restore warp drive to its previous speed ... self['warpDrive'].maxSpeed = self.previousMaxSpeed >>> GALAXY_CLASS_SPACE_SHIP = GalaxyClassSpaceShip() As shown, layers (that derive from plone.testing.Layer) support item (dict-like) assignment, access and deletion of arbitrary resources under string keys. Important: If a layer creates a resource (by assigning an object to a key on self as shown above) during fixture setup-up, it must also delete the resource on tear-down. Set-up and deletion should be symmetric: if the resource is assigned during setUp() it should be deleted in tearDown(); if it’s created in testSetUp() it should be deleted in testTearDown(). A resource defined in a base layer is accessible from and through a child layer. If a resource is set on a child using a key that also exists in a base layer, the child version will shadow the base version until the child layer is torn down (presuming it deletes the resource, which it should), but the base layer version remains intact. Note Accessing a resource is analogous to accessing an instance variable. For example, if a base layer assigns a resource to a given key in its setUp() method, a child layer shadows that resource with another object under the same key, the shadowed resource will by used during the testSetUp() and testTearDown() lifecycle methods if implemented by the base layer as well. This will be the case until the child layer “pops” the resource by deleting it, normally in its tearDown(). Conversely, if (as shown above) the child layer accesses and modifies the object, it will modify the original. Note It is sometimes necessary (or desirable) to modify a shared resource in a child layer, as shown in the example above. In this case, however, it is very important to restore the original state when the layer is torn down. Otherwise, other layers or tests using the base layer directly may be affected in difficult-to-debug ways. If the same key is used in multiple base layers, the rules for choosing which version to use are similar to those that apply when choosing an attribute or method to use in the case of multiple inheritance. In the example above, we used the resource manager for the warpDrive object, but we assigned the previousMaxSpeed variable to self. This is because previousMaxSpeed is internal to the layer and should not be shared with any other layers that happen to use this layer as a base. Nor should it be used by any test cases. Conversely, warpDrive is a shared resource that is exposed to other layers and test cases. The distinction becomes even more important when you consider how a test case may access the shared resource. We’ll discuss how to write test cases that use layers shortly, but consider the following test:: >>> try: ... import unittest2 as unittest ... except ImportError: # Python 2.7 ... import unittest >>> class TestFasterThanLightTravel(unittest.TestCase): ... layer = GALAXY_CLASS_SPACE_SHIP ... ... def test_hyperdrive(self): ... warpDrive = self.layer['warpDrive'] ... warpDrive.start(8) This test needs access to the shared resource. It knows that its layer defines one called warpDrive. It does not know or care that the warp drive was actually initiated by the ConstitutionClassSpaceShip base layer. If, however, the base layer had assigned the resource as an instance variable, it would not inherit to child layers (remember: layer bases are not base classes!). The syntax to access it would be:: self.layer.__bases__[0].warpDrive which is not only ugly, but brittle: if the list of bases is changed, the expression above may lead to an attribute error. Writing tests Tests are usually written in one of two ways: As methods on a class that derives from unittest.TestCase (this is sometimes known as “Python tests” or “JUnit-style tests”), or using doctest syntax. You should realise that although the relevant frameworks (unittest, unittest2 and doctest) often talk about unit testing, these tools are also used to write integration and functional tests. The distinction between unit, integration and functional tests is largely practical: you use the same techniques to set up a fixture or write assertions for an integration test as you would for a unit test. The difference lies in what that fixture contains, and how you invoke the code under test. In general, a true unit test will have a minimal or no test fixture, whereas an integration test will have a fixture that contains the components your code is integrating with. A functional test will have a fixture that contains enough of the full system to execute and test an “end-to-end” scenario. Python tests Python tests use the Python unittest module, or its cousin unittest2 (see below). They should be placed in a module or package called tests for the test runner to pick them up. For small packages, a single module called tests.py will normally contain all tests. For larger packages, it is common to have a tests package that contains a number of modules with tests. These need to start with the word test, e.g. tests/test_foo.py or tests/test_bar.py. Don’t forget the __init__.py in the tests package, too! unittest2 In Python 2.7+, the unittest module has grown several new and useful features. To make use of these in Python 2.4, 2.5 and 2.6, an add-on module called unittest2 can be installed. plone.testing depends on unittest2 for these versions (and uses it for its own tests), so you will have access to it if you depend on plone.testing. We will use unittest2 for the examples in this document, but try to import it with an alias of unittest. This makes the code forward compatible with Python 2.7, where the built-in unittest module will have all the features of the unittest2 module. Please note that the zope.testing test runner at the time of writing (version 3.9.3) does not (yet) support the new setUpClass(), tearDownClass(), setUpModule() and tearDownModule() hooks from unittest2. This is not normally a problem, since we tend to use layers to manage complex fixtures, but it is important to be aware of nonetheless. Test modules, classes and functions Python tests are written with classes that derive from the base class TestCase. Each test is written as a method that takes no arguments and has a name starting with test. Other methods can be added and called from test methods as appropriate, e.g. to share some test logic. Two special methods, setUp() and tearDown(), can also be added. These will be called before or after each test, respectively, and provide a useful place to construct and clean up test fixtures without writing a custom layer. They are obviously not as re-usable as layers, though. Hint: Somewhat confusingly, the setUp() and tearDown() methods in a test case class are the equivalent of the testSetUp() and testTearDown() methods of a layer class. A layer can be specified by setting the layer class attribute to a layer instance. If layers are used in conjunction with setUp() and tearDown() methods in the test class itself, the class’ setUp() method will be called after the layer’s testSetUp() method, and the class’ tearDown() method will be called before the layer’s testTearDown() method. The TestCase base class contains a number of methods which can be used to write assertions. They all take the form self.assertSomething(), e.g. self.assertEqual(result, expectedValue). See the unittest and/or unittest2 documentation for details. Putting this together, let’s expand on our previous example unit test:: >>> try: ... import unittest2 as unittest ... except ImportError: # Python 2.7 ... import unittest >>> class TestFasterThanLightTravel(unittest.TestCase): ... layer = GALAXY_CLASS_SPACE_SHIP ... ... def setUp(self): ... self.warpDrive = self.layer['warpDrive'] ... self.warpDrive.stop() ... ... def tearDown(self): ... self.warpDrive.stop() ... ... def test_warp8(self): ... self.warpDrive.start(8) ... self.assertEqual(self.warpDrive.running, True) ... ... def test_max_speed(self): ... tooFast = self.warpDrive.maxSpeed + 0.1 ... self.warpDrive.start(tooFast) ... self.assertEqual(self.warpDrive.running, False) A few things to note: - The class derives from unittest.TestCase. - The layer class attribute is set to a layer instance (not a layer class!) defined previously. This would typically be imported from a testing module. - There are two tests here: test_warp8() and test_max_speed(). - We have used the self.assertEqual() assertion in both tests to check the result of executing the start() method on the warp drive. - We have used the setUp() method to fetch the warpDrive resource and ensure that it is stopped before each test is executed. Assigning a variable to self is a useful way to provide some state to each test method, though be careful about data leaking between tests: in general, you cannot predict the order in which tests will run, and tests should always be independent. - We have used the tearDown() method to make sure the warp drive is really stopped after each test. Test suites If you are using version 3.8.0 or later of zope.testing, a class like the one above is all you need: any class deriving from TestCase in a module with a name starting with test will be examined for test methods. Those tests are then collected into a test suite and executed. With older versions of zope.testing, you need to add a test_suite() function in each module that returns the tests in the test suite. The unittest module contains several tools to construct suites, but one of the simplest is to use the default test loader to load all tests in the current module:: >>> def test_suite(): ... return unittest.defaultTestLoader.loadTestsFromName(__name__) If you need to load tests explicitly, you can use the TestSuite API from the unittest module. For example:: >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... unittest.makeSuite(TestFasterThanLightTravel) ... ]) ... return suite The makeSuite() function creates a test suite from the test methods in the given class (which must derive from TestCase). This suite is then appended to an overall suite, which is returned from the test_suite() method. Note that addTests() takes a list of suites (which are coalesced into a single suite). We’ll add additional suites later. See the unittest documentation for other options. Note Adding a test_suite() method to a module disables automatic test discovery, even when using a recent version of zope.testing. Doctests Doctests can be written in two ways: as the contents of a docstring (usually, but not always, as a means of illustrating and testing the functionality of the method or class where the docstring appears), or as a separate text file. In both cases, the standard doctest module is used. See its documentation for details about doctest syntax and conventions. Doctests are used in two different ways: - To test documentation. That is, to ensure that code examples contained in documentation are valid and continue to work as the software is updated. - As a convenient syntax for writing tests. These two approaches use the same testing APIs and techniques. The difference is mostly about mindset. However, it is important to avoid falling into the trap that tests can substitute for good documentation or vice-a-versa. Tests usually need to systematically go through inputs and outputs and cover off a number of corner cases. Documentation should tell a compelling narrative and usually focus on the main usage scenarios. Trying to kill these two birds with one stone normally leaves you with an unappealing pile of stones and feathers. Docstring doctests Doctests can be added to any module, class or function docstring:: def canOutrunKlingons(warpDrive): """Find out of the given warp drive can outrun Klingons. Klingons travel at warp 8 >>> drive = WarpDrive(5) >>> canOutrunKlingons(drive) False We have to be faster than that to outrun them. >>> drive = WarpDrive(8.1) >>> canOutrunKlingons(drive) True We can't outrun them if we're travelling exactly the same speed >>> drive = WarpDrive(8.0) >>> canOutrunKlingons(drive) False """ return warpDrive.maxSpeed > 8.0 To add the doctests from a particular module to a test suite, you need to use the test_suite() function hook:: >>> import doctest >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... unittest.makeSuite(TestFasterThanLightTravel), # our previous test ... doctest.DocTestSuite('spaceship.utils'), ... ]) ... return suite Here, we have given the name of the module to check as a string dotted name. It is also possible to import a module and pass it as an object. The code above passes a list to addTests(), making it easy to add several sets of tests to the suite: the list can be constructed from calls to DocTestSuite(), DocFileSuite() (shown below) and makeSuite() (shown above). Remember that if you add a test_suite() function to a module that also has TestCase-derived python tests, those tests will no longer be automatically picked up by zope.testing, so you need to add them to the test suite explicitly. The example above illustrates a documentation-oriented doctest, where the doctest forms part of the docstring of a public module. The same syntax can be used for more systematic unit tests. For example, we could have a module spaceship.tests.test_spaceship with a set of methods like: # It's often better to put the import into each method, but here we've # imported the code under test at module level from spaceship.utils import WarpDrive, canOutrunKlingons def test_canOutrunKlingons_too_small(): """Klingons travel at warp 8.0 >>> drive = WarpDrive(7.9) >>> canOutrunKlingons(drive) False """ def test_canOutrunKlingons_big(): """Klingons travel at warp 8.0 >>> drive = WarpDrive(8.1) >>> canOutrunKlingons(drive) True """ def test_canOutrunKlingons_must_be_greater(): """Klingons travel at warp 8.0 >>> drive = WarpDrive(8.0) >>> canOutrunKlingons(drive) False """ Here, we have created a number of small methods that have no body. They merely serve as a container for docstrings with doctests. Since the module has no globals, each test must import the code under test, which helps make import errors more explicit. File doctests Doctests contained in a file are similar to those contained in docstrings. File doctests are better suited to narrative documentation covering the usage of an entire module or package. For example, if we had a file called spaceship.txt with doctests, we could add it to the test suite above with:: >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... unittest.makeSuite(TestFasterThanLightTravel), ... doctest.DocTestSuite('spaceship.utils'), ... doctest.DocFileSuite('spaceship.txt'), ... ]) ... return suite By default, the file is located relative to the module where the test suite is defined. You can use ../ (even on Windows) to reference the parent directory, which is sometimes useful if the doctest is inside a module in a tests package. Note If you put the doctest test_suite() method in a module inside a tests package, that module must have a name starting with test. It is common to have tests/test_doctests.py that contains a single test_suite() method that returns a suite of multiple doctests. It is possible to pass several tests to the suite, e.g.: >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... unittest.makeSuite(TestFasterThanLightTravel), ... doctest.DocTestSuite('spaceship.utils'), ... doctest.DocFileSuite('spaceship.txt', 'warpdrive.txt',), ... ]) ... return suite The test runner will report each file as a separate test, i.e. the DocFileSuite() above would add two tests to the overall suite. Conversely, a DocTestSuite() using a module with more than one docstring containing doctests will report one test for each eligible docstring. Doctest fixtures and layers A docstring doctest will by default have access to any global symbol available in the module where the docstring is found (e.g. anything defined or imported in the module). The global namespace can be overridden by passing a globs keyword argument to the DocTestSuite() constructor, or augmented by passing an extraglobs argument. Both should be given dictionaries. A file doctest has an empty globals namespace by default. Globals may be provided via the globs argument to DocFileSuite(). To manage a simple test fixture for a doctest, you can define set-up and tear-down functions and pass them as the setUp and tearDown arguments respectively. These are both passed a single argument, a DocTest object. The most useful attribute of this object is globs, which is a mutable dictionary of globals available in the test. For example:: >>> def setUpKlingons(doctest): ... doctest.globs['oldStyleKlingons'] = True >>> def tearDownKlingons(doctest): ... doctest.globs['oldStyleKlingons'] = False >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... doctest.DocTestSuite('spaceship.utils', setUp=setUpKlingons, tearDown=tearDownKlingons), ... ]) ... return suite The same arguments are available on the DocFileSuite() constructor. The set up method is called before each docstring in the given module for a DocTestSuite, and before each file given in a DocFileSuite. Of course, we often want to use layers with doctests too. Unfortunately, the unittest API is not aware of layers, so you can’t just pass a layer to the DocTestSuite() and DocFileSuite() constructors. Instead, you have to set a layer attribute on the suite after it has been constructed. Furthermore, to use layer resources in a doctest, we need access to the layer instance. The easiest way to do this is to pass it as a glob, conventionally called ‘layer’. This makes a global name ‘layer’ available in the doctest itself, giving access to the test’s layer instance. To make it easier to do this, plone.testing comes with a helper function called layered(). Its first argument is a test suite. The second argument is the layer. For example:: >>> from plone.testing import layered >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... layered(doctest.DocTestSuite('spaceship.utils'), layer=CONSTITUTION_CLASS_SPACE_SHIP), ... ]) ... return suite This is equivalent to:: >>> def test_suite(): ... suite = unittest.TestSuite() ... ... spaceshipUtilTests = doctest.DocTestSuite('spaceship.utils', globs={'layer': CONSTITUTION_CLASS_SPACE_SHIP}) ... spaceshipUtilTests.layer = CONSTITUTION_CLASS_SPACE_SHIP ... suite.addTest(spaceshipUtilTests) ... ... return suite (In this example, we’ve opted to use addTest() to add a single suite, instead of using addTests() to add multiple suites in one go). Zope testing tools Everything described so far in this document relies only on the standard unittest/unittest2 and doctest modules and zope.testing, and you can use this package without any other dependencies. However, there are also some tools (and layers) available in this package, as well as in other packages, that are specifically useful for testing applications that use various Zope-related frameworks. Test cleanup If a test uses a global registry, it may be necessary to clean that registry on set up and tear down of each test fixture. zope.testing provides a mechanism to register cleanup handlers - methods that are called to clean up global state. This can then be invoked in the setUp() and tearDown() fixture lifecycle methods of a test case.: >>> from zope.testing import cleanup Let’s say we had a global registry, implemented as a dictionary:: >>> SOME_GLOBAL_REGISTRY = {} If we wanted to clean this up on each test run, we could call clear() on the dict. Since that’s a no-argument method, it is perfect as a cleanup handler.: >>> cleanup.addCleanUp(SOME_GLOBAL_REGISTRY.clear) We can now use the cleanUp() method to execute all registered cleanups:: >>> cleanup.cleanUp() This call could be placed in a setUp() and/or tearDown() method in a test class, for example. Event testing You may wish to test some code that uses zope.event to fire specific events. zope.component provides some helpers to capture and analyse events.: >>> from zope.component import eventtesting To use this, you first need to set up event testing. Some of the layers shown below will do this for you, but you can do it yourself by calling the eventtesting.setUp() method, e.g. from your own setUp() method:: >>> eventtesting.setUp() This simply registers a few catch-all event handlers. Once you have executed the code that is expected to fire events, you can use the getEvents() helper function to obtain a list of the event instances caught:: >>> events = eventtesting.getEvents() You can now examine events to see what events have been caught since the last cleanup. getEvents() takes two optional arguments that can be used to filter the returned list of events. The first (event_type) is an interface. If given, only events providing this interface are returned. The second (filter) is a callable taking one argument. If given, it will be called with each captured event. Only those events where the filter function returns True will be included. The eventtesting module registers a cleanup action as outlined above. When you call cleanup.cleanUp() (or eventtesting.clearEvents(), which is the handler it registers), the events list will be cleared, ready for the next test. Here, we’ll do it manually:: >>> eventtesting.clearEvents() Mock requests Many tests require a request object, often with particular request/form variables set. zope.publisher contains a useful class for this purpose.: >>> from zope.publisher.browser import TestRequest A simple test request can be constructed with no arguments:: >>> request = TestRequest() To add a body input stream, pass a StringIO or file as the first parameter. To set the environment (request headers), use the environ keyword argument. To simulate a submitted form, use the form keyword argument:: >>> request = TestRequest(form=dict(field1='foo', field2=1)) Note that the form dict contains marshalled form fields, so modifiers like :int or :boolean should not be included in the field names, and values should be converted to the appropriate type. Registering components Many test fixtures will depend on having a minimum of Zope Component Architecture (ZCA) components registered. In normal operation, these would probably be registered via ZCML, but in a unit test, you should avoid loading the full ZCML configuration of your package (and its dependencies). Instead, you can use the Python API in zope.component to register global components instantly. The three most commonly used functions are:: >>> from zope.component import provideAdapter >>> from zope.component import provideUtility >>> from zope.component import provideHandler See the zope.component documentation for details about how to use these. When registering global components like this, it is important to avoid test leakage. The cleanup mechanism outlined above can be used to tear down the component registry between each test. See also the plone.testing.zca.UNIT_TESTING layer, described below, which performs this cleanup automatically via the testSetUp()/testTearDown() mechanism. Alternatively, you can “stack” a new global component registry using the plone.testing.zca.pushGlobalRegistry() and plone.testing.zca.popGlobalRegistry() helpers. This makes it possible to set up and tear down components that are specific to a given layer, and even allow tests to safely call the global component API (or load ZCML - see below) with proper tear-down. See the layer reference below for details. Integration tests often need to load ZCML configuration. This can be achieved using the zope.configuration API.: >>> from zope.configuration import xmlconfig The xmlconfig module contains two methods for loading ZCML. xmlconfig.string() can be used to load a literal string of ZCML:: >>> xmlconfig.string("""\ ... <configure xmlns="" package="plone.testing"> ... <include package="zope.component" file="meta.zcml" /> ... </configure> ... """) <zope.configuration.config.ConfigurationMachine object at ...> Note that we need to set a package (used for relative imports and file locations) explicitly here, using the package attribute of the <configure /> element. Also note that unless the optional second argument (context) is passed, a new configuration machine will be created every time string() is called. It therefore becomes necessary to explicitly <include /> the files that contain the directives you want to use (the one in zope.component is a common example). Layers that set up ZCML configuration may expose a resource which can be passed as the context parameter, usually called configurationContext - see below. To load the configuration for a particular package, use xmlconfig.file():: >>> import zope.component >>> context = xmlconfig.file('meta.zcml', zope.component) >>> xmlconfig.file('configure.zcml', zope.component, context=context) <zope.configuration.config.ConfigurationMachine object at ...> This takes two required arguments: the file name and the module relative to which it is to be found. Here, we have loaded two files: meta.zcml and configure.zcml. The first call to xmlconfig.file() creates and returns a configuration context. We re-use that for the subsequent invocation, so that the directives configured are available. Installing a Zope 2 product Some packages (including all those in the Products.* namespace) have the special status of being Zope 2 “products”. These are recorded in a special registry, and may have an initialize() hook in their top-level __init__.py that needs to be called for the package to be fully configured. Zope 2 will find and execute any products during startup. For testing, we need to explicitly list the products to install. Provided you are using plone.testing with Zope 2, you can use the following:: from plone.testing import z2 with z2.zopeApp() as app: z2.installProduct(app, 'Products.ZCatalog') This would normally be used during layer setUp(). Note that the basic Zope 2 application context must have been set up before doing this. The usual way to ensure this, is to use a layer that is based on z2.STARTUP - see below. To tear down such a layer, you should do:: from plone.testing import z2 with z2.zopeApp() as app: z2.uninstallProduct(app, 'Products.ZCatalog') Note: - Unlike the similarly-named function from ZopeTestCase, these helpers will work with any type of product. There is no distinction between a “product” and a “package” (and no installPackage()). However, you must use the full name (Products.*) when registering a product. - Installing a product in this manner is independent of ZCML configuration. However, it is almost always necessary to install the package’s ZCML configuration first. Functional testing For functional tests that aim to simulate the browser, you can use zope.testbrowser in a Python test or doctest:: >>> from zope.testbrowser.browser import Browser >>> browser = Browser() This provides a simple API to simulate browser input, without actually running a web server thread or scripting a live browser (as tools such as Windmill and Selenium do). The downside is that it is not possible to test JavaScript- dependent behaviour. If you are testing a Zope 2 application, you need to change the import location slightly, and pass the application root to the method:: from plone.testing.z2 import Browser browser = Browser(app) You can get the application root from the app resource in any of the Zope 2 layers in this package. Beyond that, the zope.testbrowser documentation should cover how to use the test browser. Hint: The test browser will usually commit at the end of a request. To avoid test fixture contamination, you should use a layer that fully isolates each test, such as the z2.INTEGRATION_TESTING layer described below. Layer reference plone.testing comes with several layers that are available to use directly or extend. These are outlined below. Zope Component Architecture The Zope Component Architecture layers are found in the module plone.testing.zca. If you depend on this, you can use the [zca] extra when depending on plone.testing. Unit testing This layer does not set up a fixture per se, but cleans up global state before and after each test, using zope.testing.cleanup as described above. The net result is that each test has a clean global component registry. Thus, it is safe to use the zope.component Python API (provideAdapter(), provideUtility(), provideHandler() and so on) to register components. Be careful with using this layer in combination with other layers. Because it tears down the component registry between each test, it will clobber any layer that sets up more permanent test fixture in the component registry. Event testing This layer extends the zca.UNIT_TESTING layer to enable the eventtesting support from zope.component. Using this layer, you can import and use zope.component.eventtesting.getEvent to inspect events fired by the code under test. See above for details. Layer cleanup This layer calls the cleanup functions from zope.testing.cleanup on setup and tear-down (but not between each test). It is useful as a base layer for other layers that need an environment as pristine as possible. Basic ZCML directives This registers a minimal set of ZCML directives, principally those found in the zope.component package, and makes available a configuration context. This allows custom ZCML to be loaded as described above. The configurationContext resource should be used when loading custom ZCML. To ensure isolation, you should stack this using the stackConfigurationContext() helper. For example, if you were writing a setUp() method in a layer that had zca.ZCML_DIRECTIVES as a base, you could do:: self['configurationContext'] = context = zca.stackConfigurationContext(self.get('configurationContext')) xmlconfig.string(someZCMLString, context=context) This will create a new configuration context with the state of the base layer’s context. On tear-down, you should delete the layer-specific resource:: del self['configurationContext'] Note If you fail to do this, you may get problems if your layer is torn down and then needs to be set up again later. See above for more details about loading custom ZCML in a layer or test. ZCML files helper class The ZCMLSandbox can be instantiated with a filename and package arguments: ZCML_SANDBOX = zca.ZCMLSandbox(filename="configure.zcml", package=my.package) That layer setUp loads the ZCML file. It avoids the need to using (and understand) configurationContext and globalRegistry until you need more flexibility or modularity for your layer and tests. See above for more details about loading custom ZCML in a layer or test. Helper functions The following helper functions are available in the plone.testing.zca module. stackConfigurationContext(context=None) Create and return a copy of the passed-in ZCML configuration context, or a brand new context if it is None. The purpose of this is to ensure that if a layer loads some ZCML files (using the zope.configuration API during) during its setUp(), the state of the configuration registry (which includes registered directives as well as a list of already imported files, which will not be loaded again even if explicitly included) can be torn down during tearDown(). The usual pattern is to keep the configuration context in a layer resource called configurationContext. In setUp(), you would then use:self['configurationContext'] = context = zca.stackConfigurationContext(self.get('configurationContext')) # use 'context' to load some ZCML In tearDown(), you can then simply do:del self['configurationContext'] pushGlobalRegistry(new=None) Create or obtain a stack of global component registries, and push a new registry to the top of the stack. The net result is that zope.component.getGlobalSiteManager() and (an un-hooked) getSiteManager() will return the new registry instead of the default, module-scope one. From this point onwards, calls to provideAdapter(), provideUtility() and other functions that modify the global registry will use the new registry. If new is not given, a new registry is created that has the previous global registry (site manager) as its sole base. This has the effect that registrations in the previous default global registry are still available, but new registrations are confined to the new registry. Warning: If you call this function, you must reciprocally call popGlobalRegistry(). That is, if you “push” a registry during layer setUp(), you must “pop” it during tearDown(). If you “push” during testSetUp(), you must “pop” during testTearDown(). If the calls to push and pop are not balanced, you will leave your global registry in a mess, which is not pretty. Returns the new default global site manager. Also causes the site manager hook from zope.component.hooks to be reset, clearing any local site managers as appropriate. popGlobalRegistry() Pop the global site registry, restoring the previous registry to be the default. Please heed the warning above: push and pop must be balanced. Returns the new default global site manager. Also causes the site manager hook from zope.component.hooks to be reset, clearing any local site managers as appropriate. Zope Security The Zope Security layers build can be found in the module plone.testing.security. If you depend on this, you can use the [security] extra when depending on plone.testing. Security checker isolation This layer ensures that security checkers used by zope.security are isolated. Any checkers set up in a child layer will be removed cleanly during tear-down. Helper functions The security checker isolation outlined above is managed using two helper functions found in the module plone.testing.security: pushCheckers() Copy the current set of security checkers for later tear-down. popCheckers() Restore the set of security checkers to the state of the most recent call to pushCheckers(). You must keep calls to pushCheckers() and popCheckers() in balance. That usually means that if you call the former during layer setup, you should call the latter during layer tear-down. Ditto for calls during test setup/tear-down or within tests themselves. Zope Publisher The Zope Publisher layers build on the Zope Component Architecture layers. They can be found in the module plone.testing.publisher. If you depend on this, you can use the [publisher] extra when depending on plone.testing. Publisher directives This layer extends the zca.ZCML_DIRECTIVES layer to install additional ZCML directives in the browser namespace (from zope.app.publisher.browser) as well as those from zope.security. This allows browser views, browser pages and other UI components to be registered, as well as the definition of new permissions. As with zca.ZCML_DIRECTIVES, you should use the configurationContext resource when loading ZCML strings or files, and the stackConfigurationRegistry() helper to create a layer-specific version of this resource resource. See above. ZODB The ZODB layers set up a test fixture with a persistent ZODB. The ZODB instance uses DemoStorage, so it will not interfere with any “live” data. ZODB layers can be found in the module plone.testing.zodb. If you depend on this, you can use the [zodb] extra when depending on plone.testing. Empty ZODB sandbox This layer sets up a simple ZODB sandbox using DemoStorage. The ZODB root object is a simple persistent mapping, available as the resource zodbRoot. The ZODB database object is available as the resource zodbDB. The connection used in the test is available as zodbConnection. Note that the zodbConnection and zodbRoot resources are created and destroyed for each test. You can use zodbDB (and the open() method) if you are writing a layer based on this one and need to set up a fixture during layer set up. Don’t forget to close the connection before concluding the test setup! A new transaction is begun for each test, and rolled back (aborted) on test tear-down. This means that so long as you don’t use transaction.commit() explicitly in your code, it should be safe to add or modify items in the ZODB root. If you want to create a test fixture with persistent data in your own layer based on EMPTY_ZODB, you can use the following pattern: from plone.layer import Layer from plone.layer import zodb class MyLayer(Layer): defaultBases = (zodb.EMPTY_ZODB,) def setUp(self): import transaction self['zodbDB'] = db = zodb.stackDemoStorage(self.get('zodbDB'), name='MyLayer') conn = db.open() root = conn.root() # modify the root object here transaction.commit() conn.close() def tearDown(self): self['zodbDB'].close() del self['zodbDB'] This shadows the zodbDB resource with a new database that uses a new DemoStorage stacked on top of the underlying database storage. The fixture is added to this storage and committed during layer setup. (The base layer test set-up/tear-down will still begin and abort a new transaction for each test). On layer tear-down, the database is closed and the resource popped, leaving the original zodbDB database with the original, pristine storage. Helper functions One helper function is available in the plone.testing.zodb module. stackDemoStorage(db=None, name=None) Create a new DemoStorage using the storage from the passed-in database as a base. If db is None, a brand new storage is created. A name can be given to uniquely identify the storage. It is optional, but it is often useful for debugging purposes to pass the name of the layer. The usual pattern is:def setUp(self): self['zodbDB'] = zodb.stackDemoStorage(self.get('zodbDB'), name='MyLayer') def tearDown(self): self['zodbDB'].close() del self['zodbDB'] This will shadow the zodbDB resource with an isolated DemoStorage, creating a new one if that resource does not already exist. All existing data continues to be available, but new changes are written to the stacked storage. On tear-down, the stacked database is closed and the resource removed, leaving the original data. Zope 2 The Zope 2 layers provide test fixtures suitable for testing Zope 2 applications. They set up a Zope 2 application root, install core Zope 2 products, and manage security. Zope 2 layers can be found in the module plone.testing.z2. If you depend on this, you can use the [z2] extra when depending on plone.testing. Startup This layer sets up a Zope 2 environment, and is a required base for all other Zope 2 layers. You cannot run two instances of this layer in parallel, since Zope 2 depends on some module-global state to run, which is managed by this layer. On set-up, the layer will configure a Zope environment with: Note The STARTUP layer is a useful base layer for your own fixtures, but should not be used directly, since it provides no test lifecycle or transaction management. See the “Integration test” and “Functional” test sections below for examples of how to create your own layers. - Debug mode enabled. - ZEO client cache disabled. - Some patches installed, which speed up Zope startup by disabling the help system and some other superfluous aspects of Zope. - One thread (this only really affects the ZSERVER and FTP_SERVER layers). - A pristine database using DemoStorage, exposed as the resource zodbDB. Zope is configured to use this database in a way that will also work if the zodbDB resource is shadowed using the pattern shown above in the description of the zodb.EMPTY_ZODB layer. - A fake hostname and port, exposed as the host and port resource, respectively. - A minimal set of products installed (Products.OFSP and Products.PluginIndexes, both required for Zope to start up). - A stacked ZCML configuration context, exposed as the resource configurationContext. As illustrated above, you should use the zca.stackConfigurationContext() helper to stack your own configuration context if you use this. - A minimal set of global Zope components configured. Note that unlike a “real” Zope site, products in the Products.* namespace are not automatically loaded, nor is any ZCML. Integration test This layer is intended for integration testing against the simple STARTUP fixture. If you want to create your own layer with a more advanced, shared fixture, see “Integration and functional testing with custom fixtures” below. For each test, it exposes the Zope application root as the resource app. This is wrapped in the request container, so you can do app.REQUEST to acquire a fake request, but the request is also available as the resource request. A new transaction is begun for each test and rolled back on test tear-down, meaning that so long as the code under test does not explicitly commit any changes, the test may modify the ZODB. Hint: If you want to set up a persistent test fixture in a layer based on this one (or z2.FUNCTIONAL_TESTING), you can stack a new DemoStorage in a shadowing zodbDB resource, using the pattern described above for the zodb.EMPTY_ZODB layer. Once you’ve shadowed the zodbDB resource, you can do (e.g. in your layer’s setUp() method):... with z2.zopeApp() as app: # modify the Zope application root The zopeApp() context manager will open a new connection to the Zope application root, accessible here as app. Provided the code within the with block does not raise an exception, the transaction will be committed and the database closed properly upon exiting the block. Functional testing This layer is intended for functional testing against the simple STARTUP fixture. If you want to create your own layer with a more advanced, shared fixture, see “Integration and functional testing with custom fixtures” below. As its name implies, this layer is intended mainly for functional end-to-end testing using tools like zope.testbrowser. See also the Browser object as described under “Helper functions” below. This layer is very similar to INTEGRATION_TESTING, but is not based on it. It sets up the same fixture and exposes the same resources. However, instead of using a simple transaction abort to isolate the ZODB between tests, it uses a stacked DemoStorage for each test. This is slower, but allows test code to perform and explicit commit, as will usually happen in a functional test. Integration and functional testing with custom fixtures If you want to extend the STARTUP fixture for use with integration or functional testing, you should use the following pattern: - Create a layer class and a “fixture” base layer instance that has z2.STARTUP (or some intermediary layer, such as z2.ZSERVER_FIXTURE or z2.FTP_SERVER_FIXTURE, shown below) as a base. - Create “end user” layers by instantiating the z2.IntegrationTesting and/or FunctionalTesting classes with this new “fixture” layer as a base. This allows the same fixture to be used regardless of the “style” of testing, minimising the amount of set-up and tear-down. The “fixture” layers manage the fixture as part of the layer lifecycle. The layer class (IntegrationTesting or FunctionalTesting), manages the test lifecycle, and the test lifecycle only. For example: from plone.testing import Layer, z2, zodb class MyLayer(Layer): defaultBases = (z2.STARTUP,) def setUp(self): # Set up the fixture here ... def tearDown(self): # Tear down the fixture here ... MY_FIXTURE = MyLayer() MY_INTEGRATION_TESTING = z2.IntegrationTesting(bases=(MY_FIXTURE,), name="MyFixture:Integration") MY_FUNCTIONAL_TESTING = z2.FunctionalTesting(bases=(MY_FIXTURE,), name="MyFixture:Functional") (Note that we need to give an explicit, unique name to the two layers that re-use the IntegrationTesting and FunctionalTesting classes.) In this example, other layers could extend the “MyLayer” fixture by using MY_FIXTURE as a base. Tests would use either MY_INTEGRATION_TESTING or MY_FUNCTIONAL_TESTING as appropriate. However, even if both these two layers were used, the fixture in MY_FIXTURE would only be set up once. Note If you implement the testSetUp() and testTearDown() test lifecycle methods in your “fixture” layer (e.g. in the the MyLayer class above), they will execute before the corresponding methods from IntegrationTesting and FunctionalTesting. Hence, they cannot use those layers’ resources (app and request). It may be preferable, therefore, to have your own “test lifecycle” layer classes that subclass IntegrationTesting and/or FunctionalTesting and call base class methods as appropriate. plone.app.testing takes this approach, for example. HTTP ZServer thread (fixture only) This layer extends the z2.STARTUP layer to start the Zope HTTP server in a separate thread. This means the test site can be accessed through a web browser, and can thus be used with tools like Windmill or Selenium. Note This layer is useful as a fixture base layer only, because it does not manage the test lifecycle. Use the ZSERVER layer if you want to execute functional tests against this fixture. The ZServer’s hostname (normally localhost) is available through the resource host, whilst the port it is running on is available through the resource port. Hint: Whilst the layer is set up, you can actually access the test Zope site through a web browser. The default URL will be. HTTP ZServer functional testing This layer provides the functional testing lifecycle against the fixture set up by the z2.ZSERVER_FIXTURE layer. You can use this to run “live” functional tests against a basic Zope site. You should not use it as a base. Instead, create your own “fixture” layer that extends z2.ZSERVER_FIXTURE, and then instantiate the FunctionalTesting class with this extended fixture layer as a base, as outlined above. FTP server thread (fixture only) This layer is the FTP server equivalent of the ZSERVER_FIXTURE layer. It can be used to functionally test Zope servers. Note This layer is useful as a fixture base layer only, because it does not manage the test lifecycle. Use the FTP_SERVER layer if you want to execute functional tests against this fixture. Hint: Whilst the layer is set up, you can actually access the test Zope site through an FTP client. The default URL will be. Warning Do not run the FTP_SERVER and ZSERVER layers concurrently in the same process. If you need both ZServer and FTPServer running together, you can subclass the ZServer layer class (like the FTPServer layer class does) and implement the setUpServer() and tearDownServer() methods to set up and close down two servers on different ports. They will then share a main loop. FTP server functional testing This layer provides the functional testing lifecycle against the fixture set up by the z2.FTP_SERVER_FIXTURE layer. You can use this to run “live” functional tests against a basic Zope site. You should not use it as a base. Instead, create your own “fixture” layer that extends z2.FTP_SERVER_FIXTURE, and then instantiate the FunctionalTesting class with this extended fixture layer as a base, as outlined above. Helper functions Several helper functions are available in the plone.testing.z2 module. zopeApp(db=None, conn=Non, environ=None) This function can be used as a context manager for any code that requires access to the Zope application root. By using it in a with block, the database will be opened, and the application root will be obtained and request-wrapped. When exiting the with block, the transaction will be committed and the database properly closed, unless an exception was raised:with z2.zopeApp() as app: # do something with app If you want to use a specific database or database connection, pass either the db or conn arguments. If the context manager opened a new connection, it will close it, but it will not close a connection passed with conn. To set keys in the (fake) request environment, pass a dictionary of environment values as environ. Note that zopeApp() should not normally be used in tests or test set-up/tear-down, because the INTEGRATOIN_TEST and FUNCTIONAL_TESTING layers both manage the application root (as the app resource) and close it for you. It is very useful in layer setup, however. installProduct(app, product, quiet=False) Install a Zope 2 style product, ensuring that its initialize() function is called. The product name must be the full dotted name, e.g. plone.app.portlets or Products.CMFCore. If quiet is true, duplicate registrations will be ignored silently, otherwise a message is logged. To get hold of the application root, passed as the app argument, you would normally use the zopeApp() context manager outlined above. uninstallProduct(app, product, quiet=False) This is the reciprocal of installProduct(), normally used during layer tear-down. Again, you should use zopeApp() to obtain the application root. login(userFolder, userName) Create a new security manager that simulates being logged in as the given user. userFolder is an acl_users object, e.g. app['acl_users'] for the root user folder. Simulate being the anonymous user by unsetting the security manager. setRoles(userFolder, userName, roles) Set the roles of the given user in the given user folder to the given list of roles. makeTestRequest() Create a fake Zope request. addRequestContainer(app, environ=None) Create a fake request and wrap the given object (normally an application root) in a RequestContainer with this request. This makes acquisition of app.REQUEST possible. To initialise the request environment with non-default values, pass a dictionary as environ. Note This method is rarely used, because both the zopeApp() context manager and the layer set-up/tear-down for z2.INTEGRATION_TESTING and z2.FUNCTIONAL_TESTING will wrap the app object before exposing it. Browser(app) Obtain a test browser client, for use with zope.testbrowser. You should use this in conjunction with the z2.FUNCTIONAL_TESTING layer or a derivative. You must pass the app root, usually obtained from the app resource of the layer, e.g.:app = self.layer['app'] browser = z2.Browser(app) You can then use browser as described in the zope.testbrowser documentation. Bear in mind that the test browser runs separately from the test fixture. In particular, calls to helpers such as login() or logout() do not affect the state that the test browser sees. If you want to set up a persistent fixture (e.g. test content), you can do so before creating the test browser, but you will need to explicitly commit your changes, with:import transaction transaction.commit() Changelog 5.1.1 (2017-04-19) - Do not break on import of plone.testing.z2 when using zope.testbrowser >= 5.0 which no longer depends on mechanize. 5.1 (2017-04-13) - Fix for ZODB 5: Abort transaction before DB close. [jensens, jimfulton] - Remove BBB code and imports for Zope < 2.13. [thet] - Fix issue, which prevented using layered-helper on Python 3. [datakurre] - Fix .z2.Startup.setUpZCML() to be compatible with Zope >= 4.0a2. [icemac] - Fix version pins on the package itself to be able to run the tests. [gforcada] 5.0.0 (2016-02-19) Rerelease of 4.2.0 as 5.0.0. The version 4.2.0 had changed error handling in the public api, causing exceptions where before everything continued to work. 4.2.0 (2016-02-18) New: - Refuse to work if user breaks test isolation. [do3cc] - Check that tests don’t run together with ZopeTestCase [do3cc] Fixes: - Fix tests for Zope 4, where the app root Control_Panel is not available anymore. [thet] 4.1.0 (2016-01-08) Fixes: - Rename all txt doctest files to rst. Reformat doctests. [thet] - PEP 8. [thet] - Depend on zope.testrunner, which was moved out from zope.testing.testrunner. [thet] - Add support for Zope 4. [thet] 4.0.15 (2015-08-14) - Prevent exception masking in finally clause of zopeApp context [do3cc] 4.0.14 (2015-07-29) - Rerelease for clarity due to double release of 4.0.13. [maurits] - Added multiinit-parameter to z2.installProduct to allow multiple initialize methods for a package [tomgross] 4.0.13 (2015-03-13) - Really fix not to depend on unittest2. [icemac] - Add tox.ini [icemac] 4.0.12 (2014-09-07) -] 4.0.11 (2014-02-22) - Fix z2.txt doctest for FTP_SERVER. [timo] 4.0.10 (2014-02-11) - Read ‘FTPSERVER_HOST’ and ‘FTPSERVER_PORT’ from the environment variables if possible. This allows us to run tests in parallel on CI servers. [timo] 4.0.9 (2014-01-28) - Replace deprecated Zope2VocabularyRegistry import. [timo] 4.0.8 (2013-03-05) - Factor test request creation out of addRequestContainer into makeTestRequest. [davisagli] 4.0.7 (2012-12-09) - Fix quoting of urls by the testbrowser. [do3cc] 4.0.6 (2012-10-15) - Update manifest.in to include content in src directory. [esteele] 4.0.5 (2012-10-15) - Fixed an issue where a query string would be unquoted twice; once while setting up the HTTP request and once in the handler (the publisher). [malthe] 4.0.4 (2012-08-04) - Fixed the cache reset code. In some situations the function does not have any defaults, so we shouldn’t try to clear out the app reference. [malthe] 4.0.3 (2011-11-24) - Fixed class names in documentation to match code. [icemac] 4.0.2 (2011-08-31) - The defaults of the ZPublisher.Publish.get_module_info function cache a reference to the app, so make sure that gets reset when tearing down the app. This fixes a problem where the testbrowser in the second functional layer to be set up accessed the database from the first functional layer. [davisagli] 4.0.1 - 2011-05-20 - Moved readme file containing tests into the package, so tests can be run from released source distributions. Closes. [hannosch] - Relicense under BSD license. See [davisagli] 4.0 - 2011-05-13 - Release 4.0 Final. [esteele] - Add MANIFEST.in. [WouterVH] 4.0a6 - 2011-04-06 - Fixed Browser cookies retrieval with Zope 2.13. [vincentfretin] - Add ZCMLSandbox layer to load a ZCML file; replaces setUpZcmlFiles and tearDownZcmlFiles helper functions. [gotcha] 4.0a5 - 2011-03-02 - Handle test failures due to userFolderAddUser returning the user object in newer versions of Zope. [esteele] - Add setUpZcmlFiles and tearDownZcmlFiles helpers to enable loading of ZCML files without too much boilerplate. [gotcha] - Add some logging. [gotcha] - Add the [security] extra, to provide tear-down of security checkers. [optilude] - Let the IntegrationTesting and FunctionalTesting lifecycle layers set up request PARENTS and, if present, wire up zope.globalrequest. [optilude] - Make the test browser support IStreamIterators [optilude] 4.0a4 - 2011-01-11 - Make sure ZCML doesn’t load during App startup in Zope 2.13. [davisagli] 4.0a3 - 2010-12-14 - Ignore the testinghome configuration setting if present. [stefan] - Use the new API for getting the packages_to_initialize list in Zope 2.13. [davisagli] - De-duplicate _register_monkies and _meta_type_regs in the correct module on teardown of the Startup layer in Zope 2.13. [davisagli] - Allow doctest suites from zope.testing to work with plone.testing.layer.layered. Previously, only doctest suites from the stdlib would see the layer global. [nouri] - Changed documentation to advertise the coverage library for running coverage tests instead of the built-in zope.testing support. This also avoids using z3c.coverage. The coverage tests now run at the same speed as a normal test run, making it more likely to get executed frequently. [hannosch] - Correct license to GPL version 2 only. [hannosch] - Fix some user id vs name confusion. [rossp] - Add the option to specify ZServer host and port through environment variables - ZSERVER_HOST and ZSERVER_PORT). [esteele] 1.0a2 - 2010-09-05 - Fix a problem that would cause <meta:redefinePermission /> to break. In particular fixes the use of the zope2.Public permission. [optilude] - Set the security implementation to “Python” for easier debugging during the z2.STARTUP layer. [optilude] - Initialize Five in the z2.Startup layer, pushing a Zope2VocabularyRegistry on layer set-up and restoring the previous one upon tear-down. [dukebody] 1.0a1 - 2010-08-01 - Initial release Detailed documentation Layer base class This package provides a layer base class which can be used by the test runner. It is available as a convenience import from the package root.: >>> from plone.testing import Layer A layer may be instantiated directly, though in this case the name argument is required (see below).: >>> NULL_LAYER = Layer(name="Null layer") This is not very useful on its own. It has an empty list of bases, and each of the layer lifecycle methods does nothing.: >>> NULL_LAYER.__bases__ () >>> NULL_LAYER.__name__ 'Null layer' >>> NULL_LAYER.__module__ 'plone.testing.layer' >>> NULL_LAYER.setUp() >>> NULL_LAYER.testSetUp() >>> NULL_LAYER.tearDown() >>> NULL_LAYER.testTearDown() Just about the only reason to use this directly (i.e. not as a base class) is to group together other layers.: >>> SIMPLE_LAYER = Layer(bases=(NULL_LAYER,), name="Simple layer", module='plone.testing.tests') Here, we’ve also set the module name directly. The default for all layers is to take the module name from the stack frame where the layer was instantiated. In doctests, that doesn’t work, though, so we fall back on the module name of the layer class. The two are often the same, of course. This layer now has the bases, name and module we set:: >>> SIMPLE_LAYER.__bases__ (<Layer 'plone.testing.layer.Null layer'>,) >>> SIMPLE_LAYER.__name__ 'Simple layer' >>> SIMPLE_LAYER.__module__ 'plone.testing.tests' The name argument is required when using Layer directly (but not when using a subclass):: >>> Layer((SIMPLE_LAYER,)) Traceback (most recent call last): ... ValueError: The `name` argument is required when instantiating `Layer` directly >>> class NullLayer(Layer): ... pass >>> NullLayer() <Layer '__builtin__.NullLayer'> Using Layer as a base class The usual pattern is to use Layer as a base class for a custom layer. This can then override the lifecycle methods as appropriate, as well as set a default list of bases.: >>> class BaseLayer(Layer): ... ... def setUp(self): ... print "Setting up base layer" ... ... def tearDown(self): ... print "Tearing down base layer" >>> BASE_LAYER = BaseLayer() The layer name and module are taken from the class.: >>> BASE_LAYER.__bases__ () >>> BASE_LAYER.__name__ 'BaseLayer' >>> BASE_LAYER.__module__ '__builtin__' We can now create a new layer that has this one as a base. We can do this in the instance constructor, as shown above, but the most common pattern is to set the default bases in the class body, using the variable defaultBases. We’ll also set the default name explicitly here by passing a name to the the super-constructor. This is mostly cosmetic, but may be desirable if the class name would be misleading in the test runner output.: >>> class ChildLayer(Layer): ... defaultBases = (BASE_LAYER,) ... ... def __init__(self, bases=None, name='Child layer', module=None): ... super(ChildLayer, self).__init__(bases, name, module) ... ... def setUp(self): ... print "Setting up child layer" ... ... def tearDown(self): ... print "Tearing down child layer" >>> CHILD_LAYER = ChildLayer() Notice how the bases have now been set using the value in defaultBases.: >>> CHILD_LAYER.__bases__ (<Layer '__builtin__.BaseLayer'>,) >>> CHILD_LAYER.__name__ 'Child layer' >>> CHILD_LAYER.__module__ '__builtin__' Overriding the default list of bases We can override the list of bases on a per-instance basis. This may be dangerous, i.e. the layer is likely to expect that its bases are set up. Sometimes, it may be useful to inject a new base, however, especially when re-using layers from other packages. The new list of bases is passed to the constructor. When creating a second instance of a layer (most layers are global singletons created only once), it’s useful to give the new instance a unique name, too.: >>> NEW_CHILD_LAYER = ChildLayer(bases=(SIMPLE_LAYER, BASE_LAYER,),, <Layer '__builtin__.BaseLayer'>) >>> NEW_CHILD_LAYER.__name__ 'New child' >>> NEW_CHILD_LAYER.__module__ '__builtin__' Inconsistent bases Layer bases are maintained in an order that is semantically equivalent to the “method resolution order” Python maintains for base classes. We can get this from the baseResolutionOrder attribute:: >>> CHILD_LAYER.baseResolutionOrder (<Layer '__builtin__.Child layer'>, <Layer '__builtin__.BaseLayer'>) >>> NEW_CHILD_LAYER.baseResolutionOrder (<Layer '__builtin__.New child'>, <Layer 'plone.testing.tests.Simple layer'>, <Layer 'plone.testing.layer.Null layer'>, <Layer '__builtin__.BaseLayer'>) As with Python classes, it is possible to construct an invalid set of bases. In this case, layer instantiation will fail.: >>> INCONSISTENT_BASE1 = Layer(name="Inconsistent 1") >>> INCONSISTENT_BASE2 = Layer((INCONSISTENT_BASE1,), name="Inconsistent 1") >>> INCONSISTENT_BASE3 = Layer((INCONSISTENT_BASE1, INCONSISTENT_BASE2,), name="Inconsistent 1") Traceback (most recent call last): ... TypeError: Inconsistent layer hierarchy! Using the resource manager Layers are also resource managers. Resources can be set, retrieved and deleted using dictionary syntax. Resources in base layers are available in child layers. When an item is set on a child layer, it shadows any items with the same key in any base layer (until it is deleted), but the original item still exists. Let’s create a somewhat complex hierarchy of layers that all set resources under a key 'foo' in their setUp() methods.: >>> class Layer1(Layer): ... def setUp(self): ... self['foo'] = 1 ... def tearDown(self): ... del self['foo'] >>> LAYER1 = Layer1() >>> class Layer2(Layer): ... defaultBases = (LAYER1,) ... def setUp(self): ... self['foo'] = 2 ... def tearDown(self): ... del self['foo'] >>> LAYER2 = Layer2() >>> class Layer3(Layer): ... def setUp(self): ... self['foo'] = 3 ... def tearDown(self): ... del self['foo'] >>> LAYER3 = Layer3() >>> class Layer4(Layer): ... defaultBases = (LAYER2, LAYER3,) ... def setUp(self): ... self['foo'] = 4 ... def tearDown(self): ... del self['foo'] >>> LAYER4 = Layer4() **Important:** Resources that are created in ``setUp()`` must be deleted in ``tearDown()``. Similarly, resources created in ``testSetUp()`` must be deleted in ``testTearDown()``. This ensures resources are properly stacked and do not leak between layers. If a test was using LAYER4, the test runner would call each setup step in turn, starting with the “deepest” layer. We’ll simulate that here, so that each of the resources is created.: >>> LAYER1.setUp() >>> LAYER2.setUp() >>> LAYER3.setUp() >>> LAYER4.setUp() The layers are ordered in a known “resource resolution order”, which is used to determine in which order the layers shadow one another. This is based on the same algorithm as Python’s method resolution order.: >>> LAYER4.baseResolutionOrder (<Layer '__builtin__.Layer4'>, <Layer '__builtin__.Layer2'>, <Layer '__builtin__.Layer1'>, <Layer '__builtin__.Layer3'>) When fetching and item from a layer, it will be obtained according to the resource resolution order.: >>> LAYER4['foo'] 4 This is not terribly interesting, since LAYER4 has the resource 'foo' set directly. Let’s tear down the layer (which deletes the resource) and see what happens.: >>> LAYER4.tearDown() >>> LAYER4['foo'] 2 We can continue up the chain:: >>> LAYER2.tearDown() >>> LAYER4['foo'] 1 >>> LAYER1.tearDown() >>> LAYER4['foo'] 3 Once we’ve deleted the last key, we’ll get a KeyError:: >>> LAYER3.tearDown() >>> LAYER4['foo'] Traceback (most recent call last): ... KeyError: 'foo' To guard against this, we can use the get() method.: >>> LAYER4.get('foo', -1) -1 We can also test with ‘in’:: >>> 'foo' in LAYER4 False To illustrate that this indeed works, let’s set the resource back on one of the bases.: >>> LAYER3['foo'] = 10 >>> LAYER4.get('foo', -1) 10 Let’s now consider a special case: a base layer sets up a resource in layer setup, and uses it in test setup. A child layer then shadows this resource in its own layer setup method. In this case, we want the base layer’s testSetUp() to use the shadowed version that the child provided. (This is similar to how instance variables work: a base class may set an attribute on self and use it in a method. If a subclass then sets the same attribute to a different value and the base class method is called on an instance of the subclass, the base class attribute is used). Hint: If you definitely need to access the “original” resource in your testSetUp()/testTearDown() methods, you can store a reference to the resource as a layer instance variable:self.someResource = self['someResource'] = SomeResource() self.someResource will now be the exact resource created here, whereas self['someResource'] will retain the layer shadowing semantics. In most cases, you probably don’t want to do this, allowing child layers to supply overridden versions of resources as appropriate. First, we’ll create some base layers. We want to demonstrate having two “branches” of bases that both happen to define the same resource.: >>> class ResourceBaseLayer1(Layer): ... def setUp(self): ... self['resource'] = "Base 1" ... def testSetUp(self): ... print self['resource'] ... def tearDown(self): ... del self['resource'] >>> RESOURCE_BASE_LAYER1 = ResourceBaseLayer1() >>> class ResourceBaseLayer2(Layer): ... defaultBases = (RESOURCE_BASE_LAYER1,) ... def testSetUp(self): ... print self['resource'] >>> RESOURCE_BASE_LAYER2 = ResourceBaseLayer2() >>> class ResourceBaseLayer3(Layer): ... def setUp(self): ... self['resource'] = "Base 3" ... def testSetUp(self): ... print self['resource'] ... def tearDown(self): ... del self['resource'] >>> RESOURCE_BASE_LAYER3 = ResourceBaseLayer3() We’ll then create the child layer that overrides this resource.: >>> class ResourceChildLayer(Layer): ... defaultBases = (RESOURCE_BASE_LAYER2, RESOURCE_BASE_LAYER3) ... def setUp(self): ... self['resource'] = "Child" ... def testSetUp(self): ... print self['resource'] ... def tearDown(self): ... del self['resource'] >>> RESOURCE_CHILD_LAYER = ResourceChildLayer() We’ll first set up the base layers on their own and simulate two tests. A test with RESOURCE_BASE_LAYER1 only would look like this:: >>> RESOURCE_BASE_LAYER1.setUp() >>> RESOURCE_BASE_LAYER1.testSetUp() Base 1 >>> RESOURCE_BASE_LAYER1.testTearDown() >>> RESOURCE_BASE_LAYER1.tearDown() A test with RESOURCE_BASE_LAYER2 would look like this:: >>> RESOURCE_BASE_LAYER1.setUp() >>> RESOURCE_BASE_LAYER2.setUp() >>> RESOURCE_BASE_LAYER1.testSetUp() Base 1 >>> RESOURCE_BASE_LAYER2.testSetUp() Base 1 >>> RESOURCE_BASE_LAYER2.testTearDown() >>> RESOURCE_BASE_LAYER1.testTearDown() >>> RESOURCE_BASE_LAYER2.tearDown() >>> RESOURCE_BASE_LAYER1.tearDown() A test with RESOURCE_BASE_LAYER3 only would look like this:: >>> RESOURCE_BASE_LAYER3.setUp() >>> RESOURCE_BASE_LAYER3.testSetUp() Base 3 >>> RESOURCE_BASE_LAYER3.testTearDown() >>> RESOURCE_BASE_LAYER3.tearDown() Now let’s set up the child layer and simulate another test. We should now be using the shadowed resource.: >>> RESOURCE_BASE_LAYER1.setUp() >>> RESOURCE_BASE_LAYER2.setUp() >>> RESOURCE_BASE_LAYER3.setUp() >>> RESOURCE_CHILD_LAYER.setUp() >>> RESOURCE_BASE_LAYER1.testSetUp() Child >>> RESOURCE_BASE_LAYER2.testSetUp() Child >>> RESOURCE_BASE_LAYER3.testSetUp() Child >>> RESOURCE_CHILD_LAYER.testSetUp() Child >>> RESOURCE_CHILD_LAYER.testTearDown() >>> RESOURCE_BASE_LAYER3.testTearDown() >>> RESOURCE_BASE_LAYER2.testTearDown() >>> RESOURCE_BASE_LAYER1.testTearDown() Finally, we’ll tear down the child layer again and simulate another test. we should have the original resources back. Note that the first and third layers no longer share a resource, since they don’t have a common ancestor.: >>> RESOURCE_CHILD_LAYER.tearDown() >>> RESOURCE_BASE_LAYER1.testSetUp() Base 1 >>> RESOURCE_BASE_LAYER2.testSetUp() Base 1 >>> RESOURCE_BASE_LAYER2.testTearDown() >>> RESOURCE_BASE_LAYER1.testTearDown() >>> RESOURCE_BASE_LAYER3.testSetUp() Base 3 >>> RESOURCE_BASE_LAYER3.testTearDown() Finally, we’ll tear down the remaining layers..: >>> RESOURCE_BASE_LAYER3.tearDown() >>> RESOURCE_BASE_LAYER2.tearDown() >>> RESOURCE_BASE_LAYER1.tearDown() Asymmetric deletion It is an error to create or shadow a resource in a set-up lifecycle method and not delete it again in the tear-down. It is also an error to delete a resource that was not explicitly created. These two layers break those roles:: >>> class BadLayer1(Layer): ... def setUp(self): ... pass ... def tearDown(self): ... del self['foo'] >>> BAD_LAYER1 = BadLayer1() >>> class BadLayer2(Layer): ... defaultBases = (BAD_LAYER1,) ... def setUp(self): ... self['foo'] = 1 ... self['bar'] = 2 >>> BAD_LAYER2 = BadLayer2() Let’s simulate a test that uses BAD_LAYER2:: >>> BAD_LAYER1.setUp() >>> BAD_LAYER2.setUp() >>> BAD_LAYER1.testSetUp() >>> BAD_LAYER2.testSetUp() >>> BAD_LAYER2.testTearDown() >>> BAD_LAYER1.testTearDown() >>> BAD_LAYER2.tearDown() >>> BAD_LAYER1.tearDown() Traceback (most recent call last): ... KeyError: 'foo' Here, we’ve got an error in the base layer. This is because the resource is actually associated with the layer that first created it, in this case BASE_LAYER2. This one remains intact and orphaned:: >>> 'foo' in BAD_LAYER2._resources True >>> 'bar' in BAD_LAYER2._resources True Doctest layer helper The doctest module is not aware of zope.testing’s layers concept. Therefore, the syntax for creating a doctest with a layer and adding it to a test suite is somewhat contrived: the test suite has to be created first, and then the layer attribute set on it:: >>> class DoctestLayer(Layer): ... pass >>> DOCTEST_LAYER = DoctestLayer() >>> try: ... import unittest2 as unittest ... except ImportError: # Python 2.7 ... import unittest >>> import doctest >>> def test_suite(): ... suite = unittest.TestSuite() ... layerDoctest = doctest.DocFileSuite('layer.rst', package='plone.testing') ... layerDoctest.layer = DOCTEST_LAYER ... suite.addTest(layerDoctest) ... return suite >>> suite = test_suite() >>> tests = list(suite) >>> len(tests) 1 >>> tests[0].layer is DOCTEST_LAYER True To make this a little easier - especially when setting up multiple tests - a helper function called layered is provided:: >>> from plone.testing import layered >>> def test_suite(): ... suite = unittest.TestSuite() ... suite.addTests([ ... layered(doctest.DocFileSuite('layer.rst', package='plone.testing'), layer=DOCTEST_LAYER), ... # repeat with more suites if necessary ... ]) ... return suite This does the same as the sample above.: >>> suite = test_suite() >>> tests = list(suite) >>> len(tests) 1 >>> tests[0].layer is DOCTEST_LAYER True In addition, a ‘layer’ glob is added to each test in the suite. This allows the test to access layer resources.: >>> len(list(tests[0])) 1 >>> list(tests[0])[0]._dt_test.globs['layer'] is DOCTEST_LAYER True Zope Component Architecture layers The ZCA layers are found in the module plone.testing.zca:: >>> from plone.testing import zca For testing, we need a testrunner:: >>> from zope.testrunner import runner Unit testing The UNIT_TESTING layer is used to set up a clean component registry between each test. It uses zope.testing.cleanup to clean up all global state. It has no bases:: >>> "%s.%s" % (zca.UNIT_TESTING.__module__, zca.UNIT_TESTING.__name__,) 'plone.testing.zca.UnitTesting' >>> zca.UNIT_TESTING.__bases__ () The component registry is cleaned up between each test.: >>>> Layer setup does nothing.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, zca.UNIT_TESTING, setupLayers) Set up plone.testing.zca.UnitTesting in ... seconds. Let’s now simulate a test. Before any test setup has happened, our previously registered utility is still there.: >>> queryUtility(Interface, name="test-dummy") <Dummy> On test setup, it disappears.: >>> zca.UNIT_TESTING.testSetUp() >>> queryUtility(Interface, name="test-dummy") is None True The test would now execute. It may register some components.: >>> provideUtility(DummyUtility("Dummy2"), provides=Interface, name="test-dummy") >>> queryUtility(Interface, name="test-dummy") <Dummy2> On test tear-down, this disappears.: >>> zca.UNIT_TESTING.testTearDown() >>> queryUtility(Interface, name="test-dummy") is None True Layer tear-down does nothing.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.zca.UnitTesting in ... seconds. Event testing The EVENT_TESTING layer extends the UNIT_TESTING layer to add the necessary registrations for zope.component.eventtesting to work.: >>> "%s.%s" % (zca.EVENT_TESTING.__module__, zca.EVENT_TESTING.__name__,) 'plone.testing.zca.EventTesting' >>> zca.EVENT_TESTING.__bases__ (<Layer 'plone.testing.zca.UnitTesting'>,) Before the test, the component registry is empty and getEvents() returns nothing, even if an event is fired.: >>> from zope.component.eventtesting import getEvents >>> class DummyEvent(object): ... def __repr__(self): ... return "<Dummy event>" >>> from zope.event import notify >>> notify(DummyEvent()) >>> getEvents() [] Layer setup does nothing.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, zca.EVENT_TESTING, setupLayers) Set up plone.testing.zca.UnitTesting in ... seconds. Set up plone.testing.zca.EventTesting in ... seconds. Let’s now simulate a test. On test setup, the event testing list is emptied.: >>> zca.UNIT_TESTING.testSetUp() >>> zca.EVENT_TESTING.testSetUp() >>> getEvents() [] The test would now execute. It may fire some events, which would show up in the event testing list.: >>> notify(DummyEvent()) >>> getEvents() [<Dummy event>] On test tear-down, the list is emptied again:: >>> zca.EVENT_TESTING.testTearDown() >>> zca.UNIT_TESTING.testTearDown() >>> getEvents() [] Layer tear-down does nothing.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.zca.EventTesting in ... seconds. Tear down plone.testing.zca.UnitTesting in ... seconds. Layer cleanup The LAYER_CLEANUP layer is used to set up a clean component registry at the set-up and tear-down of a layer. It uses zope.testing.cleanup to clean up all global state. It has no bases:: >>> "%s.%s" % (zca.LAYER_CLEANUP.__module__, zca.LAYER_CLEANUP.__name__,) 'plone.testing.zca.LayerCleanup' >>> zca.LAYER_CLEANUP.__bases__ () The component registry is cleaned up on layer set-up and tear-down (but not between tests).: >>>> >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, zca.LAYER_CLEANUP, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. >>> queryUtility(Interface, name="test-dummy") is None True A sub-layer may register additional components:: >>> provideUtility(DummyUtility("Dummy2"), provides=Interface, name="test-dummy2") Let’s now simulate a test. Test setup and tear-down does nothing.: >>> zca.LAYER_CLEANUP.testSetUp() >>> queryUtility(Interface, name="test-dummy") is None True >>> queryUtility(Interface, name="test-dummy2") <Dummy2> >>> zca.LAYER_CLEANUP.testTearDown() >>> queryUtility(Interface, name="test-dummy") is None True >>> queryUtility(Interface, name="test-dummy2") <Dummy2> On tear-down, the registry is cleaned again.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.zca.LayerCleanup in ... seconds. >>> queryUtility(Interface, name="test-dummy") is None True >>> queryUtility(Interface, name="test-dummy2") is None True Basic ZCML directives The ZCML_DIRECTIVES layer creates a ZCML configuration context with the basic zope.component directives available. It extends the LAYER_CLEANUP layer.: >>> "%s.%s" % (zca.ZCML_DIRECTIVES.__module__, zca.ZCML_DIRECTIVES.__name__,) 'plone.testing.zca.ZCMLDirectives' >>> zca.ZCML_DIRECTIVES.__bases__ (<Layer 'plone.testing.zca.LayerCleanup'>,) Before the test, we cannot use e.g. a <utility /> directive without loading the necessary meta.zcml files.: >>> from zope.configuration import xmlconfig >>> xmlconfig.string("""\ ... <configure package="plone.testing" xmlns=""> ... <utility factory=".tests.DummyUtility" provides="zope.interface.Interface" name="test-dummy" /> ... </configure>""") Traceback (most recent call last): ... ZopeXMLConfigurationError: File "<string>", line 2.4 ConfigurationError: ('Unknown directive', u'', u'utility') Layer setup creates a configuration context we can use to load further configuration.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, zca.ZCML_DIRECTIVES, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.zca.ZCMLDirectives in ... seconds. Let’s now simulate a test that uses this configuration context to load the same ZCML string.: >>> zca.ZCML_DIRECTIVES.testSetUp() >>> context = zca.ZCML_DIRECTIVES['configurationContext'] # would normally be self.layer['configurationContext'] >>> xmlconfig.string("""\ ... <configure package="plone.testing" xmlns=""> ... <utility factory=".tests.DummyUtility" provides="zope.interface.Interface" name="test-dummy" /> ... </configure>""", context=context) is context True The utility is now registered:: >>> queryUtility(Interface, name="test-dummy") <Dummy utility> >>> zca.UNIT_TESTING.testTearDown() Note that normally, we’d combine this with the UNIT_TESTING layer to tear down the component architecture as well. Layer tear-down deletes the configuration context.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.zca.ZCMLDirectives in ... seconds. >>> zca.ZCML_DIRECTIVES.get('configurationContext', None) is None True Configuration registry sandboxing For simple unit tests, the full cleanup performed between each test using the UNIT_TESTING layer is undoubtedly the safest and most convenient way to ensure proper isolation of tests using the global component architecture. However, if you are writing a complex layer that sets up a lot of components, you may wish to keep some components registered at the layer level, whilst still allowing tests and sub-layers to register their own components in isolation. This is a tricky problem, because the default ZCML directives and APIs (provideAdapter(), provideUtility() and so on) explicitly work on a single global adapter registry object. To get around this, you can use two helper methods in the zca module to push a new global component registry before registering components, and pop the registry after. Registries are stacked, so the components registered in a “lower” registry are automatically available in a “higher” registry. Let’s illustrate this with a layer that stacks two new global registries. The first registry is specific to the layer, and is used to house the components registered at the layer level. The second registry is set up and torn down for each test, allowing tests to register their own components freely. First, we’ll create a simple dummy utility to illustrate registrations.: >>> from zope.interface import Interface, implements >>> class IDummyUtility(Interface): ... pass >>> class DummyUtility(object): ... implements(IDummyUtility) ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return "<DummyUtility %s>" % self.name The two key methods are: zca.pushGlobalRegistry(), which creates a new global registry. zca.popGlobalRegistry(), which restores the previous global registry. Warning: You must balance your calls to these methods. If you call pushGlobalRegistry() in setUp(), call popGlobalRegistry() in tearDown(). Ditto for testSetUp() and testTearDown(). Let’s now create our layer.: >>> from zope.component import provideUtility >>> from plone.testing import Layer >>> from plone.testing import zca >>> class ComponentSandbox(Layer): ... def setUp(self): ... zca.pushGlobalRegistry() ... provideUtility(DummyUtility("layer"), name="layer") ... def tearDown(self): ... zca.popGlobalRegistry() ... def testSetUp(self): ... zca.pushGlobalRegistry() ... def testTearDown(self): ... zca.popGlobalRegistry() >>> COMPONENT_SANDBOX = ComponentSandbox() Let’s now simulate a test using this layer. To begin with, we have the default registry.: >>> from zope.component import getGlobalSiteManager, getSiteManager >>> getSiteManager() is getGlobalSiteManager() True >>> defaultGlobalSiteManager = getGlobalSiteManager() >>> from zope.component import queryUtility >>> queryUtility(IDummyUtility, name="layer") is None True We’ll now simulate layer setup. This will push a new registry onto the stack:: >>> COMPONENT_SANDBOX.setUp() >>> getSiteManager() is getGlobalSiteManager() True >>> getGlobalSiteManager() is defaultGlobalSiteManager False >>> layerGlobalSiteManager = getGlobalSiteManager() >>> queryUtility(IDummyUtility, name="layer") <DummyUtility layer> We’ll then simulate a test that registers a global component:: >>> COMPONENT_SANDBOX.testSetUp() >>> getSiteManager() is getGlobalSiteManager() True >>> getGlobalSiteManager() is defaultGlobalSiteManager False >>> getGlobalSiteManager() is layerGlobalSiteManager False Our previously registered component is still here.: >>> queryUtility(IDummyUtility, name="layer") <DummyUtility layer> We can also register a new one.: >>> provideUtility(DummyUtility("test"), name="test") >>> queryUtility(IDummyUtility, name="layer") <DummyUtility layer> >>> queryUtility(IDummyUtility, name="test") <DummyUtility test> On test tear-down, only the second utility disappears:: >>> COMPONENT_SANDBOX.testTearDown() >>> getSiteManager() is getGlobalSiteManager() True >>> getGlobalSiteManager() is defaultGlobalSiteManager False >>> getGlobalSiteManager() is layerGlobalSiteManager True >>> queryUtility(IDummyUtility, name="layer") <DummyUtility layer> >>> queryUtility(IDummyUtility, name="test") is None True If we tear down the layer too, we’re back where we started:: >>> COMPONENT_SANDBOX.tearDown() >>> getSiteManager() is getGlobalSiteManager() True >>> getGlobalSiteManager() is defaultGlobalSiteManager True >>> queryUtility(IDummyUtility, name="layer") is None True >>> queryUtility(IDummyUtility, name="test") is None True ZCML files helper class One of the frequent use cases is a layer that loads a ZCML file and sandbox the resulting registry. The ZCMLSandbox can be instantiated with a filename` and package arguments.: >>> import plone.testing >>> ZCML_SANDBOX = zca.ZCMLSandbox(filename="testing_zca.zcml", ... package=plone.testing) Before layer setup, the utility is not registered.: >>> queryUtility(Interface, name="layer") is None True We’ll now simulate layer setup. This pushes a new registry onto the stack:: >>> ZCML_SANDBOX.setUp() >>> getSiteManager() is getGlobalSiteManager() True >>> getGlobalSiteManager() is defaultGlobalSiteManager False >>> queryUtility(Interface, name="layer") <Dummy utility> The ZCMLSandbox class can also be used as ancestor for your own classes when you need to load more than a single ZCML file. Your class then needs to override the setUpZCMLFiles() method. It is in charge of calling loadZCMLFile(), once for each ZCML file that the class needs to load.: >>> class OtherZCML(zca.ZCMLSandbox): ... def setUpZCMLFiles(self): ... self.loadZCMLFile("testing_zca.zcml", package=plone.testing) ... self.loadZCMLFile("testing_zca_more_specific.zcml", ... package=plone.testing) >>> OTHER_ZCML_SANDBOX = OtherZCML() Before layer setup, a second utility is not registered.: >>> queryUtility(Interface, name="more_specific_layer") is None True We’ll now simulate the setup of the more specific layer.: >>> OTHER_ZCML_SANDBOX.setUp() After setUp, the second utility is registered:: >>> queryUtility(Interface, name="more_specific_layer") <Dummy utility> After layer teardown, the second utility is not registered anymore.: >>> OTHER_ZCML_SANDBOX.tearDown() >>> queryUtility(Interface, name="more_specific_layer") is None True After teardown of the first layer, the first utility is not registered anymore.: >>> ZCML_SANDBOX.tearDown() >>> queryUtility(Interface, name="layer") is None True Security The Zope Security layers are found in the module plone.testing.security:: >>> from plone.testing import security For testing, we need a testrunner:: >>> from zope.testrunner import runner Layers The security.CHECKERS layer makes sure that zope.security checkers are correctly set up and torn down.: >>> "%s.%s" % (security.CHECKERS.__module__, security.CHECKERS.__name__,) 'plone.testing.security.Checkers' >>> security.CHECKERS.__bases__ () Before the test, our custom checker is not in the registry.: >>> class DummyObject(object): ... pass >>> from zope.security.interfaces import IChecker >>> from zope.interface import implements >>> class FauxChecker(object): ... implements(IChecker) ... # we should really implement the interface here, but oh well >>> from zope.security.checker import getCheckerForInstancesOf >>> getCheckerForInstancesOf(DummyObject) is None True Layer setup stacks the current checkers.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, security.CHECKERS, setupLayers) Set up plone.testing.security.Checkers in ... seconds. We can now set up a checker. In real life, this may happen during ZCML configuration, but here will just call the API directlyMost likely, we’d do this in a child layer:: >>> from zope.security.checker import defineChecker >>> fauxChecker = FauxChecker() >>> defineChecker(DummyObject, fauxChecker) >>> getCheckerForInstancesOf(DummyObject) is fauxChecker True Let’s now simulate a test that may use the checker.: >>> security.CHECKERS.testSetUp() >>> getCheckerForInstancesOf(DummyObject) is fauxChecker True >>> security.CHECKERS.testTearDown() We still have the checker after test tear-down:: >>> getCheckerForInstancesOf(DummyObject) is fauxChecker True However, when we tear down the layer, the checker is gone:: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.security.Checkers in ... seconds. >>> getCheckerForInstancesOf(DummyObject) is None True Zope Publisher layers The Zope Publisher layers are found in the module plone.testing.publisher: >>> from plone.testing import publisher For testing, we need a testrunner:: >>> from zope.testrunner import runner ZCML directives The publisher.PUBLISHER_DIRECTIVES layer extends the zca.ZCML_DIRECTIVES layer to extend its ZCML configuration context with the zope.app.publisher and zope.security directives available. It also extends security.CHECKERS.: >>> from plone.testing import zca, security >>> "%s.%s" % (publisher.PUBLISHER_DIRECTIVES.__module__, publisher.PUBLISHER_DIRECTIVES.__name__,) 'plone.testing.publisher.PublisherDirectives' >>> publisher.PUBLISHER_DIRECTIVES.__bases__ (<Layer 'plone.testing.zca.ZCMLDirectives'>, <Layer 'plone.testing.security.Checkers'>) Before the test, we cannot use e.g. the <permission /> or <browser:view /> directives without loading the necessary meta.zcml files.: >>> from zope.configuration import xmlconfig >>>>""") Traceback (most recent call last): ... ZopeXMLConfigurationError: File "<string>", line 5.4 ConfigurationError: ('Unknown directive', u'', u'permission') Layer setup creates a configuration context we can use to load further configuration.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, publisher.PUBLISHER_DIRECTIVES, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.zca.ZCMLDirectives in ... seconds. Set up plone.testing.security.Checkers in ... seconds. Set up plone.testing.publisher.PublisherDirectives in ... seconds. Let’s now simulate a test that uses this configuration context to load the same ZCML string.: >>> zca.ZCML_DIRECTIVES.testSetUp() >>> security.CHECKERS.testSetUp() >>> publisher.PUBLISHER_DIRECTIVES.testSetUp() >>> context = zca.ZCML_DIRECTIVES['configurationContext'] # would normally be self.layer['configurationContext'] >>>>""", context=context) is context True The permission and view are now registered:: >>> from zope.component import queryUtility >>> from zope.security.interfaces import IPermission >>> queryUtility(IPermission, name=u"plone.testing.Test") <zope.security.permission.Permission object at ...> >>> from zope.interface import Interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.component import getSiteManager >>> siteManager = getSiteManager() >>> [x.factory for x in siteManager.registeredAdapters() ... if x.provided==Interface and x.required==(Interface, IDefaultBrowserLayer) ... and x.name==u"plone.testing-test"] [<class '....plone.testing-test'>] We can then simulate test tear-down:: >>> publisher.PUBLISHER_DIRECTIVES.testTearDown() >>> security.CHECKERS.testTearDown() >>> zca.ZCML_DIRECTIVES.testTearDown() Note that you’d normally combine this layer with the zca.UNIT_TESTING or a similar layer to automatically tear down the component architecture between each test. Here, we need to do it manually.: >>> from zope.component.testing import tearDown >>> tearDown() Layer tear-down does nothing.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.publisher.PublisherDirectives in ... seconds. Tear down plone.testing.zca.ZCMLDirectives in ... seconds. Tear down plone.testing.zca.LayerCleanup in ... seconds. Tear down plone.testing.security.Checkers in ... seconds. >>> zca.ZCML_DIRECTIVES.get('configurationContext', None) is None True Zope Object Database layers The ZODB layers are found in the module plone.testing.zodb:: >>> from plone.testing import zodb For testing, we need a testrunner:: >>> from zope.testrunner import runner Empty ZODB layer The EMPTY_ZODB layer is used to set up an empty ZODB using DemoStorage. The storage and database are set up as layer fixtures. The database is exposed as the resource zodbDB. A connection is opened for each test and exposed as zodbConnection. The ZODB root is also exposed, as zodbRoot. A new transaction is begun for each test. On test tear-down, the transaction is aborted, the connection is closed, and the two test-specific resources are deleted. The layer has no bases.: >>> "%s.%s" % (zodb.EMPTY_ZODB.__module__, zodb.EMPTY_ZODB.__name__,) 'plone.testing.zodb.EmptyZODB' >>> zodb.EMPTY_ZODB.__bases__ () Layer setup creates the database, but not a connection.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, zodb.EMPTY_ZODB, setupLayers) Set up plone.testing.zodb.EmptyZODB in ... seconds. >>> db = zodb.EMPTY_ZODB['zodbDB'] >>> db.storage EmptyZODB >>> zodb.EMPTY_ZODB.get('zodbConnection', None) is None True >>> zodb.EMPTY_ZODB.get('zodbRoot', None) is None True Let’s now simulate a test.: >>> zodb.EMPTY_ZODB.testSetUp() The test would then execute. It may use the ZODB root.: >>> zodb.EMPTY_ZODB['zodbConnection'] <Connection at ...> >>> zodb.EMPTY_ZODB['zodbRoot'] {} >>> zodb.EMPTY_ZODB['zodbRoot']['foo'] = 'bar' On test tear-down, the transaction is aborted and the connection is closed.: >>> zodb.EMPTY_ZODB.testTearDown() >>> zodb.EMPTY_ZODB.get('zodbConnection', None) is None True >>> zodb.EMPTY_ZODB.get('zodbRoot', None) is None True The transaction has been rolled back.: >>> conn = zodb.EMPTY_ZODB['zodbDB'].open() >>> conn.root() {} >>> conn.close() Layer tear-down closes and deletes the database.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.zodb.EmptyZODB in ... seconds. >>> zodb.EMPTY_ZODB.get('zodbDB', None) is None True Extending the ZODB layer When creating a test fixture, it is often desirable to add some initial data to the database. If you want to do that once on layer setup, you can create your own layer class based on EmptyZODB and override its createStorage() and/or createDatabase() methods to return a pre-populated database.: >>> import transaction >>> from ZODB.DemoStorage import DemoStorage >>> from ZODB.DB import DB >>> class PopulatedZODB(zodb.EmptyZODB): ... ... def createStorage(self): ... return DemoStorage("My storage") ... ... def createDatabase(self, storage): ... db = DB(storage) ... conn = db.open() ... ... conn.root()['someData'] = 'a string' ... ... transaction.commit() ... conn.close() ... ... return db >>> POPULATED_ZODB = PopulatedZODB() We’ll use this new layer in a similar manner to the test above, showing that the data is there for each test, but that other changes are rolled back.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, POPULATED_ZODB, setupLayers) Set up PopulatedZODB in ... seconds. >>> db = POPULATED_ZODB['zodbDB'] >>> db.storage My storage >>> POPULATED_ZODB.get('zodbConnection', None) is None True >>> POPULATED_ZODB.get('zodbRoot', None) is None True Let’s now simulate a test.: >>> POPULATED_ZODB.testSetUp() The test would then execute. It may use the ZODB root.: >>> POPULATED_ZODB['zodbConnection'] <Connection at ...> >>> POPULATED_ZODB['zodbRoot'] {'someData': 'a string'} >>> POPULATED_ZODB['zodbRoot']['foo'] = 'bar' On test tear-down, the transaction is aborted and the connection is closed.: >>> POPULATED_ZODB.testTearDown() >>> POPULATED_ZODB.get('zodbConnection', None) is None True >>> POPULATED_ZODB.get('zodbRoot', None) is None True The transaction has been rolled back.: >>> conn = POPULATED_ZODB['zodbDB'].open() >>> conn.root() {'someData': 'a string'} >>> conn.close() Layer tear-down closes and deletes the database.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down PopulatedZODB in ... seconds. >>> POPULATED_ZODB.get('zodbDB', None) is None True Stacking DemoStorage storages The example above shows how to create a simple test fixture with a custom database. It is sometimes useful to be able to stack these fixtures, so that a base layer sets up some data for one set of tests, and a child layer extends this, temporarily, with more data. This can be achieved using layer bases and resource shadowing, combined with ZODB’s stackable DemoStorage. There is even a helper function available:: >>> from plone.testing import Layer >>> from plone.testing import zodb >>> import transaction >>> class ExpandedZODB(Layer): ... defaultBases = (POPULATED_ZODB,) ... ... def setUp(self): ... # Get the database from the base layer ... ... self['zodbDB'] = db = zodb.stackDemoStorage(self.get('zodbDB'), name='ExpandedZODB') ... ... conn = db.open() ... conn.root()['additionalData'] = "Some new data" ... transaction.commit() ... conn.close() ... ... def tearDown(self): ... # Close the database and delete the shadowed copy ... ... self['zodbDB'].close() ... del self['zodbDB'] >>> EXPANDED_ZODB = ExpandedZODB() Notice that we are using plain Layer as a base class here. We obtain the underlying database from our bases using the resource manager, and then create a shadow copy using a stacked storage. Stacked storages contain the data of the original storage, but save changes in a separate (and, in this case, temporary) storage. Let’s simulate a test run again to show how this would work.: >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, EXPANDED_ZODB, setupLayers) Set up PopulatedZODB in ... seconds. Set up ExpandedZODB in ... seconds. >>> db = EXPANDED_ZODB['zodbDB'] >>> db.storage ExpandedZODB >>> EXPANDED_ZODB.get('zodbConnection', None) is None True >>> EXPANDED_ZODB.get('zodbRoot', None) is None True Let’s now simulate a test.: >>> POPULATED_ZODB.testSetUp() >>> EXPANDED_ZODB.testSetUp() The test would then execute. It may use the ZODB root.: >>> EXPANDED_ZODB['zodbConnection'] <Connection at ...> >>> EXPANDED_ZODB['zodbRoot'] == dict(someData='a string', additionalData='Some new data') True >>> POPULATED_ZODB['zodbRoot']['foo'] = 'bar' On test tear-down, the transaction is aborted and the connection is closed.: >>> EXPANDED_ZODB.testTearDown() >>> POPULATED_ZODB.testTearDown() >>> EXPANDED_ZODB.get('zodbConnection', None) is None True >>> EXPANDED_ZODB.get('zodbRoot', None) is None True The transaction has been rolled back.: >>> conn = EXPANDED_ZODB['zodbDB'].open() >>> conn.root() == dict(someData='a string', additionalData='Some new data') True >>> conn.close() We’ll now tear down the expanded layer and inspect the database again.: >>> runner.tear_down_unneeded(options, [POPULATED_ZODB], setupLayers) Tear down ExpandedZODB in ... seconds. >>> conn = EXPANDED_ZODB['zodbDB'].open() >>> conn.root() {'someData': 'a string'} >>> conn.close() Finally, we’ll tear down the rest of the layers.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down PopulatedZODB in ... seconds. >>> EXPANDED_ZODB.get('zodbDB', None) is None True >>> POPULATED_ZODB.get('zodbDB', None) is None True Zope 2 layers The Zope 2 layers are found in the module plone.testing.z2:: >>> from plone.testing import z2 For testing, we need a testrunner:: >>> from zope.testrunner import runner Startup STARTUP is the base layer for all Zope 2 testing. It sets up a Zope 2 sandbox environment that is suitable for testing. It extends the zca.LAYER_CLEANUP layer to maximise the chances of having and leaving a pristine environment. Note: You should probably use at least INTEGRATION_TESTING for any real test, although STARTUP is a useful base layer if you are setting up your own fixture. See the description of INTEGRATION_TESTING below.: >>> "%s.%s" % (z2.STARTUP.__module__, z2.STARTUP.__name__,) 'plone.testing.z2.Startup' >>> z2.STARTUP.__bases__ (<Layer 'plone.testing.zca.LayerCleanup'>,) On layer setup, Zope is initialised in a lightweight manner. This involves certain patches to global modules that Zope manages, to reduce setup time, a database based on DemoStorage, and a minimal set of products that must be installed for Zope 2 to work. A minimal set of ZCML is loaded, but packages in the Products namespace are not automatically configured. Let’s just verify that we have an empty component registry before the test:: >>> from zope.component import getSiteManager >>> list(getSiteManager().registeredAdapters()) [] Five sets a special vocabulary registry upon the layer setup, but there’s a default one set before:: >>> from zope.schema.vocabulary import getVocabularyRegistry >>> getVocabularyRegistry() <zope.schema.vocabulary.VocabularyRegistry object ...> >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, z2.STARTUP, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.z2.Startup in ... seconds. After layer setup, the zodbDB resource is available, pointing to the default ZODB.: >>> z2.STARTUP['zodbDB'] <ZODB.DB.DB object at ...> >>> z2.STARTUP['zodbDB'].storage Startup In addition, the resources host and port are set to the default hostname and port that are used for URLs generated from Zope. These are hardcoded, but shadowed by layers that provide actual running Zope instances.: >>> z2.STARTUP['host'] 'nohost' >>> z2.STARTUP['port'] 80 At this point, it is also possible to get hold of a Zope application root. If you are setting up a layer fixture, you can obtain an application root with the correct database that is properly closed by using the zopeApp() context manager.: >>> with z2.zopeApp() as app: ... 'acl_users' in app.objectIds() True If you want to use a specific database, you can pass that to zopeApp() as the db parameter. A new connection will be opened and closed.: >>> with z2.zopeApp(db=z2.STARTUP['zodbDB']) as app: ... 'acl_users' in app.objectIds() True If you want to re-use an existing connection, you can pass one to zopeApp() as the connection argument. In this case, you will need to close the connection yourself.: >>> conn = z2.STARTUP['zodbDB'].open() >>> with z2.zopeApp(connection=conn) as app: ... 'acl_users' in app.objectIds() True >>> conn.opened is not None True >>> conn.close() If an exception is raised within the with block, the transaction is aborted, but the connection is still closed (if it was opened by the context manager):: >>> with z2.zopeApp() as app: ... raise Exception("Test error") Traceback (most recent call last): ... Exception: Test error It is common to combine the zopeApp() context manager with a stacked DemoStorage to set up a layer-specific fixture. As a sketch:: from plone.testing import Layer, z2, zodb class MyLayer(Layer): defaultBases = (z2.STARTUP,) def setUp(self): self['zodbDB'] = zodb.stackDemoStorage(self.get('zodbDB'), name='MyLayer') with z2.zopeApp() as app: # Set up a fixture, e.g.: app.manage_addFolder('folder1') folder = app['folder1'] folder._addRole('role1') folder.manage_addUserFolder() userFolder = folder['acl_users'] ignore = userFolder.userFolderAddUser('user1', 'secret', ['role1'], []) folder.manage_role('role1', ('Access contents information',)) def tearDown(self): self['zodbDB'].close() del self['zodbDB'] Note that you would normally not use the z2.zopeApp() in a test or in a testSetUp() or testTearDown() method. The IntegrationTesting and FunctionalTesting layer classes manage the application object for you, exposing them as the resource app (see below). After layer setup, the global component registry contains a number of components needed by Zope.: >>> len(list(getSiteManager().registeredAdapters())) > 1 # in fact, > a lot True And Five has set a Zope2VocabularyRegistry vocabulary registry:: >>> getVocabularyRegistry() <....Zope2VocabularyRegistry object at ...> To load additional ZCML, you can use the configurationContext resource:: >>> z2.STARTUP['configurationContext'] <zope.configuration.config.ConfigurationMachine object ...> See zca.rst for details about how to use zope.configuration for this purpose. The STARTUP layer does not perform any specific test setup or tear-down. That is left up to the INTEGRATION_TESTING and FUNCTIONAL_TESTING layers, or other layers using their layer classes - IntegrationTesting and FunctionalTesting.: >>> z2.STARTUP.testSetUp() >>> z2.STARTUP.testTearDown() Layer tear-down resets the environment.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.z2.Startup in ... seconds. Tear down plone.testing.zca.LayerCleanup in ... seconds. >>> import Zope2 >>> Zope2._began_startup 0 >>> Zope2.DB is None True >>> Zope2.bobo_application is None True >>> list(getSiteManager().registeredAdapters()) [] >>> getVocabularyRegistry() <zope.schema.vocabulary.VocabularyRegistry object at ...> Integration test INTEGRATION_TESTING is intended for simple Zope 2 integration testing. It extends STARTUP to ensure that a transaction is begun before and rolled back after each test. Two resources, app and request, are available during testing as well. It does not manage any layer state - it implements the test lifecycle methods only. Note: You would normally not use INTEGRATION_TESTING as a base layer. Instead, you’d use the IntegrationTesting class to create your own layer with the testing lifecycle semantics of INTEGRATION_TESTING. See the plone.testing README file for an example. app is the application root. In a test, you should use this instead of the zopeApp context manager (which remains the weapon of choice for setting up persistent fixtures), because the app resource is part of the transaction managed by the layer. request is a test request. It is the same as app.REQUEST.: >>> "%s.%s" % (z2.INTEGRATION_TESTING.__module__, z2.INTEGRATION_TESTING.__name__,) 'plone.testing.z2.IntegrationTesting' >>> z2.INTEGRATION_TESTING.__bases__ (<Layer 'plone.testing.z2.Startup'>,) >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, z2.INTEGRATION_TESTING, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.z2.Startup in ... seconds. Set up plone.testing.z2.IntegrationTesting in ... seconds. Let’s now simulate a test. On test setup, the app resource is made available. In a test, you should always use this to access the application root.: >>> z2.STARTUP.testSetUp() >>> z2.INTEGRATION_TESTING.testSetUp() The test may now inspect and modify the environment.: >>> app = z2.INTEGRATION_TESTING['app'] # would normally be self.layer['app'] >>> app.manage_addFolder('folder1') >>> 'acl_users' in app.objectIds() and 'folder1' in app.objectIds() True The request is also available:: >>> z2.INTEGRATION_TESTING['request'] # would normally be self.layer['request'] <HTTPRequest, URL=> We can create a user and simulate logging in as that user, using the z2.login() helper:: >>> app._addRole('role1') >>> ignore = app['acl_users'].userFolderAddUser('user1', 'secret', ['role1'], []) >>> z2.login(app['acl_users'], 'user1') The first argument to z2.login() is the user folder that contains the relevant user. The second argument is the user’s name. There is no need to give the password.: >>> from AccessControl import getSecurityManager >>> getSecurityManager().getUser() <User 'user1'> You can change the roles of a user using the z2.setRoles() helper:: >>> sorted(getSecurityManager().getUser().getRolesInContext(app)) ['Authenticated', 'role1'] >>> z2.setRoles(app['acl_users'], 'user1', []) >>> getSecurityManager().getUser().getRolesInContext(app) ['Authenticated'] To become the anonymous user again, use z2.logout():: >>> z2.logout() >>> getSecurityManager().getUser() <SpecialUser 'Anonymous User'> On tear-down, the transaction is rolled back:: >>> z2.INTEGRATION_TESTING.testTearDown() >>> z2.STARTUP.testTearDown() >>> 'app' in z2.INTEGRATION_TESTING False >>> 'request' in z2.INTEGRATION_TESTING False >>> with z2.zopeApp() as app: ... 'acl_users' in app.objectIds() and 'folder1' not in app.objectIds() True Let’s tear down the layers:: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.z2.IntegrationTesting in ... seconds. Tear down plone.testing.z2.Startup in ... seconds. Tear down plone.testing.zca.LayerCleanup in ... seconds. Functional testing The FUNCTIONAL_TESTING layer is very similar to INTEGRATION_TESTING, and exposes the same fixture and resources. However, it has different transaction semantics. INTEGRATION_TESTING creates a single database storage, and rolls back the transaction after each test. FUNCTIONAL_TESTING creates a whole new database storage (stacked on top of the basic fixture) for each test. This allows testing of code that performs an explicit commit, which is usually required for end-to-end testing. The downside is that the set-up and tear-down of each test takes longer. Note: Again, you would normally not use FUNCTIONAL_TESTING as a base layer. Instead, you’d use the FunctionalTesting class to create your own layer with the testing lifecycle semantics of FUNCTIONAL_TESTING. See the plone.testing README file for an example. Like INTEGRATION_TESTING, FUNCTIONAL_TESTING is based on STARTUP.: >>> "%s.%s" % (z2.FUNCTIONAL_TESTING.__module__, z2.FUNCTIONAL_TESTING.__name__,) 'plone.testing.z2.FunctionalTesting' >>> z2.FUNCTIONAL_TESTING.__bases__ (<Layer 'plone.testing.z2.Startup'>,) >>> now simulate a test. On test setup, the app resource is made available. In a test, you should always use this to access the application root. The request resource can be used to access the test request.: >>> z2.STARTUP.testSetUp() >>> z2.FUNCTIONAL_TESTING.testSetUp() The test may now inspect and modify the environment. It may also commit things.: >>> app = z2.FUNCTIONAL_TESTING['app'] # would normally be self.layer['app'] >>> app.manage_addFolder('folder1') >>> 'acl_users' in app.objectIds() and 'folder1' in app.objectIds() True >>> import transaction >>> transaction.commit(). The test browser The FUNCTIONAL_TESTING layer and FunctionalTesting layer class are the basis for functional testing using zope.testbrowser. This simulates a web browser, allowing an application to be tested “end-to-end” via its user-facing interface. To use the test browser with a FunctionalTesting layer (such as the default FUNCTIONAL_TESTING layer instance), we need to use a custom browser client, which ensures that the test browser uses the correct ZODB and is appropriately isolated from the test code.: >>> simulate a test:: >>> z2.STARTUP.testSetUp() >>> z2.FUNCTIONAL_TESTING.testSetUp() In the test, we can create a test browser client like so:: >>> app = z2.FUNCTIONAL_TESTING['app'] # would normally be self.layer['app'] >>> browser = z2.Browser(app) It is usually best to let Zope errors be shown with full tracebacks:: >>> browser.handleErrors = False We can add to the test fixture in the test. For those changes to be visible to the test browser, however, we need to commit the transaction.: >>> app.manage_addFolder('folder1') >>> import transaction; transaction.commit() We can now view this via the test browser:: >>> browser.open(app.absolute_url() + '/folder1') >>> 'folder1' in browser.contents True The test browser integration converts the URL into a request and passes control to Zope’s publisher. Let’s check that query strings are available for input processing:: >>> import urllib >>> qs = urllib.urlencode({'foo': 'boo, bar & baz'}) # sic: the ampersand. >>> _ = app['folder1'].addDTMLMethod('index_html', file='<dtml-var foo>') >>> import transaction; transaction.commit() >>> browser.open(app.absolute_url() + '/folder1?' + qs) >>> browser.contents 'boo, bar & baz' The test browser also works with iterators. Let’s test that with a simple file implementation that uses an iterator.: >>> from plone.testing.tests import DummyFile >>> app._setObject('file1', DummyFile('file1')) 'file1' >>> import transaction; transaction.commit() >>> browser.open(app.absolute_url() + '/file1') >>> 'The test browser also works with iterators' in browser.contents True See the zope.testbrowser documentation for more information about how to use the browser client.()\ ... and 'file. HTTP server The ZSERVER_FIXTURE layer extends STARTUP to start a single-threaded Zope server in a separate thread. This makes it possible to connect to the test instance using a web browser or a testing tool like Selenium or Windmill. The ZSERVER layer provides a FunctionalTesting layer that has ZSERVER_FIXTURE as its base.: >>> "%s.%s" % (z2.ZSERVER_FIXTURE.__module__, z2.ZSERVER_FIXTURE.__name__,) 'plone.testing.z2.ZServer' >>> z2.ZSERVER_FIXTURE.__bases__ (<Layer 'plone.testing.z2.Startup'>,) >>> "%s.%s" % (z2.ZSERVER.__module__, z2.ZSERVER.__name__,) 'plone.testing.z2.ZServer:Functional' >>> z2.ZSERVER.__bases__ (<Layer 'plone.testing.z2.ZServer'>,) >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, z2.ZSERVER, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.z2.Startup in ... seconds. Set up plone.testing.z2.ZServer in ... seconds. Set up plone.testing.z2.ZServer:Functional in ... seconds. After layer setup, the resources host and port are available, and indicate where Zope is running.: >>> host = z2.ZSERVER['host'] >>> host 'localhost' >>> port = z2.ZSERVER['port'] >>> import os >>> port == int(os.environ.get('ZSERVER_PORT', 55001)) True Let’s now simulate a test. Test setup does nothing beyond what the base layers do.: >>> z2.STARTUP.testSetUp() >>> z2.FUNCTIONAL_TESTING.testSetUp() >>> z2.ZSERVER.testSetUp() It is common in a test to use the Python API to change the state of the server (e.g. create some content or change a setting) and then use the HTTP protocol to look at the results. Bear in mind that the server is running in a separate thread, with a separate security manager, so calls to z2.login() and z2.logout(), for instance, do not affect the server thread.: >>> app = z2.ZSERVER['app'] # would normally be self.layer['app'] >>> app.manage_addFolder('folder1') Note that we need to commit the transaction before it will show up in the other thread.: >>> import transaction; transaction.commit() We can now look for this new object through the server.: >>> app_url = app.absolute_url() >>> app_url.split(':')[:-1] ['http', '//localhost'] >>> import urllib2 >>> conn = urllib2.urlopen(app_url + '/folder1', timeout=5) >>> print conn.read() <Folder at folder1> >>> conn.close() Test tear-down does nothing beyond what the base layers do.: >>> z2.ZSERVER ZServer thread is stopped.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.z2.ZServer:Functional in ... seconds. Tear down plone.testing.z2.ZServer in ... seconds. Tear down plone.testing.z2.Startup in ... seconds. Tear down plone.testing.zca.LayerCleanup in ... seconds. >>> conn = urllib2.urlopen(app_url + '/folder1', timeout=5) Traceback (most recent call last): ... URLError: <urlopen error [Errno ...] Connection refused> FTP server The FTP_SERVER layer is identical similar to ZSERVER, except that it starts an FTP server instead of an HTTP server. The fixture is contained in the FTP_SERVER_FIXTURE layer. Warning: It is generally not safe to run the ZSERVER and FTP_SERVER layers concurrently, because they both start up the same asyncore loop. If you need concurrent HTTP and FTP servers in a test, you can create your own layer by subclassing the ZServer layer class, and overriding the setUpServer() and tearDownServer() hooks to set up and close both servers. See the code for an example. The FTP_SERVER_FIXTURE layer is based on the STARTUP layer.: >>> "%s.%s" % (z2.FTP_SERVER_FIXTURE.__module__, z2.FTP_SERVER_FIXTURE.__name__,) 'plone.testing.z2.FTPServer' >>> z2.FTP_SERVER_FIXTURE.__bases__ (<Layer 'plone.testing.z2.Startup'>,) The FTP_SERVER layer is based on FTP_SERVER_FIXTURE, using the FunctionalTesting layer class.: >>> "%s.%s" % (z2.FTP_SERVER.__module__, z2.FTP_SERVER.__name__,) 'plone.testing.z2.FTPServer:Functional' >>> z2.FTP_SERVER.__bases__ (<Layer 'plone.testing.z2.FTPServer'>,) >>> options = runner.get_options([], []) >>> setupLayers = {} >>> runner.setup_layer(options, z2.FTP_SERVER, setupLayers) Set up plone.testing.zca.LayerCleanup in ... seconds. Set up plone.testing.z2.Startup in ... seconds. Set up plone.testing.z2.FTPServer in ... seconds. Set up plone.testing.z2.FTPServer:Functional in ... seconds. After layer setup, the resources host and port are available, and indicate where Zope is running.: >>> host = z2.FTP_SERVER['host'] >>> host 'localhost' >>> port = z2.FTP_SERVER['port'] >>> import os >>> port == int(os.environ.get('FTPSERVER_PORT', 55002)) True Let’s now simulate a test. Test setup does nothing beyond what the base layers do.: >>> z2.STARTUP.testSetUp() >>> z2.FUNCTIONAL_TESTING.testSetUp() >>> z2.FTP_SERVER.testSetUp() As with ZSERVER, we will set up some content for the test and then access it over the FTP port.: >>> app = z2.FTP_SERVER['app'] # would normally be self.layer['app'] >>> app.manage_addFolder('folder1') We’ll also create a user in the root user folder to make FTP access easier.: >>> ignore = app['acl_users'].userFolderAddUser('admin', 'secret', ['Manager'], ()) Note that we need to commit the transaction before it will show up in the other thread.: >>> import transaction; transaction.commit() We can now look for this new object through the server.: >>> app_path = app.absolute_url_path() >>> import ftplib >>> ftpClient = ftplib.FTP() >>> ftpClient.connect(host, port, timeout=5) '220 ... FTP server (...) ready.' >>> ftpClient.login('admin', 'secret') '230 Login successful.' >>> ftpClient.cwd(app_path) '250 CWD command successful.' >>> ftpClient.retrlines('LIST') drwxrwx--- 1 Zope Zope 0 ... . ...--w--w---- 1 Zope Zope 0 ... acl_users drwxrwx--- 1 Zope Zope 0 ... folder1 '226 Transfer complete' >>> ftpClient.quit() '221 Goodbye.' Test tear-down does nothing beyond what the base layers do.: >>> z2.FTP_SERVER FTP thread is stopped.: >>> runner.tear_down_unneeded(options, [], setupLayers) Tear down plone.testing.z2.FTPServer:Functional in ... seconds. Tear down plone.testing.z2.FTPServer in ... seconds. Tear down plone.testing.z2.Startup in ... seconds. Tear down plone.testing.zca.LayerCleanup in ... seconds. >>> ftpClient.connect(host, port, timeout=5) Traceback (most recent call last): ... error: [Errno ...] Connection refused Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/plone.testing/5.1.1/
CC-MAIN-2019-35
refinedweb
20,732
51.04
CD access to the GD-ROM drive. More... #include <sys/cdefs.h> #include <arch/types.h> Go to the source code of this file. CD access to the GD-ROM drive. This file contains the interface to the Dreamcast's GD-ROM drive. It is simply called cdrom.h and cdrom.c because, by design, you cannot directly use this code to read the high-density area of GD-ROMs. This is the way it always has been, and always will be. The way things are set up, as long as you're using fs_iso9660 to access the CD, it will automatically detect and react to disc changes for you. This file only facilitates reading raw sectors and doing other fairly low- level things with CDs. If you're looking for higher-level stuff, like normal file reading, consult with the stuff for the fs and for fs_iso9660. Pause CDDA audio playback. Play CDDA audio tracks or sectors. This function starts playback of CDDA audio. Resume CDDA audio playback after a pause. Execute a CD-ROM command. This function executes the specified command using the BIOS syscall for executing GD-ROM commands. Get the status of the GD-ROM drive. Initialize the GD-ROM for reading CDs. This initializes the CD-ROM reading system, reactivating the drive and handling initial setup of the disc. Locate the sector of the data track. This function will search the toc for the last entry that has a CTRL value of 4, and return its FAD address. Read one or more sector from a CD-ROM. This function reads the specified number of sectors from the disc, starting where requested. This will respect the size of the sectors set with cdrom_set_sector_size(). The buffer must have enough space to store the specified number of sectors. Read the table of contents from the disc. This function reads the TOC from the specified session of the disc. Re-initialize the GD-ROM drive. This function is for reinitializing the GD-ROM drive after a disc change, or something of the like. Set the sector size for read sectors. This function sets the sector size that the cdrom_read_sectors() function will return. Be sure to set this to the correct value for the type of sectors you're trying to read. Common values are 2048 (for reading CD-ROM sectors) or 2352 (for reading raw sectors). Shutdown the CD reading system. Spin down the CD. This stops the disc in the drive from spinning until it is accessed again.
http://cadcdev.sourceforge.net/docs/kos-2.0.0/cdrom_8h.html
CC-MAIN-2018-05
refinedweb
420
77.84
HTML and CSS Reference In-Depth Information the preceding code, you can begin to create instance variables that exist only within the scope of each World object , such as its name. var World = function(_name){ var name = _name; this.greet = function(guest){ alert('Hello ' + guest + ' my name is ' + name); } } var venus = new World('Venus'); var mars = new World('Mars'); venus.greet('Antony'); venus.greet('Dan'); From the preceding examples, you can see that in order to create an object in JavaScript, it's as simple as creating a function. Using the function's parameters, you create what is called a constructor. A constructor is a method to pass parameters to the object upon instantiation. These parameters are usually used to assign variables to properties within the object itself. A property can be declared as public or private in normal object orientation. In JavaScript there are no such declerations available for properties. So a property can either be an instance variable (private) or a public property (public). In this instance, the name property is an instance variable, which means that you cannot access it from outside of the object using, for example, venus.name . This is generally known as encapsulation. A property of an object is a variable that can be accessed either by using this.propertyname from within the object's scope, or by using object.propertyname from outside of the object. For example, if you attempted to access the name instance variable from outside of the object, you would get undefined as the output. You can also create object methods, which are functions that can be accessed from within or outside of the object using this from within the object or the variable assigned to the instantiated object from outside. Using the previous examples, this.greet is a public object method and can be accessed outside of the object. From here, you can see that objects allow for much more maintainable code. The object's properties live outside of the global namespace, so you avoid clashing variable names and other details for specific objects. You can go beyond this and create your own namespace for your application objects. This helps to avoid other JavaScript libraries from potentially overwriting them. The Search WWH :: Custom Search
http://what-when-how.com/Tutorial/topic-727cs6102t/Learn-HTML5-and-JavaScript-for-Android-179.html
CC-MAIN-2017-39
refinedweb
375
56.45
In this tutorial we will explore how to consume JSON web APIs using Haskell. In particular, we will use the Google Geocoding API to convert an address into a lat long, and then plug that information into the Foursquare API to get a list of trending venues. Topics covered include: - Making HTTP[S] requests. - Parsing JSON using Data.Aeson. - Using type classes to make it easy to add support for new endpoints. - Propagating errors using the IO monad. This tutorial is aimed at intermediate Haskell programmers. Basics: Making an HTTP Request At its core, consuming a web API is a matter of making HTTP requests to some server with the desired parameters (see: REST). We'll be using the Network.HTTP.Conduit library for making these requests. The interface is simple: simpleHttp :: MonadIO m => String -> m ByteString MonadIO is just a type class for monads that can embed IO operations -- including IO itself. The first parameter to this function is a URI, and it returns a ByteString -- which is a just a buffer. Here's an example: import Network.HTTP.Conduit main = do -- The GitHub API is convenient as it doesn't require authentication response <- simpleHttp "" print response You can expect to see output along the lines of: Chunk "{\"id\":237904,\"name\":\"yesod\",\"full_name\":\"yesodweb/yesod\", \"owner\":{\"login\":\"yesodweb\",\"id\":930379,\"avatar_url\":\" ure.gravatar.com/avatar/c224026a2005e5ce9a0e1a6defb9f893?d= .akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-org-420.png\", \"gravatar_id\":\"c224026a2005e5ce9a0e1a6defb9f893\",\... It's not very pretty, but this JSON response contains a lot of juicy information about the Yesod repository, including its URL, description, and owner. Take a look for yourself. Extracting Structured Data: Parsing with Aeson Data.Aeson provides tons of handy utilities for dealing with JSON. For our purposes, we mostly care about decode -- which takes a ByteString and returns a kind of JSON AST. import Data.Aeson import Data.ByteString.Lazy.Char8(pack) main = print $ (decode (pack "{\"key\": \"val\"}") :: Maybe Value) So, what's a Value? data Value = Object !Object -- The exclamation mark (!) is a strictness annotation. | Array !Array | String !Text | Number !Number | Bool !Bool | Null As you can see, it corresponds very nicely to the structure of a JSON document. Using simpleHTTP and decode together, you should be able to send a request to an endpoint and parse it into a JSON AST. However, in the next section we'll take a step back and start building some utilities to help us build out different endpoints in a generic manner. Building Out a Framework For Endpoints What is an endpoint (besides a miserable pile of secrets)? Since we're dealing with GET requests only, for our purposes it's basically a URI with some query parameters. We would like to encapsulate those parameters in a typed data structure, and provide a way to build a URI using those parameters. This notion is captured by the following type class: class Endpoint a where buildURI :: a -> String For an example, let's build out the geocoding endpoint. As a quick reminder, geocoding is the process of converting an address like "New York City" into a latitude and longitude. We'll need a lat/long for our subsequent call to the Foursquare API. From the Google Geocoding API Documentation, we can see that the form of the geocoding request is fairly simple:, where the two required parameters (that we care about) are: address: The address that you want to geocode. sensor: Boolean indicating whether the request came from a device with a location sensor. For our program this will always be false. We encapsulate these parameters with the following ADT: data GeocoderEndpoint = GeocodeEndpoint { address :: String, sensor :: Bool } To convert this data structure into a URI, we need to prepend the API endpoint path to a string consisting of the query parameterized fields. instance Endpoint GeocoderEndpoint where buildURI GeocodeEndpoint { address = address, sensor = sensor } = let params = [("address", Just address), ("sensor", Just $ map toLower $ show sensor)] in "" ++ renderQuery True params As you can see, its fairly simple. I've glossed over the implementation of renderQuery :: Bool -> [(String, Maybe String)] -> String -- it converts a set of parameters into a string like "?key1=value1&key2=value2" (making sure to URL-encode the values). To see the full definition, check out the source on GitHub. Detour: Aeson Parsers Before we get to decoding the response from the geocoder endpoint, let's take a detour and explore a powerful feature of Aeson: Parsers. Parsers are closely tied to the FromJSON type class we saw earlier. From the Aeson documentation, a FromJSON is "A type that can be converted from JSON, with the possibility of failure." Its only method is parseJSON :: Value -> Parser a. A Parser is a monad that encapsulates that possibility of failure, as well as a sequence of operations which convert a Value (JSON AST) into some type a. A naive implementation of parseJSON could simply inspect the Value and return an a based on that information, but Aeson also provides a few handy combinators operating within the Parser Monad. We'll be using .:, which allows you to easily access Object fields. For example: {-# LANGUAGE OverloadedStrings #-} import Data.Aeson import Data.Aeson.Types import Data.Text(Text) import Data.ByteString.Lazy.Char8 data Venue = Venue { venueId :: Text, name :: Text } deriving Show instance FromJSON Venue where parseJSON val = do let Object obj = val -- Use pattern matching to extract an Object venueId <- obj .: "id" name <- obj .: "name" return $ Venue venueId name main = print venue where json = "{\"id\": \"some venue id\", \"name\": \"bob's venue\"}" venue = decode json >>= parseMaybe parseJSON :: Maybe Venue Now that we have parser basics down, we should be able to model the geocoder result as an ADT, and parse it from a decoded Value. Modeling the Geocoder Result Now that we can construct a URI for calling the geocoder, we need to make sense of the response. I'd suggest hitting the endpoint in a web browser to get a rough idea of what the geocoder returns. The response is fairly generic, with support for multiple results and lots of extra metadata. The only thing we care about is the lat/long of the first result. In JavaScript notation: response.results[0].geometry.location. Since this structure is fairly nested, I built a helper method called navigateJson :: Value -> [Text] -> Parser Value. This takes a Value and a list of field names and walks down the tree -- for example, if you provided {a: {b: 2}} and ['a', 'b'] as parameters, it would return 2. I'll elide the definition here; check out the full source on GitHub. With navigateJSON, building the Parser should be trivial. Access the 'results' field of the response; get the first entry; navigate thru ['geometry', 'location']; return the 'lat' and 'lng' parts of that object. Before we continue, let's define an ADT to encapsulate this type of result. type LatLng = (Double, Double) data GeocodeResponse = GeocodeResponse LatLng deriving Show -- Handy for debugging Now we can write our parser by declaring an instance of the FromJSON type class. instance FromJSON GeocodeResponse where parseJSON (Object obj) = do (Array results) <- obj .: "results" (Object location) <- navigateJson (results V.! 0) ["geometry", "location"] (Number lat) <- location .: "lat" (Number lng) <- location .: "lng" -- Use realToFrac to convert from Aeson Numbers into simple Doubles. return $ GeocodeResponse (realToFrac lat, realToFrac lng) Putting It All Together (Part 1) So far we have a method to build URIs for endpoints and a way to parse the JSON response from those endpoints into a structure we can use. Since these steps are encapsulated by the generic type classes FromJSON and Endpoint, its easy to build a general function to call any endpoint. Let's start with a type signature: callJsonEndpoint :: (FromJSON j, Endpoint e) => e -> IO j. "Take an endpoint (with data about the call), make some HTTP request, and parse the response into some JSON object." This process must take place in the IO monad, since we're making a network request. We'll use simpleHTTP like earlier. To run our parser, we'll use a variant of decode called eitherDecode -- using the error message from Either, we can provide more helpful errors (via IO's fail). callJsonEndpoint :: (FromJSON j, Endpoint e) => e -> IO j callJsonEndpoint e = do responseBody <- simpleHttp (buildURI e) case eitherDecode responseBody of Left err -> fail err Right res -> return res With callJsonEndpoint, we could call the geocoder endpoint like so: (GeocodeResponse latLng) <- callJsonEndpoint $ GeocodeEndpoint "568 Broadway, New York, NY" False Hooking Up Foursquare Now that we have a nifty little framework, we can come back to the motivation for this tutorial: retreiving a list of trending venues around an address. Foursquare makes this easy with an endpoint called "/venues/trending". The parameter we care about is the lat/long ("ll"), but you can optionally provide a limit on the results and a radius for your search area. data FoursquareEndpoint = VenuesTrendingEndpoint { ll :: LatLng, limit :: Maybe Int, radius :: Maybe Double } instance Endpoint FoursquareEndpoint where buildURI VenuesTrendingEndpoint {ll = ll, limit = limit, radius = radius} = let params = [("ll", Just $ renderLatLng ll), ("limit", fmap show limit), ("radius", fmap show radius)] in "" ++ renderQuery True params The docs tell us that this returns a list of "venues", which is another JSON object. For our simple example, we choose to care about two fields: the venue ID, and its name. data Venue = Venue { venueId :: String, name :: String } deriving Show The whole response from this endpoint (list of venues) is encompassed by the following structure: data VenuesTrendingResponse = VenuesTrendingResponse { venues :: [Venue] } deriving Show Implementing FromJSON instances for these structures is left as an exercise for the reader (with the source on GitHub available for the lazy ;). Foursquare Authorization Even though we've implemented data structures, parsing logic, and a URI builder for the venues/trending endpoint, there remains one restriction upon using the Foursquare API: you must have access credentials. The venues/trending endpoint is "userless", so we don't need to go through OAuth, but we still need an API key/secret. I've covered the process of obtaining these credentials in an appendix below, so let's assume we have those for the remainder of this tutorial. To start, let's define a structure to represent the needed credentials: data FoursquareCredentials = FoursquareCredentials { clientId :: String, clientSecret :: String } We can actually build upon the Endpoint framework to build a type of "authorized Foursquare endpoint" that wraps another endpoint and appends the necessary access credentials. Let's call this an AuthorizedFoursquareEndpoint: data AuthorizedFoursquareEndpoint = AuthorizedFoursquareEndpoint FoursquareCredentials FoursquareEndpoint In order to build an instance of Endpoint for AuthorizedFoursquareEndpoint, all we have to do is build the URI of the inner endpoint, and then append "client_id" and "client_secret" parameters. instance Endpoint AuthorizedFoursquareEndpoint where buildURI (AuthorizedFoursquareEndpoint creds e) = appendParams originalUri authorizationParams where originalUri = buildURI e authorizationParams = [("client_id", Just $ clientId creds), ("client_secret", Just $ clientSecret creds), ("v", Just foursquareApiVersion)] Finally, let's define a handy helper that lets us authorize an endpoint using an infix syntax (e.g. endpoint `authorizeWith` creds): authorizeWith = flip AuthorizedFoursquareEndpoint Putting It All Together (Part 2) To recap: we've built a system for describing web API endpoints; we learned how to use Aeson's FromJSON to parse the results of those endpoints; and we implemented a function to call those endpoints using that functionality. At the beginning of this tutorial, we wanted to retrieve a list of trending venues about an address. At this point, we can achieve that goal. - Call Google's geocoder endpoint. Store the lat/long. - Plug that lat/long into Foursquare's trending venues endpoint. - Display those trending venues to the user. For our Main.hs, we'll also use getLine to retrieve access credentials. Here goes: targetAddress = "568 Broadway, New York, NY" main :: IO () main = do putStrLn "API key?" apiKey <- getLine putStrLn "API secret?" apiSecret <- getLine let creds = FoursquareCredentials apiKey apiSecret (GeocodeResponse latLng) <- callJsonEndpoint $ GeocodeEndpoint targetAddress False let venuesTrendingEndpoint = VenuesTrendingEndpoint latLng Nothing Nothing `authorizeWith` creds (VenuesTrendingResponse venues) <- callJsonEndpoint venuesTrendingEndpoint let printVenue v = putStrLn $ "- " ++ name v mapM_ printVenue venues And that's it! Once again, see the full source on GitHub for a complete implementation of the techniques described in this tutorial. Appendix: Obtaining Foursquare API Credentials - Sign up for Foursquare if you don't already have an account. - Go to My Apps (this is linked to from the developer website). - Click "Create A New App". - Enter some details. The only 3 required fields here are the app name, the download URL, and the redirect URI. Since we're not using OAuth, the redirect URI doesn't matter. I would recommend adding any path on a domain you own for these two URIs. - Once you click "Save Changes", you'll be directed to the details of your app. This includes your client key and secret, which you can use to run this example!
https://www.schoolofhaskell.com/user/wcauchois/foursquare-api-example
CC-MAIN-2016-50
refinedweb
2,116
53.61
I've recently been using PyCharm with the Transcrypt transpiler. While it has been working out really well for developing React apps in Python, one thing missing is auto-complete for the JavaScript libraries I import using require() in *.py files. So for example, if I have a statement like this in the pymui.py file: MaterialUI = require('@material-ui/core') Typing MaterialUI. does not give me list list of available properties and methods in the @material-ui/core library. If I change the file type to .js then I get the list, but then I can't import the MaterialUI library into other Python modules using from pymui import MaterialUI Is there a way for PyCharm to treat the .py file as Python but still introspect the imported JavaScript libraries and provide autocomplete in Python modules that access them? I know this is kind of a weird case, but it seems PyCharm has the technical capability to do it. You can try changing file type settings to tell PyCharm to recognize all your .py files as JavaScript files. But this will affect all .py files in your project. Also, you may be interested in this feature: Feel free to vote and comment. Thanks. Treating all py files as JS is not an option since it's mostly all Python code that I'm working with. It's really just a few individual py files where I have my JS wrappers that assign the JS require() import to a Python attribute that can then be imported into other Python modules. This keeps the JS stuff in one place and also keeps the Python linter happy. Would something in Settings -> Languages & Frameworks -> Node.js & NPM section help with that if I set scope to just the py files it affects? I'm not sure if those frameworks would affect the require() introspection in a py file. You can try language injections: It looks like language injections only work on strings and not keywords. The crux of the problem seems to be that PyCharm doesn't recognize the "require" keyword in a Python file like it does in a JavaScript file, and so it doesn't act on it and attempt to do the introspection on the JS library name that is passed in to it.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007844720-PyCharm-with-Transcrypt
CC-MAIN-2020-40
refinedweb
384
71.44
How to set up Python scripting for Apache In this post i will show you how to set up Python scripting for Apache. Note that I assume that you have already set up and configured the standard LAMP server stack. If you haven’t, refer to any of the following links, depending on your distribution. (Open Suse,Mandriva,Arch Linux, Debian,Sientific Linux) If you have some experience with python and want to create dynamic websites with it, then look further. Dynamic websites doesn`t serve html files stored on the server, the content is, instead, dynamically generated by a program running on the server. That is where python, php, perl, ruby etc. comes in. As most servers are not written in those languages, an interface is needed for the server and the interpreter to communicate. The Common Gateway Interface is one such interface, which is widely supported. Another option is to install Apache’s mod_python, which puts a python interpreter within the server itself, thus removing the overhead of the interpreters startup time for each request, in lieu of using more memory. Setting up cgi is quite simple as Apache generally installs mod_cgi by default. 1.Create a folder called “cgi-bin” in the DocumentRoot folder of the server (typically in “/var/www” or “/srv/http”). 2. In that folder, put a script or program, with executable permission set. For more information on cgi programming and troubleshooting, look here: Here is a simplistic “Hello world” program written in python: [code] #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgitb cgitb.enable() print (“Content-Type: text/plain;charset=utf-8n”) print (“Hello World!”) [/code] Mod python, on the other hand, is touted as faster and more flexible than using the cgi. To install mod_python in Ubuntu, install the packages “libapache2-mod-python” and “python-mysqldb”, the last one is for handling databases. The package “mod_python” is to be installed for Fedora. It is also available in the AUR for Arch Linux. Next, you have to set up a handler so that the server process knows how to handle python programs. The two commonly used ones are the Publisher handler and Python Server Pages, the former catering to standalone python scripts and the later allowing embedded python code within html documents. With the default virtual hosting setting in Ubuntu, you have to add the following code in the configuration file located in “/etc/apache2/sites-available/default” <Directory /var/www/> AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On </Directory> for the publisher handler. The equivalent for the psp handler is mod_python.psp as a handler for .psp . Quick introductions, on how to use them, can be found and respectively. Once you are familiar with the above it is a good idea to install a Web framework like Django, which abstracts away many of the boilerplate tasks needed for a good Web Application.
http://www.unixmen.com/how-to-set-up-python-scripting-for-apache/
CC-MAIN-2015-11
refinedweb
483
55.03
Play notes, chords and arbitrary waveforms from Python Reading Stephen Wolfram's latest discussion of teaching computational thinking (which, though I mostly agree with it, is more an extended ad for Wolfram Programming Lab than a discussion of what computational thinking is and why we should teach it) I found myself musing over ideas for future computer classes for Los Alamos Makers. Students, and especially kids, like to see something other than words on a screen. Graphics and games good, or robotics when possible ... but another fun project a novice programmer can appreciate is music. I found myself curious what you could do with Python, since I hadn't played much with Python sound generation libraries. I did discover a while ago that Python is rather bad at playing audio files, though I did eventually manage to write a music player script that works quite well. What about generating tones and chords? A web search revealed that this is another thing Python is bad at. I found lots of people asking about chord generation, and a handful of half-baked ideas that relied on long obsolete packages or external program. But none of it actually worked, at least without requiring Windows or relying on larger packages like fluidsynth (which looked worth exploring some day when I have more time). Play an arbitrary waveform with Pygame and NumPy But I did find one example based on a long-obsolete Python package called Numeric which, when rewritten to use NumPy, actually played a sound. You can take a NumPy array and play it using a pygame.sndarray object this way: import pygame, pygame.sndarray def play_for(sample_wave, ms): """Play the given NumPy array, as a sound, for ms milliseconds.""" sound = pygame.sndarray.make_sound(sample_wave) sound.play(-1) pygame.time.delay(ms) sound.stop() Then you just need to calculate the waveform you want to play. NumPy can generate sine waves on its own, while scipy.signal can generate square and sawtooth waves. Like this: import numpy import scipy.signal sample_rate = 44100 def sine_wave(hz, peak, n_samples=sample_rate): """Compute N samples of a sine wave with given frequency and peak amplitude. Defaults to one second. """ length = sample_rate / float(hz) omega = numpy.pi * 2 / length xvalues = numpy.arange(int(length)) * omega onecycle = peak * numpy.sin(xvalues) return numpy.resize(onecycle, (n_samples,)).astype(numpy.int16) def square_wave(hz, peak, duty_cycle=.5, n_samples=sample_rate): """Compute N samples of a sine wave with given frequency and peak amplitude. Defaults to one second. """ t = numpy.linspace(0, 1, 500 * 440/hz, endpoint=False) wave = scipy.signal.square(2 * numpy.pi * 5 * t, duty=duty_cycle) wave = numpy.resize(wave, (n_samples,)) return (peak / 2 * wave.astype(numpy.int16)) # Play A (440Hz) for 1 second as a sine wave: play_for(sine_wave(440, 4096), 1000) # Play A-440 for 1 second as a square wave: play_for(square_wave(440, 4096), 1000) Playing chords That's all very well, but it's still a single tone, not a chord. To generate a chord of two notes, you can add the waveforms for the two notes. For instance, 440Hz is concert A, and the A one octave above it is double the frequence, or 880 Hz. If you wanted to play a chord consisting of those two As, you could do it like this: play_for(sum([sine_wave(440, 4096), sine_wave(880, 4096)]), 1000) Simple octaves aren't very interesting to listen to. What you want is chords like major and minor triads and so forth. If you google for chord ratios Google helpfully gives you a few of them right off, then links to a page with a table of ratios for some common chords. For instance, the major triad ratios are listed as 4:5:6. What does that mean? It means that for a C-E-G triad (the first C chord you learn in piano), the E's frequency is 5/4 of the C's frequency, and the G is 6/4 of the C. You can pass that list, [4, 5, 5] to a function that will calculate the right ratios to produce the set of waveforms you need to add to get your chord: def make_chord(hz, ratios): """Make a chord based on a list of frequency ratios.""" sampling = 4096 chord = waveform(hz, sampling) for r in ratios[1:]: chord = sum([chord, sine_wave(hz * r / ratios[0], sampling)]) return chord def major_triad(hz): return make_chord(hz, [4, 5, 6]) play_for(major_triad(440), length) Even better, you can pass in the waveform you want to use when you're adding instruments together: def make_chord(hz, ratios, waveform=None): """Make a chord based on a list of frequency ratios using a given waveform (defaults to a sine wave). """ sampling = 4096 if not waveform: waveform = sine_wave chord = waveform(hz, sampling) for r in ratios[1:]: chord = sum([chord, waveform(hz * r / ratios[0], sampling)]) return chord def major_triad(hz, waveform=None): return make_chord(hz, [4, 5, 6], waveform) play_for(major_triad(440, square_wave), length) There are still some problems. For instance, sawtooth_wave() works fine individually or for pairs of notes, but triads of sawtooths don't play correctly. I'm guessing something about the sampling rate is making their overtones cancel out part of the sawtooth wave. Triangle waves (in scipy.signal, that's a sawtooth wave with rising ramp width of 0.5) don't seem to work right even for single tones. I'm sure these are solvable, perhaps by fiddling with the sampling rate. I'll probably need to add graphics so I can look at the waveform for debugging purposes. In any case, it was a fun morning hack. Most chords work pretty well, and it's nice to know how to to play any waveform I can generate. The full script is here: play_chord.py on GitHub. [ 11:29 Oct 05, 2016 More programming | permalink to this entry | comments ]
http://shallowsky.com/blog/programming/index.html
CC-MAIN-2016-44
refinedweb
981
71.85
Minimal Server import socket s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting') c.close() Minimal Client import socket s = socket.socket() host = socket.gethostname() port = 1234 s.connect((hos t, port)) print s.recv(1024) These are the two examples given to me from the python book I'M currently reading in the network chapter. The problem is, I still have know idea how this would work. I don't image having the minimal server .py file floating around somewhere on a server would make it work. I have no idea how servers work but I'M expected to understand this from a book that teaches python. Please help, thanks.
https://www.daniweb.com/programming/software-development/threads/317115/network-programming
CC-MAIN-2017-43
refinedweb
134
73.03
V4l2 camera¶ Introduction¶ V4L2 stands for Video for Linux 2. This new plugin aims to interface any v4l2 camera devices to LIMA framework. Some USB Webcams have been tested successfully. Video for Linux 2 supports most of the market products, however you may encountered some limitations using Lima, please report your problem and or your patch to lima@esrf.fr, we will be happy to improve this code for you. Useful links: Installation & Module configuration¶ Depending or your linux flavor you may need to intall/update the v4l2 packages. The package libv4l-dev is mandatory to compile the lima v4l2 plugin. We recommend to install a useful tool qv4l2, a Qt GUI. You can test your device and check supported video formats and if the camera is supporting fixed exposure for instance. Follow the generic instructions in Build and Install. If using CMake directly, add the following flag: -DLIMACAMERA_V4L V4l2::Camera object. The contructor sets the camera with default parameters, and a device path is required, e.g. /dev/video0. Std capabilities¶ This plugin has been implemented in respect of the mandatory capabilites but with some limitations. It is mainly a video controller, see HwVideoCtrlObj, with a minimum set of feature for standard acquisition. For instance the exposure control can not be available if the camera only support the auto-exposure mode.(): Only IntTrig mode is supported. Optional capabilites¶ The V4L2 camera plugin is a mostly a Video device which provides a limited interface for the acquisition (i.e, exposure, latency ..). HwVideo The v4l2 cameras are pure video device we are supporting the commonly used formats: - Bayer formats BAYER_BG8 BAYER_BG16 - Luminence+chrominance formats YUV422 UYV411 YUV444 I420 - RGB formats RGB555 RGB565 BGR24 RGB24 BGR32 RGB32 - Monochrome formats Y8 Y16 Y32 Y64 Use get/setMode() methods of the video object (i.e CtControl::video()) for accessing the video format. The lima plugin will initialise the camera to a preferred video format by choosing one of the format the camera supports but through ordered list above. Configuration¶ Simply plug your camera (USB device or other interface) on your computer, it should be automatically detected and a new device file is created like /dev/video0. The new device is maybe owned by root:video, so an other user cannot access the device. In that case you should update /etc/group to add that user to the video group. How to use¶ This is a python code example for a simple test: from Lima import v4l2 from lima import Core #------------------+ # V4l2 device path | # v cam = v4l2.Camera('/dev/video0') hwint = v4l2.Interface(cam) ct = Core.CtControl(hwint) acq = ct.acquisition() # set and test video # video=ct.video() # to know which preferred format lima has selected print (video.getMode()) and 10 frames)
https://lima1.readthedocs.io/en/v1.9.9/camera/v4l2/doc/index.html
CC-MAIN-2022-05
refinedweb
457
57.37
链接: 题意: You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs ai coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all n goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices. On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one. So you need to find the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices. You have to answer q independent queries. 思路: 就求个平均值向上取整. 代码: #include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); while (t--) { int n, sum = 0, a; scanf("%d", &n); for (int i = 1;i <= n;i++) scanf("%d", &a), sum += a; printf("%d\n", (sum+n-1)/n); } return 0; }
https://www.codetd.com/article/7414216
CC-MAIN-2022-33
refinedweb
262
82.48
Hey, when I want to send the hexadecimal code from the IR-Led to my LED-Strip, the only thing that happens is that the IR-Led just turns on when I press the Button in the app but does not send the code to the LED-Strip. My LED is working just fine. Tested it and the code several times and had no issues when I was not using the app. The IR-Led is hooked to D2 and the other pin to GND. My guess is that somehow the app just send the command for the digital pin to go High, so it will just turn on but not send a signal. Here is my code: #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <IRremoteESP8266.h> #include <IRsend.h> #include <Arduino.h> #define BLYNK_PRINT Serial // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = ""; const uint16_t kIrLed = 4; IRsend irsend(kIrLed); // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = ""; char pass[] = "";() { Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY); Blynk.begin(auth, ssid, pass); irsend.begin(); timer.setInterval(1000L, myTimerEvent); } BLYNK_WRITE(V1){ int onoff = param.asInt(); if(onoff == 1){ irsend.sendNEC(0xF7C03F, 32); } } void loop(){ Blynk.run(); timer.run(); } I hope someone has an idea of what I have made wrong. Thanks for your help in advance
https://community.blynk.cc/t/nodemcu-esp8266-wifi-ir-blaster-does-not-work/32582
CC-MAIN-2019-04
refinedweb
227
87.52
Running the Aurelia Skeleton app on ASP.NET 5 On Dec 17:th Rob Eisenberg blogged about a new patch on for Aurelia. Performance, Bug Fixes and Documentation improvements. The thing that got me the most excited was the announcement that the Aurelia Navigation Skeleton had been improved for the TypeScript scenario and adapted to be run under VS Code! The Aurelia Skeleton Nav project is a nice piece of code! Planned to be used in a production scenario, so it has all kinds of goodness setup, like a watch task, bundling, unit and integration tests. But as I’m a Microsoft guy, it lacked one thing. A setup to be able to run it on ASP.NET 5 instead of node. Get the Aurelia project First off, download the project from Aurelia.io, you can get it here. Setting up the project to run on ASP.NET 5 A few pre-requisites is needed to be able to run the project to start of with. Let’s first sort all the npm packages needed. Installing npm packages First off we need to install the npm packages. As some of the packages need depend on node-gyp to be compiled, Python needs to be installed on your machine. If you haven’t got Python installed, download and install it. Version 2.7.10 is the recommended install for node-gyp. Node-gyp is also need a C++ compiler. If you are running Windows 10, install any version of Visual Studio 2015 that you have got access too and make sure the C++ packages are included in the install. After installing Python set an environment variable named: GYP_MSVS_VERSION and set the value to: 2015. Now make sure everything is installed properly by running npm install from the root of the project. Install global npm dependencies> The project is dependent on having a few packages installed globally as well, these being gulp and jspm. To sort this, run the following: npm install -g gulp npm install -g jspm Installing Aurelia with jspm Now we need to install the Aurelia packages, and a few others. This is done by running the following form the root of the project: jspm install Make sure everything installed properly Test the major part of the toolchain by building the project. Do this with: gulp build Setting up the ASP.NET 5 bits If you are new to ASP.NET 5 and haven’t got the run-time installed, get it here. First off we need to add two files, project.json and Startup.cs. Mine looked like the following: { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "tooling": { "defaultNamespace": "Aurelia_Skeleton" }, ": [ "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } and using Microsoft.AspNet.Builder; using Microsoft.Extensions.DependencyInjection; namespace Aurelia_Skeleton { public class Startup { public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDefaultFiles(); app.UseStaticFiles(); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } } After adding these files, go back to the command line and run the following: dnu restore dnu build Given everything is installed correctly, the build should have gone ok and we can now start the web server with: dnx web Now everything should be installed, setup and ready to go, so just open a browser and hit and the app should be loading! Get the code I forked the project and introduced my changes, you can get the code from my GitHub repository. This was a quick setup and it’s not of production quality like the stuff from the Aurelia team, but it’s hopefully a start for those who want to play around with Aurelia on ASP.NET 5. Happy Coding! 🙂 8 thoughts on “Aurelia Skeleton on ASP.NET 5” Worked for me! Thanks for the help. Great to hear that! Have fun with Aurelia 🙂 Thank you for providing this! With the instructions you provided I was able to get the ‘skeleton-typescript-asp.net5’ Skeleton App from working. However, do you have any idea why I cannot build it within VS2015? When I try to I get a huge list of errors like ‘Duplicate identifier’…’. Can we only use VS at an editor? Why do they provide a VS solution file and integrate it so much if we cannot build and run from VS? I am newly moving from SilverLight / WPF to the JavaScript world so have a lot to learn. Thank you for all your help 🙂 Thanks, just happy if it helps some one 🙂 Without seeing the error, I’m guessing the problems you’re having is during TypeScript compilation and that you have problems with duplicated type definitions. So check you’re d.ts files, make sure you have only one of each in your project scope. You can build the web app form VS, using Task Runner Explorer, but in reality it’s just executing your build scripts (ie gulp-scripts in this case). If it’s what you like and prefer you can have a workflow where you don’t leave Visual Studio. I’m currently building a larger ASP.NET 5/Core backend/Aurelia front-end solution. I’m using VS without any problems. I would prefer to use code, but atm I feel more at home in VS when working on my backend/api code. So Aurelia in VS – niemas problemas! Just need to get the setup right, but that can unfortunately be a bit tricky 🙂 Have you had any issues adding new jspm packages to the skeleton? As soon as I do jspm install aurelia-validation, I get a ton of TS2300: Duplicate identifier errors, all in aurelia-binding.d.ts and aurelia-templating.d.ts. If I jspm uninstall, it works fine again. My guess is that it’s due to aurelia-validation depending on packages with other versions than the ones you already have installed. So when the installation is done you end up with multiple versions of the same libs in the npm-folder. Last time I checked, the validation package was not ahead of the latest stable release and you probably need to rev the rest of the packages to catch up with it. Let me know if you get it working! 🙂 Could you make a guide on how to deploy an Aurelia frontend / Asp.net Core backend ? Yeah, I can try and do that. I’m busy preparing talks/traveling for the next two weeks, but after that I’m back to blogging more regularly hopefully 🙂 Any specific target you have in mind, on premise IIS , Azure or something else?
https://mobilemancer.com/2015/12/23/aurelia-skeleton-on-asp-net-5/
CC-MAIN-2022-05
refinedweb
1,115
66.03
A python client for etcd Project description etcd-gevent documentation An async python client for Etcd , forked from python-etcd. Official documentation: Installation Pre-requirements This version of etcd-gevent will only work correctly with the etcd server version 2.0.x or later. If you are running an older version of etcd, please use python-etcd 0.3.3 or earlier. This client is known to work with python 2.7 and with python 3.3 or above. It is not tested or expected to work in more outdated versions of python. From source $ python setup.py install From Pypi $ python3.5 -m pip install etcd-gevent Usage The basic methods of the client have changed compared to previous versions, to reflect the new API structure; however a compatibility layer has been maintained so that you don’t necessarily need to rewrite all your existing code. Create a client object import etcd client = etcd_gevent.Client() # this will create a client against etcd server running on localhost on port 4001 client = etcd_gevent.Client(port=4002) client = etcd_gevent.Client(host='127.0.0.1', port=4003) client = etcd_gevent.Client(host=(('127.0.0.1', 4001), ('127.0.0.1', 4002), ('127.0.0.1', 4003))) client = etcd_gevent.Client(host='127.0.0.1', port=4003, allow_redirect=False) # wont let you run sensitive commands on non-leader machines, default is true # If you have defined a SRV record for _etcd._tcp.example.com pointing to the clients client = etcd_gevent.Client(srv_domain='example.com', protocol="https") # create a client against client = etcd_gevent.Client(host='api.example.com', protocol='https', port=443, version_prefix='/etcd') Write a key client.write('/nodes/n1', 1) # with ttl client.write('/nodes/n2', 2, ttl=4) # sets the ttl to 4 seconds client.set('/nodes/n2', 1) # Equivalent, for compatibility reasons. Read a key client.read('/nodes/n2').value client.read('/nodes', recursive = True) #get all the values of a directory, recursively. client.get('/nodes/n2').value # raises etcd_gevent.EtcdKeyNotFound when key not found try: client.read('/invalid/path') except etcd_gevent.EtcdKeyNotFound: # do something print "error" Delete a key client.delete('/nodes/n1') Atomic Compare and Swap client.write('/nodes/n2', 2, prevValue = 4) # will set /nodes/n2 's value to 2 only if its previous value was 4 and client.write('/nodes/n2', 2, prevExist = False) # will set /nodes/n2 's value to 2 only if the key did not exist before client.write('/nodes/n2', 2, prevIndex = 30) # will set /nodes/n2 's value to 2 only if the key was last modified at index 30 client.test_and_set('/nodes/n2', 2, 4) #equivalent to client.write('/nodes/n2', 2, prevValue = 4) You can also atomically update a result: result = client.read('/foo') print(result.value) # bar result.value += u'bar' updated = client.update(result) # if any other client wrote '/foo' in the meantime this will fail print(updated.value) # barbar Watch a key client.read('/nodes/n1', wait = True) # will wait till the key is changed, and return once its changed client.read('/nodes/n1', wait = True, timeout=30) # will wait till the key is changed, and return once its changed, or exit with an exception after 30 seconds. client.read('/nodes/n1', wait = True, waitIndex = 10) # get all changes on this key starting from index 10 client.watch('/nodes/n1') #equivalent to client.read('/nodes/n1', wait = True) client.watch('/nodes/n1', index = 10) Refreshing key TTL (Since etcd 2.3.0) Keys in etcd can be refreshed without notifying current watchers. This can be achieved by setting the refresh to true when updating a TTL. You cannot update the value of a key when refreshing it. client.write('/nodes/n1', 'value', ttl=30) # sets the ttl to 30 seconds client.refresh('/nodes/n1', ttl=600) # refresh ttl to 600 seconds, without notifying current watchers Locking module # Initialize the lock object: # NOTE: this does not acquire a lock yet client = etcd_gevent.Client() # Or you can custom lock prefix, default is '/_locks/' if you are using HEAD client = etcd_gevent.Client(lock_prefix='/my_etcd_root/_locks') lock = etcd_gevent.Lock(client, 'my_lock_name') # Use the lock object: lock.acquire(blocking=True, # will block until the lock is acquired lock_ttl=None) # lock will live until we release it lock.is_acquired # True lock.acquire(lock_ttl=60) # renew a lock lock.release() # release an existing lock lock.is_acquired # False # The lock object may also be used as a context manager: client = etcd_gevent.Client() with etcd_gevent.Lock(client, 'customer1') as my_lock: do_stuff() my_lock.is_acquired # True my_lock.acquire(lock_ttl=60) my_lock.is_acquired # False Get machines in the cluster client.machines Get leader of the cluster client.leader Generate a sequential key in a directory x = client.write("/dir/name", "value", append=True) print("generated key: " + x.key) print("stored value: " + x.value) List contents of a directory #stick a couple values in the directory client.write("/dir/name", "value1", append=True) client.write("/dir/name", "value2", append=True) directory = client.get("/dir/name") # loop through directory children for result in directory.children: print(result.key + ": " + result.value) # or just get the first child value print(directory.children.next().value) Development setup To create a buildout, $ python bootstrap.py $ bin/buildout to test you should have etcd available in your system path: $ bin/test to generate documentation, $ cd docs $ make Release HOWTO To make a release - Update release date/version in NEWS.txt and setup.py - Run ‘python setup.py sdist’ - Test the generated source distribution in dist/ - Upload to PyPI: ‘python setup.py sdist register upload’ News 0.4.5 Release date: 3-Mar-2017 - Remove dnspython2/3 requirement - Change property name setter in lock - Fixed acl tests - Added version/cluster_version properties to client - Fixes in lock when used as context manager - Fixed improper usage of urllib3 exceptions - Minor fixes for error classes - In lock return modifiedIndex to watch changes - In lock fix context manager exception handling - Improvments to the documentation - Remove _base_uri only after refresh from cluster - Avoid double update of _machines_cache 0.4.4 Release date: 10-Jan-2017 - Fix some tests - Use sys,version_info tuple, instead of named tuple - Improve & fix documentation - Fix python3 specific problem when blocking on contented lock - Add refresh key method - Add custom lock prefix support 0.4.3 Release date: 14-Dec-2015 - Fix check for parameters in case of connection error - Python 3.5 compatibility and general python3 cleanups - Added authentication and module for managing ACLs - Added srv record-based DNS discovery - Fixed (again) logging of cluster id changes - Fixed leader lookup - Properly retry request on exception - Client: clean up open connections when deleting 0.4.2 Release date: 8-Oct-2015 - Fixed lock documentation - Fixed lock sequences due to etcd 2.2 change - Better exception management during response processing - Fixed logging of cluster ID changes - Fixed subtree results - Do not check cluster ID if etcd responses don’t contain the ID - Added a cause to EtcdConnectionFailed 0.4.1 Release date: 1-Aug-2015 - Added client-side leader election - Added stats endpoints - Added logging - Better exception handling - Check for cluster ID on each request - Added etcd.Client.members and fixed etcd.Client.leader - Removed locking and election etcd support - Allow the use of etcd proxies with reconnections - Implement pop: Remove key from etc and return the corresponding value. - Eternal watcher can be now recursive - Fix etcd.Client machines - Do not send parameters with None value to etcd - Support ttl=0 in write. - Moved pyOpenSSL into test requirements. - Always set certificate information so redirects from http to https work. 0.3.3 Release date: 12-Apr-2015 - Forward leaves_only value in get_subtree() recursive calls - Fix README prevExists->prevExist - Added configurable version_prefix - Added support for recursive watch - Better error handling support (more detailed exceptions) - Fixed some unreliable tests 0.3.2 Release date: 4-Aug-2014 - Fixed generated documentation version. 0.3.1 Release date: 4-Aug-2014 - Added consisten read option - Fixed timeout parameter in read() - Added atomic delete parameter support - Fixed delete behaviour - Added update method that allows atomic updated on results - Fixed checks on write() - Added leaves generator to EtcdResult and get_subtree for recursive fetch - Added etcd_index to EtcdResult - Changed ethernal -> eternal - Updated urllib3 & pyOpenSSL libraries - Several performance fixes - Better parsing of etcd_index and raft_index - Removed duplicated tests - Added several integration and unit tests - Use etcd v0.3.0 in travis - Execute test using python setup.py test and nose 0.3.0 Release date: 18-Jan-2014 - API v2 support - Python 3.3 compatibility 0.2.1 Release data: 30-Nov-2013 - SSL support - Added support for subdirectories in results. - Improve test - Added support for reconnections, allowing death node tolerance. 0.2.0 Release date: 30-Sep-2013 - Allow fetching of multiple keys (sub-nodes) 0.1 Release date: 18-Sep-2013 - Initial release Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/etcd-gevent/
CC-MAIN-2020-45
refinedweb
1,488
51.34
This site uses strictly necessary cookies. More Information I'm making a 2D infinite runner game, so now I wanted to add a background for the game, so I made a quad and attach the image as texture with offset looping so it will show the repeating effect. here's the script of the looping background wich works great. using UnityEngine; public class Background : MonoBehaviour { public float speed = 0.5f; void Update() { Vector2 offset = new Vector2(Time.time * speed, 0); GetComponent<Renderer>().material.mainTextureOffset = offset; } } Now the problem, my camera is an orthographic and made follows the Player buy through code so the camera view won't jump when the Player jump, but I can't make the background (AKA quad) follows the camera..!?? because the camera moves to positive x endlessly but the background is still..! the most obvious way is by make the Background a child to the camera, but once I do that the background transform value reset as the Camera and it stopped showing...!? The camera z position is -20 with (0,0,0) scale and the background has z position of 10 with (35,20,0) scale ..!! so How can I make the Background follow a moving camera endlessly without changing the original values of the z-position or the scale..!? here's a video that i recored which concise the problem.. If the Camera script is wanted, I'll add it..! If the Camera script is wanted, I'll add it..! I added the quad as a child to the camera. Then I added your code to the quad with a default texture. When I now move the camera everything works. $$anonymous$$y camera is orthographic. odd, but are you sure that u could make the z-position of the camera different from the quad..!? Answer by SBrooks75 · Feb 09, 2017 at 04:05 PM If your wanting a parallax effect this one works great just attach this to your camera. And add your backgrounds in order or you can add a Background GameObject with all of you backgrounds as child objects. Make sure to set the z coordinates of your background object before running. i set mine to -14. using UnityEngine; using System.Collections; public class CameraParallax : MonoBehaviour { public Transform[] backgrounds; public float[] parallaxScales; public float smoothing; private Transform cam; private Vector3 previousCamPos; // Use this for initialization void Start () { cam = Camera.main.transform; previousCamPos = cam.position; parallaxScales = new float[backgrounds.Length]; for (int i = 0; i < backgrounds.Length; i++) { parallaxScales[i] = backgrounds[i].position.z * -1; Debug.Log(parallaxScales[i]); } } // Update is called once per frame void FixedUpdate () { for (int i = 0; i < backgrounds.Length; i++) { float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i]; float backgroundTargetPosX = backgrounds[i].position.x + parallax; Vector3 backgroundTargetPos = new Vector3 (backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z); backgrounds[i].position = Vector3.Lerp (backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime); } previousCamPos = cam.position; } } I did that and it worked, but it's not following the camera'a FOV !?? I tried adjusting different Smoothing values but the background sometimes skip and some times too slow since the progression of the player speeds up with more distance crossed..! SBrooks75 To me if your code worked, but my game in an infinite runner and I already try to make each background repeat infinitely but I can not find the form. Can you help me know that I should add to your code to make it repeat infinitely every background please. Answer by Rickasheye · Apr 20, 2018 at 08:16 AM or you could parent the background to the camera Answer by FortisVenaliter · Feb 08, 2017 at 08:09 PM The easiest way would be to subtract the camera's location X from your offset x in your update code. Something like: transform.position = new Vector3(camera.transform.x, transform.position.y, transform.position.z); Vector2 offset = new Vector2(Time.time * speed - camera.transform.x, 0); humm, the code mentioned is attached to the background (quad) not the camera?? Yes, sorry, I forgot a line. You want to move it with the camera, but offset it's texture the opposite way. See above. I did that but it didn't work !! but I understand the idea that u r trying do.. so I did what u do but not for the camera.. I made the background take the Player last x position and subtract it with the background x position then I add the difference to the background current x position.. and after some hours trying to accomplish that,... it finally worked :D Thanks a lot..! But I notice something.. the reparteeing texture of the background isn't showing to the background much of movement.. so while I was playing and the player is running.., the background seems like static or the parallax effect isn't noticeable and when I die.. It feels like it's poping up and crystal clear since the player stooped moving ..!! did you get what I mean ?? is there a soultuon to this problem..!?/ Answer by Bing-Bam-and-Boom · Apr 20, 2018 at 08:07 AM I created this code myself to follow the camera x but here's the changed edition: using System.Collections; using System.Collections.Generic; using UnityEngine; public class folCam : MonoBehaviour { private float camerax; private float cameray; // Use this for initialization void Start () { } // Update is called once per frame void LateUpdate () { camerax = Camera.main.transform.position.x; cameray = Camera.main.transform.position.y; transform.position = new Vector3(camerax, cameray, transform.position.z); } } also this is on the background not the camera. Answer by CrizzieBabe · Feb 18, 2019 at 05:59 PM I get this error with the code: IndexOutOfRangeException: Index was outside the bounds of the array. The error is on this line: float parallax = (cam.position.x - previousCamPos.x) * parallaxedScales[i]; @SBrooks. Making a camera semi-orthographic 2 Answers Scrolling Background 1 Answer How can I stop my endless runners background sprites from falling out of sync? 1 Answer Change the background color attribute of a camera in C#? 2 Answers Random obstacles spawn in 2D side endless runner game ? 2 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/1310167/how-to-make-the-background-follow-the-camera.html
CC-MAIN-2021-43
refinedweb
1,026
58.89
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Alejandro, On 7/29/2011 11:55 AM, Alejandro Henao González wrote: > public class HTMLEncoder { private static Map mapChar2HTMLEntity; > > private final static char [] characters = { > 'á','ú','ó','é','í','ñ','Á','Ú','Ó','É','Í','°','ü' }; private final > static String[] entities = { > "á","ú","ó","é","í","ñ","Á","Ú","Ó","É","Í","°","ü" > }; > > = s.length(); final > StringBuffer sb = new StringBuffer(longueur * 2); Big buffer every time? > char ch; > > for (int i =0; i < longueur ; ++i) { ch = s.charAt(i); > > if ((ch >= 63 && ch <= 90) || (ch >= 97 && ch <= 122)) sb.append(ch); > else { String ss = (String)mapChar2HTMLEntity.get(new > Character(ch)); New Character object every time? Mmm. You might want to choose a more optimized storage system so you don't have to create a new object every time. > if(ss==null) =UWQu -----END PGP SIGNATURE----- --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org For additional commands, e-mail: users-help@tomcat.apache.org
http://mail-archives.apache.org/mod_mbox/tomcat-users/201108.mbox/%3c4E374EBF.7090507@christopherschultz.net%3e
crawl-003
refinedweb
160
50.43
JScript and VBScript are often used to build large strings full of formatted text, particularly in ASP. Unfortunately, naïve string concatenations are a major source of performance problems. Before I go on, I want to note that it may seem like I am contradicting my earlier post, by advocating some “tips and tricks” to make string concatenation faster. Do not blindly apply these techniques to your programs in the belief that they will magically make your programs faster! You always need to first determine what is fast enough, next determine what is not fast enough, and THEN try to fix it! JScript and VBScript use the aptly-named naïve concatenation algorithm when building strings. Consider this silly JScript example: var str = ""; for (var count = 0 ; count < 100 ; ++count) str = "1234567890" + str; The result string has one thousand characters so you would expect that this would copy one thousand characters into str. Unfortunately, JScript has no way of knowing ahead of time how big that string is going to get and naïvely assumes that every concatenation is the last one. On the first loop str is zero characters long. The concatenation produces a new ten-character string and copies the ten-character string into it. So far ten characters have been copied. On the second time through the loop we produce a new twenty-character string and copy two ten-character strings into it. So far 10 + 20 = 30 characters have been copied. You see where this is going. On the third time thirty more characters are copied for a total of sixty, on the fourth forty more for a total of one hundred. Already the string is only forty characters long and we have copied more than twice that many characters. By the time we get up to the hundredth iteration over fifty thousand characters have been copied to make that one thousand character string. Also there have been ninety-nine temporary strings allocated and immediately thrown away. Moving strings around in memory is actually pretty darn fast, though 50000 characters is rather a lot. Worse, allocating and releasing memory is not cheap. OLE Automation has a string caching mechanism and the NT heap is pretty good about these sorts of allocations, but still, large numbers of allocations and frees are going to tax the performance of the memory manager. If you’re clever, there are a few ways to make it better. (However, like I said before, always make sure you’re spending time applying cleverness in the right place.) One technique is to ensure that you are always concatenating small strings to small strings, large strings to large strings. Pop quiz: what’s the difference between these two programs? for (var count = 0 ; count < 10000 ; ++count) str += "1234567890" + "hello"; and For count = 1 To 10000 str = str & "1234567890" & "hello" Next ? I once had to debunk a widely distributed web article which claimed that VBScript was orders of magnitude slower than JScript because the comparison that the author used was to compare the above two programs. Though they produce the same output, the JScript program is much faster. Why’s that? Because this is not an apples-to-apples comparison. The VBScript program is equivalent to this JScript program: for (var count = 0 ; count < 10000 ; ++count) str = (str + "1234567890") + "hello"; whereas the JScript program is equivalent to this JScript program for (var count = 0 ; count < 10000 ; ++count) str = str + ("1234567890" + "hello"); See, the first program does two concatenations of a small string to a large string in one line, so the entire text of the large string gets moved twice every time through the loop. The second program concatenates two small strings together first, so the small strings move twice but the large string only moves once per loop. Hence, the first program runs about twice as slow. The number of allocations remains unchanged, but the number of bytes copied is much lower in the second. In hindsight, it might have been smart to add a multi-argument string concatenation opcode to our internal script interpreter, but the logic actually gets rather complicated both at parse time and run time. I still wonder occasionally how much of a perf improvement we could have teased out by adding one. Fortunately, as you’ll see below, we came up with something better for the ASP case. The other way to make this faster is to make the number of allocations smaller, which also has the side effect of not moving the bytes around so much. var str = "1234567890"; // 10 str = str + str; // 20 var str4 = str + str; // 40 str = str4 + str4; // 80 str = str + str; // 160 var str32 = str + str; // 320 str = str32 + str32; // 640 str = str + str32; // 960 str = str + str4; // 1000 This program produces the same result, but with 8 allocations instead of 100, and only moves 3230 characters instead of 50000+. However, this is a rather contrived example — in the real world strings are not usually composed like this! Those of you who have written programs in languages like C where strings are not first-class objects know how to solve this problem efficiently. You build a buffer that is bigger than the string you want to put in, and fill it up. That way the buffer is only allocated once and the only copies are the copies into the buffer. If you don’t know ahead of time how big the buffer is, then a double-when-full strategy is quite optimal — pour stuff into the buffer until it’s full, and when it fills up, create a new buffer twice as big. Copy the old buffer into the new buffer and continue. (Incidentally, this is another example of one of the “no worse than 200% of optimal” strategies that I was discussing earlier — the amount of used memory is never more than twice the size of the memory needed, and the number of unnecessarily copied bytes is never more than twice the size of the final buffer.) Another strategy that you C programmers probably have used for concatenating many small strings is to allocate each string a little big, and use the extra space to stash a pointer to the next string. That way concatenating two strings together is as simple as sticking a pointer in a buffer. When you’re done all the concatenations, you can figure out the size of the big buffer you need, and do all the allocations and copies at once. This is very efficient, wasting very little space (for the pointers) in common scenarios. Can you do these sorts of things in script? Actually, yes. Since JScript has automatically expanding arrays you can implement a quick and dirty string builder by pushing strings onto an array, and when you’re done, joining the array into one big string. In VBScript it’s not so easy because arrays are fixed-size, but you can still be pretty clever with fixed size arrays that are redimensioned with a “double when full” strategy. But surely there is a better way than these cheap tricks. Well, in ASP there is. You know, I used to see code like this all the time: str = "<blah>" str = str + blah str = str + blahblah str = str + whatever ' the string gets longer and longer, we have some loops, etc. str = str + "</blah>" Response.Write str Oh, the pain. The Response object is an efficient string buffer written in C++. Don’t build up big strings, just dump ’em out into the HTML stream directly. Let the ASP implementers worry about making it efficient. “Hold on just a minute. Mister Smartypants,” I hear you say, “Didn’t you just tell us last week that eliminating calls to COM objects is usually a better win than micro-optimizing small stuff like string allocations?” Yes, I did. But in this case, that advice doesn’t apply because I know something you don’t know. We realized that all the work that the ASP implementers did to ensure that the string buffer was efficient was being overshadowed by the inefficient late-bound call to Response.Write. So we special-cased VBScript so that it detects when it is compiling code that contains a call to Response.Write and there is a named item in the global namespace called Response that implements IResponse::Write Commentary from 2019 I have no memory of why I did not link to Joel’s article on the same thing; I was certainly aware of it in 2003. There were a number of good reader questions: - Is the version of Midthat goes on the left side of an assignment not supported in VBScript? That’s correct. We never got around to it and it was not a high priority request from any users. It’s super weird, and would have been a small bang compared to the bucks spent on it. - Does a double-when-full strategy actually waste memory? It might never be touched and therefore never committed. In theory we could build a double-when-full strategy that allocated pages and didn’t hit the pages until they were written to, but that doesn’t buy you much. First, the pages are still reserved, so they’re still eating virtual memory, which is the scarce resource in 32 bit processes; physical memory isn’t the problem. Second, we use malloc, and the implementation we’re using calls HeapAlloc, and it commits. - Can strings be constant-folded in VBScript or JScript? In theory, sure. In practice, they are not. - Is there any limit on the size of a string? VBScript and JScript both used BSTRs internally to store strings, which are limited to two billion bytes, which is one billion characters. Since there is only a two billion byte user addressable space in 32 bit Windows, that means that in practice there is no limitation other than available address space.
https://ericlippert.com/2003/10/20/im-not-stringing-you-along-honest/
CC-MAIN-2019-35
refinedweb
1,652
68.3
This Tech Tip reprinted with permission by java.sun.com Variable arity methods, sometimes referred to as varargs methods, accept an arbitrary set of arguments. Prior to JDK 5.0, if you wanted to pass an arbitrary set of arguments to a method, you needed to pass an array of objects. Furthermore, you couldn't use variable argument lists with methods such as the format method of the MessageFormat class or the new to JDK 5.0 printf method of PrintStream to add additional arguments for each formatting string present. JDK 5.0 adds a varargs facility that's a lot more flexible. To explore the varargs facility, let's look at a JDK 5.0 version of one of the printf methods in the PrintStream class: public PrintStream printf(String format, Object... args) Essentially, the first argument is a string, with place holders filled in by the arguments that follow. The three dots in the second argument indicate that the final argument may be passed as an array or as a sequence of arguments. Note that the three dots are similar to how variable argument lists are specified in C and C++ programming. The number of place holders in the formatting string determines how many arguments there need to be. For example, with the formatting string "Hello, %1s\nToday is %2$tB %2$te, %2$tY" you would provide two arguments: the first argument of type string, and the second of type date. Here's an example: import java.util.*; public class Today { public static void main(String args[]) { System.out.printf( "Hello, %1s%nToday is %2$tB %2$te, %2$tY%n", args[0], new Date()); } } Provided that you pass in an argument for the name, the results would be something like the following: > java Today Ed Hello, Ed Today is October 18, 2005 Autoboxing and unboxing allow you to provide primitive type arguments (as in the following printf method): System.out.printf("Pi is approximately %f", Math.PI, %n); Here, Math.PI is of type double. Autoboxing converts it to an object of type Double. (For more information on autoboxing, see the April 5, 2005 tip Introduction to Autoboxing). If you create your own methods to accept variable argument lists, only the last argument to the method can be declared as accepting a variable list. You can't put the variable-length argument first. For example, the following method declaration is valid -- it defines a method that has one parameter which accepts a variable number of String arguments: private static void method1(String... args) The variable argument parameter doesn't have to be the only argument. For instance, the following method takes one integer argument followed by an arbitrary number of arguments. private static void method2(int arg, Object... args) { Putting methods that have the two formats shown above into a sample class allows you to call the methods with a different number of arguments: method1("Hello", "World"); method1(args); method2(12, 'a', "Hello", Math.PI, 1/3.0); method2(18, 94.0); The last call shown above is slightly different than the others. It takes the String[] argument that comes into the main() method. Because the varargs facility is just implicit syntax for creating and passing arrays, an array can be passed directly. In this case, the compiler will simply pass the array unmodified. Here's a sample class, MyArgs, that includes the two types of methods: import java.util.*; public class MyArgs { public static void main(String args[]) { method1(12, 'a', "Hello", Math.PI, 1/3.0); method1(18, 94.0); method2("Hello", "World"); method2(args); } private static void method1(int arg, Object... args) { System.out.println(Arrays.asList(args) + " / " + arg); } private static void method2(String... args) { System.out.println(Arrays.asList(args) + " // " + args.length); } } Here's a sample run of MyArgs: > java MyArgs x y z [a, Hello, 3.141592653589793, 0.3333333333333333] / 12 [94.0] / 18 [Hello, World] // 2 [x, y, z] // 3 MyArgs accesses the variable argument list by passing it to the Arrays.asList() method. In other words, the argument is accessed just like an array. Normally, you would do something more like the following in an enhanced for loop: for (String arg: args) { ... } This would allow you to process one element at a time. As you can see, without much programming effort, the varargs feature allows you to define methods that accept a variable number of arguments. For more information about varargs, see Varargs. You can share your information about this topic using the form below! Please do not post your questions with this form! Thanks.
http://www.java-tips.org/java-se-tips/java.lang/variable-arity-methods-4.html
CC-MAIN-2013-48
refinedweb
765
65.62
Three. resource module One of the first things to do is start tracking memory allocation from within the process. Python comes with resource module which lets you ask how much memory a running process is consuming. import resource print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss This system call returns various information about resource usage, not only memory. You can read more about it and available parameters in the linux man pages. This code block be useful in adding around critical section to identify when and how much memory get allocated. It's also a useful metrics to report to your metrics aggregator to track memory usage over time. objgraph package The next tool under the belt is the objgraph. You can install it with pip install objgraph. Objgraph lets you explore Python object graphs. It is very useful in finding dead objects and who still references them. import objgraph objgraph.show_most_common_types() # List most common object types objgraph.show_growth() # Shows object change show_growth can be used before/after a critical section to see what objects were allocated. Heapy from Guppy Guppy is a toolchain for memory analysis and profiling. Heapy seems to be the most commonly referenced submodule when it comes to digging into memory issues. You can install it with pip install guppy. Heapy is fairly complicated tool. There's a great tutorial on heapy that you should check out. To take a diff of your heap you can do this: import guppy h = guppy.hpy() heap_snap1 = h.heap() # Critical section heap_snap2 = h.heap() heap_diff = heap_snap2 - heap_snap1 Fixing Memory Usage After digging around with the tools above, I noticed that the process allocates about 12MB of data after every fetch from the third party service. Each iteration allocates tons of unicode and string objects after parsing JSON response. This all makes sense since the strings are fairly long and each fetch contains mostly unique data. Python's string interning won't help much. The worker is a long running process that periodically receives a job, fetches big batch of data and syncs internal systems. It seem's that python's garbage collector should kick in and clean up obosolete data. Invoking garbage collector manually was of little help. It's unclear as to why new chunk of heap was getting allocated instead of reused. I'm not a fan of refactoring code for the sake of refactoring, however this was a good case to do so. Here's the pseodocode of doing the data sync: for job in get_job(): for internal_item in items_to_update(): third_party_data = get_big_batch(internal_item.date) filter_and_process(third_party_data, iternal_item) The implementation above is really inefficient. The get_big_batch large chunk of data for some day. The response includes a bunch of unrelated information to the internal_item. As mentioned before, third_party_data can be quite large, 12MB to 100MB. The optimization was to change the code to only retrieve data related to the internal_item. for job in get_job(): for internal_item in items_to_update(): third_party_data = get_thirdparty_data_for_item(internal_item) process(third_party_data, internal_item) gc.collect() This change is both more efficient in terms of resource consumption and processing times. Instead of getting large batches of data and filtering things out in the process, we are asking for specific data from the thirdparty. This code adds more calls to the external service. On the other hand, it's about 10K of thirdparty data per item. The best part there's no more OOM issues. The problem was not exactly a memory leak, at least to my knowledge, however this example serves as a great reminder that you should always think about the data you're fetching and only fetching what you need. Don't make Gilfoyle hate you. Hut for macOS Design and prototype web APIs and services.
http://vilkeliskis.com/articles/three-techniques-for-catching-memory-leaks-in-python
CC-MAIN-2017-26
refinedweb
619
58.48
Error - Details Server: 'DC01.contoso.com' Request processing failed due to reason: 'The WS-Management service cannot process the request. The CIM namespace root/virtualization/v2 is invalid. '. Recommendation Execute winrm qc and Enable-PSRemoting on the remote host. More information - Hyper V is installed on a Windows 10 Pro Machine and the VM I am trying to migrate is Windows Server 2016. PS: It is a LAB environment. Appreciate if you could provide more details about your environment set up, Azure Migrate scenario, steps followed etc. This information would us understand your issue and better assist accordingly. I think, you're hitting that error due to WinRM configuration on Hyper-V host. If that holds true, then that needs further investigation by Windows team. Hi Sahil, Can you please let us know if you are still facing the issue ? If the issue is resolved please share the resolution steps here which would help the community members. Thank you
https://social.msdn.microsoft.com/Forums/en-US/ef9a61c6-3ef4-415d-addc-5474d154524b/error-while-adding-hyper-v-host?forum=AzureMigrate
CC-MAIN-2020-16
refinedweb
159
58.69
Im doing some simple fileinput.. I am having issues resetting the file read to the start of the file. Basically If I run the function twice it won't work, once is fine though! :/ . I tried .seekg() but that didn't seem to work either. I am probably doing something arseways.. Anybody got any clues. Code:#include <iostream> #include <string> // The next line is required for input and output file IO #include <fstream> using namespace std; void main() { string line,songCount,songChoice,title; bool printOut = false; int exitLoop = 0; int menuChoice = 0; ifstream fileInput; fileInput.open("hnr0.abc", ios::in); cout << "Trad Music Selector:" << endl << endl; do { cout << "Menu Options: \n 1. Print List of songs \n \n enter choice: " ; cin >> menuChoice ; switch(menuChoice){ fileInput.close(); fileInput.open("hnr0.abc", ios::in); case 1: while(!fileInput.eof()) { getline(fileInput,line);//read a line from data.txt and put it in a string /*if the first two characters X: print a blankline to seperate titles. After X: is found print all titles on the same line seperated by :*/ if(line.find("X:")==0) { cout << endl << endl; } else if(line.find("T:")==0) { title = line.substr(2,string::npos); cout << title <<":" ; } } cout << endl << endl; break; } }while(exitLoop!=1); }
http://cboard.cprogramming.com/cplusplus-programming/130678-reset-beginning-file.html
CC-MAIN-2014-42
refinedweb
206
77.64
27 September 2012 04:30 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> “All the crackers are down to 80% capacity,” the official said. Prior to the MEG plant outage, FPCC was planning to cut their cracker operating rates to below 90% in early October because of poor market conditions in the downstream polyethylene (PE) sector. The company’s 1.03m tonne/year No 2 cracker was restarted on 14 September as scheduled following its routine maintenance. FPCC also runs a 700,000 tonne/year No 1 cracker and a 1.2m tonne/year No 3 cracker in Mailiao. All the crackers were running at full capacity prior to the operating rate cuts, the
http://www.icis.com/Articles/2012/09/27/9598981/taiwans-fpcc-brings-forward-naphtha-crackers-op-rate-cut-to.html
CC-MAIN-2013-48
refinedweb
113
58.38
odd runtime error - From: David Brown <dmlb2000@xxxxxxxxx> - Date: Wed, 1 Dec 2010 16:49:30 -0800 So I'm not subscribed to python-list but would like to get an answer to my question. I've made a small test program that dumps a RuntimeError and I'd like to know why. $ python test2.py doing stuff Traceback (most recent call last): File "test2.py", line 3, in <module> import test RuntimeError: not holding the import lock child 3693 exited with 256 $ Here's the setup, there's two files test.py and test2.py $ cat test.py #!/usr/bin/python import os, sys if os.fork() == 0: print "doing stuff" sys.exit() print "child %d exited with %d" % os.wait() $ cat test2.py #!/usr/bin/python import test $ I understand that sys.exit() is really just doing a `raise SystemExit(0)' and the RuntimeError shows up with that as well. If you change out sys.exit with os._exit(0) then it doesn't show dump the RuntimeError. Also, this seems to be a python2.6 and python2.7 issue. Python3 doesn't have this issue. I haven't checked with python2.5 or before yet. I was more curious about what this behavior is and why python is doing things this way. I've scoured the python documentation and can't seem to figure out why. Thanks, - David Brown . - Prev by Date: I can't seem to change the timeout value on pexpect - Next by Date: Re: odd runtime error - Previous by thread: I can't seem to change the timeout value on pexpect - Next by thread: Re: odd runtime error - Index(es):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2010-12/msg00393.html
CC-MAIN-2016-40
refinedweb
276
78.35
In the previous article we began implementing tetris with React and Redux and got as far rendering the tetris shapes (called tetrominos). To follow along with this article checkout the commit 594a735. $ git clone $ git checkout 594a735 Simplifying the Components Thinking ahead it becomes apparent that we will need logic related to the shapes, such as how to rotate them and prevent collisions. If we introduce models for the tetrominos then they will be represented twice, once as models and once as React components. As we don’t want to repeat ourselves I think it is appropriate to simplify the React components. Instead of having different components for each tetromino all we really need is one component that can render a square. At the same time I will begin to introduce ES2015 modules. My new module, called components, will be in a file called components.js. Anything that I want to be available outside of the module needs to be prefixed with the export keyword. Instead of loading React using the commonjs require function we will switch to using the import keyword from ES2015. The new components module, and the new ShapeView component looks like: import * as React from 'react'; import * as ReactDOM from 'react-dom'; export var ShapeView = React.createClass({ render: function () { return <div> {this.props.shape.squares().map(sq => <Square row={sq.row} col={sq.col} />)} </div>; } }); The import * as React from 'react' statement means that we are importing the react module and assigning all of its exports to the identifier React. The refactored ShapeView component expects a model called shape having a method squares() that returns a collection of points that defines the shape. Thus the component can be reused for any shape that can describes its points. Introducing Models Having recognised that we need models to encapsulate the Tetris logic I will create another module, called models. The file models.js contains classes that model some tetrominos (O and L) and a class that models the Squares from which the other shapes are composed. export class Sqr { constructor(row,col) { this.row = row; this.col = col; } } export class O { constructor(row,col) { this.row = row; this.col = col; } squares() { return [new Sqr(this.row,this.col), new Sqr(this.row, this.col+1), new Sqr(this.row+1,this.col), new Sqr(this.row+1,this.col+1)]; } } export class L { constructor(row,col) { this.row = row; this.col = col; } squares() { return [new Sqr(this.row,this.col), new Sqr(this.row+1, this.col), new Sqr(this.row+2,this.col), new Sqr(this.row+3,this.col)]; } } As required by the ShapeView component the O and L classes both have a squares() method returning an array of Sqr. Putting it Together Now we can simplify out app.js. Firstly, import the required modules so that they are available within app.js: var React = require('react'); var ReactDOM = require('react-dom'); var Components = require('./components'); var Model = require('./model'); Note that I have not yet switched this file to use the ES2015 style imports. Next, I create an object to act as the model for React to render: var data = [new Model.O(1,1), new Model.L(1,4)]; For now, the model is an array of tetrominos, one O and one L. The rendering is now simpler. All we need to do is loop over the total set of squares and render each. ReactDOM.render( <div> {data.map(c => <Components.ShapeView shape={c} />)} </div>, document.getElementById('container') ); In the next article we will start animating the tetrominos and introduce Redux as a tool for managing state.
https://www.withouttheloop.com/articles/2015-12-27-tetris-2/
CC-MAIN-2022-27
refinedweb
603
60.21
User Guide for the PSLab Remote-Access Framework The remote-lab framework of the pocket science lab has been designed to enable user to access their devices remotely via the internet. The pslab-remote repository includes an API server built with Python-Flask and a webapp that uses EmberJS. This post is a guide for users who wish to test the framework. A series of blog posts have been previously written which have explored and elaborated various aspect of the remote-lab such as designing the API server, remote execution of function strings, automatic deployment on various domains etc. In this post, we shall explore how to execute function strings, execute example scripts, and write a script ourselves. A live demo is hosted at pslab-remote.surge.sh . The API server is hosted at pslab-stage.herokuapp.com, and an API reference which is being developed can be accessed at pslab-stage.herokuapp.com/apidocs . A screencast of the remote lab is also available Signing up at this point is very straightforward, and does not include any third party verification tools since the framework is under active development, and cannot be claimed to be ready for release yet. Click on the sign-up button, and provide a username, email, and password. The e-mail will be used as the login-id, and needs to be unique. Login to the remote lab Use the email-id used for signing up, enter the password, and the app will redirect you to your new home-page, where you will be greeted with a similar screen. Your home-page On the home-page, you will find that the first section includes a text box for entering a function string, and an execute button. Here, you can enter any valid PSLab function such as `get_resistance()` , and click on the execute button in order to run the function on the PSLab device connected to the API server, and view the results. A detailed blog post on this process can be found here. Since this is a new account, no saved scripts are present in the Your Scripts section. We will come to that shortly, but for now, there are some pre-written example scripts that will let you test them as well as view their source code in order to copy into your own collection, and modify them. Click on the play icon next to `multimeter.py` in order to run the script. The eye icon to the right of the row enables you to view the source code, but this can also be done while the app is running. The multimeter app looks something like this, and you can click on the various buttons to try them out. You may also click on the Source Code tab in order to view the source Create and execute a small python script We can now try to create a simple script of our own. Click on the `New Python Script` button in the top-bar to navigate to a page that will allow you to create and save your own scripts. We shall write a small 3-line code to print some sinusoidal coordinates, save it, and test it. Copy the following code for a sine wave with 30 points, and publish your script. import numpy as np x=np.linspace(0,2*np.pi,30) print (x, np.sin(x)) Create a button widget and associate a callback to the get_voltage function A small degree of object oriented capabilities have also been added, and the pslab-remote allows you to create button widgets and associate their targets with other widgets and labels. The multimeter demo script uses this feature, and a single line of code suffices to demonstrate this feature. button('Voltage on CH1 >',"get_voltage('CH1')","display_number") You can copy the above line into a new script in order to try it out. Associate a button’s callback to the capture routines, and set the target as a plot The callback target for a button can be set to point to a plot. This is useful if the callback involves arrays such as those returned by the capture routines. Example code to show a sine wave in a plot, and make button which will replace it with captured data from the oscilloscope: import numpy as np x=np.linspace(0,2*np.pi,30) plt = plot(x, np.sin(x)) button('capture 1',"capture1('CH1',100,10)","update-plot",target=plt)
https://blog.fossasia.org/author/jithinbp/
CC-MAIN-2021-43
refinedweb
745
68.5
(One of the summaries of the 2015 Pygrunn conference) Thomas Levine wrote vlermv. A simple “kind of database” by using folders and files. Python is always a bit verbose when dealing with files, so that’s why he wrote vlermv. Usage: from vlermv import Vlermv vlermv = Vlermv('/tmp/a-directory') vlermv['filename'] = 'something' # ^^^ This saves a python pickle with 'something' to /tmp/a-directory/filename The advantage is that the results are always readable, even if you lose the original program. You can choose a different serializer, for intance json instead of pickle. You can also choose your own key_transformer. A key_transformer translates a key to a filename. Handy if you want to use a datetime or tuple as a key, for instance. The two hard things in computer science are: Cache invalidation. Naming things. Cache invalidation? Well, vlermv doesn’t do cache invalidation, so that’s easy. Naming things? Well, the name ‘vlermv’ comes from typing randomly on his (dvorak) keyboard… :-) Testing an app that uses vlermv is easy: you can mock the entire database with a simple python dictionary. What if vlermv is too new for you? You can use the standard library shelve module that does mostly the same, only it stores everything in one file. A drawback of vlermv: it is quite slow. Fancy full-featured databases are fast and nice, but do you really need all those features? If not, wouldn’t you be better served by a simple vlermv database? You might even use it as a replacement for mongodb! That one is used often only because it is so easy to start with and so easy to create a database. If you don’t have a lot of data, vlermv might be a much better):
https://reinout.vanrees.org/weblog/2015/05/22/pygrunn-vlermv.html
CC-MAIN-2022-21
refinedweb
292
65.01
#include <cmath> #include <iostream> int operator ""_z(unsigned long long i) { return (int)std::pow(2, i); } int main() { std::cout << 5_z << std::endl; return 0; } // Output: 32Reference: Monday, July 31, 2017 C++11: User-defined Literals A User-defined literal is a constant that has a suffix that a class can define an operator for to handle. Here is an example: Posted by C++ Trivia at 5:46 PM The code compiles on Visual Studio 2015. For it to compile on g++, a space is needed between the "" and the _ in the operator name. Also g++ needs the compile switch "-std=gnu++1"
http://cpptrivia.blogspot.com/2017/07/c11-user-defined-literals.html
CC-MAIN-2018-30
refinedweb
105
56.29
[W3C] Technical Reports | Guide Publication Rules This is the checklist used by the W3C Webmaster for maintaining the W3C Technical Reports Index. Editors and Team Contacts should consult How to publish a W3C Technical Report for detailed guidance. Publication requests should be sent to webreq@w3.org (archive) and w3t-comm@w3.org (archive). If you want a member-visible archive of your request and its disposition, you may copy w3c-archive. The Webmaster starts by examining the publication request to find the information that will be used to update the tech reports index: * title * status, i.e. one of WD|CR|PR|REC|NOTE * date, i.e. title page date * author/editors * shortname * identifer of previous version, if any The shortname determines the identifier of the latest version in a series of documents as. The identifer of the particular publication is determined by the shortname, the status, and the date: Upon receiving a request to publish a technical report, the Webmaster shall make a best effort to check these constraints and, provided they are met, publish the document by linking it from the tech reports index and updating the latest version to agree with this version. If any constraint is not met, the Webmaster shall decline the publication request, detailing which of the following constraints were not met. See below regarding exceptions to this policy. 1. Has the title page date come to pass? Find the date for the title page from the publication request. It must not be in the future; if it is, don't publish it yet. If it's too far in the past then abort and try to get a document with a newer title page date. The editor must not change the document after the title page date. Editors/team, but experience shows that less than five days is risky. 2. Is this publication authorized? The form of authorization required varies with the status of the document, etc.: * Is there a previous version? no: This is the first publication in this series, i.e. the first appearance of this title on the tech reports index within a particular status (Note, public WD, CR, PR, REC). Explicit authorization from the Director is required by chapter 6 of the Process Document: + Is the requested status... NOTE written record of Director's approval of the title, and shortname (in addition to Team contact's confirmation of the approval "status of this document" text) is sufficient (i.e. required) authorization. WD written record of Director's approval of the title, and shortname (in addition to Team contact's confirmation of the approval "status of this document" text) is required; the status section must include a link to the relevant activity statement to show evidence of W3C resources dedicated to the maintenance of this document. other Abort. All W3C technical reports start life as either a NOTE or WD. yes: This is an update to an existing entry in the tech reports index. + Is the requested status... NOTE Explicit authorization from The Director is not required, but someone from the W3C management team (e.g. the relevant Domain Leader and/or the Communications Team Lead) should be aware of the status of the document. Team contact's confirmation of the approval "status of this document" text is required WD Explicit authorization from The Director is not required, but someone from the W3C management team (e.g. the relevant Domain Leader and/or the Communications Team Lead) should be aware of the status of the document.A link to the relevant activity statement is required to show evidence of W3C resources dedicated to the maintenance of this document. Team contact's confirmation of the approval of the "status of this document" text is required. CR, PR, or REC Carefully coordinate with The Director via the Communications Team Lead to synchronize with the relevant announcement to the W3C membership. For information about publications process and requirements based on document type, editors and staff contacts should consult: * How to Organize a Last Call Review * How to Organize a Candidate Recommendation Review * Starting Member review of a Proposed Recommendation * @@How to Organize a Recommendation in development@@ Note: in the past, shortnames have been changed between versions, and technical reports have been split and merged between versions. A conservative approach is to treat a merged/split technical report like a first publication, but that is not how it has been handled in the past. 3. Is the Status of This Document section novel and complete? Do all XML namespaces follow established conventions? The Webmaster must have confirmation from the team contact that: 1. The status section is novel and complete per the guidelines (per Apr 1999 chairs meeting) In particular, the status section must contain a customized paragraph that has not been copied from another document. This section should include the title page date of the document. 2. All XML namespaces created by the publication of the document follow the W3C XML namespace conventions (announced to the Chairs 26 October 1999). 4. Are there any broken links, internal to the document or otherwise? 1. If the technical report is a compound document (i.e. if it consists of more than one file), all the files must be under a directory called TR/YYYY/status-shortname-YYYYMMDD/. The main page should be called Overview.html. All other files must be reachable by links from the main page. 2. The document should have no broken links; it must not have any broken internal links and must not have any broken links to w3.org resources. Use the W3C link checker. 5. Is the document consistent with W3C Technical Reports style? Regarding the document as a whole: 1. The main page and all subordinate pages must conform to W3C HTML Recommendations. Use the W3C HTML/XML validator. (alternative representations such as plain text, postscript, etc. are optional) 2. The document must conform to the Web Content Accessibility Guidelines 1.0, Level A. Use the WCAG 1.0 Checklist (5 May 1999 version). 3. The document must not have any style sheet errors. Use the CSS validator. 4. There must be an absolute link to the appropriate technical report style sheet as follows. Any internal style sheets are cascaded before this link; i.e. the internal style sheets must not override the W3C tech report styles: For a Working Draft: For a Candidate Recommendation: For a Proposed Recommendation: For a Recommendation: For a Note: Regarding the document head, editors/team contacts see guidelines on technical reports structure, including templates etc. In particular: 1. The following markup at the beginning of the head of the document: Copyright ©2001 W3C® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.8. The following markup at the end of the head of the document:
http://www.w3.org/TR/2001/WD-DOM-Level-3-Core-20010126/DOM3-Core.txt
CC-MAIN-2016-50
refinedweb
1,140
55.34
Hi, I'm seeing this error when I try to mix the invocation of Axis1.4 and Axis2 clients in the same EJB class method (in WebSphere): nested exception is: java.lang.VerifyError: org/apache/axis2/description/AxisOperation.setName(Ljavax/xml/namespace/QName;)V I believe it's because for Axis 1.4 the class is in jaxrpc-1.1.jar and for Axis2 it's in xml-apis-1.3.02.jar and the client stub classes would have been built accordingly. To support this we need to have both Axis 1.4 and Axis2 jars in the ear file. Has anyone run across this and/or have any suggestions for resolving? Thanks, William. --------------------------------------------------------------------- To unsubscribe, e-mail: java-user-unsubscribe@axis.apache.org For additional commands, e-mail: java-user-help@axis.apache.org
http://mail-archives.apache.org/mod_mbox/axis-java-user/201006.mbox/%3CAC9BA14988527D4DA976E2ACB5660A37F4DB4B16A8@MAIL06.curamsoftware.com%3E
CC-MAIN-2014-10
refinedweb
136
54.08
The program takes any integer number from the standard input device ( keyboard) and convert that number into its equvalant binary number using division method. This program was tried and tested on Dev C++ IDE. Here is the source code of the same program. /* program to convert any decimal number into its equvalent binarynote made by : rakesh kumar */ #include #include using namespace std; int main() { int n, bin[100]; bin[0]=-1; int rem,i=0; //input phase cout<<"\n Enter any number : "; cin>>n; //processing phase while(n!=0) { rem = n%2; bin[i++]=rem; n = int(n/2); } //output phase cout<<"\n Binary No. : "; for(i=i-1;i>=0;i--) cout<<bin[i]; return 0; } The output of the same program is here.
http://cbsetoday.com/cpp-program-convert-decimal-number-binary-number/
CC-MAIN-2018-34
refinedweb
125
62.68
Directory Listing Remove .cvsignore files as we're using svn now :) tag 1.12.0. revert the -k2 addition to sort in halt.sh, #131001 pre18 misc touchups Disable CTRL+C in depscan.sh while booting #126512 by Marko Djukic. Also add -h/--help and such. style/misc touchups Sort by mount point, not mount source, in halt.sh #130219 by Mark McKenna. Fixed ifconfig handling of interface_is_up udhcpc.sh now works with the -q|--quit option again, #129437. Stop treating dm-crypt specially and just move it with the other volume related code #128908 by Luud Heck. Make sure rc-status exit status is 0 #127733 by Timo Boettcher. disable hwclock on s390 hosts. Overhaul rc-update and make it more user friendly. merge ROOT support from trunk Ensure that ifplugd, netplugd and wpa_supplicant timeouts really are infinite when requested. Thanks to embobo. Add patch by Alun Jones to respect RC_QUIET_STDOUT in conf.d/rc #123606.).. Moved wpa_supplicant and iwconfig et all from /usr/sbin to /sbin pump-0.8.21-r4 now creates ntp.conf by itself so the ntp.conf creation code has been removed from the pump module and helper. Reverted silly domain into search Added dhcp_eth0=nogateway option, generic to all dhcp clients. Fixes #98466 removed dep on logger - was causing circular deps when syslog-ng depends on us. tell users that they have to replace the issue file in order to get rid of the warning Documented nosendhost Added nosendhost dhcp option so users can request not to send their machines hostname by default. Fixes #98132 Fix hotplug policy exiting dded a rename module to rename interfaces based on MAC address (preferred) or current name. Fixes #76328 Fixed bridge module working with dhcp bridges can now be created without interfaces if you set any brctl_ options Fixed module depends in net.lo Remove the 'no net scripts in boot runlevel' restriction as we now have a hotplug policy setup instead Fixed error reporting for modules=( foo ) and foo isn't installed Do not run macnet when the interface does not have a MAC address fixed auto_interface -> RC_AUTO_INTERFACE in ifconfig and iproute2 dhclient now calls /etc/dhcp/dhclient-exit-hooks when it exits - fixes #96000 etc/{resolv,ntp,yp}.conf now link to /var/lib/net-scripts remove /etc/ppp since the ppp package provides this file style tweak strip out cvs $Header stuff strip out cvs $Header stuff update comments #95531 by Sebastian Kemper even better, just tell sysctl to run in quiet mode let users see errors from sysctl remove invalid leading sys. add pxc and rquotad eat trailing whitespace give the user some pointers on where to find docs on file format config files are now variables to change them easily system module now creates it's temporary files in /tmp instead of /etc dhcpcd backgrounder now sources rc-services.sh removed cruft from net-scripts functions helper as rc-services.sh can now be sourced by our dhcp helpers without causing errors. handle arbitrary kernel versions for autoload files #35872 add a generic framework for bootlogging quote $EDITOR #94412 fixup is_net_fs to work with /proc/mounts when available fix CIDR some more for ifconfig make sure initial swapon sends errors to /dev/null #93143 Quiet down valid_i() if /softlevel do not yet exist, try #2. reverse stupid style changes ... /etc/profile is not just for bash. Fixed init runscript.sh output when RC_PARALLEL_STARTUP is set runscript.sh now checks if service was made inactive on start - if so, exit set RC_QUIET_STDOUT when RC_PARALLEL_STARTUP is set fix typo pointed out by Gordon #93112 mount /dev with exec #92921 by Lachlan Pease move nsswitch.conf to glibc add the -f option to the unset exit try to minimize user interaction during boot with RC_FORCE_AUTO force halt/reboot if first try failed remove copyright header unset exit instead of overriding it net.lo bypasses the exit() function now provided by runscript.sh update style style updates udhcpc and dhclient now select the best interface when one goes down rework the addon code abit to support profiling run irqbalance once /var is rw #85304 touchup syntax error message make sure devs dont call exit in init.d scripts #85298 forgot to add this to HEAD moved to util-linux simplify init.d syntax checking and allow users to run /etc/init.d/script status #85892 handle LABEL/UUID properly in /etc/fstab #90603 make sure /dev is mounted with sane settings #87745 add update from upstream ssd to detect kfbsd #80021. moved to sys-apps/util-linux move crypto-loop to util-linux and skel/bash files to bash moved to app-shells fix dhclient not leaving a pid file force location of wpa_monitor.action. move the udev/selinux code after we mount /dev Removed sbin/livecd-functions.sh and bin/bashlogin as they are only used in release building, and they have been moved to livecd-tools. 15 Apr 2005 Martin Schlemmer <azarah@gentoo.org> * parse.c: Do not source rc.conf for every script - once is enough. 14 Apr 2005 Martin Schlemmer <azarah@gentoo.org> * depscan.c: Update error comments for stage name changes some time back. 14 Apr 2005 Martin Schlemmer <azarah@gentoo.org> * parse.c, * parse.h: Do not try to extract the depend() function from the scripts, but rather source the whole file. This way we can detect syntax errors, etc. Little bit slower, but not much. wpa_supplicant now stops wpa_monitor if it's been launched modified to use bash_variable} 07 Apr 2005 Martin Schlemmer <azarah@gentoo.org> * test-regex.c: Add two more tests. * depscan.c * misc.c * misc.h: Add basic klibc support. I need to add a mkstemp implementation to get it done properly. typo Updated livecd-functions.sh to include better ppc64 serial console support. fixed bug caused by last commit "service" -> "${service}" wrap pidof so we can fudge calls to weird programs like rpc.nfsd which only with with pidof when the rpc. is removed Export myservice when starting critical services, as its needed by some of the addons (dmcrypt for example). we no longer default WEP key to [1] as it messes with ndiswrapper users halt the system with -h #84654 12 Mar 2005 Martin Schlemmer <azarah@gentoo.org> * Makefile: Also remove the tests in the clean target. prepend rc-daemon.sh functions with rc_ to avoid name conflicts Make sure the last test in init.d/modules do not bork the return value of the script if not true. 2004 -> 2005 udev/selinux lovin fix style 11 Mar 2005 Martin Schlemmer <azarah@gentoo.org> * test-regex.c: Add a few strings and patterns. Enable tests to specify if they should fail or pass. 10 Mar 2005 Martin Schlemmer <azarah@gentoo.org> * test-regex.c: New file * Makefile: Add check target to compile and run tests * simple-regex.c (__match_wildcard): Get recursion right so that we do not match a wildcard _and_ inc data_p if there are still other wildcards (?, *) that could match. 10 Mar 2005 Martin Schlemmer <azarah@gentoo.org> * Makefile * depend.c * simple-regex.c: Override the debug/warning CFLAGS. Kill a few warnings. Fix UTF-8 ChangeLog breakage (again) The system() stuff in *depends.awk should be dosystem(). 10 Mar 2005 Martin Schlemmer <azarah@gentoo.org> * Makefile * depend.c * simple-regex.c: Override the debug/warning CFLAGS. Kill a few warnings. Force tarball.sh to use a non-mux cvs since it needs to run as root Update ChangeLog and tarball.sh for 1.7.0 development release (baselayout-1.12.0_alpha1) fix iwconfig setting default key 1 for madwifi cards } fixed stopping logic causes by last commit fixed starting bug with sshd rc-daemon.sh now waits for RC_WAIT_ON_START seconds and checks if the daemon is still running - if not, call stop() or stop_daemon() to clean up applied STYLE updates to rc-status rc-status now uses find correctly for -maxdepth which fixes #84055 wpa_supplicant now handles whitespace when checking the ctrl_interface dir if no net.$iface script exists, blunder ahead bridging and bonding modules now start an interface if it's not marked as started rc-daemon.sh now support stoppings with a custom signal rc-daemon.sh now checks to see if a given pid matches the pid of a given executable before stopping it iwconfig now defaults the transmit key to 1 net_service() now returns 1 for non net-services - fixes bug #83352 rc-daemon.sh now uses requote() rc-daemon.sh can now be called with spaces in parameters Add requote() for rc-daemon.sh to use; fix ChangeLog corruption improved killing process children - we now kill them all in one hit instead of doing them seperately Now in sys-fs/cryptsetup. Fix braindead logic in init.d/checkfs ([[ -z ]] &&, not -n). removed warning about sshd when setting RC_KILL_CHILDREN="yes" support --oknodo and --test for start-stop-daemon calls rc-daemon.sh now provides a working wrapper for start-stop-daemon fixes bug #7198 removed ps calls from net scripts Style updates for init.d/halt.sh. Only run pam_console_apply if we are actually using pam_console. whitespace fixes Updated livecd-functions.sh to match what we are using on the LiveCD. Updated bashlogin to match what is use don(). Add use tempory file for deptree, bug #48303, thanks to patch from Stefan Hoefer <stefan@hoefer.ch>. Localize the addons. Localize the addons. Remove dm-crypt, as its not technically a volume Split *_volume() stuff a bit more. Add {start,stop}-volumess() to /sbin/functions.sh, as well as RC_VOLUME_ORDER to /etc/conf.d/rc. * misc.c: Fix memory leak in mktree(). rc-status manpage #81917 re-order options to make find shutup move the serial init.d into the setserial package dont use none when mounting dont copyright config files Do not package src/core. Makefile: Add -fbounds-checking support when DEBUG=1. misc.h: Scrap STRING_LIST_FOR_EACH_SAFE() and recode from scratch fixing invalid pointer operations. misc.c: Remove the last strlen() from strndup() that caused an overrun. misc.c: Fix overrun in strndup(), thanks to report from Ned Ludd <solar@gentoo.org>. debug.h, misc.h, simple-regex.c: Print debug/errors to stderr, patch from Ned Ludd <solar@gentoo.org> debug.h: Replace invalid EXIT_FAILSTATUS with EXIT_FAILURE. parse.c: Modify parse_print_body() to be more ash friendly - suggestions from Ned Ludd <solar@gentoo.org>. debug.h: Remove the 'errno = ESPIPE' in DBG_MSG() for now, as it seems to be fixed by the select() changes. parse.c: Disable write select() for now, as it is not needed. depscan.c: Only print EINFO msg if we actually update the cache. parse.c: Rename write_output() macro to PRINT_TO_BUFFER(). parse.c, parse.h: Rewrote large parts of generate_stage[12]() and their machanics to use select() when writing to the pipes. This fixes a buffering issue where too much data would cause the write to be truncated, and the read pipe would then wait forever. misc.c: Fix gbasename() to compile under gcc-2.95.3. parse.c: Switch to stdio based io for reading pipes in generate_stage2(). misc.c, misc.h: Add gbasename() that is similar to GNU's basename(). parse.c: Use gbasename() instead of POSIX version. parse.c: Fix write_legacy_stage3() to quote the mtime in its output. misc.c, parse.c: Change type of length from int to size_t to avoid warnings when compiled for darwin. misc.c, misc.h: Add strndup() instead of relying on glibc's implementation (should fix some issues on bsd and darwin). depend.c, simple-regex.c: Do not define _GNU_SOURCE, but rather use our strndup() from misc.h. parse.c: Do not define _GNU_SOURCE, but rather use our strndup() from misc.h. Also change all usage of basename() to conform to POSIX, and not use the GNU variants. depscan.c: Add uid check and quit if user is not root. depend.c, depend.h: Change service_type_names declaration in depend.h to extern and move the definition to depend.c to avoid warnings. Add README. depscan.c: Add delete_var_dirs() to delete volatile directories in svcdir. Change 'char *' declarations for create_directory() and create_var_dirs() to 'const char*'. misc.h, misc.c: Add rmtree() function. Fix ls_dir() not to include '.' and '..' in its listing. Fix segfault in ls_dir() if the file list is empty. Add Header tags to all source files and Makefile. debug.h: perror() set errno to ESPIPE for some reason - restore errno after calling perror(). depscan.c: Add code to create svcdir and co if missing. misc.c: Add missing '\n' to DBG_MSG in mktree(). misc.h: Add a comment about strcatpaths() allocating the memory needed. Remove redundent test file. .cvsignore Initial checkin. linux 2.5 -> 2.6 #57689 put speedy checks first and allow override fix from #75659 tabs, not spaces declare local variables useless ; import some VServer stuff #55973 sanity checks punt PROTOCOL and move around consolefont more services (including qmqp #81111) make sure to filter devpts when unmounting change default home of man to /usr/share/man fix testing of device-mapper with lvm #80206 tag 1.11.9 style updates style updates update crypto-loop to new util-linux #40874 by J�rgen H�tzel / jochen dm-crypt loopback #73598 and dm-crypt gpg #75659 and style updates update link #74165 Punt the guest user #74737. /etc/filesystems is a configuration file too ! #74176 style updates style updates #77585 typo fixes #77582 dont use the vague 'none' when mounting stuff #78684 style updates use pure bash instead of awk ... thanks to ciaranm for holding my hand use clock, dont need it #78997 punted unused files removed udhcpc-* and dhclient-* helper modules and replaced them with a generic dhcp module which caters for all interfaces and dhcp clients that need it. We now prefer iproute2 over ifconfig if both are installed. fixed typo in reporting Updated copyright headers STYLE fixes to many net-scripts modules Removed hardcoded Version and replaced with cvs $Header: replaced awk commands with sed equivalents in net-scripts to make us more portable wpa_supplicant now works with EAP - fixes #78367 bridge now works with arrays all modules should now check interface existance correctly - fixes #76385 null and noop fixed for config_worked net.lo changed logic to read "only fail if no configuration parameters work, bring interface down and abort". Fixes #78092 comment fixes more ipppd fixes for shutting down allow pure IPv6 addresses - fixes #73844 net dependancies corrected in runscript.sh - fixes #77839 fixed remove stale socket wpa_supplicant forces ctrl_interface to /var/run/wpa_supplicant and removes stale directories clean_pidfile function no longer errors on empty pidfiles STYLE update ipppd module now stops correctly - fixes #73067 again net.lo now ignores dot files when loading modules grammar fixes #77565 noop sanity fixes added "noop" config parameter which means take no action if the interface is up and has an address configured, otherwise continue addresses are now removed when starting an interface - fixes #77111 make sieve an alias for cisco-sccp (port 2000) BSD compat fix .cvsignore fixed typo in last commit fixed searcdomains being set for essid iwconfig no longer uses iwconfig_get_essid_var Dont create /dev/sndstat link anymore in populate_udev per #69635 initial STYLE doc cleaned out unused vars regressed last commit.
https://sources.gentoo.org/cgi-bin/viewvc.cgi/baselayout/tags/baselayout-1.12.0/?sortby=log&view=log
CC-MAIN-2017-30
refinedweb
2,535
65.93
This example demonstrates the various options for showing a marker at a subset of data points using the markevery property of a Line2D object. Integer arguments are fairly intuitive. e.g. markevery=5 will plot every 5th marker starting from the first data point. Float arguments allow markers to be spaced at approximately equal distances along the line. The theoretical distance along the line between markers is determined by multiplying the display-coordinate distance of the axes bounding-box diagonal by the value of markevery. The data points closest to the theoretical distances will be shown. A slice or list/array can also be used with markevery to specify the markers to show. import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # define a list of markevery cases to plot cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], slice(100, 200, 3), 0.1, 0.3, 1.5, (0.0, 0.1), (0.45, 0.1)] # define the figure size and grid layout properties figsize = (10, 8) cols = 3 rows = len(cases) // cols + 1 # define the data for cartesian plots delta = 0.11 x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta def trim_axs(axs, N): """little helper to massage the axs list to have correct length...""" axs = axs.flat for ax in axs[N:]: ax.remove() return axs[:N] Plot each markevery case for linear x and y scales Plot each markevery case for log x and y scales Plot each markevery case for linear x and y scales but zoomed in note the behaviour when zoomed in. When a start marker offset is specified it is always interpreted with respect to the first data point which might be different to the first visible data point. fig3, axs = plt.subplots(rows, cols, figsize=figsize, constrained_layout=True) axs = trim_axs(axs, len(cases)) for ax, case in zip(axs, cases): ax.set_title('markevery=%s' % str(case)) ax.plot(x, y, 'o', ls='-', ms=4, markevery=case) ax.set_xlim((6, 6.7)) ax.set_ylim((1.1, 1.7)) # define data for polar plots r = np.linspace(0, 3.0, 200) theta = 2 * np.pi * r Plot each markevery case for polar plots Total running time of the script: ( 0 minutes 5.385 seconds) Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery
https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/markevery_demo.html
CC-MAIN-2020-10
refinedweb
398
66.03
That's good that we are able to receive the loans moreover, this opens new possibilities. Post your Comment How to use multiple declaration in jsp How to use multiple declaration in jsp  ... will learn how to declare multiple variables and methods in jsp that prints...;HEAD> <TITLE>multiple declaration in jsp</TITLE> < DECLARATION IN JSP DECLARATION IN JSP In this Section, we will discuss about declaration of variables & method in JSP using declaration tags. Using Declaration Tag, you... of the declaration is JSP page means it is valid only in JSP page & JSP Declaration JSP Declaration What is a JSP Declaration?. Explain it. Hi, The answer is: The JSP declaration used to craete one or more variable and methods that are used later in the jsp file. If you want to create variable Declaration tag Declaration tag Defined Declaration tag in JSP Declaration in JSP is way to define global java variable and method. This java variable... does not reside inside service method of JSP. Declaration tag is used to define Use multiple catch statement in single jsp Use multiple catch statement in single jsp  ..._jsp.jsp' will show you how to use multiple catch blocks to handle multiple... exception so we can use multiple catches or Exception class (base class of all Uploading Multiple Files Using Jsp to understand how you can upload multiple files by using the Jsp. We should avoid... logic, but at least we should know how we can use a java code inside the jsp page... Uploading Multiple Files Using Jsp   Use Constructor in JSP Use Constructor in JSP This section illustrates you how to use constructors in jsp... is an example which explains you to use constructors in jsp. Here is the code JSP WITH MULTIPLE FORMS JSP WITH MULTIPLE FORMS In this example, you will learn how to make multiple forms in single jsp page. Most of the times people need to use multiple forms Multiple file upload - Struts : In jsp use : enctype="multipart/form-data" method="post...Multiple file upload HI all, I m trying to upload multiple files using struts and jsp. I m using enctype="multipart". and the number of files JSP Simple Examples in a java. In jsp we can declare it inside the declaration directive... side. Multiple forms in jsp The form tag... In a jsp we should always try to use jsp- style comments Multiple Methods in Jsp Multiple Methods in Jsp Jsp is used mainly for presentation logic. In the jsp we can declare methods just like as we declare methods in java classes JSP Simple Examples Conditional Content on a JSP Page We make use of the condition...; Break Statement in JSP The use...;]}. How to Use array declaration array declaration what is the difference between declaration of these two things integer[] i={1,2,3,4,5} and integer i[]={1,2,3,4,5 arraylist declaration in java This class is used to make an fixed sized as well as expandable array. It allows to add any type of object. It is the implementation of the List interface Example of Java Arraylist Declaration import Multiple Namespace Defining multiple namespace in a single file: In a single PHP file we can declare more than one namespace. PHP allow two syntaxes to declare more than one... namespace in a single file. It is strongly discouraged to combine multiple Method in Declaration Tag ;<TITLE>Declaration Tag in jsp - Methods</TITLE></HEAD> <...Method in Declaration Tag In Jsp we define methods just like as declare Creating a Local Variable in JSP Creating a Local Variable in JSP In jsp when we have to create a method or variable we usually declare it inside the declaration tag. If we declare it inside the declaration directive array declaration array declaration String propArray = []; is this declaration correct? Hi Friend, No, This is the wrong way. Array is declared in the following way: String arr[]={}; For more more information, visit the following Am a doing a project,in that i need to send email to multiple user at a time,the to address should enter manually its not not be written in code using jsp. Regards, Santhosh reply this topicRuthie28Foster April 1, 2012 at 5:54 AM That's good that we are able to receive the loans moreover, this opens new possibilities. Post your Comment
http://www.roseindia.net/discussion/21678-How-to-use-multiple-declaration-in-jsp.html
CC-MAIN-2014-52
refinedweb
726
53.31
Condition variable with futex Ten years ago (okay, actually nine years and a few months at the time of writing), the only holdout among major general-purpose operating systems gained support for condition variables with the release of Windows Vista. Five years later, the ISO C and ISO C++ standards also defined condition variables, making them the de jure standard low-level primitive for thread synchronization, alongside mutual exclusion locks ( mutex ). Sometimes though, you need to reimplement them. Condition variable The basic functionality of condition variables is well understood and supported. There are three operations: - Atomically unlock a mutex and go to sleep (with an optional time-out). Relock the mutex when woken up. - Wake one sleeping thread up. - Wake all sleeping threads up. Differences However the devil is in the details. There are a number of subtle differences and features in the different implementations of condition variables, notably (non-exhaustive list): - Possibility of initialization failure, abort, or warranty of success. - Support for static initialization. - Destruction being necessary to avoid leaking resources, provided as a no-op or sanity check or not provided at all. - Absolute time-out, relative time-out or both. - If absolute time-out are supported, which reference clock(s) are supported. - If applicable, which reference clock(s) is used for statically initialized condition variables. - Preservation of thread priorities. - Support for inter-process "shared" condition variables. - Support for (deferred) thread cancellation, or equivalent. POSIX threads POSIX threads allow for initialization failure (and in principles, even run-time usage failure), and requires explicit destruction of dynamically allocated condition variables. This results in needlessly intricate error handling code. More often than not, the error paths are poorly tested or completely untested and riddled with bugs. POSIX also has the disadvantage, for historical/compatibility reasons, of using the real-time clock ( CLOCK_REALTIME ) by default. In most use cases involving time-outs, this is undesirable. The real-time clock is subject to warping, when it is adjusted manually or with NTP, invalidating timestamp values in running threads. The more useful monotonic clock ( CLOCK_MONOTONIC ) is available as a non-default choice, Yet it cannot be used for statically allocated condition variable. Windows On Windows, initialization cannot fail and destruction is implicit. This simplifies the code by not introducing error cases. On the downside, there is support for cancellation, which does not exist on Windows (and condition variable waiting is not alertable). Also, in the odd cases where they are actually necessary, wall clock time-outs are not supported. ISO C11 I have heard the argument that C11 support for threads and synchronization primitives was so bad as to be useless. That might be (just slightly) excessive. For one thing, the additions of a concurrent memory model (even if it is allegedly very imperfect), and of atomic operations are very welcome in my opinion. And in all due fairness, the standard authors presumably intended to design the standard according to the lowest common denominator of all existing implementations. That being said, the C11 condition variables are indeed very limited. Static initialization is impossible, which is peremptory is many scenarii. As far as I can tell though, the worst default is probably the use of absolute time-outs using the TIME_UTC wall clock. That makes all time-out subject to the time warping problem, and prevents writing correct code in most cases involving time-outs. So what is this about? This is about how to (re)implement condition variables with a lower-level primitive. That primitive happens to exist on the two most common general purpose operating system kernels (I believe): - Linux (including Android, GNU/Linux and other variants), and - Microsoft Windows. I did that because I was discontent with the existing implementation on certain operating systems (strong hint which ones right above), and also because I was curious. Futex In general, thread synchronization primitives requires userspace programs to invoke system calls (or perform a context switch if threads are implemented in userspace). The system call is fundamentally unavoidable for putting a thread to sleep while waiting for another thread, or to wake up a another thread out of sleep. But for better performances, atomic operations are used on the fast path to avoid system calls. For instance, acquiring a uncontended lock does not require a system call, at least no intrinsically. Releasing a lock that no other threads are waiting for, likewise. The futex is the solution to this problem that was introduced in Linux, in 2003 to support for POSIX threads natively and efficiently (older solutions to that problem exists, e.g. on BeOS). Futex originally means fast userspace mutex , but the mechanism is used for all those synchronization primitives that involve waiting and waking, including condition variables. That is to say all primitives other than atomic operations, and those based on atomic operations only, such as spin locks. The concept is now also implemented on Windows nearly identically (more on that below) though it is not named in the documentation. Using futeces A futex is essentially an address to an atomic integer. The address is used as the identifier for a queue of waiting threads. The value of the integer at that address is used both for to implement the fast path with atomic operations (if applicable), and to cope with corner case race conditions in case of contention. Historically, manipulationg a futex involved architecture-specific assembler code for atomic operation . Nowadays, standard C/C++ 11 atomic operations can be used , greatly simplifying the job. Futex operations glibc does not provide a direct or shallow wrapper for futex . Instead it exposes the functionality via the POSIX threads and POSIX semaphores functions. futex is actually a single system call with multiple operations. That may seem odd, even confusing if not outright ugly. However, that is common practice for a unique system call: the ioctl system call has far more operations than futex . As another example, programmers will not usually notice because glibc hides it, but all socket-related functions are implemented by the single socketcall system call. I will not enumerate all the possible operations and flags here, only the two most important and basic operations and one flag. For details and for the exact system call prototype, the curious can check the futex(2) manual page . FUTEX_WAIT #include <stdatomic.h> #include <time.h> #include <linux/futex.h> int futex_wait(atomic_int *addr, int val, const struct timespec *to) { return sys_futex(addr, FUTEX_WAIT_PRIVATE, val, to, NULL, 0); } This operation puts the calling thread to sleep, if and only if the value at address addr is equal to val . If to is not NULL , it contains a relative time-out value after which the thread wakes up. Note that we use FUTEX_WAIT_PRIVATE , which is a short-hand for FUTEX_WAIT|FUTEX_PRIVATE_FLAG . The FUTEX_PRIVATE_FLAG flag indicates that addr is only visible to the calling process, so the kernel does not need to lock and check its virtual memory management state to find other threads using the same address in other processes. FUTEX_WAKE int futex_wake(atomic_int *addr, int nr) { return sys_futex(addr, FUTEX_WAKE_PRIVATE, nr, NULL, NULL, 0); } This operation wakes up to nr threads waiting on the futex located at address addr up. Typically, nr is either: 1to wake just one thread up, or INT_MAXto wake all threads up. int futex_signal(atomic_int *addr) { return (futex_wake(addr, 1) >= 0) ? 0 : -1; } int futex_broadcast(atomic_int *addr) { return (futex_wake(addr, INT_MAX) >= 0) ? 0 : -1; } As previously, FUTEX_WAKE_PRIVATE is a shorthand for FUTEX_WAKE|FUTEX_PRIVATE_FLAG . Implementing a condition variable with a futex Lets assume we already have a mutex implementation. How do we implement a condition variabe with a futex? Simple but very wrong The most obvious solution would be something as follows: typedef struct cnd { atomic_int value; } cnd_t; /* Our static initializer */ #define CND_INITIALIZER_NP { ATOMIC_VAR_INIT(0) } int cnd_init(cnd_t *cv) { atomic_init(&cv->value, 0); return thrd_success; } void cnd_destroy(cnd_t *cv) { (void) cv; } int cnd_wait(cnd_t *cv, mtx_t *mtx) { mtx_unlock(mtx), futex_wait(&cv->value, 0, NULL); mtx_lock(mtx); return thrd_success; } /* cnd_timedwait() omitted for simplicity */ int cnd_signal(cnd_t *cv) { futex_signal(&cv->value); return thrd_success; } int cnd_broadcast(cnd_t *cv) { futex_broadcast(&cv->value); return thrd_success; } Did you spot the outrageous bug there? There is a very good reason why cnd_wait() requires a pointer to a mutex : to avoid lost signals. In this overly simplistic implementation, if cnd_signal() calls futex_wake() before the waiting thread actually starts sleeping in kernel, the call will be a no-op. Then when the sleeping thread actually gets to sleep in futex_wait() it gets stuck since it missed the wake-up. That is why futex_wait() has a second parameter: to deal with contention in corner cases. The expected futex value in race-free cases must be determined by cnd_wait() before it unlocks the mutex. If there is a race with cnd_signal() , the futex value should have changed such that the kernel does not put the thread to sleep in futex_wait() , and returns immediately. Counting waiters: too good to be true So lets try to use the futex as a counter. If it worked, it would have two benefits: - the futex_wake()system call could be optimized away when there are zero waiters, and cnd_destroy()could detect invalid attempts to destroy a condition variable still in use (non-zero waiters). int cnd_wait(cnd_t *cv, mtx_t *mtx) { unsigned refs = 1u + atomic_fetch_add(&cv->value, 1); /* Add 1u for add-and-fetch semantics instead of fetch-and-add */ mtx_unlock(mtx), futex_wait(&cv->value, refs, NULL); atomic_fetch_sub(&cv->value, 1); mtx_lock(mtx); return thrd_success; } int cnd_signal(cnd_t *cv) { if (atomic_load(&cv->value) != 0) futex_signal(&cv->value); return thrd_success; } The bugs are bleedingly obvious there. The same problem as in the first shot still remains. And there are other problems too. If you did not already spot them, here is a hint: wait if there are more than one concurrent waiting thread? Sequence counter, close but no cigar Given the semantics of futex_wait() , one essential requirement to avoid losing signals is for cnd_signal() to modify the value of the futex before waking any thread, so that it is different from the value before the waiting thread unlocked the mutex. That way either of the following happens: - The waiting thread computes the futex value then, unlocks the mutex. It then goes to sleep before the futex value changes. The waking thread changes the value (with no effects), then wakes the waiting thread with a system call. - The waiting thread computes the futex value then unlocks the mutex. Then a race happens with the waking thread. The waking thread changes the futex value. The waiting thread call to futex_wait()is a no-op because the futex value does not match. Either way, the waiting thread is not staying asleep. The simplest way to implement this is a sequence counter. The Bionic C library used by Android works that way (simplified for clarity): int cnd_wait(cnd_t *cv, mtx_t *mtx) { int val = atomic_load(&cv->value); mtx_unlock(mtx), futex_wait(&cv->value, val, NULL); mtx_lock(mtx); return thrd_success; } int cnd_signal(cnd_t *cv) { atomic_fetch_add(&cv->value, 1); futex_wake(&cv->value); return thrd_success; } The bug here is almost as well documented as the implementation. To be honest, it is extremely unlikely to occur in real use. … If cnd_signal() is called exactly 4294967296 times in a row before the waiting thread makes progress, the sequence number wraps around, gets its original value, and the signal is lost. To be precise, that would occur for exactly a non-zero multiple of two to the power CHAR_BIT * sizeof (int) (which equals 32 on all Linux systems, to my knowledge). To avoid that issue or any variant thereof, we need to ensure that the futex value set by cnd_signal() is never equal to a value computed by cnd_wait() . Toggle In the race-free scenario, the futex value must be unchanged so the thread goes to sleep. In the race scenario, as we just saw, the futex value must be changed to a value never used for sleeping. Those two requirements can only be accommodated by making both cnd_waitl() and cnd_signal() modify the futex. There is another requirement in case more than one thread is sleeping on the same condition variable. That takes us back to the other problem with the waiters counting approach. … If more than one thread goes to sleep in a row, the second one must not change the futex value. Otherwise, the first thread would potentially fail to go to sleep due to the changed futex value. The more threads wait on the same condition variable, the more likely the problem. With enough threads, it could degrade into a live loop . With that in mind, I think that the simplest solution is as follows: int cnd_wait(cnd_t *cv, mtx_t *mtx) { atomic_store(&cv->value, 1); mtx_unlock(mtx), futex_wait(&cv->value, 1, NULL); mtx_lock(mtx); return thrd_success; } int cnd_signal(cnd_t *cv) { atomic_store(&cv->value, 0); futex_wake(&cv->value); return thrd_success; } And, correct me if I am wrong, but I believe it works. We however use only 1 bit and waste the other futex 31 bits. A slightly better version that preserves those bits so they could be used for flags (they must be constant): int cnd_wait(cnd_t *cv, mtx_t *mtx) { /* Set lowest order bit */ int value = atomic_fetch_and(&cv->value, 1) | 1; mtx_unlock(mtx), futex_wait(&cv->value, value, NULL); mtx_lock(mtx); return thrd_success; } int cnd_signal(cnd_t *cv) { /* Clear lowest order bit */ atomic_fetch_and(&cv->value, -2); futex_wake(&cv->value); return thrd_success; } Relaxed memory barriers For simplicity, implicit barriers were used so far. In practice, atomic operations can be explicitly relaxed ( memory_order_relaxed ). The necessary memory barriers are provided by the mutex, not the condition variable , so do not need to add any, e.g.: int cnd_wait(cnd_t *cv, mtx_t *mtx) { int value = atomic_fetch_and_explicit(&cv->value, 1, memory_order_relaxed) | 1; mtx_unlock(mtx), futex_wait(&cv->value, value, NULL); mtx_lock(mtx); return thrd_success; } int cnd_signal(cnd_t *cv) { atomic_fetch_and_explicit(&cv->value, -2, memory_order_relaxed); futex_wake(&cv->value); return thrd_success; } Outstanding issues Timed wait We did not provide an implementation for cnd_timedwait() . This can trivially be added. The third parameter to futex_wait() should be a non- NULL pointer to a struct timespec providing the time-out duration. Also the return value must be checked to distinguish time-outs from wake-ups. Note that the time-out would follow the monotonic clock. If you want true UTC clock semantics (as in ISO C11), you need to use FUTEX_CLOCK_REALTIME flag to the futex system call. System call optimization We did not optimize the waking system call away when there no waiters. A new member would have to be added struct cnd , e.g. an atomic waiter count variable. Be careful with ordering of atomic operations though. Mutex contention We did not spend much time looking at cnd_broadcast() . We assumed that we can substitute futex_signal() with futex_broadcast() in cnd_signal() . All waiting threads will wake up at the same time, and compete for the mutex in mtx_lock() . Only one thread gets it, all other go immediately back to sleep. Linux provides the futex requeue operation to deal with that problem. due to contention on the mutex. Priorities and fairness We did not look at waiter fairness at all here. This is not usually a problem, but you should keep that in mind if you plan to make your own futex-based operations. We also did not consider thread priorities. Again, this is not a problem in typical applications, but it is obviously an issue in real-time use cases. For those, Linux has priority-inheritance (PI) futex operations. Windows support With Windows 8, futex-like operations are possible. In general, the Windows support is a strict subset of Linux support: it only provides wait, timed wait, wake one and wake all operations. There are no flags to distinguish private and shared addresses, and to support the UTC clock. There are also none of the advanced operations that we did not go through. In all due fairness, Windows has one feature that Linux does not have. The futex do not have to be int . Any data type of 1, 2, 4 or 8 bytes is supported. #include <windows.h> int futex_wait(atomic_int *addr, int val, const struct timespec *to) { if (to == NULL) { WaitOnAddress((volatile void *)addr, &val, sizeof (val), -1); return 0; } if (to->tv_nsec >= 1000000000) { errno = EINVAL; return -1; } if (to->tv_sec >= 2147) { WaitOnAddress((volatile void *)addr, &val, sizeof (val), 2147000000); return 0; /* time-out out of range, claim spurious wake-up */ } DWORD ms = (to->tv_sec * 1000000) + ((to>tv_nsec + 999) / 1000); if (!WaitOnAddress((volatile void *)addr, &val, sizeof (val), ms)) { errno = ETIMEDOUT; return -1; } return 0; } int futex_signal(atomic_int *addr) { WakeByAddressSingle(addr); return 0; } int futex_broadcast(atomic_int *addr) { WakeByAddressAll(addr); return 0; } 评论 抢沙发
http://www.shellsec.com/news/23294.html
CC-MAIN-2017-30
refinedweb
2,770
53.81
Image::Compare - Compare two images in a variety of ways. use Image::Compare; use warnings; use strict; my($cmp) = Image::Compare->new(); $cmp->set_image1( img => '/path/to/some/file.jpg', type => 'jpg', ); $cmp->set_image2( img => '', ); $cmp->set_method( method => &Image::Compare::THRESHOLD, args => 25, ); if ($cmp->compare()) { # The images are the same, within the threshold } else { # The images differ beyond the threshold } This library implements a system by which 2 image files can be compared, using a variety of comparison methods. In general, those methods operate on the images on a pixel-by-pixel basis and reporting statistics or data based on color value comparisons. Image::Compare makes heavy use of the Imager module, although it's not neccessary to know anything about it in order to make use of the compare functions. However, Imager must be installed in order to use this module, and file import types will be limited to those supported by your installed Imager library. In general, to do a comparison, you need to provide 3 pieces of information: the first image to compare, the second image to compare, and a comparison method. Some comparison methods also require extra arguments -- in some cases a boolean value, some a number and some require a hash reference with structured data. See the documentation below for information on how to use each comparison method. Image::Compare provides 3 different ways to invoke its comparison functionality -- you can construct an Image::Compare object and call set_* methods on it to give it the information, then call compare() on that object, or you can construct the Image::Compare with all of the appropriate data right off the bat, or you can simply call compare() with all of the information. In this third case, you can call compare() as a class method, or you can simply invoke the method directly from the Image::Compare namespace. If you'd like, you can also pass the word compare to the module when you use it and the method will be imported to your local namespace. The EXACT method simply returns true if every single pixel of one image is exactly the same as every corresponding pixel in the other image, or false otherwise. It takes no arguments. $cmp->set_method( method => &Image::Compare::EXACT, ); The THRESHOLD method returns true if no pixel difference between the two images exceeds a certain threshold, and false if even one does. Note that differences are measured in a sum of squares fashion (vector distance), so the maximum difference is 255 * sqrt(3), or roughly 441.7. Its argument is the difference threshold. (Note: EXACT is the same as THRESHOLD with an argument of 0.) $cmp->set_method( method => &Image::Compare::THRESHOLD, args => 50, ); The THRESHOLD_COUNT method works similarly to the THRESHOLD method, but instead of immediately returning a false value as soon as it finds a pixel pair whose difference exceeds the threshold, it simply counts the number of pixels pairs that exceed that threshold in the image pair. It returns that count. $cmp->set_method( method => &Image::Compare::THRESHOLD_COUNT, args => 50, ); The AVG_THRESHOLD method returns true if the average difference over all pixel pairings between the two images is under a given threshold value. Two different average types are available: MEDIAN and MEAN. Its argument is a hash reference, contains keys "type", indicating the average type, and "value", indicating the threshold value. $cmp->set_method( method => &Image::Compare::AVG_THRESHOLD, args => { type => &Image::Compare::MEAN, value => 35, }, ); The IMAGE method returns an Imager object of the same dimensions as your input images, with each pixel colored to represent the pixel color difference between the corresponding pixels in the input. Its only argument is a boolean. If the argument is omitted or false, then the output image will be grayscale, with black meaning no change and white meaning maximum change. If the argument is a true value, then the output will be in color, ramping from pure red at 0 change to pure green at 50% of maximum change, and then to pure blue at maximum change. $cmp->set_method( method => &Image::Compare::IMG, args => 1, # Output in color ); In addition to providing the two images which are to be compared, you may also provide a "mask" image which will define a subset of those images to compare. A mask must be an Imager object, with one channel and 8 bit color depth per channel. Image processing will not occur for any pixel in the test images which correspond to any pixel in the mask image with a color value of (255, 255, 255), that is, black. Put another way, the pure black section of the mask image effectively "hide" that section of the test images, and those pixels will be ignored during processing. What that means will differ from comparator to comparator, but should be obviously predictable in nature. This is the constructor method for the class. You may optionally pass it any of 3 arguments, each of which takes a hash reference as data, which corresponds exactly to the semantics of the set_* methods, as described below. You may optionally pass in a match mask argument using the "mask" argument, which must be an Imager object, as described above. Sets the data for the appropriate image based on the input parameters. The img parameter can either be an Imager object, a file path or a URL. If a URL, it must be of a scheme supported by your LWP install. The type argument is optional, and will be used to override the image type deduced from the input. Again, the image type used must be one supported by your Imager install, and its format is determined entirely by Imager. See the documentation on Imager::Files for a list of image types. Note that providing images as URLs requires that both LWP and Regexp::Common be available in your kit. Returns the underlying Imager object for the appropriate image, as created inside of $cmp by either of the previous two methods. Sets the comparison method for the object. See the section above for details on different comparison methods. Returns a hash describing the method as set by the call previous. In this hash, the key "method" will map to the method, and the key "args" will map to the arguments (if any). Sets the match mask parameter as described above. Returns the match mask (if any) currently set in this object. Actually does the comparison. The return value is determined by the comparison method described in the previous section, so look there to see the details. As described above, this can be called as an instance method, in which case the values set at construction time or through the set_* methods will be used, or it can be called as a class method or as a simple subroutine. In the latter case, all of the information must be provided as arguments to the function call. Those argument have exactly the same semantics as the arguments for new(), so see that section for details. I also more than welcome suggestions from users as to comparison methods they would find useful, so please let me know if there's anything you'd like to see the module be able to do. This module is meant more to be a framework for image comparison and a collection of systems working within that framework, so the process of adding new comparison methods is reasonably simple and painless. This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see)
http://search.cpan.org/~avif/Image-Compare-0.5/lib/Image/Compare.pm
crawl-002
refinedweb
1,271
58.52
I have gotten started on my while loop but I'm kinda stuck I dont know where to go from here :( My assignment is to write a program to read in 6 numbers from the keyboard and then indicate whether any of them were larger than 500 or smaller than 10. After that I need to add in a flag that will detect numbers larger than 500. Use a bool variable for this. Then add in a flag that will detect numbers less than 10. Use a bool variable for this.. And this is all I have gotten so far :( .... Im just not cut out for computer science #include <iostream> using namespace std; int main () { int num; int ctr = 0; cout << " **** A Flag question ****" << endl; cout << endl; cout << "Please Enter 6 numbers"; while ( ctr < 7 ) cin >> num; if (num > 500 || num < 10) return true; else return false; ctr ++; return 0; Thanks guys -UKmason
https://www.daniweb.com/programming/software-development/threads/234953/need-help-with-a-simple-while-loop
CC-MAIN-2016-50
refinedweb
153
83.29
This post is outdated now Here we will discuss about how we can create a simple app using angular js 2. So first up all the question is why angular js 2? Angular js 1 is basically developed for google developers for their internal use and more over it is developed for UI designing purpose and later they extended many features like two way data binding etc. Now Angular js 1 is widely used by developers. Recent past some architectures and developers points about performance issues and angular core team finally come up with a new version of Angular and it is Angular js 2. Which is well structured and it offers a very good performance. There is a lot of difference between angular one and two. Angular two is supporting JavaScript ES6 which is not yet supported by latest browsers however you can use current JavaScript ES5 with angular 2, but you may not be able to enjoy all features of angular 2 in this case. So the best option is to use Angular two with typescript. In this case you need to compile the files before rendering into the browser as browser is not yet supporting ES6. But in coming future it should be supported and you can use angular 2 with JavaScript ES6 directly. In this article I am going to explain how we can start a simple application using Angular 2 + Typescript. Typescript is superscript of JavaScript. Before starting be ready with following things. 1. Visual Studio Code [ ] (As this editor supporting typescript so that you can enjoy coding) 2. NodeJS [ ] Create folder structure similar like below screen shot package.json { "name": "angular2_app", "version": "1.0.0", "description": "My first Angular 2", "main": "index.js", "scripts": { "start": "tsc && concurrent \"npm run tsc:w\" \"npm run lite\" ", "lite" : "lite-server", "tsc": "tsc", "tsc:w" : "tsc -w", "typings" : "typings" }, "keywords": [ "angular2", "node", "typescript", "javascript", "html5" ], "dependencies": { "angular2": "2.0.0-beta.17", "es6-shim": "0.35.1", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.6", "zone.js": "0.6.12", "systemjs":"0.19.31" }, "devDependencies": { "concurrently" : "1.0.0", "lite-server" : "1.3.1", "typescript":"1.7.3" }, "author": "Prashobh", "license": "ISC" } It contains all the dependencies. The script sections details are used for typescript for compiling purpose.Once you add package.json, go to command prompt and run "npm install" or you can open the folder and do "shift + right" click you will find an option "open command window here" ,click that and type "npm install". You can add other dependencies as well (eg:bootsrtap) then you can just type "npm update". You can see a folder "node-modules" is created with all the files. Index.html <html> <head> <link rel="stylesheet" href="css/bootstrap.min.css"> <!--Lib includes--> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="node_modules/angular2/bundles/angular2.dev.js"></script> <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> <script src="node_modules/rxjs/bundles/Rx.js"></script> <!--App includes--> <script type="text/javascript"> System.config({ packages: { app : { format: 'register', defaultExtension: 'js' } } }); System.import('app/boot').then( console.log.bind(console), console.error.bind(console) ); </script> <title>MY first angular 2 app</title> </head> <body class="container"> <sample-list></sample-list> </body> </html> tsconfig.json { "compilerOptions": { "target": "es6", "module":"system", "moduleResolution":"node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false }, "exclude":["node_modules"] } Under App I am creating some files, please see the below screenshot sample-list.html <h2>{{title}}</h2> <div> <ul> <li * <p>{{i.name}}</p> <p>{{i.des}}</p> <p>{{i.exp}}</p> </li> </ul> </div> sampleComponent.ts sampleComponent.ts is typescript file. I added JSON file inside the constructor itself for now, ideally it should be from service file, I am not going to explain those in this post. import {Component} from 'angular2/core' @Component({ selector: 'sample-list', templateUrl: 'app/sample-list.html', }) export class sampleComponent { title: string; items: any[]; constructor() { this.title = "My first Angular 2 Application"; this.items = [{ name:'Prashobh', des:'SSE', exp:'10', }, { name:'Abraham', des:'PM', exp:'15', }, { name:'Anil', des:'SE', exp:'2', }] } } Boot.ts In angular 2 we need to initialize the things rather than browser taking the control. import { bootstrap } from 'angular2/platform/browser' import { sampleComponent } from './sampleComponent' bootstrap(sampleComponent) .then( a => { console.log('--Bootstrap success!') console.log('--Catalog App is ready!') }, err => console.error(err) ); Now open command prompt and type "npm start". You can see your first Angular 2 app. If you are getting any error check typo mistake and also try to debug in chrome. The above demo is a kind of hello word application just to start with angular js 2. I will be writing more about on angular js 2 and things like setting a single page application. If you are interested bookmark this page. Related Post 1. ng-repeat in angular js 2 2. Angular 2 filter using pipe concept 3. ng-click in angular js 2 It worked for me ,simple explanation thanks Nice Post dude
http://www.angulartutorial.net/2016/06/how-to-start-with-angular-js-2.html?showComment=1466437698104
CC-MAIN-2020-34
refinedweb
837
51.34
Gpy for simple Alarm via LTE M or NB-IOT Hey friends, my plan is to use a Gpy for an simple Alarm System - if Door is open, send me an message.. noting fancy but.. puh, I am not used to MicroPython .. or Python and i am missing (for me logical steps) So basically is there a way to do this: Sleep, wake up, every xx minutes and log "everything's okay" (battery status, door status) maybe mqtt..? and on interrupt: send: "ALARM" to different Smartphones ( maybe mqqtPushClient App..?) those devices can turn of the alarm. - say like "stop/deactivate alarm for xx minutes" is there some examples I could use?? anyone there who could help? I am from Germany, SIM from is from 1nce. (Telekom Network) Oneway would be to use AWS, or a other Broker would be fine too. I could even install Mosquito with static IP. the only thing I can't figure out is, how to write code in python :D there is an Pycom 1nce blueprint on Github is there a way to modify this to my needs? i also found a script of an member using lte on MQTT - the only problem I have that after some minutes I get back OSError: [Errno 104] ECONNRESET is this problem on my side ( LTE connection down )? I also try to figure out why on one loop the print("") comes random and on a other loop it stay on one spot.. - Gijs Global Moderator last edited by You could use a while loop to check on the pin state as so: from machine import Pin import time #define buttons button1 = Pin('P9', Pin.IN) ... #check button press while True: if button1() == True: print('button 1 pressed') if button2() == True: print('button 2 pressed') #we need the sleep to give the microcontroller some downtime to complete background processes time.sleep_ms(10) I wouldn’t mind spoiling a easy solution with a lot of #infotext inside. ;) I had contact to 1nce in Germany and they said I can start with their blueprint on GitHub. I would.. if I could read it.. there is like zero #infotext.. Of course turning on and of the alarm, using keys or mqtt would be great. I have one big question: How would I tell my gpy to wait for one pin go high and than first send any mqtt? „Button 1 pressed“ „Button 2 pressed“ Battery level ok Battery level low That would be the next steps i would try to play with to get in deeper. Thanks for helping :) - Gijs Global Moderator last edited by Gijs You could get started with the examples from the documentation:, get connected to WLAN or LTE, try a couple of things using the socket module, or external urequest library from micropython. In essence, micropython is very similar to regular python, just keep in mind there's less processing power on the development modules than what you would experience on a normal computer. Your thought process seems okay, though, there are still some caveats you'll probably run into (opening the door while sleeping, turning the alarm off reliably, detecting power loss etc.). A lot of things to learn there :) Im not going to spoil the project by giving you a direct solution, as there really is no unique solution. Let us know if you have any 'concrete' questions about certain aspects, and there will be a lot of people on the forum happy to help you!
https://forum.pycom.io/topic/6825/gpy-for-simple-alarm-via-lte-m-or-nb-iot
CC-MAIN-2021-10
refinedweb
580
76.25
Back to lambda library pages I'm trying to figure out how to do something like this: for_each(container.begin(), container.end(), cout << _1.member << "\n"); which is obviously wrong, but hopefully you know what I mean... Experimenting with ways of accessing members inside a lambda, I wrote the following: #include <iostream> #include <boost/lambda/lambda.hpp> #include <vector> using namespace std; using namespace boost; using namespace lambda; struct XX { XX(int a, int b) { a_ = a; b_ = b; } int a_; int b_; }; int main() { XX xx(5, 6); XX *xxp = &xx; cout << "These are all equivalent:\n"; cout << xxp ->* &XX::a_ << endl; cout << (_1 ->* &XX::a_)(xxp) << endl; //cout << (_1 ->* &XX::a_)(&xx) << endl; // Doesn't compile! cout << (&_1 ->* &XX::a_)(xx) << endl; cout << "Now, let's try with the vector:\n"; vector<XX> xxVec; xxVec.push_back(XX(3, 4)); cout << (&_1 ->* &XX::a_)(xxVec[0]) << endl; //cout << (_1 ->* &XX::a_)(&xxVec[0]) << endl; // Doesn't compile! cout << (_1 ->* &XX::a_)(xxp = &xxVec[0]) << endl; // Now it compiles... //cout << (_1 ->* &XX::a_)(xxVec.begin()) << endl; // Doesn't compile! //cout << (_1 ->* &XX::a_)(&*xxVec.begin()) << endl; // Still not... cout << (_1 ->* &XX::a_)(xxp = &*xxVec.begin()) << endl; // Now it compiles... exit(0); } I'm mystified by why some of these lines don't compile (gcc 3.2.2). Can anyone explain it? The compiler generates some horrific error messages -- I haven't tried to pick through them yet... - People/Chuck Messenger
http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Problems_-_Lambda_Library
CC-MAIN-2017-13
refinedweb
240
77.13
Your Account If you’re new to Mac, you might be surprised to find that applications don’t come in the form of .exe files. The excellent design for which Apple is known in its hardware and graphics extends into its software architecture as well, and includes the way applications are laid out in the file system. The same strategy used in Apple desktop systems carries over into the iPhone. .exe This excerpt is from iPhone Open Application Development.. Apple has adopted the practice of creating modular, self-contained applications with their own internal file resources. As a result, installing most applications is as easy as simply dragging them into your applications folder; deleting them as easy as dragging them into the trash. In this chapter, the structure of applications on the iPhone will be explained. You’ll also get up and running with the free open source tool chain used to build executables, and you’ll learn how to install applications on your iPhone. Finally, you’ll be introduced to the Objective-C language and enough of its idiosyncrasies to make an easy transition from C or C++. result was to treat an application as a bundle inside a directory and use standard APIs to access resources, execute binaries, and read information about the application. If you look inside any Mac application, you’ll find that the .app extension denotes not a file, but a directory. This is the application’s program directory. Inside it is an organized structure containing resources the application needs to run, information about the application, and the application’s executable binaries. A compiler doesn’t generate this program directory structure, but only builds the executable binaries. So to build a complete application, it’s up to the developer to create a skeleton structure that will eventually host the binary and all of its resources. app The program directory for an iPhone application is much less structured than desktop Mac applications. In fact, all of the files used by the application are in the root of the .app program folder: .app The above reflects a very basic iPhone application called MobileTerminal. MobileTerminal is an open source terminal client for the iPhone, allowing the user to pull up a shell and work in a Unix environment (which also must be installed as third-party software). MobileTerminal illustrates all of the major components of an iPhone application: Terminal.app The directory that all of the application’s resources reside in. Default.png A PNG image (Portable Network Graphics file). When the user starts the application, the iPhone animates it to give the appearance that it’s zooming to the front of the screen. This is done by loading Default.png and scaling it up until it fills the screen. This 320×480 image zooms to the front and remains on the screen until the application finishes launching, at which point it serves as the background for whatever user interface elements are drawn on the screen. Applications generally use a solid black or white background. Info.plist A property list containing information about the application. This includes the name of its binary executable and a bundle identifier, which is used by the SpringBoard application to launch it. You’ll see an example property list later on in this section. Terminal The actual binary executable that is called when the application is launched. This is what your compiler outputs when it builds your application. Your makefile can copy your binary into the application folder when doing a production build. This chapter will provide an example of this process. icon.png An image forming the application’s icon on the SpringBoard (the iPhone’s desktop application). SpringBoard isn’t concerned with the size of the file and will attempt to draw the image outside of its icon space if it is large enough. Most icons are generally 60×60 pixels. pie.png An image resource used by the MobileTerminal application. There are many methods provided by the iPhone framework to fetch resources, and most of them accept only a filename instead of a path. The file supplied to these methods must therefore be stored directly in the program directory. This is consistent with Apple’s effort to keep applications self-contained. The first thing you’ll need to do before building an application is to put together a skeleton .app directory to contain it.[1] The skeleton will provide all of the information necessary for the iPhone to acknowledge the existence of your application so it can be run from the SpringBoard. This book presents many fully functional code examples, and in order to properly run them, you’ll need to build an example skeleton called MyExample.app. Creating the directory is easy enough: MyExample.app $ mkdir MyExample.app mkdir MyExample.app Next, write a property list to describe the application and how to launch it. The Info.plist file expresses the property list in XML and should look like this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" ""> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>MyExample</string> <key>CFBundleIdentifier</key> <string>com.oreilly.</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> </dict> </plist> MyExample The most important options above have been bolded. These are the values for CFBundleExecutable and CFBundleIdentifier. The CFBundleExecutable property specifies the filename of the binary executable within the folder. This is the file that gets executed when your application is launched—the output from your compiler. In this example, the filename is the same as the application’s name, but this isn’t absolutely necessary. CFBundleExecutable CFBundleIdentifier The CFBundleIdentifier property specifies a unique identifier by which your application is known. The application layer of the iPhone is more concerned about addressing your application as a whole rather than the binary itself. Whenever SpringBoard (or another application) launches MyExample, it will be referenced using this identifier. The name must be unique among all other applications on the iPhone. It’s common practice to incorporate the URL of your website to ensure it’s unique. The application’s icon.png and Default.png files are also copied in. If these are left out, the iPhone will use the worst-looking images possible to serve as default images for both. We’ll leave the files out of our example to show you what we mean. Make sure to create and include images with these names when you publish your own applications to make them look professional. Our skeleton is now good enough to run examples. In the next section, you’ll install the tool chain on your desktop, after which you can get started compiling example applications. In the coming chapters, you’ll build many examples. After each has been built, the binary executable MyExample will need to be copied into your program folder. Your completed application will look like this: drwxr-xr-x root admin MyExample.app/ -rw-r--r-- root admin Info.plist -rwxr-xr-x root admin MyExample The examples provided in this book generally do not need any additional resources, so images and sounds will be necessary only when the example calls for them. When they do, however, you’ll copy the files required into the MyExample.app directory. Most examples make use of existing files on the iPhone to avoid filling up the book with binary code. As we discussed in Chapter 1, Breaking Into and Setting Up the iPhone, the iPhone began life as a closed platform. This originally meant that no developer tools were publicly available to build iPhone-native applications. There has been much speculation about whether Apple secretly hoped the community would break into the phone, thus bolstering its status among the geek community. Over the first few months of the iPhone’s life, this is exactly what happened. The open source community successfully cracked the phone and began writing a tool chain to build applications. It has since been released as free software. The tool chain consists of a cross-compiler, a linker, an assembler, a C hook into the assembler called Csu, and class headers for Objective-C frameworks generated by a tool called class-dump. Today, the tool chain has undergone many improvements by Jay Freeman (also known as saurik) and is available in two forms. A desktop version of the tool chain uses a cross-compiler, which is a compiler that runs on one machine (namely, your desktop) but builds executables that can run on a different machine (the ARM processor in an iPhone). A native compiler can also be installed directly on the iPhone, allowing you to build applications without installing any special software on your desktop. The commands and pathnames provided throughout this book presume that you’ve used the procedures from this chapter to build and/or install the tool chain. The tool chain is updated periodically as new versions of it are released, so its setup can sometimes change. The latest instructions for building the tool chain on the desktop can be found on Jay Freeman’s site at. The tool chain builds and installs into /toolchain by default. All of the examples provided in this book will presume that this is where you’ve installed it. If you’ve built the tool chain before, or are just concerned about modifying files there, you’ll want to move your current /toolchain out of the way and start with a fresh directory. /toolchain If you have a previous version of the tool chain, newer versions may not build correctly. To ensure that you start with a clean installation, move your old copy out of the way. If you’re looking to install the tool chain directly on the iPhone, the only thing you’ll need is a jailbroken iPhone with the community installer, Cydia, runing on it. To install the tool chain, simply launch Cydia and then choose the Development section from the Sections list. Scroll down and select iPhone 2.0 Toolchain, then tap the Install button. The tool chain will then be installed on the iPhone, and you can invoke it using the standard gcc command. You can now skip the rest of this section. gcc Building on the desktop is more involved. While there are some unofficial binary distributions of the tool chain floating around the Internet, you’ll be building it from sources in this section. The following are requirements for building from sources. The first thing you’ll need is a desktop platform that is supported. Platforms currently supported by the tool chain are: Mac OS X 10.4 Intel or PPC Mac OS X 10.5 Intel Ubuntu Feisty Fawn, Intel Ubuntu Gutsy Gibbon, Intel Fedora Core, Intel Gentoo Linux 2007.0, x86_64 Debian 2.6.18 CentOS 4 Other platforms follow the same basic steps as these. Official tool chain instructions can be found at. The tool chain is considerable in size—even just the sources. Unless you want to be sitting around for a few days, you’ll likely want to download the sources over a high-speed connection. If you don’t have one, it might be a good idea to perform the installation from a library or local coffee The next things you’ll need are the necessary open source tools installed on your desktop: bison (v1.28 or later) bison flex (v2.5.4 or later) flex gcc (the GNU compiler that handles C, C++, and Objective-C) git (a source code control utility) git If you’re missing any of these tools, download and install them before proceeding. On the Mac, all but git are included with Xcode tools, and you’ll want to install or upgrade to the latest version of Xcode before proceeding. Most other operating systems provide them as optional components in their distribution. Xcode tools can be downloaded from Apple’s website at. You’ll need a copy of your iPhone’s filesystem, specifically, the libraries and frameworks. For dramatic effect, and because our lawyers make us, we’ll display this general disclaimer: Installing the tool chain requires that you copy libraries from your iPhone to your desktop. Check your local, state, and federal laws to ensure this is legal where you reside. Having installed SSH onto the iPhone in Chapter 1, Breaking Into and Setting Up the iPhone, use the following commands to download the files you need into a folder called /toolchain/sys: /toolchain/sys $ Before you get started, you’ll set a few environment variables to specify where the tool chain is to be installed. To install into /toolchain, use the following paths. You may also change these to your liking. Make sure you place the downloaded libraries and frameworks into whatever you specify as ${sysroot}: ${sysroot} # Once you’ve got all of the variables exported, you’re ready to start building. The Csu provides C hooks into assembly’s “start” entry point, and sets up the stack so that your program’s main( ) function can be called. It’s essentially glue code: main( ) # The following commands build and install the cross-compiler components of the tool chain. These are specific to Mac OS X, so be sure to read the official documentation if you’re using a different platform: # The system headers found in your Xcode SDK are shared by your desktop and the iPhone platform, but some pre-compiler macros are architecture-specific. Because the iPhone’s architecture is different from the desktop’s, these headers need to be installed to work for the iPhone. Issue the following commands to install an iPhone-custom set of headers into your newly created tool chain. These will be based on Xcode’s headers: # cd "${build}" # svn co include # cd include # ./configure --prefix="${sysroot}"/usr # bash install-headers.sh svn co include cd include ./configure --prefix="${sysroot}"/usr bash install-headers.sh After the headers are installed, the final step is to build the LLVM compiler.: # rm -rf "${gcc}" # git clone git://git.saurik.com/llvm-gcc-4.2 "${gcc}" # # mkdir -p "${sysroot}"/"$(dirname "${prefix}")" # ln -s "${prefix}" "${sysroot}"/"$(dirname "${prefix}")" rm -rf "${gcc}" git clone git://git.saurik.com/llvm-gcc-4.2 "${gcc}" mkdir gcc-4.2-iphone cd gcc-4.2-iphone "${gcc}"/configure \ --with-sysroot="${sysroot}" \ --enable-languages=c,c++,objc,obj-c++ \ --with-as="${prefix}"/bin/"${target}"-as \ --with-ld="${prefix}"/bin/"${target}"-ld \ --enable-wchar_t=no \ --with-gxx-include-dir=/usr/include/c++/4.0.0 make -j2 mkdir -p "${sysroot}"/"$(dirname "${prefix}")" ln -s "${prefix}" "${sysroot}"/"$(dirname "${prefix}")" Now that the tool chain has been installed, the next step is to learn how to use it. There are two essential ways to build an executable: the command line or a makefile. The examples in this book are simple enough that they can be built using the command line. The tool chain is compliant to standard compiler arguments, and should be familiar if you’ve ever used gcc in the past. You’ll want to make sure /toolchain/pre/bin is in your path before you try to use the cross-compiler: /toolchain/pre/bin $ export PATH=$PATH:/toolchain/pre/bin export PATH=$PATH:/toolchain/pre/bin The anatomy of a typical command-line compiler is: $ arm-apple-darwin9-gcc -o MyExample MyExample.m -lobjc \ -framework CoreFoundation -framework Foundation \ -march=armv6 -mcpu=arm1176jzf-s arm-apple-darwin9-gcc -o MyExample MyExample.m -lobjc \ -framework CoreFoundation -framework Foundation \ -march=armv6 -mcpu=arm1176jzf-s arm-apple-darwin9-gcc The name of the cross-compiler itself. This is located in /toolchain/pre/bin, so be sure you’ve added it to your path. -o MyExample Tells the compiler to output the compiled executable to a file named MyExample. MyExample.m The name of the source file(s) being included in the program, separated by spaces. The .m extension tells the compiler that the sources are written in Objective-C. .m -lobjc Tells the compiler to link in the tool chain’s Objective-C messaging library, which is needed by all iPhone applications. This library glues C-style function calls to Objective-C messages, among other things. -framework CoreFoundation -framework Foundation Two of the base frameworks to be linked into the application. Depending on what components of the operating system are being used in the code, different frameworks provide different layers of functionality. You’ll be introduced to many different frameworks throughout this book. -march=armv6 -mcpu=arm1176jzf-s Sets the correct architecture and CPU type of the executable. The command line will suffice for most small applications and examples, but for larger applications, it makes sense to write a makefile. A makefile is a simple text file that acts as a manifest for building applications. It is used by a program called make, which is a portable build utility included with most development kits. The make program is responsible for calling the compiler (and linker) and passing them whatever flags and parameters are needed. Makefiles are logical ways to lay out the composition of an application. They also allow the developer to easily clean up the object files in a directory, create application packages, and perform a number of other tasks useful to building applications. The previous command-line example could be rewritten as a makefile like the one below, named Makefile, and placed into the source directory: Makefile CC = /toolchain/pre/bin/arm-apple-darwin9-gcc LD = $(CC) LDFLAGS = -lobjc \ -framework CoreFoundation \ -framework Foundation CFLAGS = -march=armv6 -mcpu=arm1176jzf-a all: MyExample MyExample: MyExample.o $(LD) $(LDFLAGS) -o $@ $^ %.o: %.m $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ %.o: %.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ %.o: %.cpp $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ All indentations are actually tabs. Tabs must be used in order for the makefile to work properly. Once the makefile file is in place, the application’s executable can be built with one simple command: $ make In addition to building an application, functionality can be added to copy the application’s executable into the program folder skeleton you made: package: cp -p MyExample ./MyExample.app/ With this added to the makefile, you can run make package to automatically set up your .app directory. make package Another popular use for makefiles is to clean the directory so that it can be sent to someone else. You can even tell the makefile to delete the executable that was copied into the program folder: clean: rm -f *.o *.gch rm -f ./MyExample.app/MyExample Once an application has been built, it can be installed by copying the entire program directory into the /Applications folder on the iPhone. Using the SSH server you set up in Chapter 1, Breaking Into and Setting Up the iPhone, you can do this over WiFi: /Applications $ scp -r MyExample.app root@iphone:/Applications scp -r MyExample.app root@iphone:/Applications Before the iPhone will recognize the application, either the iPhone must be powered down and rebooted, or the SpringBoard application must be restarted on the iPhone itself. Log in to the iPhone using SSH and execute the following command to restart SpringBoard: $ killall SpringBoard killall SpringBoard Once restarted, you should see the application on the SpringBoard. If you are running iPhone firmware v2.0 or greater, you’ll need to digitally sign your application in order for it to run. This can be done right on the iPhone by installing the link-identity tool. This is done through Cydia, or you can use Cydia’s apt-get tool from the command line on the iPhone, if you’re running SSH: # apt-get install ldid apt-get install ldid Once you’ve installed ldid, sign your application using the command below: ldid # ldid -S /Applications/MyExample.app/MyExample ldid -S /Applications/MyExample.app/MyExample You can now tap the icon to launch your application from the SpringBoard. Objective-C was written in the early 1980s by scientist and software engineer Brad Cox. It was designed as a way of introducing the capabilities of the Smalltalk language into a C programming environment. A majority of the iPhone’s framework libraries are written in Objective-C, but because the language was designed to accommodate the C language, you can use C and C++ in your application as well. Objective-C is used primarily on Mac OS X and GNUstep (a free OpenStep environment). Many languages, such as Java and C#, have borrowed from the Objective-C language. The Cocoa framework makes heavy use of Objective-C on the Mac desktop, which carries over onto the iPhone. If you’ve developed on the Mac OS X desktop before, you’re already familiar with Objective-C, but if the iPhone is your first Apple platform, then you’re likely transitioning from C or C++. This section will cover some of the more significant differences between these languages. If you have a prior background in C or C++, this should be enough to get you up and writing code using the examples in this book as a guide. The first thing you’ll notice in Objective-C is the heavy use of brackets. In Objective-C, methods are not called in a traditional sense; instead, they are sent messages. Likewise, a method doesn’t return, but rather responds to the message. Unlike C, where function calls must be predefined, Objective-C’s messaging style allows the developer to dynamically create new methods and messages at runtime. The downside to this is that it’s entirely possible to send an object a message to which it can’t respond, causing an exception and likely program termination. Given an object named myWidget, a message can be sent to its powerOn method this way: myWidget powerOn returnValue = [ myWidget powerOn ]; The C++ equivalent of this might look like: returnValue = myWidget->powerOn( ); The C equivalent might declare a function inside of its flat namespace: returnValue = widget_powerOn(myWidget); Arguments can also be passed with messages, provided that an object can receive them. The following example invokes a method named setSpeed and passes two arguments: setSpeed returnValue = [ myWidget setSpeed: 10.0 withMass: 33.0 ]; Notice the second argument is explicitly named in the message. This allows multiple methods with the same name and data types to be declared—polymorphism on steroids: returnValue = [ myWidget setSpeed: 10.0 withMass: 33.0 ]; returnValue = [ myWidget setSpeed: 10.0 withGyroscope: 10.0 ]; While C++ classes can be defined in Objective-C, the whole point of using the language is to take advantage of Objective-C’s own objects and features. This extends to its use of interfaces. In standard C++, classes are structures, and their variables and methods are contained inside the structure. Objective-C, on the other hand, keeps its variables in one part of the class and methods in another. The language also requires that the interface declaration be specifically declared in its own code block (called @interface) separate from the block containing the implementation (called @implementation). The methods themselves are also constructed in a Smalltalk-esque fashion, and look very little like regular C functions. @interface @implementation The interface for our widget example might look like Example 2.1, “Sample interface (MyWidget.h)”, which is a file named MyWidget.h. MyWidget.h Example 2.1. Sample interface (MyWidget.h) #import <Foundation/Foundation.h> @interface MyWidget : BaseWidget { BOOL isPoweredOn; @private float speed; @protected float mass; @protected float gyroscope; } + (id)alloc; - (BOOL)needsBatteries; - (BOOL)powerOn; - (void)setSpeed:(float)_speed; - (void)setSpeed:(float)_speed withMass:(float)_mass; - (void)setSpeed:(float)_speed withGyroscope:(float)_gyroscope; @end Each of the important semantic elements in this file are explained in the following sections. The preprocessor directive #import replaces the traditional #include directive (although #include may still be used). One advantage to using #import is that it has built-in logic to ensure that the same resource is never included more than once. This replaces the roundabout use of macro flags found routinely in C code: #import #include #ifndef _MYWIDGET_H #define _MYWIDGET_H ... #endif The interface is declared with the @interface statement followed by the interface’s name and the base class (if any) it is derived from. The block is ended with the @end statement. @end Methods are declared outside of the braces structure. A plus sign (+) identifies the method as a static method, while a minus sign (−) declares the method as an instance method. Thus, the alloc method (to allocate a new object) will be called using a reference directly to the MyWidget class, whereas methods that are specific to an instance of the MyWidget class, such as needsBatteries and powerOn, will be invoked on the instance returned by alloc. alloc MyWidget needsBatteries Every declared argument for a method is represented by a data type, local variable names, and an optional external variable name. Examples of external variable names in Example 2.1, “Sample interface (MyWidget.h)” are withMass and withGyroscope. The notifier (calling function) that invokes the method refers to external variable names, but inside the method the arguments are referenced using their local variable name. Thus, the setSpeed method uses the local _mass variable to retrieve the value passed as withMass. withMass withGyroscope _mass If no external variable name is supplied in the declaration, the variable is referenced only with a colon, for example, :10.0. :10.0 The code suffix for Objective-C source is .m. A skeleton implementation of the widget class from the last section might look like Example 2.2, “Sample implementation (MyWidget.m)”, which is named MyWidget.m. MyWidget.m Example 2.2. Sample implementation (MyWidget.m) #import "MyWidget.h" @implementation MyWidget + (id)alloc { } + (BOOL)needsBatteries { return YES; } − (BOOL)powerOn { isPoweredOn = YES; return YES; } − (void)setSpeed:(float)_speed { speed = _speed; } − (void)setSpeed:(float)_speed withMass:(float)_mass { speed = _speed; mass = _mass; } − (void)setSpeed:(float)_speed withGyroscope:(float)_gyroscope { speed = _speed; gyroscope = _gyroscope; } @end Just as the interface was contained within its own code block, the implementation begins with an @implementation statement and ends with @end. In C++, it is common practice to prefix member variables with m_ so that public methods can accept the name of the variable. This makes it easy to reuse someone else’s code because they can deduce a variable’s purpose by its name. Since Objective-C allows for an external variable name to be used, the method is able to provide a sensible name for the developer to use while internally using some proprietary name. The true name can then be used inside the object, while the method’s local variable name is prefixed with an underscore, e.g., _speed. m_ _speed Objective-C adds a new element to object-oriented programming called categories. Categories were designed to solve the problem where base classes are treated as fragile to prevent seemingly innocuous changes from breaking the more complex derived classes. When a program grows to a certain size, the developer can often become afraid to touch the smaller base classes because it’s too difficult by then to determine what changes are safe without auditing the entire application. Categories provide a mechanism to add functionality to smaller classes without affecting other objects. A category class can be placed “on top” of a smaller class, adding to or replacing methods within the base class. This can be done without recompiling or even having access to the base classes’ source code. Categories allows for base classes to be expanded within a limited scope, so that any objects using the base class (and not the category) will continue to see the original version. From a development perspective, this makes it much easier to improve on a class written by a different developer. At runtime, portions of code using the category will see the new version of the class, and code using the base class directly will see only the original version. The difference between inheritance and categories is the difference between tricking out your car versus dressing it up as a parade float. When you soup up your sports car, new components are added to the internals of the vehicle that cause it to perform differently. Sometimes components are even pulled out and replaced with new ones. The act of adding a new component to the engine, such as a turbo, affects the function of the entire vehicle. This is how inheritance works. Categories, on the other hand, are more like a parade float in that the vehicle remains completely intact, but cardboard cutouts and papier-mâché are affixed to the outside of the vehicle so that it appears different. In the context of a parade, the vehicle is a completely different animal, but when you take it to the mechanic, it’s the same old stock car you’ve been driving around. The widget factory is coming out with a new type of widget that can fly through space, but is concerned that making changes to their base class might break existing applications. By building a category, applications using the MyWidget base class will continue to see the original class, while the newer space applications will use a category instead. The following example builds a new category named MySpaceWidget on top of the existing MyWidget base class. Because we need the ability to blow things up in space, a method named selfDestruct is added. This category also replaces the existing powerOn method with its own. Contrast the use of parentheses here to hold the MySpaceWidget contained class with the use of a colon in Example 2.1, “Sample interface (MyWidget.h)” to carry out inheritance: MySpaceWidget selfDestruct #import "MyWidget.h" @interface MyWidget (MySpaceWidget) - (void)selfDestruct; - (BOOL)powerOn; @end Example 2.3, “Sample category (MySpaceWidget.m)” shows a complete source file implementing the category. Example 2.3. Sample category (MySpaceWidget.m) #import "MySpaceWidget.h" @implementation MyWidget (MySpaceWidget) - (void)selfDestruct { isPoweredOn = 0; speed = 1000.0; mass = 0; } - (BOOL)powerOn { if (speed == 0) { isPoweredOn = YES; return YES; } /* Don't power on if the spaceship is moving */ return NO; } @end In Objective-C, a subclass class can pose as one of its superclasses, virtually replacing it as the recipient of all messages. This is similar to overriding, only an entire class is being overridden instead of a single method. A posing class is not permitted to declare any new variables, although it may override or replace existing methods. Posing is similar to categories in that it allows a developer to augment an existing class at runtime. In past examples, mechanical widget classes were created. Well, at some point after designing all of these widgets, perpetual energy was discovered. This allowed many of the newer widgets to be autonomous, while some legacy widgets still required batteries. Because autonomous widgets have such a significant amount of different code, a new object called MyAutonomousWidget was derived to override all of the functionality that has changed, such as the static needsBatteries method. See Examples 2.4 and 2.5. MyAutonomousWidget Example 2.4. Sample interface for posing (MyAutonomousWidget.h) #import <Foundation/Foundation.h> #import "MyWidget.h" @interface MyAutonomousWidget : MyWidget { } + (BOOL)needsBatteries; @end Example 2.5. Sample implementation for posing (MyAutonomousWidget.m) #import "MyAutonomousWidget.h" @implementation MyAutonomousWidget + (BOOL)needsBatteries { return NO; } @end Instead of changing all of the existing code to use this class, the autonomous class can simply pose as the widget class. The class_poseAs method is called from the main program or another high-level method to invoke this behavior: class_poseAs MyAutonomousWidget *myAutoWidget = [ MyAutonomousWidget alloc ]; MyWidget *myWidget = [ MyWidget alloc ]; class_poseAs(myAutoWidget, myWidget); At this point, any other methods we’ve replaced in the posing class (to change how we talk to autonomous devices) would pose as the original base class. To learn more about Objective-C programming, check out the following great resources from O’Reilly: Learning Cocoa with Objective-C, Second Edition, by James Duncan Davidson Objective-C Pocket Reference by Andrew M. Duncan [1] Technically, it’s possible to run an application directly from the iPhone’s command line, but this breaks many application-level functions. SpringBoard itself is heavily integrated with the user interface framework, and your applications will need to be assembled and invoked appropriately to make them entirely usable. If you enjoyed this excerpt, buy a copy of iPhone Open Application Development. © 2014, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.oreillynet.com/pub/a/iphone/excerpts/iphone-open-dev/getting-started-applications.html
CC-MAIN-2014-41
refinedweb
5,413
55.13
OpenGL Output Class About the Class The class makes it possible to create a font simply and to display text all kinds in OpenGL. Unlike the class CGLInput, this class can work great under MFC (but if you use it, you have to go to the settings of the project in VC++ 6.0 and and choose for the files of the class not to use precompiled headers). The functions of the class are based on the ones that appear on the site, and it should get the credit it deserves. How to Use the Class First of all, you have to define (of course) a variable. Then, use the SetFont function to set the font's definitions. Once you have called the SetFont function, you can use the Print function; that works exactly the way printf (of the standard IO of C Language) does. You can use SetFont more than once to change the font's properties. The Functions of the Class SetFont void SetFont( HDC hDC, char* fName = NULL, GLfloat fDepth = 0.5f, int fWeight = FW_BOLD, DWORD fItalic = FALSE, DWORD fUnderline = FALSE, DWORD fStrikeOut = FALSE, DWORD fCharSet = ANSI_CHARSET ) Parameters: - hDC—Handle of GDI Device Contex. - fName—Font name as defined in Windows; for example, "Arial" or "Times New Roman." - fDepth—How "deep" the font goes, meaning how long it gets on the Z axis. - fWeight—Weight of the font. There is a list of values that will fit in MSDN (CreateFont function). - fItalic—For italic font, TRUE; otherwise, FALSE. - fUnderline—For underlined font, TRUE; otherwise, FALSE. - fStrilkeOut—For strikeout font, TRUE; otherwise, FALSE. - fCharSet—The character set. For a specific language, it is the name of language in capital letters, then CHARSET. For example, GREEK_CHARSET or HEBREW_CHARSET. It can write in English anyway, so if you don't use another language, just leave it or enter ANSI_CHARSET, which is the default. bool Print(const char *fmt, ...) Parameters: A string and afterwards the variables that you want to print, in the same template that printf function uses. Return values: If the font isn't set or if the entered string is NULL, the function will return true. Otherwise, it will return false. Class Constants The class has only one constant: GLO_DEFAULT_FONT[] of char. It contains the name of the default font (that is used in case no font name or NULL was entered for the fName parameter of SetFont). Example #include "CGLOutput.h" ... char myname[]; CGLOutput OC; // Output Class variable ... OC.SetFont(hDC, "Comic Sans MS"); // Set font definitions OC.Print("Hello %s", myname); // Print "hello" + a string"" ... Other Remarks This article, and another one that I wrote about an input class and a class for both Input & Output in OpenGL, can all be found in NeHe's Productions Site at. There is another example in the attached file. There are no comments yet. Be the first to comment!
http://www.codeguru.com/cpp/g-m/opengl/openfaq/article.php/c7017/OpenGL-Output-Class.htm
CC-MAIN-2013-20
refinedweb
480
75.1
spawnvpe() Spawn a child process, given a vector of arguments, an environment, and a relative path Synopsis: #include <spawn.h> int spawnvpe( int mode, const char * file, char * const argv[], char * constv - A pointer to an argument vector; this argument can't be NULL. The value in argv[0] can't be NULL, and should represent the filename of the program being loaded. The last member of argv must be a NULL pointer. -vpe() function creates and executes a new child process, named in file with the NULL-terminated list of arguments in the argv vector. - : ()): -). A parent/child relationship doesn't imply that the child process dies when the parent process dies.vpe() function isn't implemented for the filesystem specified in file. -). Caveats: If mode is P_WAIT, this function is a cancellation point. Last modified: 2014-11-17 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/spawnvpe.html
CC-MAIN-2018-05
refinedweb
156
66.64
Itertools Recipe: All Equal all_equal() def all_equal(iterable): "Returns True if all the elements are equal to each other" g = groupby(iterable) return next(g, True) and not next(g, False) Demo all_equal('aaaaaaaaa') True all_equal('aaaaaaab') False Why this works This one relies on how the itertools.groupby() function resolves. Calling it on an iterable yields a stream of tuples of the form (unique group found, iterable). When they’re all the same, this will be one tuple obj = itertools.groupby('aaaaaaa') list(obj) [('a', <itertools._grouper at 0x25db4853cc0>)] list(obj) [('a', <itertools._grouper at 0x1e531b6bf28>)] and when it gets a different value on the end, it’s got two obj = itertools.groupby('aaaaaab') list(obj) [('a', <itertools._grouper at 0x25db486d240>), ('b', <itertools._grouper at 0x25db486d2e8>)] the default behavior of the next() function is what ties this all together. Calling next() on an iterable with a second argument is very similar to the behavior of dict.get(default_val) # without default try: obj = iter([]) print(next(obj)) except StopIteration: print('Empty Iter') # with default try: obj = iter([]) print(next(obj, 0)) except StopIteration: print('Empty Iter') Empty Iter 0 So in this context, lets look at that second chunk and not next(g, False) If we only have one tuple returned by groupby(), next(g) will raise the StopIterationException, thus giving us the default value False. Applying the leading not evaluates the statement to True. Otherwise, if it weren’t empty, anything that gets returned will be “Truthy”, get the not applied to it and evaluate to False.
https://napsterinblue.github.io/notes/python/internals/itertools_all_equal/
CC-MAIN-2021-04
refinedweb
258
55.03
Let's say I want to create an HTML list helper that would allow me to loop through a collection, and only output the <ul> or <ol> tags if there are any list items (what I actually have in mind is a bit nastier, but this'll work for an example). Something like: <% html_list(:ul, MyModel.all) do |my_model| %> <span><%= my_model.id %></span> <% end %> (As you can tell, I'm lost.) I cannot wrap my head around what would go in my html_list method. Would you mind pointing me in the right direction? You'd probably want something like this: def html_list(tag, enum)<li>' html << enum.map { |e| yield e }.join('</li><li>') html << '</li></' + tag.to_s + '>' html.html_safe end or perhaps this way: def html_list(tag, enum) html = [ '<' + tag.to_s + '>', '<li>', enum.map { |e| yield e }.join('</li><li>'), '</li>', '</' + tag.to_s + '>' ] html.join.html_safe end There are various ways to build the final string, the meat of it is that you're building a method that takes a block and iterates over an enumerable and applies the block to each element along the way.
http://m.dlxedu.com/m/askdetail/3/318e4b1dfa6001820537998381b563be.html
CC-MAIN-2019-04
refinedweb
187
84.98
A friend class in C++, can access the private.protected and public members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared. Friend status is not inherited; every friendship has to be explicitly declared. Example #include <iostream> class B { // B declares A as a friend... friend class A; private: void privatePrint() { std::cout << "firend classes" << std::endl; } }; class A { public: A() { B b; // ... and A now has access to B's private members b.privatePrint(); } }; int main() { A a; getchar(); return 0; }
http://www.loopandbreak.com/friend-classes-in-c/
CC-MAIN-2021-17
refinedweb
108
75.3
Tarun Jha2,844 Points Except not working as it should! import random cmp_choice = random.randint(1,10) def win_msg(): print('You win!') return def lose_msg(): print('Sorry! you lost') return def compare(): print('Type any integer b/w 1 to 10') for chances in range(5): try: user_choice = int(input('What\'s your guess? ')) except ValueError: print('{} is not an integer'.format(user_choice)) else: if cmp_choice == user_choice: win_msg() break else: if user_choice > cmp_choice: print('Nooo!,it\'s too much, my number is smaller than {}'.format(user_choice)) elif user_choice < cmp_choice : print('You are too low, mine number is higher than {}'.format(user_choice)) print('Chances left: ',5 - chances) else: print('You didn\'t get it it was {}'.format(user_choice)) try_again = input('Wanna play again? ').upper() if try_again == 'Y': compare() compare() unboundLocalError at line 24 2 Answers Ryan S27,269 Points Hi Tarun, An UnboundLocalError in Python gets raised when you try to use a variable that hasn't been assigned a value. This is happening in your code because you are trying to convert a user input to an int and assign it to a variable all in one statement (in your try block). Let's say you enter a non-numeric string. It will throw a value error like you'd expect because it can't be converted to an int. But the input value won't actually get assigned to "user_choice", because the error will be raised before that can happen. Now when you get to your except block, you are trying to use "user_choice" in your string, but it has no value assigned to it yet, which gives you your UnboundLocalError. To fix this, you can separate the try block into two steps. The first step would be get an input and assign it to "user_choice", then in the second step, try to convert it to an int. Or another option is to just remove the reference to "user_choice" in your string in the except block. Hope this helps. Krishna Pratap Chouhan15,187 Points Krishna Pratap Chouhan15,187 Points If indentation is fine then i would say the line 24 has a function. win_msg() is not shared. Could you please share it as well.
https://teamtreehouse.com/community/except-not-working-as-it-should
CC-MAIN-2020-29
refinedweb
365
74.39
Flash Remoting checklist for JRun 4 users When setting up or troubleshooting a project that uses Flash Remoting with JRun, be sure to double-check that you have performed the tasks outlined in this TechNote. Verify ALL necessary items are successfully installed for both server-side and client-side functionality Note: Client-side refers to the software needed when developing your project. If you are not authoring the project, the client-side installations are not required. Flash Remoting Development Requirements - Macromedia JRun 4 must be installed and runningincluding the Flash Remoting gateway. Installing JRun provides instructions on the installation process for JRun 4.0. - Macromedia Flash MX must be installed if you are going to develop the user interface (UI). Flash MX provides the authoring environment needed to build the front-end of the application. Visit the Macromedia Flash Support Center Installation page if you are encountering installation issues. - Macromedia Flash Remoting Components must be installed if you are going to develop the code for the application. Components are a set of client-side ActionScript code snippets which allow Macromedia Flash MX to interact with the server-side gateway. To install the components, you must first install Macromedia Flash MX on the system. Verify that Macromedia Flash MX was successfully installed BEFORE attempting to install the Flash Remoting Components. Note: When you run the setup file "FlashRemotingCmpntsInstall.exe", the installer doesn't prompt you for a serial number. It simply installs the componentswhich may then be used within Macromedia Flash MX. Follow these steps to verify that the installations listed above were successful: - Macromedia JRun 4.0 (server) must be running. The easiest way to test this is to make a request to the gateway::{JRunPort}/flashservices/gateway Replace the {JRunPort} in the path above with the actual port of your JRun instance that you want to test. If the page is blank, then the gateway is running and working properly. If you receive an error, then ask yourself the following questions: - Is the server and/or services running? - Are you connecting to the correct server/instance? Double-check the port number. - Does the flashgateway.ear file exist in the {Server.RootDir}\lib folder? - Do you see the following line display in the command window when starting the server, (or in the {ServerName}-out.log?): 05/19 18:23:46 info Deploying web application "Flash Remoting" from: file:/D:/dev/JRun4/lib/flashgateway.ear Note: The {ServerName}-out.log file only exists on Windows, AND only appears if it is activated in the registry. - If the request doesn't work on a server you created, then test the Samples server. - Macromedia Flash MX (client) is used to develop a Flash user interface (UI). To check if Macromedia Flash MX is successfully installed, choose: Start > Programs > Macromedia > Macromedia Flash MX Note: Macromedia Flash MX is only required if you are developing Flash UI's. If you are only deploying existing Flash applications (SWF files), you do not need to install the authoring software. - Macromedia Flash Remoting Components (client)is used to develop Flash UI's that connect to the Flash Remoting Gateway. The components include pre-written ActionScripts and a NetConnection Debugger utility. The ActionScript items include: - NetServices.as Used to connect to the Flash Remoting gateway - NetDebug.as Used to enable debugging, without it NetConnection Debugger will not work - DataGlue.as Used to format data - RecordSet.as Used to return a recordset How to verify Flash Remoting Components are installed Choose from either of the following two methods listed below: - Navigate through your system to locate the: {Flash MX install}\Configuration\Include folder. If the "Include" folder exists, then the Macromedia Flash Remoting Components are installed. OR - Launch Macromedia Flash MX. Select Window in the Menu bar, (or press ALT+W). If you see "NetConnection Debugger" listed in the Window menu, then the Macromedia Flash Remoting Components have been successfully installed. Using the NetConnection Debugger (within Macromedia Flash MX) Method one - Select Window > NetConnection Debugger, (or press ALT+W). - Run the movie by selecting File > Publish Preview > Flash. - After the movie runs, select Window > MyMovie.fla. This will bring the NetConnection Debugger in focus. Note: When using this method, you need to close the MyMovie.swf file each time. Otherwise, the movie will not update the NetConnection Debugger. Method two - Select Window > NetConnection Debugger, (or press ALT+W). - Run the movie by pressing CTRL + ENTER. - While the movie runs, the NetConnection Debugger will show the progress of the Flash Remoting calls. Note: You do not need to close the MyMovie.swf file each time when using this method. Troubleshooting issues Investigate the following only AFTER confirming that everything is installed correctly. Is the NetConnection Debugger (within Macromedia Flash MX) not working? - Make sure that you include the NetDebug.as class in the ActionScript in Macromedia Flash: #include "NetDebug.as" - If you use method one (listed above) to access the NetConnection Debugger, make sure to close the SWF file each time you want to use NetConnection Debugger, then run the movie Publish Preview again. Is the Flash movie (within Macromedia Flash MX) not connecting? - It is recommended that you include the NetServices.as class in the first frame of the movie, and the connection to the gateway in the same frame. If you have chosen not to put them in the first frame, then make sure they are defined before you use the connection in your movie. To check this, do the following: - Select Window > Actions (or press F9). - From the pop-up menu, select "Actions for frame 1 of Layer Name Layer 1". "Layer 1" will be the name of your layer. - Make sure that the code connecting your movie to Flash Remoting is in this frame, (or defined before using it). - Make sure to include the NetServices.as class file, again in the first frame: #include "NetServices.as" - The actual connection ActionScript should look like the following: #include "NetServices.as" #include "NetDebug.as" #include "DataGlue.as" if (inited != true) { inited = true; NetServices.setDefaultGatewayUrl(""); gatewayConnection = NetServices.createGatewayConnection(); MyService = gatewayConnection.getService("package.JavaBean", this); } Error messages that may occur in the NetConnection Debugger when using Flash Remoting:
http://www.adobe.com/support/flash_remoting/ts/documents/jrun-fr-checklist.htm
crawl-002
refinedweb
1,026
58.99
This is an implementation of: BluePrintSynchronisation Evaluators guide Current Status - All webservices are implemented. They can be consumed using JSON and JSON-RPC. - Daemon which automates synchronization is functional though its status can not be confirmed without testing Zeroconf with it. ToDo - Daemon as cronjob is not initialized automatically: - Zeroconf doesn't seems to be very promising. Extensive testing should be done. - Automatic Synchronization is limited to SahanaPy. SahanaPHP port should be implemented. Evaluation Guide - Install python 2.5 or 2.6 (2.6 passes all json-rpc tests, whilst 2.5 fails a couple) - Install json-rpc from - Install Bazaar bzr branch lp:~mdipierro/web2py/devel web2py cd web2py/applications bzr branch lp:~hasanatkazmi/sahana/p2psync cd p2psync/cron - start web2py 8 start daemonX: python daemonX.py - Replicate same procedure on another machine - Synchronization module should list other server in Administration | Synchronisation | Sync Partners. After sometime, synchronization history should list sync activity. Logs are also maintained in {{cron/synclogs}}}. WEB SERVICES API This API is used by daemonX which drives the automatic p2p syncing between clients Supported web services - JSON - JSON-RPC ToDo (partial work has been done) - XML - XML-RPC Service Proxy JSON: e.g.......... JSON-RPC:'s-ip:port/sahana/admin/call/jsonrpc replace json and jsonrpc with xml and xmlrpc respectively for xml Available functions putdata(uuid, username, password, nicedbdump) This function is used to insert data in the system. args: uuid (required): uuid of the machine which is calling, uuid of machine is 16 character unique string. In the case when web services client is also a Sahana instance, uuid will be generated and stored by deamonX. Username, password (required): Used for authentication purposes. Both are strings. A user must be registered at the host machine with data alteration privileges. e.g. Administrator of the system can put data in the system. nicedbdump (required): nicedbdump can be best illustrated using diagrammatically representation. If [] represents a python list then: nicedump = [ each element of this list is another list representing a database table table name, [ comma separated table attributes as string] [ each element in this list is a list which represents a row in table [comma separated row values] [] .. .. ] ] [] [] .. .. .. ] Note that if you pass a table using nicedbdump which is not present in database, it will be simply ignored. If nicedbdump is not formated properly then an error string will be returned. Following situations will raise an error: If nicedbdump is not a list. If nicedbdump is not list of lists. Each list in nicedbdump represents a table, say n: If n does not exactly has 3 elements. If first of these three elements is not a string data type. If second of these three elements, say s, is not a list: if s in this list is not a string If third of these three elements, say t, is not a list: if each element in t is not a list, let such an element be r: if number of elements in r is not equal to number of elements in s If a table (s in the case described above) is not having 'id', 'uuid' and 'modified_on' as attribute. 'id' is unique id for each row in table. This 'uuid' is different from the 'uuid' which daemonX maintains, this is row uuid. 'modified_on' represents the last time data was modified (or created it not altered after creation) Note that only that data (referenced by row uuid) which has never life then the one in database will be added. In case of absence of that uuid in database, that data is be added. return: If user is authenticated and nicedbdump is successfully parsed, data will be added to the database and True will be returned. On the other hand, in case of error, error message will be returned as String. getdata(uuid, username, password, timestamp = None) returns data as nicedbdump defined in putdata. Data after timestamp time will returned, if None is passes as timestamp, then that data which has been added to the system after last getdata call from uuid will be returned. Args: uuid (required): uuid of the machine which is calling, uuid of machine is 16 character unique string. In the case when web services client is also a Sahana instance, uuid will be generated and stored by deamonX. username, password (required except for local machine): Both are strings. used for authentication, user must have privileges for reading the database. If service is called from local machine (i.e. with IP 127.0.0.1) username and password are ignored and user is given access. e.g. deamonX accesses this function locally without providing username and password. Timestamp (optional): timestamp is of string type. It should be like “YYYY-MM-DD HH:MM:SS”. If timestamp = null is passes, system will automatically return data after last getdata operation between uuid and machine. deamonX uses this setting return: In case of error (like failure to authenticate), error message as string will be returned. If successful, then nicedbdump will be returned which is described above. Example code Note: This example is in Python, but you can write a client in any language of your choice. from jsonrpc import ServiceProxy, JSONRPCException #jsonrpc needs simplejson which we have to install first s = ServiceProxy("") try: nicedbdump = s.getdata("machinename12345","email@lums.edu.pk", "myPassword") if type(result) == str: #it means there is an error, now result has error messege pass else: #result is list type for sure, #result is nicedbdump type putit = s.putdata("machinename12345", "email@lums.edu.pk", "myPassword", nicedbdump) if putit == True: #data sucessfully sent, parsed and processes at server (but in this case no data will be added because you just queried data and sent it back) pass else: #its an error pass except JSONRPCException, e: print repr(e.error) Choosing ZeroConf for Network discovery Automatic synchronization between servers require automatic service discovery. We had two major options to choose from: - ZeroConf - Mesh4x ZeroConf & Mesh4x solve different problems. They don't overlap in functionality at all: - ZeroConf provides a solution to automatic discovery. - Mesh4x provides a solution to the data sync. We were more interested in Zeroconf because: - ZeroConf has Python library but Mesh4x doesn't. I means double work was required if we go with Mesh4x. - We just needed automatic discovery of service because we wanted to use web services, so that foreign developers can also use Restful API - Mesh4x required java daemon, which meant adding jre in the package which would double Sahana package size. daemonX: Daemon which runs automatic synchronization We created a daemon which calls web services listed above. DaemonX uses ZeroConf libraries available at Note that ZeroConf is not being maintained after Dec 2006. daemonX also requires installing jsonrpc libraries from for processing JSON. Very initial tests of daemonX using Zeroconf are below expectations. Using a GPRS moderm as network source, Zeroconf library has thrown errors. More testing needs to be done before making any final statement.
https://eden.sahanafoundation.org/wiki/SynchronisationImplementation?version=3
CC-MAIN-2022-27
refinedweb
1,157
55.34
Python is created by Guido van Rossum in 1991 and developed by Python Software Foundation. It was primarily enhanced for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. So, nowadays, Python can be programmed in many applications such as: - Web development: Web framework Django, Flask. - Machine Learning - Data Analysis - Scripting - Game development - Embedded applications - Desktop applications Therefore, Utilizing Python will always cope with many common problems, and some tricks. In this article, we will discuss about some problems that we need to know. Table of contents - Merge two tuples into dictionary - Check list is null - Swap values of two variables - Get input from command line - Working with modules - Wrapping up Merge two tuples into dictionary We can use the following way: keys = ('name', 'age', 'food') values = ('Bill Gate', '60', 'Hamburger') map = dict(zip(keys, values)) or t = ((1, 'a'), (2, 'b')) map = dict((y, x) for x, y in t) # OR map = dict(map(reversed, t)) Check list is null if not a: print('List is empty.\n') # OR if len(a) == 0: print('List is empty.\n') # OR if a == []: print('List is empty.\n') Swap values of two variables a, b = b, a Get input from command line name = raw_input('What is your name?') number = int(raw_input('Number of children: ')) The variable that recieve data from raw_input() method has string data type. So, we need to convert it to use it. Loops in Python forloop for x in range(0, 3): print("The value of x is: " + x) # OR for x in range(1, 10): for y in range(1, 10): print('%d * %d = ' %(x, y, x * y)) whileloop x = 1 while True: if x > 10: break x += 1 Loop with indexes presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Jackson"] for i in range(len(presidents)): print("President {}: {}".format(i + 1, presidents[i])) # OR using enumerate for num, name in enumerate(presidents, start = 1): print("President {}: {}".format(num, name)) The enumeratefunction creates an iterable where each element is a tuple that contains the index of the item and the original item value. The start = 1option to enumerateis optional. By default, it will start counting at 0. This function will solve the task of: - Accessing each item in a list (or another iterable). - Getting the index of each item accessed. Loop over multiple lists at the same time –> Use zip colors = ["red", "green", "blue", "purple"] ratios = [0.2, 0.3, 0.1, 0.4] for color, ratio in zip(colors, ratios): print("{}% {}".format(ratio * 100, color)) Note about range and xrange: - In Python 2.x, we can use both rangeand xrange. But in Python 3, we only use range. - In Python 2.x, range()returns a list of numbers –> So, rangereturn a listobject. To Python 3, rangereturns a range object. xrange()returns the generator object that can be used to display numbers only by looping. Only particular range is displayed on demand and hence called lazy evaluation–> So, xrangereturns xrangeobject. xrangeuse less memory, and should the for loop exit early, there’s no need to waste time creating the unused numbers. This effect is tiny in smaller lists, but increases rapidly in larger lists. –> range is faster if iterating over the same sequence multiple times. –> xrange has to reconstruct the integer object every time, but range will have real integer objects. Convert dynamic Python object to JSON json.dumps(data, default = lambda o: o.__dict__) Reversing string str = 'abc' str = str[::-1] Get common element in two sets s1= {4, 5, 7, 6} s2 = {1, 2, 4, 5, 6} s_common = s1.intersection(s2) Get the differences between two sets s1= {4, 5, 7, 6} s2 = {1, 2, 4, 5, 6} s_differ = s1.difference(s2) Get distinct combined set of two sets s1= {4, 5, 7, 6} s2 = {1, 2, 4, 5, 6} s_union = s1.union(s2) Pass unknown arguments def func(*args): return first_arg func(first_arg) func(first_arg, second_arg) func(first_arg, second_arg, third_arg) Working with modules All information in this section is referred from this link. #") Whenever the Python interpreter reads a source file, it does two things: - It sets a few special variables like __name__, and then - It executes all of the code found in this file. modules - In prints the string before import(without quotes). It loads the mathmodule and assigns it to a variable called math. This is equivalent to replacing import mathwith the following (note that __import defblock, creating another function object, then assigning that function object - If your module is not the main program but was imported by another one, then __name__will be “foo”, not __main__, and it’ll skip the body of the if statement. Always - It will print the string after __name__ guardin both situations. Wrapping up Refer:
https://ducmanhphan.github.io/2019-05-28-Common-problems-in-python/
CC-MAIN-2021-25
refinedweb
794
62.88
mono-shlib-cop (1) - Linux Man Pages mono-shlib-cop: Shared Library Usage Checker NAMEmono-shlib-cop - Shared Library Usage Checker SYNOPSISmono-shlib-cop [OPTIONS]* [ASSEMBLY-FILE-NAME]* OPTIONS - -p, --prefixes=PREFIX - Mono installation prefixes. This is to find $prefix/etc/mono/config. The default is based upon the location of mscorlib.dll, and is normally correct. DESCRIPTIONmono-shlib-cop is a tool that inspects a managed assembly looking for erroneous or suspecious usage of shared libraries. The tool takes one or more assembly filenames, and inspects each assembly specified. The errors checked for include: - * - Does the shared library exist? - * - Does the requested symbol exist within the shared library? The warnings checked for include: - * - Is the target shared library a versioned library? (Relevant only on Unix systems, not Mac OS X or Windows.) In general, only versioned libraries such as libc.so.6 are present on the user's machine, and efforts to load libc.so will result in a System.DllNotFoundException. There are three solutions to this: - 1. - Require that the user install any -devel packages which provide the unversioned library. This usually requires that the user install a large number of additional packages, complicating the installation process. - 2. - Use a fully versioned name in your DllImport statements. This requires editing your source code and recompiling whenever you need to target a different version of the shared library. - 3. - Provide an assembly.config file which contains <dllmap/> elements to remap the shared library name used by your assembly to the actual versioned shared library present on the users system. Mono provides a number of pre-existing <dllmap/> entries, including ones for libc.so and libX11.so. EXAMPLEThe following code contains examples of the above errors and warnings: using System.Runtime.InteropServices; // for DllImport class Demo { [DllImport ("bad-library-name")] private static extern void BadLibraryName (); [DllImport ("libc.so")] private static extern void BadSymbolName (); [DllImport ("libcap.so")] private static extern int cap_clear (IntPtr cap_p); } - Bad library name - Assuming that the library bad-library-name doesn't exist on your machine, Demo.BadLibraryName will generate an error, as it requires a shared library which cannot be loaded. This may be ignorable; see BUGS - Bad symbol name - Demo.BadSymbolName will generate an error, as libc.so (remapped to libc.so.6 by mono's $prefix/etc/mono/config file) doesn't contain the function BadSymbolName - Unversioned library dependency - Assuming you have the file libcap.so , Demo.cap_clear will generate a warning because, while libcap.so could be loaded, libcap.so might not exist on the users machine (on FC2, /lib/libcap.so is provided by libcap-devel , and you can't assume that end users will have any -devel packages installed). FIXING CODEThe fix depends on the warning or error: - Bad library names - Use a valid library name in the DllImport attribute, or provide a <dllmap/> entry to map your existing library name to a valid library name. - Bad symbol names - Reference a symbol that actually exists in the target library. - Unversioned library dependency - Provide a <dllmap/> entry to reference a properly versioned library, or ignore the warning (see BUGS ). DLLMAP ENTRIESMono looks for an ASSEMBLY-NAME .config file for each assembly loaded, and reads this file to find Dll mapping information. For example, with mcs.exe , Mono would read mcs.exe.config , and for Mono.Posix.dll , Mono would read Mono.Posix.dll.config . The .config file is an XML document containing a top-level <configuration/> section with nested <dllmap/> entries, which contains dll and target attributes. The dll attribute should contain the same string used in your DllImport attribute value, and the target attribute specifies which shared library mono should actually load at runtime. A sample .config file is: <configuration> <dllmap dll="gtkembedmoz" target="libgtkembedmoz.so" /> </configuration> BUGS - * - Only DllImport entries are checked; the surrounding IL is ignored. Consequently, if a runtime check is performed to choose which shared library to invoke, an error will be reported even though the specified library is never used. Consider this code: using System.Runtime.InteropServices; // for DllImport class Beep { [DllImport ("kernel32.dll")] private static extern int Beep (int dwFreq, int dwDuration); [DllImport ("libcurses.so")] private static extern int beep (); public static void Beep () { if (System.IO.Path.DirectorySeparatorChar == '\\') { Beep (750, 300); } else { beep (); } } }If mono-shlib-cop is run on this assembly, an error will be reported for using kernel32.dll , even though kernel32.dll will never be used on Unix platforms. - * - mono-shlib-cop currently only examines the shared library file extension to determine if a warning should be generated. A .so extension will always generate a warning, even if the .so is not a symlink, isn't provided in a -devel package, and there is no versioned shared library (possible examples including /usr/lib/libtcl8.4.so, /usr/lib/libubsec.so, etc.). Consequently, warnings for any such libraries are useless, and incorrect. Windows and Mac OS X will never generate warnings, as these platforms use different shared library extensions. MAILING LISTSVisit for details. WEB SITEVisit for details Linux man pages generated by: SysTutorials
https://www.systutorials.com/docs/linux/man/docs/linux/man/1-mono-shlib-cop/
CC-MAIN-2020-29
refinedweb
841
50.84
Vispy-based viewers for Glue Project description Requirements Note that this plugin requires Glue and PyOpenGL to be installed - see this page for instructions on installing Glue. PyOpenGL should get installed automatically when you install the plugin (see below). While this plugin uses VisPy, for now we bundle our own version of VisPy since we rely on some recently added features, so you do not need to install VisPy separately. Installing If you use the Anaconda Python Distribution, you can install this plugin with: conda install -c glueviz glue-vispy-viewers To install the latest stable version of the plugin, you can do: pip install glue-vispy-viewers or you can install the latest developer version from the git repository using: pip install git+ This will auto-register the plugin with Glue. Now simply start up Glue, open a data cube, drag it onto the main canvas, then select ‘3D viewer’. Testing To run the tests, do: py.test glue_vispy_viewers at the root of the repository. This requires the pytest module to be installed. Using the isosurface viewer The isosurface viewer is currently still unstable - to enable it, put the following in a file called config.py file in your current working directory: from glue_vispy_viewers.isosurface import setup as setup_isosurface setup_isosurface() Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/glue-vispy-viewers/
CC-MAIN-2022-27
refinedweb
240
51.99
UFDC Home | Help | RSS Group Title: Economic information report Title: North Florida wheat basis, 1982-1989 CITATION THUMBNAILS PAGE IMAGE ZOOMABLE Full Citation STANDARD VIEW MARC VIEW Permanent Link: Material Information Title: North Florida wheat basis, 1982-1989 Series Title: Economic information report Physical Description: iii, 18 p. : ill. ; 28 cm. Language: English Creator: Blythe, Beth PrideFord, S. A ( Stephen Allyn )Hewitt, Tim Publisher: Food & Resource Economics Dept., Agricultural Experiment Stations, Institute of Food and Agricultural Sciences, University of FloridaFood & Resource Economics Dept., Agricultural Experiment Stations and Cooperative Extension Service, Institute of Food and Agricultural Sciences, University of Florida Place of Publication: Gainesville Publication Date: 1990 Copyright Date: 1990 Subjects Subject: Wheat -- Marketing -- Florida ( lcsh )Wheat -- Prices -- Florida ( lcsh ) Genre: government publication (state, provincial, terriorial, dependent) ( marcgt )non-fiction ( marcgt ) Notes Statement of Responsibility: Beth Pride Blythe, Steve Ford, Tim Hewitt. General Note: Cover title. General Note: "December 1990." Record Information Bibliographic ID: UF00026489 Volume ID: VID00001 Source Institution: University of Florida Holding Location: University of Florida Rights Management: All rights reserved by the source institution and holding location. Resource Identifier: notis - AHL3274alephbibnum - 001589302oclc - 23111381731 seth Pride Blythe Economic Information "Steve Ford Report 282 Tim Hewitt North Florida Wheat Basis, 1982-1989 i,,ra i7 I. r Food & Resource Economics Department Agricultural Experiment Stations and Cooperative Extension Service Institute of Food and Agricultural Sciences December 1990 University of Florida, Gainesville 32611 North Florida Wheat Basis 1982-1989 Beth Pride Blythe, Steve Ford, and Tim Hewitt' Abstract The wise use of futures markets for risk management purposes requires information about local commodity basis. Historical data and summary analysis is provided for wheat basis in Campbellton, Florida. A brief description of the components and use of basis is provided with graphical analysis. key words: wheat, basis, futures market, hedging "Graduate Research Assistant and Assistant Professor, Food and Resource Economics Department, University of Florida, Gainesville, and Associate Professor, North Florida Research and Education Center, Marianna. I TABLE OF CONTENTS Abstract List of Tables and Graphs iii Introduction 1 Basis Terminology 1 Factors Affecting Basis 2 Using Basis 3 Basis Tables and Graphs 5 Summary 7 References 8 Tables and Graphs 9-18 ii LIST OF TABLES AND GRAPHS Table 1 Harvest Contract Basis 9 Table 1 Harvest Contract Basis 9 Table 2 Current Contract Basis 10 Figure 1 Cash Prices 11 Figure 2 Harvest Contract Basis 12 Figure 3 Current Contract Basis 13 Figure 4 Average Basis Calculation Harvest Contracts 14 Figure 5 Average Basis Calculation Current Contracts 15 Figure 6 Harvest Contract Average 16 Figure 7 Current Contract Average 17 Figure 8 Price and Basis Variability 18 iii INTRODUCTION Wheat producers are constantly faced with production and market risks. Various strategies can be used to minimize these risks. Market or price risk can be effectively managed with a marketing plan that includes the use of futures markets through hedging or using options. The use of futures markets allows producers to minimize downside cash price risk by establishing a price floor or a price range. The determination of the final price producers receive using such marketing strategies is affected by deviations in the expected difference between local cash prices and futures contract prices at marketing. This difference is called the basis. This publication defines basis and discusses terms frequently associated with basis analysis. Several of the factors which affect basis are also discussed. A brief section is included on understanding the importance of basis in hedging. The remainder of the publication contains wheat basis tables and graphs calculated for Campbellton, a major sales point for commodities grown in North Florida. These graphs and tables provide information about historical wheat basis and its behavior over time. BASIS TERMINOLOGY Basis is calculated by subtracting the price of a futures contract from the commodity cash price at a particular point in time. For example, if July wheat contracts are trading for $3.40, and the local cash market for wheat in June is $3.20 per bushel, the basis is 20 cents under the July futures price ($3.20 $3.40 = -$0.20). Basis is always determined for a particular market location since cash prices differ from market to market. Basis may be calculated as a current basis or a harvest basis. Current basis is found using the nearby or current futures contract month. Harvest basis is calculated using the contract which expires 1 near the harvest month. For wheat, the harvest month contract is typically the July contract. The current basis and the harvest basis are the same during the harvest season. There are several characteristics to consider when analyzing basis. A basis is said to be under if the cash price is lower than the futures price and over if the cash price is higher than the futures price. If the basis becomes more positive over time, the basis is strenathenina. Conversely, a basis that becomes more negative over time is weakening. Basis also narrows and widens. A basis narrows as cash and futures prices converge. A narrowing basis typically occurs near harvest when cash prices are peaking and futures prices reflect only transportation costs. Basis usually widens after harvest, as cash prices fall and futures prices rise to reflect storage and interest costs. FACTORS AFFECTING BASIS The following economic factors typically affect basis. Transportation Costs. The basis reflects costs of moving a commodity from a production point to a futures delivery point. For example, if the cost to move wheat from Florida to Chicago, the delivery point for futures contracts, is 40 cents per bushel, then the wheat price in Chicago should be at least 40 cents higher than prices in Florida. If not, wheat will not be transported to the Chicago market. The shorter the distance between markets, the narrower the basis will be. Storage Costs. Monthly storage costs accumulate during the crop year. The further away the delivery month, the higher the carrying charges will be to reflect storage costs until that time. As a futures delivery month approaches, carrying charges will decline until the basis reflects mainly transportation costs. 2 Interest Costs. Interest costs are incurred with stored commodities since either borrowed or equity capital is committed to the investment. The longer commodities are stored, the longer cash returns are delayed, causing the interest portion of the basis to be greater the further away from the futures contract maturity. Local Market Conditions. Supply and demand determinants in local cash markets may differ from those in the national market. A commodity may command a premium over the futures price or be discounted relative to the futures price because of local commodity surpluses or deficits. Local supply and demand for a commodity should be considered when localizing or adjusting futures prices for basis. Seasonal local supply and demand conditions are particularly important to consider. Additional factors affecting the basis may include: variations between the cash commodity quality and the contract grade specifications; supply, demand, and prices for substitute commodities; and future price expectations. Storage costs and transportation costs are generally considered the principle factors affecting basis. USING BASIS An understanding of basis is necessary to determine the expected local effective price when using futures markets to manage market risk. The basis is used to translate a futures price to the approximate selling price established by a market strategy. The following example illustrates how the basis is used to determine the expected final market price established by hedging in the futures market. 3 Example Cash Market Futures Market Basis January 31 sell July contract expected price: July futures price: expected basis: $3.40/bu $3.60/bu $0.20 under ($3.60 $0.20) July 1 buy July contract sell wheat: July futures price: actual basis: $3.00/bu $3.25/bu $0.25 under ($3.00- $3.25) Hedging Summary 1 expected market price $3.40/bushel change in basis ($0.20 $0.25) -$0.05 net return $3.35/bushel Hedging Summary 2 cash price received $3.00/bushel gain/loss in futures ($3.60 $3.25) $0.35 net return $3.35/bushel The hedge allows the producer to establish a range of expected market prices, dependent only upon the difference between the expected basis and the actual basis at harvest. If the basis remains constant, the final price received equals the initial expected market price of $3.40/bushel. Any basis movement from the original expected basis is added to or subtracted from the expected market price to determine the net return (Hedging Summary 1). The net return to the producer can also be calculated by adding the gain/loss in the futures market to the cash price received from selling wheat in the local market (Hedging Summary 2). Brokerage or handling charges must also be deducted to determine 4 net returns. In this example, brokerage charges of 2 cents per bushel would reduce the net return to $3.33 per bushel. This example illustrates how a change in basis affects the final price received by the producer. The deviation of the actual basis in July from its expected value in the previous January accounts for the market risk the wheat producer faces. However, in this example, basis movement (-$0.05) is significantly less than cash price movement (-$0.40). Relying on cash market sales alone is risky since downward cash price movements may be large and unpredictable. With hedging, price risk lies solely with basis movement and is no longer dependent on the variability in the cash market. Since basis risk is significantly smaller than cash price risk, hedging is an effective risk management tool for producers. In the example, the producer was able to set a market price subject only to the variation in basis. Note that the actual basis might have been smaller than expected as well. In that case, a positive change in basis would have been added to the expected market price, resulting in a higher expected net return. BASIS TABLES AND GRAPHS The remainder of this publication contains tables and graphs of historical wheat basis for Campbellton, Florida. There are two tables listing wheat basis for Campbellton from January 1982 through December 1989. Table 1 contains weekly and average weekly basis for July harvest contracts. Table 2 contains weekly basis and average weekly basis for current nearby futures contracts. The basis figures in each table are calculated from Tuesday futures prices from the Chicago Board of Trade as published in the Wednesday issue of The Wall Street Journal and actual prices received by farmers in Campbellton. Basis is reported in cents. Historical cash prices for the 8-year period are graphed in Figure 1. The historical 5 basis for the July harvest contract is graphed in Figure 2. Note that in Figure 2, the basis shows a fairly cyclical pattern of strengthening early in each year, then peaking right before harvest, and weakening after harvest. Strengthening occurs as cash prices rise within the crop year and peak near harvest. After harvest, cash prices fall in response to new production entering the market and the basis weakens accordingly. The current contract basis is graphed in Figure 3. The current contract basis is less variable than the harvest contract basis, as can be shown by comparing Figure 2 and Figure 3. The average basis is calculated as the difference between average cash prices and average futures contract prices in Figure 4 and Figure 5. The basis units are on the right-hand axis. The 8-year average weekly basis for harvest and current futures contracts is graphed in Figure 6 and Figure 7, respectively. One standard deviation around the average basis is included to show basis variability. In other words, 66 percent of the time the basis will fall within the range presented in the figures. The graph in Figure 6 illustrates how basis narrows as harvest approaches, reflecting only costs of transportation. The basis begins to widen after harvest as it reflects storage and interest costs for the following year. The basis then narrows at harvest as does its variability. The wheat basis shown in Figure 6 falls most often within a 20 cent range at harvest; between 25 cents and 45 cents under the futures price. The difference between basis risk and cash price risk is illustrated in Figure 8. The basis is shown in the top half of the graph and its units appear on the right-hand axis. Cash prices are shown in the bottom half of the graph, with units on the left-hand axis. Basis variability for the harvest futures contract is approximately 40 cents, narrowing to 20 cents at harvest. However, cash prices may vary as much as $1.00. 6 SUMMARY The basis is the difference between local cash prices and futures contract prices at a specific point in time. Storage and transportation costs are the primary factors affecting basis, although other economic forces may also influence basis. Basis also reflects seasonal cash price changes. This seasonality can be seen as the basis narrows around harvest and widens afterwards. Fluctuations in local cash prices are risky for producers who sell commodities in the cash market. An understanding of basis allows producers to effectively utilize marketing strategies that minimize downside cash price risk. Hedging is one tool that reduces the risk of adverse cash price movements. When a wheat producer hedges on the futures market, the final price received depends upon changes in the basis. Thus, basis becomes the bottom-line determinant of the price received by farmers when they use risk management marketing strategies in the futures market. 7 USEFUL REFERENCES ON BASIS AND COMMODITY FUTURES Chicago Board of Trade. Commodity Marketing: Hedgina. Basis. Marketing Alternatives. 1982. Chicago Board of Trade. Options On Agricultural Futures: A Home Study Course. 1984. Chicago Board of Trade. Options On Soybean Futures: Fundamentals. Pricing, and Applications. 1984. 8 Table 1 Harvest Contract Basis (cents) Campbelfton, Florida Week 1982 1983 1984 1985 1986 1987 1988 1989 Average J 1 -79.75 -55.50 -35.00 -32.75 -29.75 -7.50 -35.25 -44.75 -40.03 2 -80.50 -64.25 -35.50 -29.25 -43.75 -9.50 -35.25 -45.25 -42.91 3 -80.00 -60.25 -35.25 -29.75 -30.25 -10.25 -25.00 -46.50 -39.66 4 -78.75 60.00 -34.50 -29.75 -29.50 -10.75 -25.50 -44.75 -39.19 5 -79.75 -60.25 -34.50 -30.25 -30.25 -20.75 -30.25 -38.00 -40.50 F 6 -80.00 -55.25 -35.25 -30.75 -30.75 -17.25 -30.50 -41.25 -40.13 7 -76.50 -55.00 -35.25 -32.00 -30.25 -21.00 -31.00 -45.50 -40.81 8 -79.25 -54.50 -35.50 -30.00 -29.50 -10.50 -30.25 -45.75 -39.41 9 -79.75 -47.25 -30.25 -30.25 -30.50 -19.75 -35.50 -45.25 -39.81 M 10 -88.50 -55.25 -24.75 -30.25 -25.00 -20.50 -34.75 -51.75 -41.34 11 -78.75 -55.50 -25.25 -30.25 -25.00 -18.50 -36.25 -45.00 -39.31 12 -79.00 -48.75 -24.75 -29.75 -25.00 -19.75 -35.00 -44.75 -38.34 13 -79.75 -50.25 -25.25 -30.25 -24.25 -20.00 -34.75 -46.75 -38.91 14 -78.75 -51.75 -25.25 -30.00 -24.00 -20.25 -35.75 -41.25 -38.38 A 15 -84.50 -60.75 -25.25 -30.50 -24.25 -25.50 -35.25 -45.00 -41.38 16 -85.00 -77.25 -25.00 -30.50 -25.75 -20.25 -35.00 -44.25 -42.88 17 -70.50 -50.00 -24.75 -27.00 -25.50 -19.75 -34.50 -45.00 -37.13 18 -77.25 -50.25 -24.75 -30.00 -20.00 -19.75 -35.00 -47.50 -38.06 M 19 -74.50 -49.00 -25.50 -34.75 -4.75 -24.00 -30.25 -32.00 -34.34 20 -80.25 -45.25 -25.25 -24.50 -4.50 -22.50 -29.75 -26.75 -32.34 21 -64.25 -40.00 -19.75 -35.00 -19.50 -21.75 -35.50 -36.00 -33.97 -69,75 -55.50 -41.25 -18.50 -6.75 -54.50 -27.00 -11.50 -35.59 31 -69.50 -45.50 -40.50 -14.75 -36.00 -47.50 -37.00 -26.75 -39.69 A 32 -69.75 -52.00 -39.50 -23.00 -21.75 -53.00 -36.50 -20.00 -39.44 33 -70.25 -57.50 -39.75 -27.00 -17.25 -48.00 -50.50 -23.75 -41.75 34 -70.25 -66.75 -40.25 -30.00 -31.50 -46.50 -40.50 -28.75 -44.31 35 -70.00 -78.50 -40.00 -32.00 -31.50 -37.50 -19.00 -26.00 -41.81 S 36 -70.25 -70.00 -40.00 -35.00 -30.50 -36.50 -50.25 -21.50 -44.25 37 -54.50 -79.50 -39.75 -38.00 -20.25 -39.75 -54.00 -44.75 -46.31 38 -70.00 -44.50 -40.00 -34.75 -20.25 -34.50 -56.00 -43.75 -42.97 39 -69.25 -58.75 -39.75 -29.50 -18.50 -39.75 -51.50 -48.50 -44.44 0 40 -70.00 -62.00 -40.25 -29.50 -20.75 -42.50 -50.00 -52.75 -45.97 41 -67.50 -50.50 -40.50 -30.00 -19.75 -42.00 -50.00 -45.00 -43.16 42 -68.25 -40.50 -39.75 -29.75 -19.75 -49.50 -39.50 -44.25 -41.41 43 -60.00 -40.25 -40.25 -31.50 -20.00 -48.00 -39.25 -47.25 -40.81 44 -65.50 -40.00 -40.25 -29.00 -20.00 -30,00 -40.50 -45.50 -38.84 N 45 -58.25 -39.75 -35.00 -30.00 -18.00 -38.25 -37.75 -47.25 .38.03 46 -60.00 -40.00 -27.25 -30.00 -19.75 -38.00 -35.00 -44.25 -36.78 47 -58.00 -39.75 -30.25 -29.75 -9.75 -34.75 -34.75 -34.50 -33.94 48 -60.00 -40.25 -29.75 -30.00 -9.75 -33.75 -35.25 -37.00 -34.47 D 49 -60.00 -30.25 -29.75 -30.50 -9.75 -35.25 -34.75 -36.00 -33.28 50 -54.00 -35.25 -29.75 -29.50 -8.00 -30.75 -39.75 -36.50 -32.94 51 -62.50 -34.75 -30.25 -30.00 -6.75 -29.00 -43.25 -36.25 -34.09 52 -59.25 -35.25 -30.50 -29.25 -11.50 -35.25 -45.00 -33.00 -34.88 53* -26.50 * Extra Tuesdays in these years. 9 Table 2 Current Contract Basis (cents) Campbelton, Florida Week 1982 1983 1984 1985 1986 1987 1988 1989 Average J 1 -66.00 -42.00 -49.00 -45.25 -83.25 -36.25 -46.00 -88.25 -57.00 2 -67.50 -51.50 -52.25 -40.50 -97.50 -44.25 -45.00 -94.75 -1.66 3 -64.75 -47.25 -48.00 -48.75 -80.75 -45.00 -34.25 -84.75 -56.69 4 -58.50 -40.75 -38.75 -45.50 -86.25 -47.00 -37.00 -78.75 -54.06 5 -55.50 -45.25 -30.75 -46.00 -86.25 -55.25 -41.75 -67.25 -53.50 F 6 -54.50 -40.75 -38.00 -49.75 -95.75 -45.25 -36.00 -62.25 -52.78 7 -52.25 -85.25 -35.25 -50.50 -107.00 -48.75 -29.00 -61.50 -58.69 8 -54.75 -32.00 -42.00 -45.75 -110.25 -29.50 -18.50 -71.00 -50.47 9 -61.75 -22.75 -31.75 -50.50 -117.25 -47.75 -23.00 -75.25 -53.75 M 10 -71.50 -32.00 -31.50 -51.25 -116.00 -52.75 -20.75 -76.00 -56.47 11 -60.00 -34.75 -33.25 -49.25 -124.00 -51.75 -23.00 -59.50 -54.44 12 -72.25 -31.00 -37.75 -60.00 -86.75 -40.25 -20.00 -59.00 -50.88 13 -73.50 -40.00 -40.50 -50.75 -76.75 -35.50 -28.00 -69.75 -51.84 14 -70.75 -43.25 -43.75 -52.00 -64.50 -35.75 -25.50 -51.25 -48.34 A 15 -72.50 -50.00 -40.25 -59.75 -61.25 -41.75 -26.25 -57.00 -51.09 16 -73.50 -66.00 -43.25 -59.75 -54.25 -30.50 -26.25 -52.00 -50.69 17 -56.75 -37.50 -37.25 -43.50 -60.00 -34.50 -25.00 -55.50 -43.75 18 -60.50 -43.00 -38.25 -52.00 -74.50 -32.00 -24.75 -61.50 -48.31 M 19 -59.50 -40.50 -49.00 -49.25 -62.00 -38.50 -20.50 -44.00 -45.41 20 -68.00 -37.00 -42.00 -45.25 -104.00 -28.50 -22.00 -35.50 -47.78 21 -64.25 -40.00 -19.75 -39.75 -17.50 -21.75 -35.50 -36.00 -34.31 -24.25 -41.75 -30.75 -40.00 -31.50 -46.25 -51.75 -43.25 -38.69 31 -21.25 -42.00 -25.25 -39.50 -57.50 -40.00 -60.50 -55.75 -42.72 A 32 -22.75 -42.50 -23.25 -40.50 -38.25 -39.75 -65.25 -49.50 -40.22 33 -24.25 -41.50 -26.25 -40.25 -35.75 -38.75 -84.50 -53.25 -43.06 34 -27.25 -41.75 -31.00 -38.25 -40.25 -39.50 -80.00 -50.50 -43.56 35 -19.00 -42.00 -34.25 -38.00 -46.50 -42.00 -51.50 -46.50 -39.97 S 36 -22.75 -41.50 -37.50 -40.75 -46.25 -40.25 -85.50 -45.25 -44.97 "37 -2.00 -41.50 -42.50 -38.00 -51,00 -39.50 -90.00 -50.50 -44.38 38 -18.50 -14.00 -41.25 -34.00 -48.25 -51.75 -89.50 -37.75 -41.88 39 -38.25 -36.00 -50.75 -46.25 -48,25 -56.00 -102.75 -46.75 -53.13 0 40 -37.25 -49.50 -48.50 -43.50 -48.75 -53.25 -109.50 -56.25 -55.81 41 -36.25 -47.50 -48.00 -47.50 -57.00 -5700 -112.25 -55.25 -57.59 42 -35.00 -42.50 -47.25 -49.50 -63.75 -55.75 -91.00 -35.25 -52.50 43 -33.50 -46.25 -55.75 -61.25 -64.50 -53.75 -80.50 -26.75 -52.78 44 -49.25 -43.25 -57.75 -56.50 -66.75 -31.25 -80.50 -49.25 -54.31 N 45 -36.25 -40.75 -53.50 -62.00 -53.50 -37.25 -83.25 -46.00 -51.56 46 -38.50 -38.75 -39.25 -9.75 -59.50 -39.25 -64.75 -25.50 -46.91 47 -37.00 -31.25 -47.75 -88.75 -25.75 -42.00 -70.00 -28.00 -46.31 48 -31.75 -37.75 -46.75 -73.50 -50.75 -38.00 -76.50 -38.50 -49.19 D 49 -29.75 -32.25 -41.75 -85.25 -42.00 -43.50 -76.00 -32.50 -47.88 50 -25.00 -36.00 -41.25 -78.50 -43.75 -40.00 -80.00 -40.00 -48.06 51 -53.25 -38.75 -46.75 -84.50 -38.75 -38.50 -84.50 -46.00 -53.88 52 -46.25 -51.75 -44.50 -78.75 -41.25 -46.00 -87.25 -41.25 -54.63 53* -82.25 Extra Tuesdays in these years. 10 FIGURE 1 CASH PRICES 1982-1989 CAMPBELLTON, FL $4.00 $3.80- $3.60- $3.40- 8 $3.20- n $3.00- r- I $2.80- $2.60- $2.40- $2.20- $2.00 82 83 84 85 86 87 88 89 Year 11 FIGURE 2 HARVEST CONTRACT BASIS 1982-1989 CAMPBELLTON, FL 0- -10- -20- -30-3 S-40- . -50" z -60- -70- -80- -90- -100- 82 83 84 85 86 87 88 89 Year 12 FIGURE 3 CURRENT CONTRACT BASIS 1982-1989 CAMPBELLTON, FL 0 -20- -40- -60- -80- -100- -120- -140 82 83 84 85 86 87 88 89 Year 13 FIGURE 4 AVERAGE BASIS CALCULATION HARVEST CONTRACTS $3.60- 5 Futures - $3.40- --5 $3.20 --15 u Cash C S $ 3 .0 0 .... ...-.. .... ...... S.......... ........ ........... ......." ........... . / . --25 u) $2.80- m -- 35 V$2.0 --45 " $2.40 -65 $2.20. --55 $ 2 .00 , , , , , , , ,, , , , , , , , , ,, ,, -6 5 J F M A M J J A S O N D Month Harvest Avg. ....--.. Avg. Price Avg. Basis 14 FIGURE 5 AVERAGE BASIS CALCULATION CURRENT CONTRACTS $3.60- 5 $3.40 Futur--5 $3.40- -----\^-&"----t-------/^V^t~-c-=------- $3.20 -15 j: u $3.00 .. \ ...... .. .............. .. .. S... ... / -25 S$2.80 a, -35 " $2.60- $2.20- --5 ,,o-----^-----V4----4 $2.00 ,, , ,, , ,, , ,, , ,, ,,, --65 J F M A M J J A S O N D Month Current Avg. -....... Avg. Price Avg. Basis 15 FIGURE 6 HARVEST CONTRACT AVERAGE 1982-1989 CAMPBELLTON, FL -10- A N *c. \\ i C."' ..40.. -750 -80 iI I I I I J F ... A M J J A 0 N D Month Average -60- .... + Std. Dev . ......- Std. Dev. 16 J F M A M J J A S O N D Month -- Average -.-......-. + Std. Dev. .-......... Std. Dev. 16 FIGURE 7 CURRENT CONTRACT AVERAGE 1982-1989 CAMPBELLTON, FL -20 A / \ -" "_ \' 3--0- * I.. .', i, /^ -50- c\ -80- -"------- F , Month -6 i ,, .. Average + Std. Dev. ----- Std. Dev. 17 \- .., ,,. J J A S -80 ,,h ',:ag "l- \ St.Dv :---- -t.D :i v '. FIGURE 8 PRICE AND BASIS VARIABILITY 1982-1989 CAMPBELLTON, FL $4.50- 0 $4.30- --20 $4.10- ...---..--------- --40 $3.90- ------"^---'>- --60 " 4-- ) $3.70- --80 "00 $3.50- --100 .- cc "$3.30- --120 S$3.10- --140 , $2.90-~ .......................................... ,'". ........ '. ............... ".--160 " $2.90- ....... .. .. ..... .. --160 I- o $2.70- --180 $2.50- ."--.....- ......__-200 -220 $2.30- 1 i i 1 1 1 1 1 1 1 1 I i i i i i1 i i I 1 1 i 1 1 -220 J F M A M J J A S O N D Month ............ Avg. Price + Std. Dev. Std. Dev. Avg. Basis + Std. Dev. Std. Dev. 18 Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2010 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Last updated October 10, 2010 - - mvs
http://ufdc.ufl.edu/UF00026489/00001
CC-MAIN-2016-36
refinedweb
4,529
66.44