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 |
|---|---|---|---|---|---|
In order to avoid the difficulties inherent in parsing raw XML input, almost all programs that need to process XML documents rely on an XML parser to actually read the document. The parser is a software library (in Java it’s a class) that reads the XML document and checks it for well-formedness. Client applications use method calls defined in the parser API to receive or request information the parser retrieves from the XML document.
The parser shields the client application from all the complex and not particularly relevant details of XML including:
Transcoding the document to Unicode
Assembling the different parts of a document divided into multiple entities.
Resolving character references
Understanding CDATA sections
Checking hundreds of well-formedness constraints
Maintaining a list of the namespaces in-scope on each element.
Validating the document against its DTD or schema
Associating unparsed entities with particular URLs and notations
Assigning types to attributes
One of the original goals of XML was that it be simple enough that a “Desperate Perl Hacker” (DPH) be able to write an XML parser. The exact interpretation of this requirement varied from person to. The middle ground was a smart grad student and a couple of weeks.
Whichever way you interpreted the requirement, it wasn’t met. In fact, it took Larry Wall more than a couple of months just to add the Unicode support to Perl that XML assumed. Java developers already had adequate Unicode support, however; and thus Java parsers were a lot faster out the gate. Nonetheless, it still probably isn’t possible to write a fully conformant XML parser in a weekend, even in Java. Fortunately, however, you don’t need to. There are several dozen XML parsers available under a variety of licenses that you can use. In 2002, there’s very little need for any programmer to write their own parser. Unless you have very unusual requirements, the chance that you can write a better parser than Sun, IBM, the Apache XML Project, and numerous others have already written is quite small.
Java 1.4 is the first version of Java to include an XML parser as a standard feature. In earlier versions of Java, you need to download a parser from the Web and install it in the usual way, typically by putting its .jar file in your jre/lib/ext directory. Even in Java 1.4, you may well want to replace the standard parser with a different one that provides additional features or is simply faster on your documents.
If you’re using Windows, then chances are good you have two different ext directories, one where you installed the JDK such as C:\jdk1.3.1\jre\lib\ext and one in your Program Files folder, probably C:\Program Files\Javasoft\jre\1.3.1\lib\ext. The first is used for compiling Java programs, the second for running them. To install a new class library you need to place the relevant JAR file in both directories. It is not sufficient to place the JAR archive in one and a shortcut in the other. You need to place full copies in each ext directory.
The most important decision you'll make at the start of an XML project is the application programming interface (API) you'll use. Many APIs are implemented by multiple vendors, so if the specific parser gives you trouble you can swap in an alternative, often without even recompiling your code. However, if you choose the wrong API, changing to a different one may well involve redesigning and rebuilding the entire application from scratch. Of course, as Fred Brooks taught us, “In most projects, the first system built is barely usable. It may be too slow, too big, awkward to use, or all three. There is no alternative but to start again, smarting but smarter, and build a redesigned version in which these problems are solved.… Hence plan to throw one away; you will, anyhow. ” [1] Still, it is much easier to change parsers than APIs.
There are two major standard APIs for processing XML documents with Java, the Simple API for XML (SAX) and the Document Object Model (DOM), each of which comes in several versions. In addition there are a host of other, somewhat idiosyncratic APIs including JDOM, dom4j, ElectricXML, and XMLPULL. Finally each specific parser generally has a native API that it exposes below the level of the standard APIs. For instance, the Xerces parser has the Xerces Native Interface (XNI). However, picking such an API limits your choice of parser, and indeed may even tie you to one particular version of the parser since parser vendors tend not to worry a great deal about maintaining native compatibility between releases. Each of these APIs has its own strengths and weaknesses.
SAX, the Simple API for XML, is the gold standard of XML APIs. It is the most complete and correct by far. Given a fully validating parser that supports all its optional features, there is very little you can’t do with it. It has one or two holes, but they're really off in the weeds of the XML specifications, and you have to look pretty hard to find them. SAX is a event driven API. The SAX classes and interfaces model the parser, the stream from which the document is read, and the client application receiving data from the parser. However, no class models the XML document itself. Instead the parser feeds content to the client application through a callback interface, much like the ones used in Swing and the AWT. This makes SAX very fast and very memory efficient (since it doesn’t have to store the entire document in memory). However, SAX programs can be harder to design and code because you normally need to develop your own data structures to hold the content from the document.
SAX works best when your processing is fairly local; that is, when all the information you need to use is close together in the document. For example, you might process one element at a time. Applications that require access to the entire document at once in order to take useful action would be better served by one of the tree-based APIs like DOM or JDOM. Finally, because SAX is so efficient, it’s the only real choice for truly huge XML documents. Of course, “truly huge” has to be defined relative to available memory. However, if the documents you're processing are in the gigabyte range, you really have no choice but to use SAX.
DOM, the Document Object Model, is a fairly complex API that models an XML document as a tree. Unlike SAX, DOM is a read-write API. It can both parse existing XML documents and create new ones. Each XML document is represented as Document object. Documents are searched, queried, and updated by invoking methods on this Document object and the objects it contains. This makes DOM much more convenient when random access to widely separated parts of the original document is required. However, it is quite memory intensive compared to SAX, and not nearly as well suited to streaming applications.
JAXP, the Java API for XML Processing, bundles SAX and DOM together along with some factory classes and the TrAX XSLT API. (TrAX is not a general purpose XML API like SAX and DOM. I'll get to it in Chapter 17.) It is a standard part of Java 1.4 and later. However, it is not really a different API. When starting a new program, you ask yourself whether you should choose SAX or DOM. You don’t ask yourself whether you should use SAX or JAXP, or DOM or JAXP. SAX and DOM are part of JAXP.
JDOM is a Java-native tree-based API that attempts to remove a lot of DOM’s ugliness. The JDOM mission statement is, “There is no compelling reason for a Java API to manipulate XML to be complex, tricky, unintuitive, or a pain in the neck,” and for the most part JDOM delivers. Like DOM, JDOM reads the entire document into memory before it begins to work on it; and the broad outline of JDOM programs tends to be the same as for DOM programs. However, the low-level code is a lot less tricky and ugly than the DOM equivalent. JDOM uses concrete classes and constructors rather than interfaces and factory methods. It uses standard Java coding conventions, methods, and classes throughout. JDOM programs often flow a lot more naturally than the equivalent DOM program.
I think JDOM often does make the easy problems easier; but in my experience JDOM also makes the hard problems harder. Its design shows a very solid understanding of Java, but the XML side of the equation feels much rougher. It’s missing some crucial pieces like a common node interface or superclass for navigation. JDOM works well (and much better than DOM) on fairly simple documents with no recursion, limited mixed content, and a well-known vocabulary. It begins to show some weakness when asked to process arbitrary XML. When I need to write programs that operate on any XML document, I tend to find DOM simpler despite its ugliness.
dom4j was forked from the JDOM project fairly early on. Like JDOM, it is a Java-native, tree-based, read-write API for processing generic XML. However, it uses interfaces and factory methods rather than concrete classes and constructors. This gives you the ability to plug in your own node classes that put XML veneers on other forms of data such as objects or database records. (In theory, you could do this with DOM interfaces too; but in practice most DOM implementations are too tightly coupled to interoperate with each other’s classes.) It does have a generic node type that can be used for navigation.
ElectricXML is yet another tree-based API for processing XML documents with Java. It’s quite small, which makes it suitable for use in applets and other storage limited environments. It’s the only API I mention here that isn’t open source, and the only one that requires its own parser rather than being able to plug into multiple different parsers. It’s gained a reputation as a particularly easy-to-use API. However, I’m afraid its perceived ease-of-use often stems from catering to developers’ misconceptions about XML. It is far and away the least correct of the tree-based APIs. For instance, it tends to throw away a lot of white space it shouldn’t; and its namespace handling is poorly designed. Ideally, an XML API should be as simple as it can be and no simpler. In particular, it should not be simpler than XML itself is. ElectricXML pretends that XML is less complex than it really is, which may work for a while as long as your needs are simple, but will ultimately fail when you encounter more complex documents. The only reason I mention it here is because the flaws in its design aren’t always apparent to casual users; and I tend to get a lot of e-mail from ElectricXML users asking me why I’m ignoring it.
SAX is fast and very efficient, but its callback nature is uncomfortable for some programmers. Recently some effort has gone into developing pull parsers that can read streaming content like SAX does, but only when the client application requests it. The recently published standard API for such parsers is XMLPULL. XMLPULL shows promise for the future (especially for developers who need to read large documents quickly but just don’t like callbacks). However, pull parsing is still clearly in its infancy. On the XML side, namespace support is turned off by default. Even worse, XMLPULL ignores the DOCTYPE declaration, even the internal DTD subset, unless you specifically ask it to read it. From the Java side of things, XMLPULL does not take advantage of polymorphism, relying instead on such un-OOP constructs as int type codes to distinguish nodes instead of making them instances of different classes or interfaces. I don’t think XMLPULL is ready for prime time quite yet. However, none of this is unusual for such a new technology. Some of the flaws I cite were also present in earlier versions of SAX, DOM, and JDOM and were only corrected in later releases. In the next couple of years, as pull parsing evolves, XMLPULL may become a much more serious competitor to SAX.
Recently, there’s been a flood of so-called data binding APIs that try to map XML documents into Java classes. While DOM, JDOM, and dom4j all map XML documents into Java classes, these data binding APIs attempt to go further, mapping a Book document into a Book object rather than just a generic Document object, for example. These are sometimes useful in very limited and predictable domains. However, they tend to make too many assumptions that simply aren’t true in the general case to make them broadly suitable for XML processing. In particular, these products tend to implicitly depend on one or more of the following common fallacies:
Documents have schemas or DTDs.
Documents that do have schemas and/or DTDs are valid.
Structures are fairly flat and definitely not recursive; that is, they look pretty much like tables.
Narrative documents aren’t worth considering.
Mixed content doesn’t exist.
Choices don’t exist; that is, elements with the same name tend to have the same children.
Order doesn’t matter.
The fundamental flaw in these schemes is an insistence on seeing the world through object-colored glasses. XML documents can be used for object serialization, and in that use-case all these assumptions are reasonably accurate; but XML is a lot more general than that. The large majority of XML documents cannot be plausibly understood as serialized objects, though a lot of programmers approach it from that point of view because that’s what they’re familiar with. When you're an expert with a hammer, it’s not surprising that world looks like it’s full of nails.
The fact is, XML documents are not objects and schemas are not classes. The constraints and structures that apply to objects simply do not apply to XML elements and vice versa. Unlike Java objects, XML elements routinely violate their declared types, if indeed they even have a type in the first place. Even valid XML elements often have different content in different locations. Mixed content is quite common. Recursive content isn’t quite as common, but it does exist. A little more subtly, though even more importantly, XML structures are based on hierarchy and position rather than the explicit pointers of object systems. It is possible to map one to the other, but the resulting structures are ugly and fragile; and you tend to find that when you’re finished what you’ve accomplished is merely reinventing DOM. XML needs to be approached and understood on its own terms, not Java’s. Data binding APIs are just a little too limited to interest me, and I do not plan to treat them in this book.
When choosing a parser library many factors come into play. These include what features the parser has, how much it costs, which APIs it implements, how buggy it is, and last and certainly least how fast the parser parses.
The XML 1.0 specification does allow parsers some leeway in how much of the specification they implement. Parsers can be roughly divided into three categories:
Fully validating parsers
Parsers that do not validate, but do read the external DTD subset and resolve external parameter entity references in order to supply entity replacement text and assign attribute types
Parsers that read only the internal DTD subset and do not validate.
In practice there’s also a fourth category of parsers that reads the instance document but do not perform all the mandated well-formedness checks. Technically such parsers are not allowed by the XML specification, but there are still a lot of them out there.
If the documents you’re processing have DTDs, then you need to use a fully validating parser. You don’t necessarily have to turn on validation if you don’t want to. However, XML is designed in such a way that you really can’t be sure to get the full content of an XML document without reading its DTD. In some cases, the differences between a document whose DTD has been processed and the same document whose DTD has not been processed can be huge. For instance, a parser that reads the DTD will report default attribute values; but one that doesn’t won’t. The handling of ignorable white space can vary between a validating parser and one that merely reads the DTD but does not validate. External entity references will be expanded by a validating parser, but not necessarily by a non-validating parser. You should only use a non-validating parser if you’re confident none of the documents you’ll process carry document type declarations. One situation in which this is reasonable is a SOAP server or client, since SOAP specifically prohibits documents from using DOCTYPE declarations. (Even in that case, though, I still recommend that you check to see whether there is a DOCTYPE declaration and throw an exception if you spot one.)
Beyond the lines set out by XML 1.0, parsers also differ in their support for subsequent specifications and technologies. In 2002, all parsers worth considering support namespaces and automatically check for namespace well-formedness as well as XML 1.0 well-formedness. Most of these do allow you to disable these checks for the rare legacy documents that don’t adhere to namespaces rules. Currently Xerces and Oracle are the only Java parsers that support schema validation though other parsers are likely to add this in the future.
Some parsers also provide extra information not required for normal XML parsing. For instance, at your request, Xerces can inform you of the ELEMENT, ATTLIST, and ENTITY declarations in the DTD. Crimson will not do this, so if you need to read the DTD you’d pick Xerces over Crimson.
Most of the major parsers support both SAX and DOM. However, there are a few parsers that only support SAX, and at least a couple that only support their own proprietary API. If you want to use DOM or SAX, make sure you pick a parser that can handle it. Xerces and Crimson can.
SAX actually includes a number of optional features that parsers are not required to support. These include validation, reporting comments, reporting declarations in the DTD, reporting the original text of the pre-parsed document, and more. If any of these are important to you, you’ll need to make sure that your parser supports them too.
The other APIs including JDOM and dom4j generally don’t provide parsers of their own. Instead they use an existing SAX or DOM parser to read a document which they then convert into their own tree model. Thus they can work with any convenient parser. The notable exception here is ElectricXML which does include its own built-in parser. ElectricXML is optimized for speed and size and does not interoperate well with SAX and DOM.
One often overlooked consideration when choosing a parser is the license under which the parser is published. Most parsers are free in the free-beer sense, and many are also free in the free-speech sense. However, license restrictions can still get in your way.
Since parsers are essentially class libraries that are dynamically linked to your code (as all Java libraries are) and since parsers are mostly released under fairly lenient licenses, you don’t have to worry about viral infections of your code with the GPL. In one case I’m aware of, Ælfred, any changes you make to the parser itself would have to be donated back to the community; but this would not affect the rest of your classes. That being said, you’ll be happier and more productive if you do donate your changes back to the communities for the more liberally licensed parsers like Xerces. It’s better to have your changes rolled into the main code base than to have to keep applying them every time a new version is released.
There actually aren’t that many parsers you can buy. If your company is really insistent about not using open source software, then you can probably talk IBM into selling you an overpriced license for their XML for Java parser (which is just an IBM-branded version of the open source Xerces). However, there isn’t a shrink-wrapped parser you can buy; nor is one really needed. The free parsers are more than adequate.
An often overlooked criterion for choosing a parser is correctness, how much of the relevant specifications are implemented how well. All of the parsers I’ve used have had non-trivial bugs in at least some versions. However although no parser is perfect, some parsers are definitely more reliable than others.
I wish I could say that there was one or more good choices here, but the fact is that every single parser I’ve ever tried has sooner or later exhibited significant conformance bugs. Most of the time these fall into two categories:
Reporting correct constructs as errors
Failing to report incorrect syntax.
It’s hard to say which is worse. On the one hand, unnecessarily rejecting well-formed documents prevents you from handling data others send you. On the other hand, when a parser fails to report incorrect XML documents, it’s virtually guaranteed to cause problems for people and systems who receive the malformed documents and correctly reject them.
One thing I will say is that well-formedness is the most important criterion of all. To be seriously considered a parser has to be absolutely perfect in this area, and many aren’t. A parser must allow you to confidently determine whether a document is or is not well-formed. Validity errors are not quite as important, though they’re still significant. Many programs can ignore validity and consequently ignore any bugs in the validator.
Continuing downward in the hierarchy of seriousness are failures to properly implement the standard SAX and DOM APIs. A parser might correctly detect and report all well-formedness and validity errors, but fail to pass on the contents of the document. For example, it might throw away ignorable white space rather than making it available to the application. Even less serious but still important are violations of the contracts of the various public APIs. For example, DOM guarantees that each Text object read from a parsed document will contain the longest possible string of characters uninterrupted by markup. However, I have seen parsers that occasionally passed in adjacent text nodes as separate objects rather than merging them.
Java parsers are also subject to a number of edge conditions. For example, in SAX each attribute value is passed to the client application as a single string. Because the Java String class is backed by an array of chars indexed by an int, the maximum number of characters in a String is the same as the maximum size of an int, 2,147,483,647. However, there is no maximum number of characters that may appear in an attribute value. Admittedly a three gigabyte attribute value doesn’t seem too likely (perhaps a Base-64 encoded video?) and you’d probably run out of memory long before you bumped up against the maximum size of a string; but nonetheless XML doesn’t prohibit strings of such lengths and it would be nice to think that Java could at least theoretically handle all XML documents within the limits of available memory.
The last consideration is efficiency, how fast the parser is and how much memory it uses. Let me stress that again: efficiency should be your last concern when choosing a parser. As long as you use standard APIs and keep parser-dependent code to a minimum, you can always change the underlying parser later if the one you picked initially proves too inefficient.
The speed of parsing tends to be dominated by I/O considerations. If the XML document is served over the network, it’s entirely possible that the speed with which data can move over the network is the bottleneck, not the XML parsing at all. In situations where the XML is being read from the disk, the time to read the data can still be significant even if it’s not quite the bottleneck it is in network applications.
Anytime you’re reading data from a disk or the network, you should buffer your streams. You can buffer at the byte level with a BufferedInputStream or at the character level with a BufferedReader. Perhaps a little counter-intuitively, you can gain extra speed by double buffering with both byte and character buffers. However, most parsers are happier if you feed them a raw InputStream and let them convert the bytes to characters (parsers are normally better at detecting the right encoding than most client code) so I prefer to use just a BufferedInputStream and not a BufferedReader unless speed is very important and I’m very sure of the encoding in advance. If you don’t buffer your I/O, then total performance is going to be limited by I/O considerations no matter how fast the parser is.
Complicated programs can also be dominated by processing that happens after the document is parsed. For example, if the XML document lists store locations, and the client application is attempting to solve the traveling salesman problem for those store locations, then parsing the XML document is the least of your worries. In such a situation, changing the parser isn’t going to help very much at all. The time taken to parse a document normally grows only linearly with the size of the document.
One area where parser choice does make a significant difference is in the amount of memory used. SAX is generally quite efficient no matter which parser you pick. However, DOM is exactly the opposite. Building a DOM tree can easily eat up as much as ten times the size of the document itself. For example, given a one megabyte document, the DOM object representing it could be ten megabytes. If you’re using DOM or any other tree-based API to process large documents, you want a parser that uses as little memory as possible. The initial batch of DOM-capable parsers were not really optimized for space, but the more recent versions are doing a lot better. With some testing you should be able to find parsers that only use two to three times as much memory as the original document. Still, it’s pretty much guaranteed that the memory usage will be larger than the document itself.
I now want to discuss a few of the more popular parsers and the relative advantages and disadvantages of each.
I’ll begin with my parser of choice, Xerces-J from the Apache XML Project. This is a very complete, validating parser that has the best conformance to the XML 1.0 and Namespaces in XML specifications I’ve encountered. It fully supports the SAX2 and DOM Level 2 APIs, as well as JAXP, though I have encountered a few bugs in the DOM support. The latest versions feature experimental support for parts of the DOM Level 3 working drafts. Xerces-J is highly configurable and suitable for almost any parsing needs. Xerces-J is also notable for being the only current parser to support the W3C XML Schema Language, though that support is not yet 100% complete or bug-free.
The Apache XML Project publishes Xerces-J under the very liberal open source Apache license. Essentially, you can do anything you like with it except use the Apache name in your own advertising. Xerces-J 1.x was based on IBM’s XML for Java parser, whose code base IBM donated to the Apache XML Project. Today, the relationship’s reversed and XML for Java is based on Xerces-J 2.x. However, in both versions there’s no significant technical difference between Xerces-J and XML for Java. The real differentiation is that if you work for a large company with a policy against using software from somebody you can’t easily sue, then you can probably pay IBM a few thousand dollars for a support contract for XML for Java. Otherwise, you might as well just use Xerces-J.
The Apache XML Project also publishes Xerces-C, an open source XML parser written in C++, which is based on IBM’s XML for C++ product. However, since this is a book about Java, henceforth when you see the undifferentiated name “Xerces” it should be understood that I’m talking strictly about the Java version.
Crimson, previously known as Java Project X, is the parser Sun bundles with the JDK 1.4. Crimson supports more or less the same APIs and specifications Xerces does—SAX2, DOM2, JAXP, XML 1.0, Namespaces in XML, etc. —with the notable exception of schemas. In my experience Crimson is somewhat buggier than Xerces. I’ve encountered well-formed documents that Crimson incorrectly reported as malformed, but that Xerces could parse without any problems. The bugs I’ve encountered in Xerces all related to validation, not to the more basic criterion of well-formedness.
The reason Crimson exists is because some Sun engineers disagreed with some IBM engineers about the proper internal design for an XML parser. (Also, the IBM code was so convoluted that nobody outside of IBM could figure it out.) Crimson was supposed to be significantly faster, more scalable, and more memory efficient than Xerces-J and not get soggy in milk either. However whether it’s actually faster than Xerces (much less significantly faster) is questionable. When first released, Sun claimed that Crimson was several times faster than Xerces. IBM ran the same benchmarks and got almost exactly opposite results. They claimed that Xerces was several times faster than Crimson. After a couple of weeks of hooting and hollering on several mailing lists, the true cause was tracked down. Sun had heavily optimized Crimson for the Sun virtual machine and just-in-time compiler; and they were naturally running their tests on Sun virtual machines. IBM publishes their own Java virtual machine, and they were optimizing for and benchmarking on their virtual machine. To no one’s great surprise, Sun’s optimizations didn’t perform nearly as well when run on non-Sun virtual machines; and IBM’s optimizations didn’t perform nearly as well when run on non-IBM virtual machines. As Donald Knuth wrote back in 1974 (when machines were a lot slower than they are today), “premature optimization is the root of all evil.”[2] Eventually both Sun and IBM began testing on multiple virtual machines and watching out for optimizations that were too tied to the architecture of any one virtual machine; and now both Xerces-J and Crimson seem to run about equally fast on equivalent hardware, regardless of VM.
The real benefit to Crimson is that it’s bundled with the JDK 1.4. (Crimson does work with earlier virtual machines back to Java 1.1. It just isn’t bundled with them in the default distribution.) Thus if you know you’re running in a 1.4 or later environment, you don’t have to worry about installing extra JAR archives and class libraries just to parse XML. You can write your code to the standard SAX and DOM classes and expect it to work out of the box. If you want to use a non-Crimson parser, then you can still install the JAR files for Xerces-J or some other parser and load its implementation explicitly. However, in Java 1.3 and earlier (which is the vast majority of the installed base at the time of this writing) you have to include some parser library with your own application.
Going forward, Sun and IBM are cooperating on Xerces-2 which will probably become the default parser in the JDK in a future release. Crimson is unlikely to be developed further or gain support for new technologies like XInclude and schemas.
The GNU Classpath Extensions Project’s Ælfred is actually two parsers, gnu.xml.aelfred2.SAXDriver and gnu.xml.aelfred2.XmlReader. SAXDriver aims for a small footprint rather than a large feature set. It supports XML 1.0 and Namespaces in XML. However, it does not validate and it does not make all the well-formedness checks it should make. It can miss malformed documents, and on rare occasions may even report well-formed documents as malformed. It supports SAX but not DOM. Its small size makes it particularly well-suited for applets. For less resource constrained environments, Ælfred provides XmlReader, a validating parser that supports both SAX and DOM.
Ælfred was originally written by the now defunct Microstar, who placed it in the public domain. David Brownell picked up development of the parser and brought it under the aegis of the GNU Classpath Extensions Project, an attempt to reimplement Sun’s Java extension libraries (the javax packages) as free software. Ælfred is published under the GNU General Public License with library exception. In brief, this means that as long as you only call Ælfred through its public API and don’t modify the source code yourself, the GPL does not infect your code.
Yuval Oren’s Piccolo is the latest entry into the parser arena. It is a very small, very fast, open source, non-validating XML parser. However, it does read the external DTD subset in order to apply default attribute values and resolve external entity references. Piccolo supports the SAX API exclusively. It does not have a DOM implementation. | http://www.cafeconleche.org/books/xmljava/chapters/ch05s02.html | CC-MAIN-2019-09 | refinedweb | 5,692 | 61.67 |
Conversion error when launching OData v4 Client Code Generator
I have an OData service that returns the
/$metadata
following from an endpoint :
<edmx:Edmx <edmx:DataServices xmlns: <Schema Namespace="(...)" xmlns: <!-- ... --> </Schema> </edmx:DataServices> </edmx:Edmx>
When I try to run OData v4 Client Code Generator (v2.3.0) against this XML file, I get the following errors:
Warning: Transformation start: element "edmx: Edmx" was unexpected for root element. The root element must be Edmx.
Warning: The attribute has not been declared.
I also only see an empty file
.cs
.
I tried removing the space prefix
edmx:
from the elements
<Edmx>
and
<DataServices>
making that namespace the default and setting prefixes on the remaining elements, but that doesn't work either:
<Edmx Version="1.0" xmlns="" xmlns: <DataServices m: <edm:Schema <!-- ... --> </edm:Schema> </DataServices> </Edmx>
source to share
Ok, it looks like the problem might be the version of OData that the service provides, namely OData v1.0 . The designated space
edm
is this
. See OData Version 4.0 Part 3: Common Schema Definition Language (CSDL), §2.2 :
The elements and attributes that define the entity model exposed by the OData service are qualified using the Entity model namespace:
Previous versions of CSDL for EDM used the following namespaces:
- CSDL version 1.0:
- CSDL 1.1 version:
- CSDL 1.2 version:
- CSDL version 2.0:
- CSDL version 3.0:
Using the Add Service Link tool in Visual Studio 2013 (optional with this update ) resolves the client code generation issue for this OData service.
source to share | https://daily-blog.netlify.app/questions/2222703/index.html | CC-MAIN-2021-21 | refinedweb | 255 | 58.89 |
Basement.Compat.Base
Description
internal re-export of all the good base bits
Synopsis
- ($) :: (a -> b) -> a -> b
- ($!) :: (a -> b) -> a -> b
- (&&) :: Bool -> Bool -> Bool
- (||) :: Bool -> Bool -> Bool
- (.) :: Category k cat => forall (b :: k) (c :: k) (a :: k). cat b c -> cat a b -> cat a c
- (<$>) :: Functor f => (a -> b) -> f a -> f b
- not :: Bool -> Bool
- otherwise :: Bool
- fst :: (a, b) -> a
- snd :: (a, b) -> b
- id :: Category k cat => forall (a :: k).
- class Functor (f :: * -> *) where
- class Functor f => Applicative (f :: * -> *) where
- class Applicative m => Monad (m :: * -> *) where
- when :: Applicative f => Bool -> f () -> f ()
- unless :: Applicative f => Bool -> f () -> f ()
- data Maybe a :: * -> *
- data Ordering :: *
- data Bool :: *
- data Int :: *
- data Integer :: *
- data Char :: *
- class Integral a where
- class Fractional a where
- class HasNegation a where
- data Int8 :: *
- data Int16 :: *
- data Int32 :: *
- data Int64 :: *
- data Word8 :: *
- data Word16 :: *
- data Word32 :: *
- data Word64 :: *
- data Word :: *
- data Double :: *
- data Float :: *
- data IO a :: * -> *
- class IsList l where
- class IsString a where
- class Generic a
- data Either a b :: * -> * -> *
- class Typeable * a => Data a where
- mkNoRepType :: String -> DataType
- data DataType :: *
- class Typeable k (a :: k)
- class Monoid a where
- (<>) :: Monoid m => m -> m -> m
- class (Typeable * e, Show e) => Exception e
- throw :: Exception e => e -> a
- throwIO :: Exception e => e -> IO a
- data Ptr a :: * -> * = Ptr Addr#
- ifThenElse :: Bool -> a -> a -> a
- internalError :: [Char] -> a
Documentation
($) :: (a -> b) -> a -> b infixr 0 #
($!) :: (a -> b) -> a -> b infixr 0 #
Strict (call-by-value) application operator. It takes a function and an argument, evaluates the argument to weak head normal form (WHNF), then calls the function with that value.
(.) :: Category k cat => forall (b :: k) (c :: k) (a :: k). cat b c -> cat a b -> cat a c infixr 9 #
morphism composition
(<$>) :: #
The
maybe function takes a default value, a function, and a
Maybe
value. If the
Maybe value is
Nothing, the function returns the
default value. Otherwise, it applies the function to the value inside
the
Just and returns the result.
Examples
Basic usage:
>>>
maybe False odd (Just 3)True
>>>
maybe False odd NothingFalse
Read an integer from a string using
readMaybe. If we succeed,
return twice the integer; that is, apply
(*2) to it. If instead
we fail to parse an integer, return
0 by default:
>>>
import Text.Read ( readMaybe )
>>>
maybe 0 (*2) (readMaybe "5")10
>>>
maybe 0 (*2) (readMaybe "")0
Apply
show to a
Maybe Int. If we have
Just n, we want to show
the underlying
Int
n. But if we have
Nothing, we return the
empty string instead of (for example) "Nothing":
>>>
maybe "" show (Just 5)"5"
>>>
maybe "" show Nothing""
either :: (a -> c) -> (b -> c) -> Either a b -> c #
Case analysis for the
Either type.
If the value is
, apply the first function to
Left a
a;
if it is
, apply the second function to
Right b
b.
Examples
We create two values of type
, one using the
Either
String
Int
Left constructor and another using the
Right constructor. Then
we apply "either" the
length function (if we have a
String)
or the "times-two" function (if we have an
Int):
>>>
let s = Left "foo" :: Either String Int
>>>
let n = Right 3 :: Either String Int
>>>
either length (*2) s3
>>>
either length (*2) n6
flip :: (a -> b -> c) -> b -> a -> c #
const x is a unary function which evaluates to
x for all inputs.
For instance,
>>>
map (const 42) [0..3][42,42,42,42]
error :: HasCallStack => [Char] -> a #
and :: Foldable t => t Bool -> Bool #
undefined :: HasCallStack => a #
The value of
seq a b is bottom if
a is bottom, and
otherwise equal to
b..
Conversion of values to readable
Strings..
showList :: [a] -> ShowS # #
(<) ::.
Minimal complete definition: either
== or
/=. | https://hackage.haskell.org/package/basement-0.0.7/docs/Basement-Compat-Base.html | CC-MAIN-2021-39 | refinedweb | 610 | 64.24 |
The implementation of a 'Class' type in ActionScript 3. More...
#include <as_class.h>
The implementation of a 'Class' type in ActionScript 3.
A Class is a first-class type, i.e. it can be referenced itself in ActionScript. Although Classes are nominally 'dynamic' types, there seems to be no way to alter them in ActionScript, or to create them dynamically. In order to reference them, the Class must already be constructed and known in the execution scope, then retrieved by name. Accordingly, all as_class objects have an associated Class, which is its static definition. TODO: see how to implement "[class Class]", the prototype of all classes.
Return the string representation for this object.
This is dependent on the VM version and the type of object, function, or class.
Reimplemented from gnash::as_object. | https://www.gnu.org/software/gnash/manual/doxygen/classgnash_1_1abc_1_1as__class.html | CC-MAIN-2021-43 | refinedweb | 132 | 59.7 |
can I get that change into hours/minutes.
I can't simply subtract 12 from the input
This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.
But "military time" (like 1400) could be split up into hours and minutes with division and mod:
// convert it to integer:
int mt=-1;
try
{ mt=Integer.parseInt(entry)
} catch(NumberFormatExceptio
{ // input problem
}
int hours=mt/100;
int min=mt%100;
public TimeCheck(String entry) {
hours = Integer.parseInt(entry.sub
minutes = Integer.parseInt(entry.sub
}
As for comment from CEHJ,
what will the (entry.substring(0, 3)); do??
don't get that bit
Get the hours from the entry.
TimeCheck may as well have a method to return 12hr format
public int getHours12() {
return hours > 12? (hours - 12) : hours;
}
This line converts the String of "1400" to a number 1400.
Once you have a number you can do arithmetic operations with it. So:
int hours=mt/100;
This will divide mt (which is the number 1400) by 100, and leaving no remainder. So hours will wind up being 14. You could now, if needed, check if it is greater than 12, and then subtract 12, if that is desirable.
int min=mt%100;
This will get the remainder after dividing mt by 100. In this case min would wind up being 0. If mt were 1410, the min would wind up being 10.
also, would i need to parse this from a string to integer in my TimeCheck constructor if it has been parse'd at that stage in the driver?
>>
No - i just did it that way for convenience
Get the hours from the entry.
In that case what does the (0,3) stand for? don't see where they've come from.
Thanks for all the help so far by the way
Bye, Giant.
this is the problem i'm havin as i have no flexibility with the given driver
Hope these links could help you.
Giant.
See here for Java1.4
So you can manipulate it by breaking out hours and minutes (as I indicated). You could then recombine it and pass it in to TimeCheck.
tc=new TimeCheck(hours*100+min);
int hours = tc.getHours();
if (hours > 12) {
hours -= 12;
}
import java.io.*;
public class TimeTest {
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.i
static PrintWriter screen = new PrintWriter(System.out, true);
public static void main(String[] args) {
try {
TimeCheck tc;
int entry;
screen.print("Time on 24hr timetable? ");
screen.flush();
entry = Integer.parseInt(keyboard.
tc = new TimeCheck(entry);
if (tc.isValid()) {
int hours = tc.getHours();
int minutes = tc.getMinutes();
screen.println("Thats" + hours + "." + minutes + tc.timeOfDay());
if (hours > 12) {
int hours12 = hours - 12;
screen.println("Thats" + hours12 + "." + minutes + tc.timeOfDay() + " in 12-hour clock");
}
}
else {
screen.println("Can't cope");
}
}
catch (Exception e) {
screen.println("Input Problem");
}
}
}
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
There may be bits in the wrong place etc.
And by now you'll probably be getting the idea that i'm not too good at this.......yet!!!!!
But hopefully I'll get there.
Anyway when i run my program it compiles fine, asks me to enter the time then...nothing.
Anyway here we go:
import java.io.*;
import java.text.DecimalFormat;
class TimeCheck {
private int hour; //0-23
private int minute; //0-59
private int time;
public TimeCheck() {
}
public TimeCheck(int time){
this.time=time;
}
public boolean isValid(){
if(
time == ((time>=0 && time<2400) ? time:0))
return true;
else return false;
}
public int getHours(){
hour = time/100;
if (hour>12){
hour = hour - 12;
}
return hour;
}
public int getMinutes(){
minute = time%100;
return minute;
}
public String timeOfDay(){
DecimalFormat twoDigits = new DecimalFormat("00");
return((getHours() ==12 || getHours() == 0) ? 12: getHours() %12)+
twoDigits.format( getMinutes())+ ":" +
(getHours() <12 ? "am" : "pm");
}
}
If you have a debugger this is relatively easy. If not, you will have to make do with old fashioned method of putting in print statements to find out how far it got.
How'd you mean its working??!!!
U get it to do everything its supposed to?
Been away working hence the delayed reply
C:\java\dumpit>java TimeTest
Time on 24hr timetable? 2235
That's 10.35 1035:am
(ok the 'am's wrong but ..)
so i was at least on sort-of the right lines!!
must be the way my JDE's set-up, i'll try it on the Linux machines we use at uni.
Look, much appreciation to you guys who've helped.
Very quick reply service aswell.
How do the points on the site get rewarded? what do you guys need to get the credit for helping?
i try to run my program and I can half-see the result coming ok but the window very quickly shuts down. using JBuilder and it is set up using packages, not quite got to grips with the ins and outs of it yet!
No - only a space and an apostrophe changed here and there ;-
>>using JBuilder and it is set up using packages, not quite got to grips with the ins and outs of it yet!
You must also get familiar with running at the command line too.
>>How do the points on the site get rewarded?
By you ;-) Just accept an answer. You can split points if you want | https://www.experts-exchange.com/questions/21184564/I'm-looking-to-convert-from-24hour-clock-to-12hour-using-a-set-driver.html | CC-MAIN-2018-30 | refinedweb | 928 | 76.72 |
public class SanderRossel : Lazy<Person>
{
public void DoWork()
{
throw new NotSupportedException();
}
}
Visual Studio 2010 says:Cannot implicitly convert type 'System.Data.DataRowView' to 'System.Data.IDataRecord'. An explicit conversion exists
Visual Studio 2010 says:Unable to cast object of type 'System.Data.DataView' to type 'System.Data.IDataRecord'.
PIEBALDconsult wrote:If you know of one, please show me.
Nareesh1 wrote:Is it a programming quesiton
delete this;
object herp = (object) myDataRowView;
IDataRecord derp = (IDataRecord)herp;
IDataRecord derp = (IDataRecord) myDataRowView;
PIEBALDconsult wrote:I've never seen one. If you know of one, please show me.
Ian Shlasko wrote: If it wasn't for Java, Microsoft wouldn't have created C# to rescue us from it!
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Lounge.aspx?fid=1159&df=90&mpp=25&noise=3&prof=False&sort=Position&view=None&spc=None&select=4390109&fr=2077 | CC-MAIN-2014-52 | refinedweb | 143 | 58.18 |
Join the 85,000 open source advocates who receive our giveaway alerts and article roundups.
Open source code libraries for MARC-formatted records for Java, C#, and Perl
3 open source code libraries to handle MARC-formatted records
Developers can use these libraries for Java, C#, and Perl.
opensource.com
Get the newsletter
Welcome back to Nooks & Crannies! After a month off for my wedding, I've been digging around for some interesting bits for upcoming columns. This month, I'll take a look at some open source code libraries that developers can use to handle MARC-formatted records.
A little background for the MARC novice
MARC stands for MAchine Readable Cataloging records. It's a format first developed in the 1960s for the U.S. Library of Congress in order to facilitate the exchange of bibliographic records among libraries. By the mid-1970s, it was an international standard, used around the world.
There are several variants of the MARC format. MARC21 was a merger in the 1990s between USMARC and CANMARC, the US and Canadian variants then in use, and other countries have their own formats. In much of Europe, UNIMARC is the variant most often seen. All of these records are formatted the same, with a structure of tags that are used to contain information, a directory which tells what tags are in the record, and where they are located.
Each tag, in each format, means something specific. For instance, in MARC21 bibliographic format, the 245 tag holds information about the title of the work. Additional information, including the publisher, author, size of the physical book, publication date, and subjects, are contained in other tags.
The format of the record, if you were to just print it out, is kind of hard to read. It was originally designed for serial interchange, via 9-track tape, and that medium was still in use in the early days of my career, in the 1990s. The first five bytes of the record are digits and tell you how long the record is, in bytes—including those five bytes. The clever modern nerd will instantly perceive the limitation of this structure: the record cannot be 100,000 bytes in length. Following that is the directory of tags, telling what tags to look for, and at which byte each tag starts. After that comes the tag data, and the next byte after that is the first byte of the next record. The leader/directory/tag structure is generically defined in ISO-2709; MARC21 or UNIMARC are the formats that define the meanings of the tags.
Yes, it's a poorly designed format by modern standards. Yes, it needs updating, in the worst way, but that's the subject of another article altogether. In this article, I'll show you three code libraries that you can use to manipulate MARC records without having to know all the nitty-gritty of the arcane tag directory.
Java: MARC4J
MARC4J allows the creation of an iterator to read an input stream such as a file, and do things with the MARC21 or UNIMARC records that it finds in the stream. There are record-writing tools, too, of course, and iterators for examining the records in detail. Here's a quick example that will read in a file of records, and if the title of the work in field 245, subfield a, starts with the letter J, writes it to another file:
import org.marc4j.MarcReader;
import org.marc4j.MarcStreamReader;
import org.marc4j.MarcStreamWriter;
import org.marc4j.marc.Record;
import org.marc4j.marc.DataField;
import org.marc4j.marc.Subfield;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class JMarcExample {
public static void main(String args[]) throws Exception {
InputStream in = new FileInputStream("inputfile.mrc");
OutputStream out = new FileOutputStream("outputfile.mrc");
MarcReader reader = new MarcStreamReader(in);
MarcWriter writer = new MARCStreamWriter(out);
while (reader.hasNext()) {
Record record = reader.next();
datafield = (DataField) record.getVariableField("245");
list subfields = datafield.getSubfields();
i = subfields.iterator();
while (i.hasNext()) {
Subfield subfield = (Subfield) i.next();
char code = subfield.getCode();
if ( code == 'a' ) {
String data = subfield.getData();
if ( data.startsWith("J") ) {
writer.write(record);
}
}
}
}
}
}
MARC4J also includes handlers for Unicode, and for the MARCXML variant (where MARC records are rendered in XML) the tag structure is easier to read for human eyes, but it's much wordier, as you can imagine. MARC4J is agnostic about what the 245 tag might actually mean, so, in that sense, it should be able to read and write any ISO-2709-formatted record.
MARC4J is licensed under LGPL V2.1 and is available on GitHub.
C#: CSharp_MARC
CSharp_MARC has a rich set of tools for importing and exporting MARC21 and MARCXML records, including record validation and search-and-replace tools that allow for the batch editing of records. It also has some reporting tools built right in, to report on copyright year or classifications. It's very lightweight, capable of handling up to 28,000 records per minute.
Here's a sample program, to read a file of MARC21 records, and print out the author name from each record's 100 tag, subfield a, in the order the records appear:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MARC;
using System.IO;
namespace CSharp_Show_Authors
{
class Program
{
static void Main(string[] args)
{
string rawMarc = File.ReadAllText("inputfile.mrc");
FileMARC marcRecords = new FileMARC(rawMarc);
foreach (Record record in marcRecords)
{
Field authorField = record["100"];
if (authorfield.IsDataField())
{
DataField authorDataField = (Datafield)authorField;
Subfield authorName = authorDataField['a'];
Console.WriteLine(authorName.Data);
}
else if (authorField.IsControlField())
{
//unreachable
Console.WriteLine("Something awful has happened. The author field should never be a control field!");
}
}
}
}
}
As with MARC4J, the CSharp_MARC reader and writer tools don't really care what each tag actually means in the bibliographic record, so should be usable for UNIMARC or other MARC variants. However, the built-in validation tools appear to be constrained to MARC21 and MARCXML. CSharp_MARC is licensed GPL V3.0 and is available on GitHub.
Perl 5: MARC::Record
You didn't really think I was going to let this article go by without some Perl, did you? MARC::Record, like the other tools here, has mechanisms for handling any ISO-2709-formatted record reading or writing needs you might have. It's got a built-in pretty-printer, it can handle insertion or deletion of fields into a record, and will properly update the tag directory on output. It's not as feature-rich as the C# library but can handle most basic record-manipulation needs. I've used this library for years in my own work. (Disclaimer: MARC::Record is maintained by my great friend and colleague, Galen Charlton.)
Here is an example script to read a file of MARC21 records, and write out a pipe-delimited file of the author (100 subfield a) and title (245 subfield a):
use strict;
use warnings;
use MARC::File::USMARC;
use MARC::Record;
use MARC::Batch;
use MARC::Charset;
my $in_fh = IO::File->new("inputfile.mrc");
my $batch = MARC::Batch->new('USMARC',$in_fh);
$batch->warnings_off();
$batch->strict_off();
my $iggy = MARC::Charset::ignore_errors(1);
my $setting = MARC::Charset::assume_encoding('marc8');
open my $out_fh,">:utf8","outputfile.psv";
RECORD:
while () {
my $this_record = $batch->next();
last RECORD unless ($this_record);
my $author = $this_record->field('100')->subfield('a');
my $title = $this_record->field('245')->subfield('a');
print $out_fh "$author|$title\n";
}
close $in_fh;
close $out_fh;
MARC::Record is available on CPAN and is available under the Perl license. To date, no one has written a MARC handler for Perl 6; I can hear a half-dozen of my colleagues yelling "well volunteered!" at me about now...
I did some open source searching
I did a little bit of digging around on GitHub, and quickly found libraries in Python, JavaScript, Ruby, Node.js, and Scala. I didn't test any of them out, so they might be incomplete or partial, but for any language you want to code in, it's likely you can find a module that will work for you.
1 Comments
And PHP at ! | https://opensource.com/article/17/4/bit-about-marc-handlers | CC-MAIN-2018-39 | refinedweb | 1,348 | 57.57 |
Hi,
I have a dataframe in my DSS workflow which I want to change and store in a non-csv file within a folder.
Assume my dataframe is called df and for the example you can recreate is as follows
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]})
I now want to add a few lines of comment above the dataframe and then save the file automatically in a folder.
Firstly, I have taken my dataset and load it into a folder ("my_input_folder") with the DSS recipe "Export to folder" calling the file df.csv. Then I have added a python script which reads the file, adds the comments and output it in another folder ("my_output_folder"). The code is below but it didn't get what I wanted. Could you please help?
# -*- coding: utf-8 -*-
import dataiku
import pandas as pd, numpy as np
from dataiku import pandasutils as pdu
import os.path
# Recipe inputs
folder_path = dataiku.Folder("my_input_folder").get_path()
path_of_csv = os.path.join(folder_path, "df.csv")
# Recipe outputs
output2 = dataiku.Folder("my_output_folder")
output2_path = output2.get_path()
completeName = os.path.join(folder_path, "df.csv")
file1 = open(completeName, "w")
toFile = raw_input("# This is my first comment\n This is my other comment \n") # I need to write two comments on two different rows
file1.write(toFile)
file1.close()
dirPath2 = os.path.join(output2_path,file1)
Thank you!
©Dataiku 2012-2018 - Privacy Policy | https://answers.dataiku.com/2314/output-tab-file-to-managed-folder-in-dss | CC-MAIN-2019-22 | refinedweb | 242 | 68.06 |
I'm not sure what's happening in my code. But I'm trying the excercice in notepad++ and load it into python terminal. [code is not complete, I'm just not sure why I get this output]
When I import the code it prints all the "print" after the for loop like it is in the for loop for. I assume it's because it has text[c] in one print (I have no clue why it would print the other one) and c is defined in the for-loop, but when I add it to the loop I get an "unexpected indent" Error.
When I remove the last "print"-line [print "not in for loop??"] and reload the file back into python the for loop only runs once. Because this makes no sense for me.
def reverse(text):
new = ()
for x in range(1,len(text)+1):
c = len(text) - x
print c
print "\t", text[c]
print "not in for loop??"
return
reverse("abcd")
output:
3
d
not in for loop??
2
c
not in for loop??
1
b
not in for loop??
0
a
not in for loop??
Very important that your indents are 4 spaces per level of indentation. Please edit your post and format the code sample so we see the correct indentation.
How to format code samples in forum posts
Fix your post and ping this thread so we can return for a better look. Thank you.
ok thanks. finally found the problem, I think I was using the wrong characters to have the proper formatting.
I also retried the code again and now my output seems to be correct (as in it's not adding the print functions in the for-loop.) Not sure how that happened since it should be the same function I tried when I posted this. Guess I made a mistake somewhere in the code, just not sure what It could have been. | https://discuss.codecademy.com/t/7-reverse-for-loop-problem/18346/2 | CC-MAIN-2017-39 | refinedweb | 325 | 80.41 |
Sometimes a mobile application needs to know when it becomes active or inactive. React Native provides the AppState API for this. There are several ways to use this API, including a new one that my colleagues and I just released.
In React Native, the
AppState API lets you check the current state of the application with
AppState.currentState. You can also add an event listener to be notified when the state changes.
Possible states include:
null: Initial value while the real state is being retrieved.
active: The app is running in the foreground.
background: The app is running in the background while the user is in another app or on the home screen.
inactive: The app is transitioning between foreground and background or otherwise inactive (such as when there’s an incoming call).
When you want to use an event listener, the normal approach is to use the React component lifecycle methods
componentDidMount and
componentWillUnmount along with an event handler to handle the change.
AppStateListener
My colleagues and I at Zeal have just released a new library, react-native-appstate-listener, that takes care of this for you.
AppStateListener is a React component that takes three callback functions as props:
onActive,
onBackground, and
onInactive. Whenever
AppState signals a state change,
AppStateListener calls the appropriate callback, allowing your application to respond as necessary.
In addition,
AppStateListener calls the
onActive callback when the component mounts and the
onBackground callback when it unmounts.
All three props are optional, so you only need to specify the props you care about.
As an example from one of our applications, we cache some state locally on the device but we want to refresh that state from the server whenever the application becomes active. Here’s the code for that:
import React from 'react'
import { View } from 'react-native'
import AppStateListener from 'react-native-appstate-listener'
export function Main({ refreshState }) {
<AppStateListener onActive={refreshState} />
In our case,
refreshState is a bound Redux action creator that does what we need, but it can be any function.
You can have several instances of
AppStateListener in your application at the same time, each responding to changes in a different way.
Alternatives
If you’re using Redux and you’d prefer that AppState changes be converted into Redux actions that are dispatched through your Redux store, take a look at redux-enhancer-react-native-appstate.
In general, I’ve found that my responses to AppState changes involve side effects, so responding to them in a reducer doesn’t normally work for me.
However, if your responses can be handled by reducers, or if you use something like redux-saga, this can be a really good approach. You can define a saga that watches for the AppState change actions and responds to them.
Conclusion
The
AppState API can be really useful in React Native applications, whether you use it directly or via a more convenient wrapper. | http://brianyang.com/react-native-appstate/ | CC-MAIN-2017-47 | refinedweb | 483 | 51.07 |
I have a trivial resize function that just doubles array size when original list is full. From what I see, C++ treats unset indices as "empty" with values of 0. After I declared new double-sized array and copied elems from old list, I tried to output it in main but once it goes past last index w/ an item, it starts printing weird values, rather than 0's to indicate unset indices. The old and new lists are respectively: hashtable_1, hashtable_2.
The code is very trivial. Please let me know.
Code:#include <iostream> using namespace std; //Note: trivial resize...I think there's a better one yet void resize_v1(int* old_list, int* new_list, int size)//Note: new list will be declared in main { for ( int i = 0; i < size; ++i ) new_list[i] = old_list[i]; } int main() { int hashtable_1[15] = {0,0,9,0,1000,44,19,201,666,444,57,88,88908,77,33}; int size_1 = sizeof(hashtable_1)/sizeof(int);//this is capacity, NOT num elems in list so far int hashtable_2[30] = {}; cout << "Empty slot: " << hashtable_2[29] << endl;//I'm talking about this line, why does it output 0, yet in the for-loop below, it outputs: -1 etc int size_2 = sizeof(hashtable_2)/sizeof(int); resize_v1(&hashtable_1[0], &hashtable_2[0], size_2); cout << size_2 << endl; for ( int i = 0; i < size_2; ++i )//weird values outputted once its past 15th index (last index that's occupied from old list: hashtable_1 { cout << "cur i: " << i << endl; cout << hashtable_2[i] << " , " << endl << endl; } cout << endl; return 0; } | http://cboard.cprogramming.com/cplusplus-programming/149631-resize-array-values-empty-indices.html | CC-MAIN-2014-35 | refinedweb | 254 | 69.86 |
Added tarball of v3.1 source to the "View All Files" download page.
Added tarballs of the source in 'v4.0' and 'trunk' directories to the download page.
Branched off v4.0 of the HLA stdlib. Also renamed the "working" directory to "trunk" in order to match the SVN documentation and SVN common usage.
Fixed the pat.onePat, pat.oneOrMorePat, pat.zeroOrOnePat, and pat.zeroOrMorePat macros (they were completely broken before).
Finally finished the strings module documentation and posted several new str.catbuf* functions. This update becomes the stdlib v3.1 release.
Documentation for the new filesys file/pathname string functions was added to the system and lots of little defects in those functions were corrected.
Renamed a large number of the sourcefiles in the library so that the prefix of the filename matches the module to which it belongs. This helps reduce "namespace pollution" in the library file created when linking all the modules together into the library.
Sevag's string functions were added to the source code base. I also took the liberty of breaking up the source files into individual function files and filled in a few missing routines. Still have to include the test files he wrote, write additional test files, and write the documentation for all the routines.
The functions in the Bits, Chars, and Cset modules have been renamed to following the new naming conventions (i.e., they have "bit_", "ch_", and "cs_" filename prefixes).
The string functions were just renamed with a "str_" prefix. This is to make the library function naming more consistent and eliminate some problems having to do with two object modules in the library having the same name (a no-no for the linker).
Quick note to everyone -- the strings module documentation describes stdlib v1.x, not v3.0. This will be updated at one point or another. In the meantime, verify all string function prototypes by looking at the include/strings.hhf header file.
I've just uploaded the HLA v3.0 source code to the source forge repository. It's kept under Subversion source control. I recommend the Tortoise SVN client under Win32. | http://sourceforge.net/p/hla-stdlib/news/ | CC-MAIN-2014-23 | refinedweb | 356 | 68.97 |
On Fri, 16 Nov 2007 16:52:34 +0100 Daniel Lezcano wrote:> > +1. Both the IPC and the PID namespaces provide IDs to address> > + object inside the kernel. E.g. semaphore with ipcid or> > + process group with pid.> > +> > + In both cases, tasks shouldn't try exposing this id to some> > + other task living in a different namespace via a shared filesystem> > + or IPC shmem/message. The fact is that this ID is only valid> > + within the namespace it was obtained in and may refer to some> > + other object in another namespace.> > +> > +2. Intentionnaly, two equal user ids in different user namespaces> Intentionaly Intentionally,> > + should not be equal from the VFS point of view. In other> > + words, user 10 in one user namespace shouldn't have the same> > + access permissions to files, beloging to user 10 in another> belonging> > + namespace. But currently this is not so.> > +---~Randy-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/11/16/136 | CC-MAIN-2016-30 | refinedweb | 174 | 63.39 |
Closed Bug 609114 Opened 9 years ago Closed 9 years ago
use freetype's configure script configure its build rather than hard coding the makefile
Categories
(Firefox Build System :: General, defect)
Tracking
(fennec2.0b3+)
mozilla2.0b8
People
(Reporter: blassey, Assigned: blassey)
References
Details
Attachments
(1 file, 4 obsolete files)
I'm open to any suggestions for cleaning this up
Assignee: nobody → blassey.bugs
Attachment #487694 - Attachment is obsolete: true
Status: NEW → ASSIGNED
Attachment #487696 - Flags: review?(ted.mielczarek)
Comment on attachment 487696 [details] [diff] [review] patch >diff --git a/toolkit/library/Makefile.in b/toolkit/library/Makefile.in >--- a/toolkit/library/Makefile.in >+++ b/toolkit/library/Makefile.in >@@ -271,6 +271,11 @@ endif > > include $(topsrcdir)/config/rules.mk > >+ifdef MOZ_TREE_FREETYPE >+-lfreetype: >+ make -C ../../modules/freetype2 >+endif >+ > export:: $(RDF_UTIL_SRC_CPPSRCS) $(INTL_UNICHARUTIL_UTIL_CPPSRCS) > $(INSTALL) $^ . > Why is this necessary?
(In reply to comment #2) > Comment on attachment 487696 [details] [diff] [review] > Why is this necessary? I removed modules/freetype2 from tier_platform_dirs because we no longer need to create the Makefile from (the no deleted) Makefile.in. Unfortunately, this also removes the rule for making libfreetype. As I said in comment 0, any suggestions for making this cleaner are welcome.
I believe you can add it to tier_platform_staticdirs, and it will do what you want.
Attachment #487696 - Attachment is obsolete: true
Attachment #487885 - Flags: review?(khuey)
Attachment #487696 - Flags: review?(ted.mielczarek)
Whiteboard: [has-patch]
Comment on attachment 487885 [details] [diff] [review] patch Not too thrilled about exporting all those variables; bumping this to ted to see if he has a better idea.
Attachment #487885 - Flags: review?(khuey) → review?(ted.mielczarek)
A few concerns here: 1. It feels like a static library is being generated almost coincidentally as a result of a configure test failing due to quirks in our toolchain. Specifying --disable-shared explicitly would be nicer. 2. Freetype's build system uses libtool, which doesn't do -fPIC because shared libs are disabled. Right now, not using -fPIC causes more memory usage due to code that can't be shared between processes. 3. This makes it more difficult to do fakelibs. Fakelibs lets us lay out libxul better (bug 603370) and improve startup time and memory usage (via custom linker tricks).
Comment on attachment 487885 [details] [diff] [review] patch >diff --git a/configure.in b/configure.in >+# Run freetype configure scrip "script". >+ >+if test "$MOZ_TREE_FREETYPE"; then >+ export+ export+ export+ export+ export+ ac_configure_args="$ac_configure_args --host=$host" You may want to sanity-check this, since the meaning of --host and --target is different in our configure and every other configure. In our configure --host is the build machine, and --target is the thing you're compiling for, but in every other configure --build is the build machine, --host is the thing you're compiling for, and --target is the platform your binaries will generate code for (if you were building a compiler). >+ AC_OUTPUT_SUBDIRS(modules/freetype2) >+fi I take it freetype's configure script doesn't know how to calculate these values correctly, which is why we have to pass them down from our configure? Does the freetype configure work with MSVC? If not, please make --enable-tree-freetype fail when using MSVC. r=me with those fixes.
Attachment #487885 - Flags: review?(ted.mielczarek) → review+
Before you check this in, *please* make sure the thing is building with -fPIC.
carrying ted's review
Attachment #487885 - Attachment is obsolete: true
Attachment #489919 - Flags: review+
(In reply to comment #10) > Created attachment 489919 [details] [diff] [review] > patch for checkin > > carrying ted's review IIRC CPPFLAGS are for the c preprocessor and CXXFLAGS are for the c++ compiler so the -fPIC in CPPFLAGS isn't necessary, though I guess harmless if it still builds.
found a configure flag for -fPIC, which I like better
Attachment #489919 - Attachment is obsolete: true
pushed
Status: ASSIGNED → RESOLVED
Closed: 9 years ago
Resolution: --- → FIXED
Flags: in-testsuite-
Whiteboard: [has-patch]
Target Milestone: --- → mozilla2.0b8
Product: Core → Firefox Build System | https://bugzilla.mozilla.org/show_bug.cgi?id=609114 | CC-MAIN-2019-51 | refinedweb | 655 | 55.34 |
Using a codec in a Grails unit test
February 24, 2010 14.
A couple of typos: I wrapped the XSS attack in a <script> tag, but of course when I posted the result here the tag was lost. I should have escaped the angle brackets.
Also, in the last code listing, the method is loadCodec, not loadCode.
Thanks! Had the very same problem a couple of days ago but solved it with a metaClass-hack, this is a much nicer solution.
Another little type – the code should say String.metaClass, not String.metaclass
Sweet, thanks.. asked the question; found the answer
Nice
Came across a similar use case in which I had to use a bit of code which was using encodeAsURL()
This approach worked like a charm! Thanks. 🙂
— Vivek
I found you can use the loadCodec to access the included codecs… For some reason, the customers ones in grails-app/utils don’t load either directly or via the loadCodec.
What I used.
import org.codehaus.groovy.grails.plugins.codecs.*
.
.
.
protected void setUp() {
super.setUp()
println “loading codecs”
loadCodec (HTMLCodec)
loadCodec (Base64Codec)
loadCodec (SHA1Codec)
// loadCodec (UnderscoreCodec) // custom but if included, not loaded for some reason.
println “loaded Codecs”
loadedCodecs.each { println it.toString() }
}
.
.
.
void testSimpleConstraints() {
// in order to not need to be an intgr. test.
//
mockLogging(User)
mockForConstraintsTests(User)
def user = new User(login:”someone”,
password:”blah”.encodeAsSHA1(),
role:”SuperUser”)
// oops—role should be either ‘admin’ or ‘user’
// will the validation pick that up?
assertFalse user.validate()
// mocking check.
assertEquals “inList”, user.errors[“role”]
}
Thanks, this was really helpful
Pingback: Podcast grails.org.mx: Episodio 6 de la Temporada 1: Desarrollo web con Groovy | GrailsMX
Thanks for this!
I’m happy to discover all these.
this helped a lot! although my final solution is using String.metaClass, not String.metaclass like the original post says (thanks to the commenter that noticed this also)
Pingback: Podcast grails.org.mx: Episodio 6 de la Temporada 1: Desarrollo web con Groovy |
Grails 2.4.3 GrailsUnitTestMixin offers mockCodec method.
@TestMixin(GrailsUnitTestMixin)
class CheckForOrderUpdateJobSpec extends Specification {
def setup() {
mockCodec(MD5Codec.class)
}
}
Pingback: 在Grails单元测试中使用Codec的两种方法 – grails开发平台
Thanks, this helped me see why my code was failing!
I think for Unit tests, you should mock the encodeAsHTML method, since your not testing its code.
For example:
String.metaClass.encodeAsHTML = { -> return ‘Some String’ }
This way you can just test that it was called.
Thanks again! | https://kousenit.org/2010/02/24/using-a-codec-in-a-grails-unit-test/ | CC-MAIN-2019-22 | refinedweb | 398 | 60.72 |
very good one...thanks a lot
very good one...thanks a lot
Hi Everybody,
I made a small sample about using HashMaps in Java ,and i hope to be useful to everyone what to know how to manipulate with it.
/**
* @author : Mohamed Saleh AbdEl-Aziz
*/...
Thanks a lot helloworld922,
It just a tip to view how to interact with binary data and files...
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import...
For you Hassan
in main method..Take an instance of your class and your program will run successfuly
Or
new YOUR_CLASS_NAME();
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange()== evt.SELECTED && evt.getItem().toString().equals("Item 1"))
{
...
I got this sample from JavaPassion site.It's great one for beginners
it's very good sample about getting current Threads information...
Hi everybody i did a small sample about using Timers in Java it's so simple to use.The main idea that you want to execute simple process every specific time.
import java.util.Timer;
import...
Class number 1
class PrintNameThread extends Thread
{
public PrintNameThread(String name) {
super(name);
}
public void run(){
Hi Everybody.
I'm trying to used these classes but i got an error about package.This is my sample
import java.nio.file.Paths;
public class UsingPaths {
public static void main(String args[])...
Thanks a lot for hint.
i was tired.
Thanks a lot for your replay....
but what do you talking about i can't see it...???
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.border.*;
import javax.swing.JFrame;
import javax.swing.JList;
import...
I'm trying to implement simple sample about using JRadioButton and i don't know Why some Buttons works and others not
That is my code...
import java.awt.FlowLayout;
import java.awt.Font;...
Thanks Json for your replay.
Hi Everybody,
I just what to know why some samples contains this portion in calling main method
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new...
Never mind JavaPF,That's the main purpose form the forum.
Thanks again....
Thanks a lot for your comment again...I will do my best.
Thanks a lot for your comment...I'm just want to do what i have to do in this new and great forum
This example code shows you how to use a JSlider swing component.
import java.awt.BorderLayout;
import java.awt.Color;
import...
Please PF if you make comments for this sample.
Thanks for your help
I hope to be useful for everyone.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
//Note : Java can't insert...
This sample demonstrate how to pass unlimited arguments to your function and how to know object types passed to your function.
public class UnlimitedArgs {
/** Default constructor */...
Thanks a lot for your effort
Perfect sample....Good Person
Thanks all for replay... | http://www.javaprogrammingforums.com/search.php?s=3d9750d051b310451dd7dd21fbf16f73&searchid=246588 | CC-MAIN-2016-36 | refinedweb | 500 | 62.64 |
Hello, im beginning to write a program to calculate the determinant of a 3x3 matrix - i need to read the elements of the matrix from an external file matrix.dat (contains 9 numbers, 3 rows, 3 columns seperated by spaces)
I have written the first part of the program - reading from the file: It compiles but doesnt work, i got it to print a value from the matrix to see if it read it but when i run the program it says 0.00000, implying a problem
where have i gone wrong? thanks so much!
Code:#include <stdio.h> #include <stdlib.h> #include <math.h> /*need to use an external function to computer det of a minor (2x2 matrix)*/ /*Need to read from a file named matrix.dat*/ /* Prototype your function here, also make sure you change all of these comments*/ int ReadFromFile(float fullmatrix[3][3], FILE *input); int main(int argc, char* argv[]) { FILE *input; int i, j; float fullmatrix[3][3]; const char inp_fn[]="matrix.dat"; /* Open files */ input = fopen(inp_fn, "r"); /* Check the pointers to files are not NULL, also check matrix has correct number of elements */ if( (input != (FILE*) NULL) ) { for(i=0; i<3; i++) { for(j=0; j<3; j++) { fullmatrix[i][j]=ReadFromFile(fullmatrix, input); } fscanf(input, "\n"); } fclose(input); printf("%f", fullmatrix[2][2]); return(0); } else { printf("*** Could not open input file, or there are not 9 elements in the matrix ***\n"); } } /*Write the external fucntion here, need a 2 dimensional array*/ int ReadFromFile(float fullmatrix[3][3], FILE *input) { float element; fscanf(input,"%i,", &element); return (element); } | http://cboard.cprogramming.com/c-programming/132211-reading-2d-array-file-compiles-but-doesnt-work-properly.html | CC-MAIN-2015-14 | refinedweb | 268 | 56.49 |
This page shows you how to reduce the risk of privilege escalation attacks in your cluster by telling Google Kubernetes Engine (GKE) to schedule your workloads on a separate, dedicated node pool away from privileged GKE-managed workloads.
Overview
GKE clusters use privileged GKE-managed workloads to enable specific cluster functionality and features, such as metrics gathering. These workloads are given special permissions to run correctly in the cluster.
Workloads that you deploy to your nodes might have the potential to be compromised by a malicious entity. Running these workloads alongside privileged GKE-managed workloads means that an attacker who breaks out of a compromised container can use the credentials of the privileged workload on the node to escalate privileges in your cluster.
Preventing container breakouts
Your primary defense should be your applications. GKE has multiple features that you can use to harden your clusters and Pods. In most cases, we strongly recommend using GKE Sandbox to isolate your workloads. GKE Sandbox is based on the gVisor open source project, and implements the Linux kernel API in the userspace. Each Pod runs on a dedicated kernel that sandboxes applications to prevent access to privileged system calls in the host kernel. Workloads running in GKE Sandbox are automatically scheduled on separate nodes, isolated from other workloads.
You should also follow the recommendations in Harden your cluster's security.
Avoiding privilege escalation attacks
If you can't use GKE Sandbox, and you want an extra layer of isolation in addition to other hardening measures, you can use node taints and node affinity to schedule your workloads on a dedicated node pool. A node taint tells GKE to avoid scheduling workloads without a corresponding toleration (such as GKE-managed workloads) on those nodes. The node affinity on your own workloads tells GKE to schedule your Pods on the dedicated nodes.
Limitations of node isolation
- Attackers can still initiate Denial-of-Service (DoS) attacks from the compromised node.
- Compromised nodes can still read many resources, including all Pods and namespaces in the cluster.
- Compromised nodes can access Secrets and credentials used by every Pod running on that node.
- Using a separate node pool to isolate your workloads can impact your cost efficiency, autoscaling, and resource utilization.
- Compromised nodes can still bypass egress network policies.
- Some GKE-managed workloads must run on every node in your cluster, and are configured to tolerate all taints.
- If you deploy DaemonSets that have elevated permissions and can tolerate any taint, those Pods may be a pathway for privilege escalation from a compromised node.
How node isolation works
To implement node isolation for your workloads, you must do the following:
- Taint and label a node pool for your workloads.
- Update your workloads with the corresponding toleration and node affinity rule.
This guide assumes that you start with one node pool in your cluster. Using node affinity in addition to node taints isn't mandatory, but we recommend it because you benefit from greater control over scheduling.
Before you begin
Before you start, make sure you have performed the following tasks:
- Ensure that you have enabled the Google Kubernetes Engine API.Enable Google Kubernetes Engine API
- Ensure that you have installed the Google Cloud CLI.
- Set up default Google Cloud CLI CLI CLI like the
following:
One of [--zone, --region] must be supplied: Please specify location.
- Choose a specific name for the node taint and the node label that you want to use for the dedicated node pools. For this example, we use
workloadType=untrusted.
Taint and label a node pool for your workloads
Create a new node pool for your workloads and apply a node taint and a node label. When you apply a taint or a label at the node pool level, any new nodes, such as those created by autoscaling, will automatically get the specified taints and labels.
You can also add node taints and node labels to existing node pools. If you use
the
NoExecute effect, GKE evicts any Pods running on those
nodes that don't have a toleration for the new taint.
To add a taint and a label to a new node pool, run the following command:
gcloud container node-pools create POOL_NAME \ --cluster CLUSTER_NAME \ --node-taints KEY=VALUE:EFFECT \ --node-labels NODE_LABELS
Replace the following:
POOL_NAME: the name of the new node pool for your workloads.
CLUSTER_NAME: the name of your GKE cluster.
KEY=VALUE: a key value pair associated with a scheduling
EFFECT. For example,
workloadType=untrusted.
EFFECT: one of the following effect values:
NoSchedule,
PreferNoSchedule, or
NoExecute.
NoExecuteprovides a better eviction guarantee than
NoSchedule.
Add a toleration and a node affinity rule to your workloads
After you taint the dedicated node pool, no workloads can schedule on it unless they have a toleration corresponding to the taint you added. Add the toleration to the specification for your workloads to let those Pods schedule on your tainted node pool.
If you labelled the dedicated node pool, you can also add a node affinity rule to tell GKE to only schedule your workloads on that node pool.
The following example adds a toleration for the
workloadType=untrusted:NoExecute taint and a node affinity rule for the
workloadType=untrusted node label.
kind: Deployment apiVersion: apps/v1 metadata: name: my-app namespace: default labels: app: my-app spec: replicas: 1 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: tolerations: - key: workloadType operator: Equal value: untrusted affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: workloadType operator: In values: - "untrusted" containers: - name: sleep image: ubuntu command: ["/bin/sleep", "inf"]
When you update your Deployment with
kubectl apply, GKE
recreates the affected Pods. The node affinity rule forces the Pods onto the
dedicated node pool that you created. The toleration allows only those Pods to be
placed on the nodes.
Verify that the separation works
To verify that the scheduling works correctly, run the following command and check whether your workloads are on the dedicated node pool:
kubectl get pods -o=wide
Recommendations and best practices
After setting up node isolation, we recommend that you do the following:
- Restrict specific node pools to GKE-managed workloads only by adding the
components.gke.io/gke-managed-componentstaint. Adding this taint prevents your own Pods from scheduling on those nodes, improving the isolation.
- When creating new node pools, prevent most GKE-managed workloads from running on those nodes by adding your own taint to those node pools.
- Whenever you deploy new workloads to your cluster, such as when installing third-party tooling, audit the permissions that the Pods require. When possible, avoid deploying workloads that use elevated permissions to shared nodes.
What's next
- Learn more about GKE Sandbox.
- Learn about GKE Autopilot, which implements many GKE security features by default. | https://cloud.google.com/kubernetes-engine/docs/how-to/isolate-workloads-dedicated-nodes | CC-MAIN-2022-27 | refinedweb | 1,124 | 51.48 |
Simple base32 encode/decode matching the base32 method used by Google Authenticator.
Features:
pub.dartlang.org: (you can use 'any' instead of a version if you just want the latest always)
dependencies: base32: 0.0.7
import 'package:base32/base32.dart';
Start encoding/decoding ...
// Encode a hex string to base32 base32.encodeHexString('48656c6c6f21deadbeef'); // -> 'JBSWY3DPEHPK3PXP' // base32 decoding to original string. base32.decode("JBSWY3DPEHPK3PXP"); // -> '48656c6c6f21deadbeef'
Generate and return a RFC4122 v1 (timestamp-based) UUID.
byteList- (List) A list of bytes representing your input.
Returns
String representation of the encoded base32.
Generate and return a RFC4122 v4 UUID.
hexString- (String) A string of hex values intended to be converted to bytes and encoded.
Returns
String representation of the encoded base32
Example: Encode a hex string.
base32.encodeHexString('48656c6c6f21deadbeef'); // -> 'JBSWY3DPEHPK3PXP'
Decodes a base32 string back to its original byte values.
base32- (String) The base32 string you wish to decode.
Returns
Uint8List of the decoded data.
Example: Decode a base32 string, then output it in hex format
var decoded = base32.decode("JBSWY3DPEHPK3PXP"); var decodedHex = CryptoUtils.bytesToHex(decoded); // -> '48656c6c6f21deadbeef'
In dartvm
dart test\base32_test.dart
In Browser
At the moment, this package does not work client-side as it uses server-side only UInt8Lists. I might have to wait till UInt8Arrays and UInt8Lists are merged into 1
v0.1.2 - Merge Pull Request to move most dependencies to dev_dependecies
v0.1.0 & v0.1.1wq - Updates for Dart 1.0 readiness.
v0.0.8 - Fix crypto import in the test.
v0.0.7 - Fix for typed_data name change. Thanks to the pull requestor for bringing it to my attention and fixing it.
v0.0.6 - Fix for language changes.
v0.0.5 - Fix for language changes.
v0.0.4 - Fixes and changes for M3 - New hex to byte converter.
v0.0.3 - Made all functions static.
v0.0.2 - Fixed unittest dependency
v0.0.1 - Initial Documented Release
Add this to your package's pubspec.yaml file:
dependencies: base32: ">=0.1.2 <0.2:base32/
base32.dart';base32.dart'; | https://pub.dartlang.org/packages/base32 | CC-MAIN-2015-11 | refinedweb | 333 | 62.64 |
Hi, is there a reason why there is no monadic version of "until" in the Haskell libraries? It would be defined as follows: untilM :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a untilM p f x | p x = return x | otherwise = f x >>= untilM p f The same applies to scanM, also not part of the libraries: scanM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a] scanM f q [] = return [q] scanM f q (x:xs) = do q2 <- f q x qs <- scanM f q2 xs return (q:qs) I often find myself in need for these. To me these seem idiomatic enough to be included in the library. But since they is not, I guess there must be another, more idiomatic way to do this. Thank you, Jan | http://www.haskell.org/pipermail/beginners/2009-January/000667.html | CC-MAIN-2014-42 | refinedweb | 133 | 78.72 |
Hello,
I'm trying to bring some assemblies into my bin folder for my website. I've got some C# script on the page that references and uses the assemblies. It looks like this:
Code:
<%@>
...
I can create a new MySqlConnection object just fine but it's the System.Windows.Forms object (or namespace?) that's giving me trouble.
I found the dll in C:\Windows\Microsoft.NET\assembly\GAC_MSIL and copied it over to my wwwroot/bin/ folder.
The error I get when I try to load the page is:
[error]
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'System.Windows.Forms'64\v2.0.50727\Config\web.config Line: 59
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Windows.Forms'.5456; ASP.NET Version:2.0.50727.5456
[/error]
So it says that the assembly I copied over was built more recently than whatever's already loaded (that's how I'm interpreting it at least). It tells me where the exact location of the problem is (line 59 in web.config) and that's where you see the <add assembly="*"/> but it doesn't tell me what to replace it with. It also tells me how to turn assembly binding logging off (whatever assembly binding means), but I don't seem to have the registry path it gives me on my computer.
<%@>
...
If you are using an Integrated Development Environment (IDE) such as Visual Studio or SharpDevelop, you should not be copying core .Net Framework files into your bin folder manually. Use the AddReference dialog to add a reference, this will prompt the IDE to copy the file to your bin folder at compile time. The advantage to this is that the dialog will be famaliar with what is available in the specific .Net Framework version that you are working with, and present those choices as a list that you can select from. By adding a reference through the dialog, the IDE knows to copy the proper Framework dll into your bin folder for access by your application. The web.config file will also be updated by the IDE to reference the proper dll file.
If you are developing without an IDE, using a text editor and the commald line tools, you must be exceedingly careful that all of the dll files that you use are from the same version/build of the .Net Framework. However, with all of the free choices of IDE out there today for developing under .Net, it seems a bit foolish not to use one. (Visual Studio Express from Microsoft and SharpDevelop from icsharpcode to name the two most popular)
Now, on to your code sample:
You must realize that, when developing a web page, some of the code runs on the server and some of the code runs at the client in their browser.
When a page is requested by the client's browser, the server-side code performs any processing necessary and generates the markup to be rendered by the client's browser and any script that will be run by the client's browser. This markup and script is sent back to the requesting browser. This is called a request/response pair and is primarily how the web works (much simplified).
The server-side code has access to the resources of the server and the client-side script has access to any browser resources made available by the browser's implementation of the Domain Object Model (DOM). The two of them do not have any direct accesss to the resources exposed by the other.
The call you are making to System.Windows.Forms.MessageBox.Show, even if it worked (I don't believe it will work though, IIS should block it and may throw an Exception), would pop up a dialog at the server, not on the client. In order to pop up a dialog at the client, you must use the browser's resources through a call in script to alert("your message here") or window.open() (you should Google window.open if you want to use it as it has many parameters to control how the new window opens and the specifics of it's use are a bit beyond the depth of this discussion).
Thanks CGKevin,
I downloaded VS 2012 Exp. Web and I'm developing in that now.
Forum Rules | http://forums.codeguru.com/showthread.php?528939-assembly-reference-not-working-in-C-script&p=2090767 | CC-MAIN-2014-35 | refinedweb | 762 | 61.56 |
As part of the
ipyrad.analysis toolkit we've created convenience functions for easily distributing STRUCTURE analysis jobs on an HPC cluster, and for doing so in a programmatic and reproducible way. Importantly, our workflow allows you to easily sample different distributions of unlinked SNPs among replicate analyses, with the final inferred population structure summarized from a distribution of replicates. We also provide some simple examples of interactive plotting functions to make barplots.. We make use of the
ipyparallel Python library to distribute STRUCTURE jobs across processers in parallel (more can be found about that here). structure -c ipyrad ## conda install clumpp -c ipyrad ## conda install toytree -c eaton-lab
import ipyrad.analysis as ipa ## ipyrad analysis toolkit import ipyparallel as ipp ## parallel processing import toyplot ## plotting library
Start an
ipcluster instance in a separate terminal. An easy way to do this in a jupyter-notebook running on an HPC cluster is to go to your Jupyter dashboard, and click [new], and then [terminal], and run '
ipcluster start' in that terminal. This will start a local cluster on the compute node you are connected to. See our [ipyparallel tutorial] (coming soon) for further details.
## ## ipcluster start --n=4 ##
## get parallel client ipyclient = ipp.Client() print "Connected to {} cores".format(len(ipyclient))
Connected to 4 cores
## set N values of K to test across kvalues = [2, 3, 4, 5, 6]
## init an analysis object s = ipa.structure( name="quick", workdir="./analysis-structure", data="./analysis-ipyrad/pedic-full_outfiles/pedic-full.ustr", ) ## set main params (use much larger values in a real analysis) s.mainparams.burnin = 1000 s.mainparams.numreps = 5000 ## submit N replicates of each test to run on parallel client for kpop in kvalues: s.run(kpop=kpop, nreps=4, ipyclient=ipyclient) ## wait for parallel jobs to finish ipyclient.wait()
submitted 4 structure jobs [quick-K-2] submitted 4 structure jobs [quick-K-3] submitted 4 structure jobs [quick-K-4] submitted 4 structure jobs [quick-K-5] submitted 4 structure jobs [quick-K-6]
True
## return the evanno table (deltaK) for best K etable = s.get_evanno_table(kvalues) etable
## get admixture proportion tables avg'd across reps tables = s.get_clumpp_table(kvalues, quiet=True)
## plot bars for a k-test in tables w/ hover labels table = tables[3].sort_values(by=[0, 1, 2]) toyplot.bars( table, width=500, height=200, title=[[i] for i in table.index.tolist()], xshow=False, );
The
.str file is a structure formatted file output by ipyrad. It includes all SNPs present in the data set. The
.snps.map file is an optional file that maps which loci each SNP is from. If this file is used then each replicate analysis will randomly sample a single SNP from each locus in reach rep. The results from many reps therefore will represent variation across unlinked SNP data sets, as well as variation caused by uncertainty. The
workdir is the location where you want output files to be written and will be created if it does not already exist.
## the structure formatted file strfile = "./analysis-ipyrad/pedic-full_outfiles/pedic-full.str" ## an optional mapfile, to sample unlinked SNPs mapfile = "./analysis-ipyrad/pedic-full_outfiles/pedic-full.snps.map" ## the directory where outfiles should be written workdir = "./analysis-structure/"
Structure is kind of an old fashioned program that requires creating quite a few input files to run, which makes it not very convenient to use in a programmatic and reproducible way. To work around this we've created a convenience wrapper object to make it easy to submit Structure jobs and to summarize their results.
## create a Structure object struct = ipa.structure(name="structure-test", data=strfile, mapfile=mapfile, workdir=workdir)
Our Structure object will be used to submit jobs to the cluster. It has associated with it a name, a set of input files, and a large number of parameter settings. You can modify the parameters by setting them like below. You can also use tab-completion to see all of the available options, or print them like below. See the full structure docs here for further details on the function of each parameter. In support of reproducibility, it is good practice to print both the mainparams and extraparams so it is clear which options you used.
## set mainparams for object struct.mainparams.burnin = 10000 struct.mainparams.numreps = 100000 ## see all mainparams print struct.mainparams ## see or set extraparams print struct.extraparams
burnin 10000 extracols 0 label 1 locdata 0 mapdistances 0 markernames 0 markovphase 0 missing -9 notambiguous -999 numreps 100000 onerowperind 0 phased 0 phaseinfo 0 phenotype 0 ploidy 2 popdata 0 popflag 0 recessivealleles 0 admburnin 500 alpha 1.0 alphamax 10.0 alphapriora 1.0 alphapriorb 2.0 alphapropsd 0.025 ancestdist 0 ancestpint 0.9 computeprob 1 echodata 0 fpriormean 0.01 fpriorsd 0.05 freqscorr 1 gensback 2 inferalpha 1 inferlambda 0 intermedsave 0 lambda_ 1.0 linkage 0 locispop 0 locprior 0 locpriorinit 1.0 log10rmax 1.0 log10rmin -4.0 log10rpropsd 0.1 log10rstart -2.0 maxlocprior 20.0 metrofreq 10 migrprior 0.01 noadmix 0 numboxes 1000 onefst 0 pfrompopflagonly 0 popalphas 0 popspecificlambda 0 printlambda 1 printlikes 0 printnet 1 printqhat 0 printqsum 1 randomize 0 reporthitrate 0 seed 12345 sitebysite 0 startatpopinfo 0 unifprioralpha 1 updatefreq 10000 usepopinfo 0
The function
run() distributes jobs to run on the cluster and load-balances the parallel workload. It takes a number of arguments. The first,
kpop, is the number of populations. The second,
nreps, is the number of replicated runs to perform. Each rep has a different random seed, and if you entered a mapfile for your Structure object then it will subsample unlinked snps independently in each replicate. The
seed argument can be used to make the replicate analyses reproducible. The
extraparams.seed parameter will be generated from this for each replicate. And finally, provide it the
ipyclient object that we created above. The structure object will store an asynchronous results object for each job that is submitted so that we can query whether the jobs are finished yet or not. Using a simple for-loop we'll submit 20 replicate jobs to run at four different values of K.
## a range of K-values to test tests = [3, 4, 5, 6]
## submit batches of 20 replicate jobs for each value of K for kpop in tests: struct.run( kpop=kpop, nreps=20, seed=12345, ipyclient=ipyclient, )
submitted 20 structure jobs [structure-test-K-3] submitted 20 structure jobs [structure-test-K-4] submitted 20 structure jobs [structure-test-K-5] submitted 20 structure jobs [structure-test-K-6]
You can check for finished results by using the
get_clumpp_table() function, which tries to summarize the finished results files. If no results are ready it will simply print a warning message telling you to wait. If you want the notebook to block/wait until all jobs are finished then execute the
wait() function of the ipyclient object, like below.
## see submitted jobs (we query first 10 here) struct.asyncs[:10]
[<AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>, <AsyncResult: _call_structure>]
## query a specific job result by index if struct.asyncs[0].ready(): print struct.asyncs[0].result()
## block/wait until all jobs finished ipyclient.wait()
We ran 20 replicates per K-value hypothesis. We now need to concatenate and purmute those results so they can be summarized. For this we use the software clumpp. The default arguments to clumpp are generally good, but you can modify them the same as structure params, by accessing the
.clumppparams attribute of your structure object. See the clumpp documentation for more details. If you have a large number of samples (>50) you may wish to use the
largeKgreedy algorithm (m=3) for faster runtimes. Below we run clumpp for each value of K that we ran structure on. You only need to tell the
get_clumpp_table() function the value of K and it will find all of the result files given the Structure object's
name and
workdir.
## set some clumpp params struct.clumppparams.m = 3 ## use largegreedy algorithm struct.clumppparams.greedy_option = 2 ## test nrepeat possible orders struct.clumppparams.repeats = 10000 ## number of repeats struct.clumppparams
datatype 0 every_permfile 0 greedy_option 2 indfile 0 m 3 miscfile 0 order_by_run 1 outfile 0 override_warnings 0 permfile 0 permutationsfile 0 permuted_datafile 0 popfile 0 print_every_perm 0 print_permuted_data 0 print_random_inputorder 0 random_inputorderfile 0 repeats 10000 s 2 w 1
## run clumpp for each value of K tables = struct.get_clumpp_table(tests)
[K3] 20/20 results permuted across replicates (max_var=0). [K4] 20/20 results permuted across replicates (max_var=0). [K5] 20/20 results permuted across replicates (max_var=0). [K6] 20/20 results permuted across replicates (max_var=0).
## return the evanno table w/ deltaK struct.get_evanno_table(tests)
## custom sorting order myorder = [ "32082_przewalskii", "33588_przewalskii", "41478_cyathophylloides", "41954_cyathophylloides", "29154_superba", "30686_cyathophylla", "33413_thamno", "30556_thamno", "35236_rex", "40578_rex", "35855_rex", "39618_rex", "38362_rex", ] print "custom ordering" print tables[4].ix[myorder]
custom ordering 0 1 2 3 32082_przewalskii 1.0 0.000 0.000e+00 0.000 33588_przewalskii 1.0 0.000 0.000e+00 0.000 41478_cyathophylloides 0.0 0.005 9.948e-01 0.000 41954_cyathophylloides 0.0 0.005 9.948e-01 0.000 29154_superba 0.0 0.019 6.731e-01 0.308 30686_cyathophylla 0.0 0.020 6.820e-01 0.298 33413_thamno 0.0 0.845 0.000e+00 0.155 30556_thamno 0.0 0.892 7.000e-04 0.107 35236_rex 0.0 0.908 1.000e-04 0.092 40578_rex 0.0 0.989 2.000e-04 0.010 35855_rex 0.0 0.990 0.000e+00 0.010 39618_rex 0.0 1.000 0.000e+00 0.000 38362_rex 0.0 1.000 0.000e+00 0.000
The function automatically parses the table above for you. It can reorder the individuals based on their membership in each group, or based on an input list of ordered names. It returns the table of data as well as a list with information for making interactive hover boxes, which you can see below by hovering over the plots.
def hover(table): hover = [] for row in range(table.shape[0]): stack = [] for col in range(table.shape[1]): label = "Name: {}\nGroup: {}\nProp: {}"\ .format(table.index[row], table.columns[col], table.ix[row, col]) stack.append(label) hover.append(stack) return list(hover)
for kpop in tests: ## parse outfile to a table and re-order it table = tables[kpop] table = table.ix[myorder] ## plot barplot w/ hover canvas, axes, mark = toyplot.bars( table, title=hover(table), width=400, height=200, xshow=False, style={"stroke": toyplot.color.near_black}, )
## save plots for your favorite value of K table = struct.get_clumpp_table(kpop=3) table = table.ix[myorder]
mean scores across 20 replicates.
## further styling of plot with css style = {"stroke":toyplot.color.near_black, "stroke-width": 2} ## build barplot canvas = toyplot.Canvas(width=600, height=250) axes = canvas.cartesian(bounds=("5%", "95%", "5%", "45%")) axes.bars(table, title=hover(table), style=style) ## add names"} axes.x.spine.style = style axes.y.show = False ## options: uncomment to save plots. Only html retains hover. import toyplot.svg import toyplot.pdf import toyplot.html toyplot.svg.render(canvas, "struct.svg") toyplot.pdf.render(canvas, "struct.pdf") toyplot.html.render(canvas, "struct.html") ## show in notebook canvas
struct.get_evanno_table([3, 4, 5, 6])
The
.get_evanno_table() and
.get_clumpp_table() functions each take an optional argument called
max_var_multiple, which is the max multiple by which you'll allow the variance in a 'replicate' run to exceed the minimum variance among replicates for a specific test. In the example below you can see that many reps were excluded for the higher values of K, such that fewer reps were analyzed for the final results. By excluding the reps that had much higher variance than other (one criterion for asking if they converged) this can increase the support for higher K values. If you apply this method take care to think about what it is doing and how to interpret the K values. Also take care to consider whether your replicates are using the same input SNP data but just different random seeds, or if you used a
map file, in which case your replicates represent different sampled SNPs and different random seeds. I'm of the mind that there is no true K value, and sampling across a distribution of SNPs across many replicates gives you a better idea of the variance in population structure in your data.
struct.get_evanno_table([3, 4, 5, 6], max_var_multiple=50.)
[K3] 4 reps excluded (not converged) see 'max_var_multiple'. [K4] 11 reps excluded (not converged) see 'max_var_multiple'. [K5] 1 reps excluded (not converged) see 'max_var_multiple'. [K6] 17 reps excluded (not converged) see 'max_var_multiple'.. | https://nbviewer.org/github/dereneaton/ipyrad/blob/0.9.63/tests/cookbook-structure-pedicularis.ipynb | CC-MAIN-2021-43 | refinedweb | 2,120 | 59.09 |
SwiftBar plugin for storing text snippets
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Introduction
I found that I was constantly referring to the IPython documentation to look up the code for the autoreload magic command and wished there was an easy place for me to keep and access these sort of “oft-copied” texts. I realized I could just build a simple SwiftBar application and put these snippets in my menu bar.
SwiftBar
SwiftBar is a macOS tool for quickly creating a menu bar application. It is as simple as writing an executable script (in any language) that prints to Standard Out in a specified format. The documentation is very good and there are many examples, so I highly recommend diving in if this seems at all interesting to you. It is really pretty simple to get a good looking and functional menu bar application.
Explaining the code
Below, I go through the major portions of the script. The entire script is available on my SwiftBar plugin GitHub repo.
Copied-text information
First, the copied text is just organized as a dictionary, shown below. The keys are recognizable labels for the text that will appear in the menu bar, and the values are the snippets that get copied. Currently, I only have one snippet, but as I find more, I just need to add them to this dictionary.
COPY_TEXT_INFO: Final[dict[str, str]] = { "IPython autoreload": "%load_ext autoreload\n%autoreload 2" }
Instructions for SwiftBar
Below are the two functions for adding a copyable snippet to the menu bar.
The
_copyables() function just runs each key-value pair in
COPY_TEXT_INFO through
_format_copyable().
This function just organizes the data into the correct format for SwiftBar to parse.
def _format_copyable(title: str, text: str) -> str: out = f"{title} | bash={self_path} param0='--to-copy={title}'" text = text.replace("\n", "\\\\n") out += f" tooltip='{text}'" out += " refresh=true terminal=false" return out def _copyables() -> None: for title, text in COPY_TEXT_INFO.items(): print(_format_copyable(title, text)) return None
Below is an example of the output (I’ve made it multi-line so it is easier to read). This is parsed by SwiftBar into the option in the drop down menu pictured at the top of this post.
IPython autoreload | bash=oft-copied.1h.py param0='--to-copy=IPython autoreload' tooltip='%load_ext autoreload\\n%autoreload 2' refresh=true terminal=false
Adding text to Pasteboard in Python
Below is the function that actually adds from text to the Pasteboard. There are Python libraries that can do this, but they seem like an unnecessary dependency for this simple process. If I run into any weird behavior with new snippets, though, then I will likely try them out.
def copy_text(title: str) -> None: """Copy desired text to pasteboard. Args: title (str): Title of the copyable text in the look-up table. """ text = COPY_TEXT_INFO[title] p1 = subprocess.Popen(["echo", text], stdout=subprocess.PIPE) p2 = subprocess.Popen(["pbcopy"], stdin=p1.stdout) if p1.stdout is not None: p1.stdout.close() if p2.stdin is not None: p2.stdin.close() return None
Method dispatch per script input
The code below is the entry point for the script when it is run. Ideally, I could use the ‘Tpyer’ library how it is intended, but there is not a native way to have ‘Typer’ use a default command. The default command (i.e. when to argument is supplied when the script is run) would run the normal SwiftBar-output-generating function, and then different commands could be used to run the other features (adding text to the Pasteboard, in this case). There is a workaround, but I chose to keep it simpler here.1
I just have a single ‘Typer’ command,
main(), that takes an optional input and uses that input to decide which methods to run.
If no argument is supplied, then the normal SwiftBar output is produced by calling
swiftbar_app().
If an argument is supplied, then it should be a key in
COPY_TEXT_INFO and the corresponding value will be added to Pasteboard in the
copy_text() function.
@app.command() def main(to_copy: Optional[str] = None) -> None: """Primary entry point for the SwiftBar application. This function handles the possible input and runs the appropriate method: - If there is no input, then the SwiftBar application information needs to be presented for SwiftBar. - If a string is provided, then the corresponding text needs to be added to the pasteboard. Args: to_copy (Optional[str], optional): Title of the text to copy. Defaults to None. """ if to_copy is not None: copy_text(to_copy) else: swiftbar_app() return None if __name__ == "__main__": app()
Other useful options in the app
To finish, I thought I would just point out two other nice options I’ve included in the app.
The first is a Refresh button that has SwiftBar re-run the script. This is useful if I’ve added a new snippet and want it to appear in the menu bar app now (instead of the next time SwiftBar runs it according to the 1 hour schedule).
def _refresh() -> None: print("---") print(":arrow.clockwise: Refresh | symbolize=true refresh=true terminal=false") return None
The second helpful feature I’ve added is an Edit button that opens the script up in TextMate. I imagine using this to quickly add a new snippet.
def _edit() -> None: out = ":pencil.tip.crop.circle: Edit... | symbolize=true" out += f" bash='mate' param0='{str(plugin_path)}'" out += " refresh=true terminal=false" print(out) return. | https://www.r-bloggers.com/2022/01/swiftbar-plugin-for-storing-text-snippets/ | CC-MAIN-2022-40 | refinedweb | 917 | 64.2 |
Top Core Java Interview QuestionsNIT Manager
Core Java Interview Questions
1. Can we write static block within the method?
Answer:
No. Compiler will give error.
public class Test{
public static void main(String[] args) {
static{
}
}
}
Compiletime Error: Illegal start of expression.
2. Can we write return statement without value in constructors?
Answer: Yes.
public class Test{
Test(){
return;
}
public static void main(String[] args) {
{
System.out.println(“non static block”);
}
}
}
3.What is the difference between static and new keyword?
Answer:
New keyword is useful for providing memory for non-static data, it is individual, where as static keyword is useful for providing memory static data by default by JVM, it is common for all.
4.Is bellow code valid?
Answer:
public class Test{
public static void main(String[] args) {
final int a = 100;
a = 200;
}
}
No.
Once we initialize the final variable, we can’t reinitialize the variable again either with same value or different value.
5.What is the use of constructor?
Answer:
Constructor is useful for initialize the non-static variables meanwhile of object creation.
6.What is the use of preparer?
Answer:
Preparer is useful for providing default values for static variables in static loading phase.
7.What is the use of initializer?
Answer:
Initializer is useful for replacing default values with original values of static variables in static initialization phase.
8.What is the use of copy constructor?
Answer:
Mean while of creating object, if we want to copy the data from existed object to new creating object within the different memory location then we should use copy constructor.
9.Why should we go for constructor overloading?
Answer:
If we want perform different operations in different object creations mode then we should prefer constructor overloading.
Update Your Skills form Our Experts: Core Java Online Training
10.What is use of this () in java?
Answer:
This () method is useful for making communication between one constructor to another constructor within the same class.
11.What is use of super () in java?
Answer:
Super () method is useful for making communication between one constructor to another constructor between super and sub classes.
12.What is singleton?
Answer:
A class which is allows to programmer to create only one object.
13.What is use of non-static block?
Answer:
To make our logic/functionalities to common for all objects, mean while of object creation then we should use non-static block.
14.What is the difference between constructor and non-static block?
Answer:
To make our logic/functionalities to common for all we should use non-static block, whereas constructor is useful for providing different functionalities for different object.
15.Can we this and super keywords in static context?
Answer:
No, we are unable to use, the reason are by default non-static final reference variables.
16.What is use of static methods?
Answer:
If we are unable to create object for a class, but still if we want to execute some logic and if we are not giving to subclasses to change our logic then we should prefer static methods.
17.Can we write return statement without value in void method?
Answer: Yes.
18.What the difference between void and non-void method?
Answer: The method which is unable to carry information from called area to calling area is called void method the method which is able to carry the information from called area to calling area is called non-void method.
19.What is factory method?
Answer: A method which is returns either same class memory other class memory is called factory method.
20.What is factory class?
Answer: A class which is ready to returns memory for other classes is called factory class.
21.What is the use of abstract methods and concrete methods?
Answer: To providing rules or specifications to third party vendors we should use abstract methods, where as if we want provides implementations for specifications we should prefer concrete methods.
22.What is the use of default methods in java?
Answer: Without doing modifications to implementation classes if we want write logic to interface then we should use default methods. These are introduced in java 8.
23.How many interfaces do we have from java 1.7?
Answer:
- We have three interfaces from java 1.7.
- Normal interface/non-functional interface
- Functional interfaces
- Marker interfaces.
24.Can we write default methods in functional interface?
Answer:
Yes, we can write multiple default methods and java.lang.Object class methods also (abstract format only).
25.Can we override static, final, private methods?
Answer: No
26.What are required things to call methods?
Answer:
The following things are very much mandatory for calling any method. Those are
- Access modifier
- Modifier (static/non-static)
- Return type
- Method name
- Parameters(number of, type of , place of parameters)
- Throws keyword(Exceptions)
27.What is encapsulation?
Answer: The process of providing security for our data, if the end user is authorized then we should provides permissions to security data is called encapsuaiton.
28.What is marker interface and it usage?
Answer: The interface which contains zero abstract method is called marker interface, which is useful for making our object as specialized object to participated in special operations like serialization, cloning and etc…
29.How can we call abstract class constructor?
Answer: By creating object for its sub class.
30.Are interface talks about state of an object?
Answer: No. The reason is by default interface variables are public static final.
Update Your Skills form Our Experts: Core Java Online Training
31.Is java supports multiple inheritance?
Answer: Yes. Java supports multiple inheritance only through interfaces but not through classes.
32.What is method overloading?
Answer: The process of writing same method multiple times with different parameters is called method overloading.
33.What is method overriding?
Answer: The logic which is given by the java software or already existed, if that logic is not suitable for project requirement then we should write same method with different logic within the super and sub classes is called method overriding.
34.How many memories are given by the JVM meanwhile of subclass object creation?
Answer: JVM will provide only one memory for subclass but super class non-static data will come stored in sub class memory.
35.What is upcasting and its usage?
Answer: The process of placing sub class memory into super class reference variable is called upcasting.
If we are not aware about type of value and memory but still if we want hold then we should prefer upcasting.
36.What is downcasting and its usage?
Answer: The process of placing super class reference into sub class reference by using cast operator, but super class memory should contains sub class memory. With the support of upcasting reference variable we can able to communicating with super class data but not sub class data, if we want to communicating with sub class data then we should prefer downcasting.
37.What is the output of bellow code?
public class Test{
void m1(float x){
System.out.println(“m1-float: “+x);
}
void m1(int x){
System.out.println(“m1-int: “+x);
}
public static void main(String[] args) {
Test t = new Test();
t.m1(100);
}
}
Output: m1-int: 100
38.What is output of bellow code?
Answer: public class Test{
void m1(Object x){
System.out.println(“m1-Object: “+x);
}
void m1(String x){
System.out.println(“m1-String: “+x);
}
public static void main(String[] args) {
Test t = new Test();
t.m1(“ram”);
}
}
Output: m1-Sstring: ram
39.What is static and dynamic polymorphism?
Answer:
- The process of executing the method by JVM at runtime, which is binds by the compiler at compilation time, is called dynamic polymorphism.
- The process of executing the method from subclass by JVM at runtime, which is not binds by the compiler at compilation time, is called dynamic polymorphism.
40.What is immutable object and examples?
Answer: The process of unable to change the state of the object is called immutable object.
Ex: String and Wrapper classes.
Update Your Skills form Our Experts: Core Java Online Training
41.What is difference between StringBuffer and StringBuilder?
Answer: StringBuffer is thread-safe (synchronized), multiple threads are unable to processing the StringBuffer object at time, so it will gives less performance, where as StringBuilder is not a thread-safe so multiple objects can processing the object, which gives more performance.
42.How convert StringBuffer object to String object?
Answer: StringBuffer object we can convert into String object using toString().
43.What is difference between the following code?
Answer: String s = “ram”;
String s1 = new String(“ram”);
In the first statement, JVM only creates one object in String constant pool.
In the second statement, JVM will create two objects, one is in heap area and another one is in String constant pool area.
44.What is use of intern() in String class?
Answer: The intern () will go to memory of a String object and read the data later it will pointing to same data in string constant pool area.
45.What type of data holding by method area and heap area?
Answer: Method are always hold static type data where as heap area always holds objects, in that object non-static data will store.
46.Are String and wrapper classes participated in inheritance?
Answer: No, the reason is final classes are not participated in inheritance.
47.What are the rules followed to create java bean?
Answer: The java standard edition class which maintain the following rules.
- Class should implements either java.io.Serializable or Externalizable
- Variables should be private
- Public zero or default constructor.
- Public setters and getters
- Class should be public.
48.What is wrapper class?
Answer: The class which is representing the data in the form object is called wrapper class.
49.What is auto boxing and unboxing?
Answer: The process of converting primitive data to object type is called auto boxing where as converting object type data to primitive is called auto unboxing.
Update Your Skills form Our Experts: Core Java Online Training
50.What is package?
Answer: The process of encapsulating the similar type of classes, interfaces and enum in a single unit is called package.
51.What is use of static import statement?
Answer: Static import statement is useful for loading only static type data.
52.How to compile and execute package program?
Answer:
Compilation: javac –d path filename.java
Execution: java packagename.classname
53.What is the use of throw keyword?
Answer: Throw keyword is useful for forward the exception object from one area to another area.
54.What is the use of throws keyword?
Answer: throws keyword is useful forward the checked exception from our program to JVM and giving information to compiler there may be chance of raising the exception in our program.
55.How many ways can able print exception message?
Answer: There are three ways to print exception messages.
- printStackTrace()
- toString()
- getMessage()
56.What is the difference between initCause(-) and getCause() method?
Answer: InitCause(-) will provides root cause or more meaningful information of the exception whereas getCause() will read exception information which added in the initCause(-) method.
57.What is different between byte streams and character streams?
Answer: Byte streams are sending and writing at a time one byte of data whereas character streams are sending and writing two byte of data at time. Byte streams are use full for working image related information whereas character streams are useful for working with textual file.
58.What is serialization?
Answer: The process of sending data from java application to file in the form of entire object is called serialization.
59.What is externalization?
Answer: The process of sending the data from java application to file in the form of some part of object is called externalization.
Update Your Skills form Our Experts: Core Java Online Training
60.What is internal functionalities of JVM meanwhile of object creation?
Answer: JVM mainly follows five steps meanwhile of exception.
- Jvm checks the problem.
- Jvm will select predefine exception class
- Jvm will create object for selected exception class
- Jvm will add reason of the exception if required
- Finally that exception object handover to catch block if not existed then handover to console.
61.Why can’t we write Object type parameter in catch block?
Answer:
- Catch block always executing meanwhile of exception raise in the try block.
- Try block always throwing exception objects, which are directly or indirectly subclass of Throwable class.
- So catch block parameter type required both Object class functionalities and Throwable class functionalities.
If we are writing
catch(Object o){
}
- Parameter ‘o’ only have Object class functionalities but does not Throwable functionalities.
- That’s why we can’t write Object type parameter in catch block.
62.Can we stop of finally block execution?
Answer: Yes. We can by writing the following statement.
Syatem.exit(0)
63.What is cloning?
Answer: The process of creating new object with the support of existed object data is called cloning.
64.What is use of hashCode(), equals(-) of Object class?
Answer: To get memory identification number which is given by the jvm without checking we should use hashCode(-). To check whether objects are same or not by using memory identification which is given by the JVM then we should use equals(-).
65.What are the difference between comparator and comparable interfaces?
Answer: Comparable interface to check whether the homogenous object are same or not where as comparator will check whether the heterogeneous objects are same or not.
Comparable having only one method like compareTo(Object).
Comparator having two method like compare(Object,Object) and equals(Object)
66.What is collection?
Answer: It is one well define mechanism, to group homogeneous, heterogeneous, duplicate and unique objects into a single container is called collection.
67.What is the difference between Vector and ArrayList?
Answer: By default vector is synchronized class, so its object never allows to multiple threads to processing, whereas ArrayList will allows to multiple thread to processing its object. The load factor of Vector is current capacity*2, whereas ArrayList load factor is current capacity * 3/2.
68.What is generic collection?
Answer: The process of providing type safety on collection object is called generic.
69.What is fail-fast and fail-safe?
Answer: Whenever we reading the data from ArrayList by using one thread, if we are doing modification on ArrayList by using another thread we will get exception that is fail-fast, to overcome this problem we have concurrent collection, that means meanwhile of reading the data from ArrayList by using one thread object, we can able to do modifications by using another thread object on same object is called fail-safe.
Update Your Skills form Our Experts: Core Java Online Training
70.What are functionalities of TreeSet?
Answer: TreeSet not allows heterogenous, null objects, it will provide sorting technique.
71.What is the difference between new and newInstance()?
Answer: Meanwhile of creating a class if we are aware about for which class we are going to creating object then we should use new keyword, if we want to create an object for a class which is loading at runtime by using byte code then we should use newInstance().
72.Can we write compile and execute the program without class?
Answer: Yes. From java 1.5 onwards by using enum and from java 1.8 onwards by using interface we can able to compile and execute the program.
73.Why is String immutable?
Answer: While working with Hashtable, if our String object state changes then we should faces the problem like null or NullPointerExceptions, to avoiding this problem Java community people make String as immutable and also to maintain proper memory management in string constant pool area.
74.What is lambda expression?
Answer: It is one anonymous expression or function to provide implementation for functional interface in a concise and clear manner and within the less time.
With the help of lambda we can develop functional programming in java.
75.What is functional programming?
Answer: The process of sending functional as method argument is called functional programming.
76.Can we use peek() and pop() on empty stack and what is the difference between them?
Answer: Pop() will give top most element with deletion from Stack whereas peek() will give top most element without deletion from Stack.
Both the methods will throw exception like java.util.EmptyStackException if elements are not existed.
import java.util.Stack;
class A{
public static void main(String[] ss){
Stack s = new Stack();
//System.out.println(s.pop());
System.out.println(s.peek());
}
}
78.What is the advantage and disadvantage of ArrayList?
Answer: The advantage of ArrayList is we can able to read any index element within the same time. The drawback is whenever we insert elements in the middle of ArrayList the next position elements are going to shifted to right side, it will reduce performance.
Update Your Skills form Our Experts: Core Java Online Training
79.What is synchronization in java?
Answer: The process of allowing only one thread at a time to execute entire work is called synchronization.
80.What is race condition?
Answer: The process of allowing multiple threads at a time to execute the task simultaneously is called race condition, it will give unreliable result.
81.What is dead lock?
Answer: Placing the thread into wait mode up to life time is called deadlock.
82.What is loosely coupling?
Answer: The process of holding multiple subclass type of objects with the single reference variable is called loosely coupling, but at a time reference variable can hold only one sub class object. | https://nareshit.com/core-java-interview-questions/ | CC-MAIN-2021-39 | refinedweb | 2,929 | 58.18 |
Frequentism and Bayesianism II: When Results Differ
In a previous post.
While it is easy to show that the two approaches are often equivalent for simple problems, it is also true that they can diverge greatly for more complicated problems. I've found that in practice, this divergence makes itself most clear in two different situations:
- The handling of nuisance parameters
- The subtle (and often overlooked) difference between frequentist confidence intervals and Bayesian credible intervals.
A nuisance parameter is any quantity whose value is not relevant to the goal of an analysis, but is nevertheless required to determine some quantity of interest. For example, in the second application worked-through in the previous post, we estimated both the mean $\mu$ and intrinsic scatter $\sigma$ for the observed photons. In practice, we may only be interested in $\mu$, the mean of the distribution. In this case $\sigma$ is a nuisance parameter: it is not of immediate interest, but is nevertheless an essential stepping-stone in determining the final estimate of $\mu$, the parameter of interest.
To illustrate this, I'm going to go through two examples where nuisance parameters come into play. We'll explore both the frequentist and the Bayesian approach to solving both of these problems:
I'll start with an example of nuisance parameters that, in one form or another, dates all the way back to the posthumous 1763 paper written by Thomas Bayes himself. The particular version of this problem I use here is borrowed from Eddy 2004.
The setting is a rather contrived game in which Alice and Bob bet on the outcome of a process they can't directly observe:
Alice and Bob enter a room. Behind a curtain there is a billiard table, which they cannot see, but their friend Carol can. Carol rolls a ball down the table, and marks where it lands. Once this mark is in place, Carol begins rolling new balls down the table. If the ball lands to the left of the mark, Alice gets a point; if it lands to the right of the mark, Bob gets a point. We can assume for the sake of example that Carol's rolls are unbiased: that is, the balls have an equal chance of ending up anywhere on the table. The first person to reach six points wins the game.
Here the location of the mark (determined by the first roll) can be considered a nuisance parameter: it is unknown, and not of immediate interest, but it clearly must be accounted for when predicting the outcome of subsequent rolls. If the first roll settles far to the right, then subsequent rolls will favor Alice. If it settles far to the left, Bob will be favored instead.
Given this setup, here is the question we ask of ourselves:
In a particular game, after eight rolls, Alice has five points and Bob has three points. What is the probability that Bob will go on to win the game?
Intuitively, you probably realize that because Alice received five of the eight points, the marker placement likely favors her. And given this, it's more likely that the next roll will go her way as well. And she has three opportunities to get a favorable roll before Bob can win; she seems to have clinched it. But, quantitatively, what is the probability that Bob will squeak-out a win?
Someone following a classical frequentist approach might reason as follows:
To determine the result, we need an intermediate estimate of where the marker sits. We'll quantify this marker placement as a probability $p$ that any given roll lands in Alice's favor. Because five balls out of eight fell on Alice's side of the marker, we can quickly show that the maximum likelihood estimate of $p$ is given by:
$$ \hat{p} = 5/8 $$
(This result follows in a straightforward manner from the binomial likelihood). Assuming this maximum likelihood probability, we can compute the probability that Bob will win, which is given by:
$$ P(B) = (1 - \hat{p})^3 $$
That is, he needs to win three rolls in a row. Thus, we find that the following estimate of the probability:
p_hat = 5. / 8. freq_prob = (1 - p_hat) ** 3 print("Naïve Frequentist Probability of Bob Winning: {0:.2f}".format(freq_prob))
Naïve Frequentist Probability of Bob Winning: 0.05
In other words, we'd give Bob the following odds of winning:
print("Odds against Bob winning: {0:.0f} to 1".format((1. - freq_prob) / freq_prob))
Odds against Bob winning: 18 to 1
So we've estimated using frequentist ideas that Alice will win about 18 times for each time Bob wins. Let's try a Bayesian approach next.
We can also approach this problem from a Bayesian standpoint. This is slightly more involved, and requires us to first define some notation.
We'll consider the following random variables:
- $B$ = Bob Wins
- $D$ = observed data, i.e. $D = (n_A, n_B) = (5, 3)$
- $p$ = unknown probability that a ball lands on Alice's side during the current game
We want to compute $P(B~|~D)$; that is, the probability that Bob wins given our observation that Alice currently has five points to Bob's three.
The general Bayesian method of treating nuisance parameters is marginalization, or integrating the joint probability over the entire range of the nuisance parameter. In this case, that means that we will first calculate the joint distribution $$ P(B,p~|~D) $$ and then marginalize over $p$ using the following identity: $$ P(B~|~D) \equiv \int_{-\infty}^\infty P(B,p~|~D) {\mathrm d}p $$ This identity follows from the definition of conditional probability, and the law of total probability: that is, it is a fundamental consequence of probability axioms and will always be true. Even a frequentist would recognize this; they would simply disagree with our interpretation of $P(p)$ as being a measure of uncertainty of our own knowledge.
To compute this result, we will manipulate the above expression for $P(B~|~D)$ until we can express it in terms of other quantities that we can compute.
We'll start by applying the following definition of conditional probability to expand the term $P(B,p~|~D)$:
$$ P(B~|~D) = \int P(B~|~p, D) P(p~|~D) dp $$
Next we use Bayes' rule to rewrite $P(p~|~D)$:
$$ P(B~|~D) = \int P(B~|~p, D) \frac{P(D~|~p)P(p)}{P(D)} dp $$
Finally, using the same probability identity we started with, we can expand $P(D)$ in the denominator to find:
$$ P(B~|~D) = \frac{\int P(B~|~p,D) P(D~|~p) P(p) dp}{\int P(D~|~p)P(p) dp} $$
Now the desired probability is expressed in terms of three quantities that we can compute. Let's look at each of these in turn:
- $P(B~|~p,D)$: This term is exactly the frequentist likelihood we used above. In words: given a marker placement $p$ and the fact that Alice has won 5 times and Bob 3 times, what is the probability that Bob will go on to six wins? Bob needs three wins in a row, i.e. $P(B~|~p,D) = (1 - p) ^ 3$.
- $P(D~|~p)$: this is another easy-to-compute term. In words: given a probability $p$, what is the likelihood of exactly 5 positive outcomes out of eight trials? The answer comes from the well-known Binomial distribution: in this case $P(D~|~p) \propto p^5 (1-p)^3$
- $P(p)$: this is our prior on the probability $p$. By the problem definition, we can assume that $p$ is evenly drawn between 0 and 1. That is, $P(p) \propto 1$, and the integrals range from 0 to 1.
Putting this all together, canceling some terms, and simplifying a bit, we find $$ P(B~|~D) = \frac{\int_0^1 (1 - p)^6 p^5 dp}{\int_0^1 (1 - p)^3 p^5 dp} $$ where both integrals are evaluated from 0 to 1.
These integrals might look a bit difficult, until we notice that they are special cases of the Beta Function: $$ \beta(n, m) = \int_0^1 (1 - p)^{n - 1} p^{m - 1} $$ The Beta function can be further expressed in terms of gamma functions (i.e. factorials), but for simplicity we'll compute them directly using Scipy's beta function implementation:
from scipy.special import beta bayes_prob = beta(6 + 1, 5 + 1) / beta(3 + 1, 5 + 1) print("P(B|D) = {0:.2f}".format(bayes_prob))
P(B|D) = 0.09
The associated odds are the following:
print("Bayesian odds against Bob winning: {0:.0f} to 1".format((1. - bayes_prob) / bayes_prob))
Bayesian odds against Bob winning: 10 to 1
So we see that the Bayesian result gives us 10 to 1 odds, which is quite different than the 18 to 1 odds found using the frequentist approach. So which one is correct?
For this type of well-defined and simple setup, it is actually relatively easy to use a Monte Carlo simulation to determine the correct answer. This is essentially a brute-force tabulation of possible outcomes: we generate a large number of random games, and simply count the fraction of relevant games that Bob goes on to win. The current problem is especially simple because so many of the random variables involved are uniformly distributed. We can use the
numpy package to do this as follows:
import numpy as np np.random.seed(0) # play 100000 games with randomly-drawn p, between 0 and 1 p = np.random.random(100000) # each game needs at most 11 rolls for one player to reach 6 wins rolls = np.random.random((11, len(p))) # count the cumulative wins for Alice and Bob at each roll Alice_count = np.cumsum(rolls < p, 0) Bob_count = np.cumsum(rolls >= p, 0) # sanity check: total number of wins should equal number of rolls total_wins = Alice_count + Bob_count assert np.all(total_wins.T == np.arange(1, 12)) print("(Sanity check passed)") # determine number of games which meet our criterion of (A wins, B wins)=(5, 3) # this means Bob's win count at eight rolls must equal 3 good_games = Bob_count[7] == 3 print("Number of suitable games: {0}".format(good_games.sum())) # truncate our results to consider only these games Alice_count = Alice_count[:, good_games] Bob_count = Bob_count[:, good_games] # determine which of these games Bob won. # to win, he must reach six wins after 11 rolls. bob_won = np.sum(Bob_count[10] == 6) print("Number of these games Bob won: {0}".format(bob_won.sum())) # compute the probability mc_prob = bob_won.sum() * 1. / good_games.sum() print("Monte Carlo Probability of Bob winning: {0:.2f}".format(mc_prob)) print("MC Odds against Bob winning: {0:.0f} to 1".format((1. - mc_prob) / mc_prob))
(Sanity check passed) Number of suitable games: 11068 Number of these games Bob won: 979 Monte Carlo Probability of Bob winning: 0.09 MC Odds against Bob winning: 10 to 1
The Monte Carlo approach gives 10-to-1 odds on Bob, which agrees with the Bayesian approach. Apparently, our naïve frequentist approach above was flawed.
This example shows several different approaches to dealing with the presence of a nuisance parameter p. The Monte Carlo simulation gives us a close brute-force estimate of the true probability (assuming the validity of our assumptions), which the Bayesian approach matches. The naïve frequentist approach, by utilizing a single maximum likelihood estimate of the nuisance parameter $p$, arrives at the wrong result.
Before my comment thread explodes and I get ripped to shreds – again – on Reddit and Hacker News, I should emphasize that this does not imply frequentism itself is incorrect. The incorrect result above is more a matter of the approach being "naïve" than it being "frequentist". There certainly exist frequentist methods for handling this sort of nuisance parameter – for example, it is theoretically possible to apply a transformation and conditioning of the data to isolate the dependence on $p$ – but I've not been able to find any approach to this particular problem that does not somehow take advantage of Bayesian-like marginalization over $p$.
Another potential point of contention is that the question itself is posed in a way that is perhaps unfair to the classical, frequentist approach. A frequentist might instead hope to give the answer in terms of null tests or confidence intervals: that is, they might devise a procedure to construct limits which would provably bound the correct answer in $100\times(1 - p)$ percent of similar trials, for some value of $p$ – say, 0.05 (note this is a different $p$ than the $p$ we've been talking about above). This might be classically accurate, but it doesn't quite answer the question at hand. I'll leave discussion of the meaning of such confidence intervals for my follow-up post on the subject.
There is one clear common point of these two potential frequentist responses: both require some degree of effort and/or special expertise; perhaps a suitable frequentist approach would be immediately obvious to someone with a PhD in statistics, but is most definitely not obvious to a statistical lay-person simply trying to answer the question at hand. In this sense, I think Bayesianism provides a better approach for this sort of problem: by simple algebraic manipulation of a few well-known axioms of probability within a Bayesian framework, we can straightforwardly arrive at the correct answer without need for other special expertise.
We'll explore a more data-oriented example of dealing with nuisance parameters next.
One situation where the concept of nuisance parameters can be helpful is accounting for outliers in data. Consider the following dataset, relating the observed variables $x$ and $y$, and the error of $y$ stored in $e$.
x = np.array([ 0, 3, 9, 14, 15, 19, 20, 21, 30, 35, 40, 41, 42, 43, 54, 56, 67, 69, 72, 88]) y = np.array([33, 68, 34, 34, 37, 71, 37, 44, 48, 49, 53, 49, 50, 48, 56, 60, 61, 63, 44, 71]) e = np.array([ 3.6, 3.9, 2.6, 3.4, 3.8, 3.8, 2.2, 2.1, 2.3, 3.8, 2.2, 2.8, 3.9, 3.1, 3.4, 2.6, 3.4, 3.7, 2.0, 3.5])
We'll visualize this data below:
%matplotlib inline import matplotlib.pyplot as plt plt.errorbar(x, y, e, fmt='.k', ecolor='gray');
Our task is to find a line of best-fit to the data. It's clear upon visual inspection that there are some outliers among these points, but let's start with a simple non-robust maximum likelihood approach. Like we saw in the previous post, the following simple maximum likelihood result can be considered to be either frequentist or Bayesian (with uniform priors): in this sort of simple problem, the approaches are essentially equivalent.
We'll propose a simple linear model, which has a slope and an intercept encoded in a parameter vector $\theta$. The model is defined as follows: $$ \hat{y}(x~|~\theta) = \theta_0 + \theta_1 x $$ Given this model, we can compute a Gaussian likelihood for each point: $$ p(x_i,y_i,e_i~|~\theta) \propto \exp\left[-\frac{1}{2e_i^2}\left(y_i - \hat{y}(x_i~|~\theta)\right)^2\right] $$ The total likelihood is the product of all the individual likelihoods. Computing this and taking the log, we have: $$ \log \mathcal{L}(D~|~\theta) = \mathrm{const} - \sum_i \frac{1}{2e_i^2}\left(y_i - \hat{y}(x_i~|~\theta)\right)^2 $$ This should all look pretty familiar if you read through the previous post. This final expression is the log-likelihood of the data given the model, which can be maximized to find the $\theta$ corresponding to the maximum-likelihood model. Equivalently, we can minimize the summation term, which is known as the loss: $$ \mathrm{loss} = \sum_i \frac{1}{2e_i^2}\left(y_i - \hat{y}(x_i~|~\theta)\right)^2 $$ This loss expression is known as a squared loss; here we've simply shown that the squared loss can be derived from the Gaussian log likelihood.
Following the logic of the previous post, we can maximize the likelihood (or, equivalently, minimize the loss) to find $\theta$ within a frequentist paradigm. For a flat prior in $\theta$, the maximum of the Bayesian posterior will yield the same result. (note that there are good arguments based on the principle of maximum entropy that a flat prior is not the best choice here; we'll ignore that detail for now, as it's a very small effect for this problem).
For simplicity, we'll use scipy's
optimize package to minimize the loss (in the case of squared loss, this computation can be done more efficiently using matrix methods, but we'll use numerical minimization for simplicity here)
from scipy import optimize def squared_loss(theta, x=x, y=y, e=e): dy = y - theta[0] - theta[1] * x return np.sum(0.5 * (dy / e) ** 2) theta1 = optimize.fmin(squared_loss, [0, 0], disp=False) xfit = np.linspace(0, 100) plt.errorbar(x, y, e, fmt='.k', ecolor='gray') plt.plot(xfit, theta1[0] + theta1[1] * xfit, '-k') plt.title('Maximum Likelihood fit: Squared Loss');
It's clear on examination that the outliers are exerting a disproportionate influence on the fit. This is due to the nature of the squared loss function. If you have a single outlier that is, say 10 standard deviations away from the fit, its contribution to the loss will out-weigh that of 25 points which are 2 standard deviations away!
Clearly the squared loss is overly sensitive to outliers, and this is causing issues with our fit. One way to address this within the frequentist paradigm is to simply adjust the loss function to be more robust.
The variety of possible loss functions is quite literally infinite, but one relatively well-motivated option is the Huber loss. The Huber loss defines a critical value at which the loss curve transitions from quadratic to linear. Let's create a plot which compares the Huber loss to the standard squared loss for several critical values $c$:
t = np.linspace(-20, 20) def huber_loss(t, c=3): return ((abs(t) < c) * 0.5 * t ** 2 + (abs(t) >= c) * -c * (0.5 * c - abs(t))) plt.plot(t, 0.5 * t ** 2, label="squared loss", lw=2) for c in (10, 5, 3): plt.plot(t, huber_loss(t, c), label="Huber loss, c={0}".format(c), lw=2) plt.ylabel('loss') plt.xlabel('standard deviations') plt.legend(loc='best', frameon=False);
The Huber loss is equivalent to the squared loss for points which are well-fit by the model, but reduces the loss contribution of outliers. For example, a point 20 standard deviations from the fit has a squared loss of 200, but a c=3 Huber loss of just over 55. Let's see the result of the best-fit line using the Huber loss rather than the squared loss. We'll plot the squared loss result in light gray for comparison:
def total_huber_loss(theta, x=x, y=y, e=e, c=3): return huber_loss((y - theta[0] - theta[1] * x) / e, c).sum() theta2 = optimize.fmin(total_huber_loss, [0, 0], disp=False) plt.errorbar(x, y, e, fmt='.k', ecolor='gray') plt.plot(xfit, theta1[0] + theta1[1] * xfit, color='lightgray') plt.plot(xfit, theta2[0] + theta2[1] * xfit, color='black') plt.title('Maximum Likelihood fit: Huber loss');
By eye, this seems to have worked as desired: the fit is much closer to our intuition!
However a Bayesian might point out that the motivation for this new loss function is a bit suspect: as we showed, the squared-loss can be straightforwardly derived from a Gaussian likelihood. The Huber loss seems a bit ad hoc: where does it come from? How should we decide what value of $c$ to use? Is there any good motivation for using a linear loss on outliers, or should we simply remove them instead? How might this choice affect our resulting model?:
$$ \begin{array}{ll} p(\{x_i\}, \{y_i\},\{e_i\}~|~\theta,\{g_i\},\sigma,\sigma_b) = & \frac{g_i}{\sqrt{2\pi e_i^2}}\exp\left[\frac{-\left(\hat{y}(x_i~|~\theta) - y_i\right)^2}{2e_i^2}\right] \\ &+ \frac{1 - g_i}{\sqrt{2\pi \sigma_B^2}}\exp\left[\frac{-\left(\hat{y}(x_i~|~\theta) - y_i\right)^2}{2\sigma_B^2}\right] \end{array} $$
What we've done is expanded our model with some nuisance parameters: $\{g_i\}$ is a series of weights which range from 0 to 1 and encode for each point $i$ the degree to which it fits the model. $g_i=0$ indicates an outlier, in which case a Gaussian of width $\sigma_B$ is used in the computation of the likelihood. This $\sigma_B$ can also be a nuisance parameter, or its value can be set at a sufficiently high number, say 50.
Our model is much more complicated now: it has 22 parameters rather than 2, but the majority of these can be considered nuisance parameters, which can be marginalized-out in the end, just as we marginalized (integrated) over $p$ in the Billiard example. Let's construct a function which implements this likelihood. As in the previous post, we'll use the emcee package to explore the parameter space.
To actually compute this, we'll start by defining functions describing our prior, our likelihood function, and our posterior:
# theta will be an array of length 2 + N, where N is the number of points # theta[0] is the intercept, theta[1] is the slope, # and theta[2 + i] is the weight g_i def log_prior(theta): #g_i needs to be between 0 and 1 if (all(theta[2:] > 0) and all(theta[2:] < 1)): return 0 else: return -np.inf # recall log(0) = -inf def log_likelihood(theta, x, y, e, sigma_B): dy = y - theta[0] - theta[1] * x g = np.clip(theta[2:], 0, 1) # g<0 or g>1 leads to NaNs in logarithm logL1 = np.log(g) - 0.5 * np.log(2 * np.pi * e ** 2) - 0.5 * (dy / e) ** 2 logL2 = np.log(1 - g) - 0.5 * np.log(2 * np.pi * sigma_B ** 2) - 0.5 * (dy / sigma_B) ** 2 return np.sum(np.logaddexp(logL1, logL2)) def log_posterior(theta, x, y, e, sigma_B): return log_prior(theta) + log_likelihood(theta, x, y, e, sigma_B)
Now we'll run the MCMC samples to explore the parameter space:
# Note that this step will take a few minutes to run! ndim = 2 + len(x) # number of parameters in the model nwalkers = 50 # number of MCMC walkers nburn = 10000 # "burn-in" period to let chains stabilize nsteps = 15000 # number of MCMC steps to take # set theta near the maximum likelihood, with np.random.seed(0) starting_guesses = np.zeros((nwalkers, ndim)) starting_guesses[:, :2] = np.random.normal(theta1, 1, (nwalkers, 2)) starting_guesses[:, 2:] = np.random.normal(0.5, 0.1, (nwalkers, ndim - 2)) import emcee sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=[x, y, e, 50]) sampler.run_mcmc(starting_guesses, nsteps) sample = sampler.chain # shape = (nwalkers, nsteps, ndim) sample = sampler.chain[:, nburn:, :].reshape(-1, ndim)
-c:16: RuntimeWarning: divide by zero encountered in log -c:15: RuntimeWarning: divide by zero encountered in log
Once we have these samples, we can exploit a very nice property of the Markov chains. Because their distribution models the posterior, we can integrate out (i.e. marginalize) over nuisance parameters simply by ignoring them!
We can look at the (marginalized) distribution of slopes and intercepts by examining the first two columns of the sample:
plt.plot(sample[:, 0], sample[:, 1], ',k', alpha=0.1) plt.xlabel('intercept') plt.ylabel('slope');
We see a distribution of points near a slope of $\sim 0.45$, and an intercept of $\sim 31$. We'll plot this model over the data below, but first let's see what other information we can extract from this trace.
One nice feature of analyzing MCMC samples is that the choice of nuisance parameters is completely symmetric: just as we can treat the $\{g_i\}$ as nuisance parameters, we can also treat the slope and intercept as nuisance parameters! Let's do this, and check the posterior for $g_1$ and $g_2$, the outlier flag for the first two points:
plt.plot(sample[:, 2], sample[:, 3], ',k', alpha=0.1) plt.xlabel('$g_1$') plt.ylabel('$g_2$') print("g1 mean: {0:.2f}".format(sample[:, 2].mean())) print("g2 mean: {0:.2f}".format(sample[:, 3].mean()))
g1 mean: 0.63 g2 mean: 0.39
There is not an extremely strong constraint on either of these, but we do see that $(g_1, g_2) = (1, 0)$ is slightly favored: the means of $g_1$ and $g_2$ are greater than and less than 0.5, respecively. If we choose a cutoff at $g=0.5$, our algorithm has identified $g_2$ as an outlier.
Let's make use of all this information, and plot the marginalized best model over the original data. As a bonus, we'll draw red circles to indicate which points the model detects as outliers:
theta3 = np.mean(sample[:, :2], 0) g = np.mean(sample[:, 2:], 0) outliers = (g < 0.5) plt.errorbar(x, y, e, fmt='.k', ecolor='gray') plt.plot(xfit, theta1[0] + theta1[1] * xfit, color='lightgray') plt.plot(xfit, theta2[0] + theta2[1] * xfit, color='lightgray') plt.plot(xfit, theta3[0] + theta3[1] * xfit, color='black') plt.plot(x[outliers], y[outliers], 'ro', ms=20, mfc='none', mec='red') plt.title('Maximum Likelihood fit: Bayesian Marginalization');
The result, shown by the dark line, matches our intuition! Furthermore, the points automatically identified as outliers are the ones we would identify by hand. For comparison, the gray lines show the two previous approaches: the simple maximum likelihood and the frequentist approach based on Huber loss.
Here we've dived into linear regression in the presence of outliers. A typical Gaussian maximum likelihood approach fails to account for the outliers, but we were able to correct this in the frequentist paradigm by modifying the loss function, and in the Bayesian paradigm by adopting a mixture model with a large number of nuisance parameters.
Both approaches have their advantages and disadvantages: the frequentist approach here is relatively straightforward and computationally efficient, but is based on the use of a loss function which is not particularly well-motivated. The Bayesian approach is well-founded and produces very nice results, but requires a rather subjective specification of a prior. It is also much more intensive in both coding time and computational time.
In the previous post, I discussed the philosophical differences between frequentism and Bayesianism, and showed that, despite these differences, they often give the same result for simple problems. Here we've explored one category of problem where the results begin to diverge: accounting for nuisance parameters. outliers in our data. Using a robust frequentist cost function is relatively fast and painless, but is dubiously motivated and leads to results which are difficult to interpret. Using a Bayesian mixture model takes more effort and requires more intensive computation, but leads to a very nice result in which multiple questions can be answered at once: in this case, marginalizing one way to find the best-fit model, and marginalizing another way to identify outliers in the data.
So which is better, frequentism or Bayesianism?
The answer probably depends on your level of expertise in frequentist and Bayesian methods, as well as the size of your problem and your available computational resources. I, like many with a Physics background, tend to lean toward Bayesian methods partly because they appeal to my desire to be able to derive anything from fundamental principles. With Bayesianism, based on algebraic manipulation of a few probability axioms, we can construct extremely flexible methods to address a wide variety of problems. Just as the conservation of mass-energy can be applied to everything from projectile motion to stellar structure, Bayes' rule and the Bayesian probability interpretation can be applied to solve virtually any statistical problem: from computing gambling odds to detecting exoplanet transits in noisy photometric data. In a Bayesian paradigm, you need not spend years memorizing and understanding obscure frequentist techniques and jargon (p-values, null tests, confidence intervals, breakdown points, etc.) in order to do such nontrivial analyses. It's a common misconception, I think: people imagine that Bayesian analysis is hard. On the contrary, many scientists use it just because it's easy!
Ease and aesthetics aside, though, there's a further important reason that I sit firmly in the Bayesian camp, and that has to do with the interpretation of frequentist confidence intervals and Bayesian credibility regions within the context of scientific data. As this post is already way too long, that discussion will have to wait for next time.
This post was written entirely in the IPython notebook. You can download this notebook, or see a static view on nbviewer. | http://jakevdp.github.io/blog/2014/06/06/frequentism-and-bayesianism-2-when-results-differ/ | CC-MAIN-2018-39 | refinedweb | 4,793 | 53 |
Also, you should never get into the habit of any 'using namespace' in general and std in particular in a header. Typing an extra std:: is not bad, adds a lot of clarity and the first time your polluted global namespace gives you hell you will understand the remaining point.
I have no idea why, but I converted everything to 'std::' and removed the using namespace and that solved my issue! So weird how it was that tat was causing trouble
Thanks to everyone who tried to help me as well! I researched most vexing parse and I learned something new! | http://www.gamedev.net/user/100490-nuclear-rabbit/?tab=reputation | CC-MAIN-2016-44 | refinedweb | 101 | 67.89 |
My IDE is eclipse and my project is a stand-alone javaFX application (pure CS architecture with OSGI framework).
How to use Preloader thus the preloader would be started before my main Application and hid later?
I found some code in
But I still don't know how to deploy the Preloader with my startup Application in a OSGI framework. I give some code of my startup application below:
public class MyPrjMain extends Application { private static Stage primaryStage; public void start(final Stage stage) throws BusinessException { primaryStage = stage; init(primaryStage); primaryStage.show(); } }
Thanks very much, everybody.
This is a long answer, the quick answer for the impatient is to download this sample code for displaying a splash page for an intensive startup task and see if it is adaptable to your situation.
My answer provides general information about Preloader style functionality in JavaFX. Your question specifically mentions
Preloader usage in an Eclipse and OSGI environment, but I won't directly address that scenario as I don't use those technologies. Hopefully the general information is still applicable to your scenario.
1. Java has native support for displaying a splash page when Java is started.
-splash:<image>VM switch.
Advantages and disadvantages:
+ The simplest way to get your standalone application to show a splash image.
+ Can be displayed very quickly
=> it's an argument input to the VM process, so (presumably) it can be displayed even before the VM itself has fully initialized.
- Has limited features
=> only allows display of an image, not other preloader features such as reporting of initialization progress, animation, login prompts etc (unless you make use of AWT APIs)
- Won't work on all platforms until Java 8 (see issue Mac: Impossible to use -splash: with JavaFX 2.2 and JDK 7).
2. Preloaders may be used for standalone applications.
The JavaFX Preloader tutorial has an example in the section
9.3.4 Using a Preloader to Display the Application Initialization Progress. The tutorial provides executable sample code in the
LongInitAppPreloader and
LongInitApp classes (use the class names I provide in this answer as one name in the tutorial is currently wrong).
The sample standalone application has a long initialization time and a custom
Preloader provides feedback on the progress of the initialization. The sample simulates the long initialization through a Task with a
Thread.sleep call, but a real application would be doing something like establishing network connections, retrieving and parsing network data and setting up the initial application Scene.
Preloaders are not specific to applets and WebStart, but are primarily targeted to those deployment types. The applet and WebStart initialization process is more complex than standalone application initialization, so much of the Preloader documentation is devoted to those more complex scenarios.
3. You don't need to place a Preloader in a separate JAR.
You can place the
Preloader in the same JAR as your Application class. For large applications dynamically deployed and updated over network loading protocols such as WebStart, placing the
Preloader in a seperate JAR makes sense. For standalone applications performing network based initialization, it probably doesn't make much difference and the separate packaging step could be skipped to simplify the build and deployment process.
4. You can achieve Preloader style functionality without using a Preloader.
Much (not all) of the Preloader functionality can be achieved without subclassing Preloader.
You can:
5b is probably preferred so that you don't need to create multiple windows.
For examples of this strategy, see my answers to the following questions:
The related sample code for displaying Progress Monitoring splash screens in JavaFX without using a
Preloader is:
The above code could be refactored to use a Preloader subclass instead, in which case there is a well defined framework for notification of application initialization events and more flexible deployment models (e.g. preloader in seperate jar) are available. However use of a
Preloader may be a little complicated. For some implementations, it may not be worth the time to understand the
Preloader framework.
5. WebStart Apps have JNLP support for Splash Images
(this point is pretty irrelevant and just included for completeness).
I believe that webstart applications can have a flag in their jnlp file to show the startup image as the webstart application launches, but I've never been able to get that flag to work in a JavaFX 2 application, only in a Swing application and even then it wasn't all that reliable as it would only display the second time the application was launched.
IMHO a Preloader only makes sense when you are running as an applet or webstart because the preloader can be packaged as an extra Jar which is downloaded first and executed while the rest of your application is downloaded in the background.
So my suggestion would be to open a stage at the first point in time when you get a Stage and e.g. display a splash. | https://javafxpedia.com/en/knowledge-base/15126210/how-to-use-javafx-preloader-with-stand-alone-application-in-eclipse- | CC-MAIN-2020-50 | refinedweb | 821 | 50.67 |
Google Interview Question: Chain of strings
There is a list of strings and they ask if it is possible create a chain of string using all the strings in the given list.
A chain can be formed b/w strings if last char of the 1st string matches with 1st char of second string. (this question is taken from careercup)
To give an example;
let’s say the given list is {aaszx, prtws, stuia} in this case the only posible chain is prtws–stuia–aaszx
At first sight the problem looks to be pretty easy, just put the first and last characters on two seperate hasmaps ;
List<String> stringList = ... stringList.add ... Map<Character, Integer> firstCharacterCountMap = ...; for each string : str in the list increment firstCharacterCountMap(first character of str) decrement lastCharacterCountMap(last character of str)
in the pseudo code above the idea is finding the number of characters at start position and number of end characters at the end. after check if there final sum of the results is 0. A reasonable solution yet doesn’t provide the chain to be constructed.
the difficulty is that there might be some dead-ends. let say the list is {ab, bd, cb, bc} if we start with ab; ab->bd->? there is no solution even though there is one. (Btw the solution is; ab->bc->cb->bd). At this point one solution may come to mind is starting from a string whose first character doesn’t correspond to and end. Unfortunately this idea is not as good as it seems since there might all the first characters have a correspondence.
My solution is in O(n^2) 🙁 yet it works. Anyway topological sorting also has n^2 complexity.
I first create two separate hashmaps for both start and end characters. then I put the strings to these maps with corresponding characters. next I check for all possible combinations recursively;
You also can run the code from ideone
import java.util.*; /** * Created with IntelliJ IDEA. * User: uerturk * Date: 08/10/13 * Time: 17:04 * To change this template use File | Settings | File Templates. */ class HasChain { Map<Character, List<String>> startsWithStringMap = new HashMap<Character, List<String>>(); Map<Character, List<String>> endsWithStringMap = new HashMap<Character, List<String>>(); private Character getFirstChar(String str) { return str.charAt(0); } private Character getLastChar(String str) { return str.charAt(str.length() - 1); } boolean hasChain(List<String> stringList) { // create relations between strings and their first // and last characters using two hasmaps. for (String str : stringList) { Character start = getFirstChar(str); Character end = getLastChar(str); List<String> startsWithList; List<String> endsWithList; if (startsWithStringMap.containsKey(start)) { startsWithList = startsWithStringMap.get(start); } else { startsWithList = new ArrayList<String>(); startsWithStringMap.put(start, startsWithList); } if (endsWithStringMap.containsKey(end)) { endsWithList = endsWithStringMap.get(end); } else { endsWithList = new ArrayList<String>(); endsWithStringMap.put(end, endsWithList); } startsWithList.add(str); endsWithList.add(str); } // this stack is the solution stack Stack<String> stringStack = new Stack<String>(); for (String str : stringList) { if (hasChain(stringList.size(), str, stringStack)) { System.out.println(stringStack); return true; } } return false; } // recursively iterates through all possibilities private boolean hasChain(int size, String startString, Stack<String> stringStack) { if (size == stringStack.size()) return true; // if the stack is full of strings, we found it! Character last = getLastChar(startString); if (startsWithStringMap.containsKey(last)) { List<String> stringList = startsWithStringMap.get(last); for (int i = 0; i < stringList.size(); i++) { String candidate = stringList.remove(i--); // remove the candidate as it shouldn't be used in the next iterations stringStack.push(candidate); // as if it is the solution if (hasChain(size, candidate, stringStack)) { return true; // no need to continue } stringStack.pop(); // candidate is not the solution stringList.add(++i, candidate); // put it back to the list, where it belongs } } return false; } public static void main(String[] args) { List<String> stringList = new ArrayList<String>(); stringList.add("bd"); stringList.add("fk"); stringList.add("ab"); stringList.add("kl"); stringList.add("cf"); stringList.add("ff"); stringList.add("fa"); stringList.add("ak"); stringList.add("ka"); stringList.add("lf"); stringList.add("bc"); System.out.println(new HasChain().hasChain(stringList)); // should return true as there is a solution stringList.remove("ka"); // we break the chain here System.out.println(new HasChain().hasChain(stringList)); // should return false as there is no solution after removing 'ka' } }
hope that helped to someone 🙂 | http://hevi.info/uncategorized/google-interview-question-chain-of-strings/ | CC-MAIN-2022-27 | refinedweb | 701 | 58.48 |
Details
Description
There are a lot of common file names used in HDFS, mainly created by mapreduce, such as file names starting with "part". Reusing byte[] corresponding to these recurring file names will save significant heap space used for storing the file names in millions of INodeFile objects.
Activity
- All
- Work Log
- History
- Activity
- Transitions
preliminary patch.
Hi suresh, awesome idea. Can we somehow make this automatic (instead of yet another regex configuration that an administrator has to configure). what if we make the NN do some periodic housekeeping that looks for the top-N matching path components?
also, do you have a measurement on how much space this could save on your cluster?
Here is an analysis of an fsimage on one of Yahoo production clusters with 54 million files:
Dictionary stores names that are used more than 10 times to benefit from reuse. Names used less than 10 times may not result in a lot of saving, considering those names are stored in HashMap as HashMap.Entry (size 28 bytes) and other HashMap overhead.
Given that, my proposal is:
- From my previous proposal, name dictionary will use regex listed in a config file "hdfs-filenames-regex" to track common file names. This file is setup with part-.*. This is will be a admin configured file.
- Build a tool to generate list names that is used more than 10 times from fsimage. The generated list excludes the names that are already covered by regex, to reduce the size of the list and loading time. This list is saved as config file "hdfs-filenames".
- NameDictionary loads "hdfs-filenames-regex" and "hdfs-filesnames". NN stores list of regex and a HashMap of name (String) to internal object (byte[]). A file name is first looked up in the map. If the name is not found, then a check is made to see if it matches any regex. A name matching the regex is added to the map.
Optional:
- In the longer run:
- the tool runs offline periodically (on any machine) on the namenode image.
- namenode could refresh its dictionary with the new list of common names used. It could lazily walk through the directory structure and set the INodeFile to reuse the byte[].
Dhruba, see my comments on what can be done in the longer run. I feel analysis of what are common names can be offline to reduce the load on NN. Also if you have ideas on doing it online, let me know.
For the above table, 448832 file names are used for ~47 million files. So instead of 47 million byte[], we should be able to 448832 byte[]. Assuming a file size of 10 bytes, this translated to 4.7GB for a namenode with heap size 40G.
Build a tool to generate list names that is used more than 10 times from fsimage.
Also, we don't actually have to build a separate tool, as the offline image viewer can quickly be extended to provide these numbers and generate the new file. The numbers above were generated from just a few lines in a new viewer.
File names used > 100000 times 24
What are the names of these 24 files? Do they fall under the proposed default pattern. How big is the noise if we use the default pattern.
On the one hand I see the point of providing a generic approach for people to specify their own patterns.
But I also agree with Dhruba that we need to optimize only for the top ten (or so) file names, which will give us 5% saving in the meta-data memory footprint. The rest should be ignored, it would be a wast of resources to optimize for the rest. Your approach 2 would be a move in this direction.
So may be it would be useful to have a tool Jacob mentions (OIV-based), so that admins could run it offline on the image and get top N frequently used names, with an estimate how much space this saves. Then they will be able to formulate the reg exp. Otherwise, it is going to be a painful guessing game.
What are the names of these 24 files? Do they fall under the proposed default pattern. How big is the noise if we use the default pattern.
Of 24, 22 are part-* files.
we need to optimize only for the top ten (or so) file names, which will give us 5% saving in the meta-data memory footprint
I do not think top 10 will save 5% of meta-data memory fooprint. See the posted results below.
I have a bug in my previous calculation, that made the savings seem too good to be true. With 47 million files optimized to use the dictionary, the saving of 10 bytes gives 470MB and not 4.7GB
Also I did not account for byte[] overhead of 24 bytes.
Any way I have a tool NamespaceDedupe with the new patch. You could run on fsimage to see the frequency of occurence and savings in heap size. Dhruba you can run this on images on your production cluster to see how savings compare with what I have posted below.
23 names are used by 3343781 between 100000 and 360461 times. Saved space 114962311
468 names are used by 12944154 between 10000 and 100000 times. Saved space 448255164
4335 names are used by 10522601 between 1000 and 10000 times. Saved space 391364352
40031 names are used by 10654372 between 100 and 1000 times. Saved space 382273386
403974 names are used by10722689 between 10 and 100 times. Saved space 354416484
Total saved space 1691271697
Won't this require a lot of synchronization that previously didn't exist? ie every time you delete a file you'll need to atomically decrement the count in the map and possibly mutate the map to remove the file. Would be nice if different parts of the namespace didn't require synchronization because they happened to share files with the same name.
Access to the map is only during write operations (create and while digesting editslog). All of that is synchronized by a large FSNamesystem lock. Also I am not proposing to do reference counting. Once in this map, it will remain there. The map it self should not have large number of entries, only the top N popular names.
hi suresh, are you saying that we save 470MB on a 40GB heap size? If that is the case, then the savings might be too meagre compared to the code complexity of the patch. do you agree?
470MB was based on my rough calculation. Look at detailed info I posted earlier. If we use dictionary for names used more than 10, the savings is 1.6G in old generation of size 37G (BTW not all the 37G was used in old gen, ~30G was used and the remaining was headroom).
Thanks Suresh for the numbers.
> agree with Dhruba that we need to optimize only for the top ten (or so) file names, which will give us 5% saving in the meta
One fear I have is that the regex matching inside the fsnamesystem lock could increase CPU increase in such a way that the 5% gain in memory might not be a good tradeoff. any thoughts on this?
agree with Dhruba that we need to optimize only for the top ten (or so) file names, which will give us 5% saving in the meta
As I had commented earlier, we need to have at least a dictionary of size 500K to see gains, not just top ten file names. See the breakdown from my previous analysis. Regex matching should not be a big issue. Look up is always made in the dictionary hashmap (for most of the frequently used file names, there will be a hit). Regex is used only for names not found in the dictionary. This is done only while creating a file.
After thinking about this solution, here is an alternate solution I am leaning towards. Let me know what you guys think:
- During startup, maintain two maps. One is a transient map used for counting number of times a file name is used and the corresponding byte[]. The second is the dictionary map which maintains file name to byte[].
- While consuming fsimage and editslog:
- If name is found in the dictionary map, use byte[] corresponding to it
- if name is found in the transient map, increment the number of times the name is used. If the name is used more than threshold (10 times), delete it from the transient map and promote it to dictionary.
- if name is not found in the transient map, add it to the transient map with use count set to 1.
- At the end of consuming editslog, delete the transient map.
Advantages:
- No configuration files and no regex. Simplified administration.
Disadvantages:
- Dictionary is initialized only during startup. Hence it does not react to and optimize for files names that become popular post startup.
- Impacts startup time due to two hashmap lookups (though it should be a small fraction of disk i/o time during startup)
Awesome. I like this idea because it has no configuration shing-bang and is automatic. My opinion is that it is ok to do this only during NN startup time. Maybe you can have only one dictionary where you store the count-of-occurances as well. i.e move the count from the transient map to the dictionary... otherwise the same logic as u described. when the image is fully loaded, we have to purge the dictionary of all items whose count is lesser than 10 .
also, this has some relationship to
HDFS-1140.
Maybe you can have only one dictionary where you store the count-of-occurances as well. i.e move the count from the transient map to the dictionary...
I prefer having two different hashmaps for the following reasons:
- If a single hashmap is used, it grows to the size of all the names, not just the names stored in the dictionary. Either we have shrink the map post purging entries (by making another copy) or use heap more than necessary to retain a map much larger than what it should be.
- In dictionary, I do not intend to track the number of times the name is used. This information is unnecessary. All we care about is whether it used more than certain threshold and not the exact number of times a name is used.
Attached patch implements the solution I had proposed previously. There is an additional optimization due to the chosen mechanism. During startup, if a name is used more than once, byte[] is reused (not just for the names used more than 10 times).
Only the names used more than 10 times is added to the dictionary. Adding other names will undo the space gained due to heap used for storing hashmap entries (as described earlier).
I ran tests to benchmark startup time and total heap size (gotten by triggering full GC after startup). Here are the results:
Startup time increased by 12s with 1.825G saved from 24.197G heap.
BTW I am thinking of removing NamespaceDeduper tool attached in the patch. Any thoughts?
Dhruba or Jakob, can you please comment...
Looking good.
Review:
- If you keep NamespaceDedupe, which I would recommend as I do think it adds value in and of itself, it's probably best to move its user-facing bits with the rest of the offline image viewers. OfflineImageViewer.java handles all the command line arguments and such.
- NamespaceDedupe.java:51 line goes more than 80 characters.
- Nit: TestNameDictionary::testNameReuse() at first looked to me like a unit test that hadn't annotated. Maybe verifyNameReuse?
- The static class ByteArray seems like a candidate either for being a stand-alone class or wrapped by NameDictionary; it's not really an integral part of FSDirectory.
-?
Overall I think this is a good thing to do. The 12 second startup cost compared to the almost 2 gb savings seems worth it to me. There should be a linear tradeoff such that small clusters should see essentially no impact and large clusters pay a very small penalty at startup but have the benefits for their entire runtime.
A useful improvement later on may be a safemode command to repopulate the dictionary, which would take into account changes since cluster startup, particularly newly popular filenames.
> The 12 second startup cost compared to the almost 2 gb savings seems worth it to me.
I agree, sounds good.
Thanks Jakob.?
I see your point. I decided to use same key and value to reduce object count. I do not want to rule out using NameDictionary for other things and hence it is generic with the possibility of key and value being different. I can add a comment to indicate key and value are the same when doing lookup. Let me know if you think of other alternatives.
Alternatively we can follow the convention in java.util.Dictionary:
- Change the method name from lookup to put
- Add methods get and remove for completeness
Change the method name from lookup to put
That sounds good. To me, this seems more like a cache (or as Suresh pointed out, interning of Strings), than a dictionary, but the distinction is definitely blurry.
Add methods get and remove for completeness
This would be extra complexity that wouldn't be called by anyone, correct? I'd hold off on that functionality until it's needed.
Named the class NameCache instead NameDictionary. Also moved ByteArray class to util package.
- variable cache should read nameCache
- comment for it should be transformed to JavaDoc comments.
- FSDirectory.cache should be initialized in the constructor rather than during declaration.
And 10 should be declared as a constant.
- I would consider using NameCache<byte[]> instead of NameCache<ByteArray>.
You get less objects and conversions, if of course I didn't miss anything here.
- Introduce FSDirectory.cache(INode) method, which calls NameCache.put().
- In NameCache some comments need clarification
- "This class has two phases"
Probably something else has 2 phases.
- "This class must be synchronized externally"
- Member inline comments should be transformed into javadoc.
- NameCache.cache should be initialized in the constructor rather than during declaration.
- UseCount should probably be a private inner (rather than static) class,
and should use the same parameter K with which NameCache<K> is parametrized.
private class UseCount { int count; // Number of times a name occurs final K value; // Internal value for the name UseCount(final K value) { this.value = value; } }
- UseCount.count should be initialized in the constructor. It is better to have increment()
and get() methods rather than accessing count directly from the outside.
I like the idea of using the useThreshold to determine names that should be promoted to the nameCache.
My main concern is, that the threshold is 10. This means there will a lot of names in the cache.
And all these names are in a HashTable, which has a huge overhead, as we know from another jira.
We still save space, but for names that occur only 10 times the savings are probably negligible.
I would imagine that only 5% or 10% of the most frequently used names get promoted.
It is fine with me to use this simple promoting scheme as a starting point, with an intention to
optimize it later. But I would increase the useThreshold to 1000 or so.
Should we make it configurable? Could be useful for testing.
-1 overall. Here are the results of testing the latest attachment
against trunk revision 9515.
Removed NamespaceDedupe and added it as a processor "NameDistribution" to oiv tool.
Took care of all the comments from Konstantin (thanks!).
I would consider using NameCache<byte[]> instead of NameCache<ByteArray>....
Cache inserts byte[] into HashMap. This requires wrapping byte[] in another class to provide hashCode() and equals()
My main concern is, that the threshold is 10. This means there will a lot of names in the cache...
For the fsimage I am working with, threshold of 10 results in addition of 10% of the files names to the cache. See the analysis I have posted.
For each name cached, a HashMap.Entry takes 48 bytes. With threshold 10, space equivalent 9 byte arrays is saved. This is 9 * (24+bytes in array) = 216+9*(bytes in array) bytes. This is significant savings, compared to the cost of HashMap.Entry.
I have made the threshold configurable with a hidden option "dfs.namenode.name.cache.threshold". This could be used to run tests to see if we can decrease the threshold further.
Minor chages:
- fixed typo "in in" in ByteArray.java
- Removed NameCache.UseCount.count initialization during declaration.
-1 overall. Here are the results of testing the latest attachment
against trunk revision 9528.
Failed tests TestBalancer and TestLargeDirectoryDelete are not related to this...
+1 on the patch.
We also talked about replacing HashMap with a TreeMap.
The advantages of TreeMap are
- you don't need to wrap byte[] into a class, as it lets to provide a comparator, which compares byte[]s, and
- it does not have memory overhead of HashMap
The disadvantage is that file creation will require a log-time lookup in TreeMap instead of a constant lookup in HashMap. Besides, the HashMap memory overhead is small compared to the overall memory savings provided by the approach.
The decision is to use HashMap with a byte[] wrapped into ByteArray class.
Attaching 20 version of patch. It does not include OfflineImageViewer tool (since oiv is not available in 20).
+1 for the patch for 0.20
I committed the change to trunk.
Integrated in Hadoop-Hdfs-trunk-Commit #310 (See)
Hi Suresh, new commit should be appended at end of the list in CHANGE.txt but not inserted in the beginning.
--- hadoop/hdfs/trunk/CHANGES.txt 2010/06/11 18:09:48 953802 +++ hadoop/hdfs/trunk/CHANGES.txt 2010/06/11 18:15:17 953803 @@ -9,6 +9,9 @@ IMPROVEMENTS + HDFS-1110. Reuses objects for commonly used file names in namenode to + reduce the heap usage. (suresh) + HDFS-1096. fix for prev. commit. (boryas)
Sure. Next time I commit some thing I will fix it.
Approach:
Alternative approach:
Alternative approach has the advantage that regex file to define names that need to be added dictionary is not requried. It does not work when the namenode starts fresh or recurring names get added post startup.
I am planning to go with approach 1. | https://issues.apache.org/jira/browse/HDFS-1110?focusedCommentId=12880355&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-48 | refinedweb | 3,082 | 73.88 |
I am trying to list the contents of all my Web maps for a user. I have a list of all the Web Maps but cannot find how to list the Web Maps content. Each web map has a number of layers, these shown in portal but want to know how to get this list in python.
It looks like you can access the layers of a web map using the ArcGIS API for Python. The section "Fix errors in web map" on this link, show an example of doing that.
Using and updating GIS content | ArcGIS for Developers
Leon
Here's a snippet that should get you started. This will return the JSON for a given webmap or list of webmaps in your portal.
from arcgis.gis import GIS
from IPython.display import display
import pandas as pd
import json
gis = GIS('url', 'username', 'password')
webmaps = gis.content.search('', 'Web Map', max_items = 500)
for webmap in webmaps:
print('Title ' + webmap.title, '\nWebmapId ' +webmap.id, '\nOwner ' +webmap.owner)
webmapJSON = webmap.get_data()
for layer in webmapJSON['operationalLayers']:
display(layer)
Thanks Seth! very helpful!
Finding this gem made my morning. | https://community.esri.com/t5/arcgis-api-for-python-questions/web-map-content/td-p/807968 | CC-MAIN-2021-25 | refinedweb | 188 | 76.52 |
Before understanding ,what is routing ,let me explain you why even the concept of routing has been introduced , and the simplest reason that comes in my mind is ,it enables you define URLs of your services and web pages.
Let's discuss some points regarding URLs.
How the URLs of a web application should look like.
See the below URLs of a blog site :-
1. Home/Articles/3/4
2. articles/csharp/array
• obviously the first one is technical and not user-friendly, also it is not informative, on the other hand, the other one is user-friendly, well structured, and informative, anybody can tell only by seeing the URL about the content they are going to get with this request. Nowadays people like to share the link if they liked it over various social platforms and believe me a user-friendly URL gets more exposure.
• second, it boosts your SEO, it makes sense that if your page's URL contains keywords and your page content really describes those keywords, then chances of ranking well in the search engines becomes higher.
How the URLs of a REST service should be
Let me explain some concepts which you will find unrelated at a first glance but at the end of this article, you will be able to relate everything easily.
1. GetAllStudent is a verb, as it is pointing to an action, which does something.
Students are noun, as it is pointing towards a group of students.
Now remember the Rest Principles
• Everything on the web is a resource.
• Each resource has a URL.
Now, use common sense and say which of the below URL belongs to a rest service.
1. or
2.
Obviously, the second URL is better than the first one from the "REST" point of view, because it is pointing to a resource on the server while the first one is action based which is against the Rest principle. So, the rule of thumb is if you are creating a restful service then your URL will have noun segments and not a verb.
2. Path parameters (routed data) are used to identify a resource on the server while query strings are used to sort or filter a resource. So, until you don't want filtering never use query string parameters in the URL, in other words, a rest service will not have a URL with query string parameters unless it is filtering or sorting a resource.
for example-, is a good URL than, from Rest point of view, as the URL is pointing towards a particular student resource not filtering the resource based on Id. But, is a good URL even from the rest point, as it is actually filtering the courses taken by a particular student based on some category. obviously, anyone can debate on this, but this is what I think a URL should look like for a rest service.
so, now we know how the URLs of a rest service should look like, let's try to achieve the same, obviously the first step would be creating a Web API project and create any service as you wish, I am going to create a Student service where there will be two methods one which will expose students data and other will expose the list of courses taken by a particular student.
Step 1.Create two model classes , Student and Course.
public class Student { public int Id { get; set; } public string Name { get; set; } public List<Course> Courses { get; set; } } public class Course { public int Id { get; set; } public string Name { get; set; } }
Step 2.Create a Controller and Name it StudentService and Create 3 methods as shown below.
public class StudentServiceController : ApiController { public List<Student> LoadStudentData() { List<Student> students = new List<Student>() { new Student(){Id=1,Name="Sachin",Courses=new List<Course>(){new Course(){Id=1,Name="CSharp"},new Course() {Id=2,Name="Asp.Net"}}}, new Student(){Id=1,Name="Vikash",Courses=new List<Course>(){new Course(){Id=1,Name="CSharp"},new Course() {Id=2,Name="Asp.Net"},new Course(){Id=3,Name="KendoUI"}}}, new Student(){Id=1,Name="Arjun",Courses=new List<Course>(){new Course(){Id=1,Name="CSharp"},new Course() {Id=4,Name="Angular"}}}, }; return students; } public HttpResponseMessage GetAllStudent() { try { var students= LoadStudentData(); if(students!=null){ return Request.CreateResponse(HttpStatusCode.OK, students); } return Request.CreateErrorResponse(HttpStatusCode.NotFound,"no student found"); } catch { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error"); } }"); } } }
At this point our service is ready , now we want the following URLs for our service.
1. All Student :-
2. Course taken by a student:-{studentName}/courses
Now , the challenge that comes is , how to tell the Web API that if either of the above requests come then map it to appropriate handlers meaning if the request is then invoke the GetAllStudent() action of StudentService controller and if the request is{studentName}/courses , then invoke GetStudentCourses() action of StudentService controller.
And this is the place where exactly the Routing comes into the picture. Routing can be considered as a pattern matching system that matches the incoming http request's url pattern with all the url patterns stored in route collection and then maps that http request to appropriate controller Action. When the application launches then application registers one or more URL patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns.
Routing involes the following three steps
• Step 1: Finding the exact Route Template
• Step 2: Finding the Controller
• Step 3: Finding the Action Method
1. Finding the exact Route Template
Here you must be thinking, what exactly is the route template? You can think of Route template as a URI that consists of placeholders.
Example: "API/{controller}/{id}"
The above example looks like a normal URL the only difference is it is having placeholders for controller and id. These placeholders are kept within curly braces.
Note:
• Route Template can also contain literals, like "API/{controller}/{id}". Here the word "API" is literal.
• Placeholder's value can also be given in the defaults of the Route. Like defaults: new { Controller="Employee" }.
Route Template acts as an entry point for the Routing in ASP.NET WEB API. The Web API looks for the controller and action method if the requested URL matches with any of the registered URI in the form of a route template.
When a Request arrives at the API, first of all, the web API tries to match the URI with one of the Route Templates. If the template contains literals, then the API checks for an exact match of characters. And placeholders are replaced with the dynamic value from the URL. In the above example, the Route Template has 'API' as literal, API checks the same literal in the requested URL.
Note:
• API does not check URI's hostname.
• By default the Web API selects the very first route which is matched with the route template.
• Web API doesn't search for the placeholder's value if they are already provided in the defaults.
Example: URI:
The above URI match with the defined Route Template as Controller placeholder value has already been provided in the default of the Route.
Once the Requested URI is matched with Route Template, the placeholder's values are stored as the Key-value pair in Route Dictionary, where Keys are the placeholders and their values are taken from the URI.
Based on the above Route Template, Route Dictionary will have the following values
"Controller: Employee" and "id:1".
2. Finding the Controller
Finding the controller is simple. We know that the Route Dictionary stores the value of the controller which it gets from the URL, Web API gets the controller's value from this dictionary by providing the key, where the key is simply the word 'controller'. In the above example, the Controller's value is Employee. This value is been taken as the Controller key has Employee value. At last, the framework appends the Controller string to the value and Search for that controller. i.e EmployeeController. If there is no match for this controller then API returns an error message.
3. Finding the Action Method
This is a little typical phase of Routing. To find the exact action method, the framework looks for the three things, They are:
• The HTTP Method of the Request.
• Action placeholder value from the route dictionary.
• Parameters of the actions.
Here, the HTTP Method has an important role in selecting the exact action method. An important aspect is that the Action methods are selected based on the Naming Convention of the HTTP method or Attribute placed with the HTTP Method above it.
Explanation:
• If the request is a Get request, then either Action name should be Get or it should start with the word "Get___"
Example: GetEmployee() or GetEmployeeDetails() actions will be selected.
• The Action method selection will be made on the attribute as well.
[HttpGet] public HttpResponseMessage ShowEmployee() { //To Do }
Note:
• The Framework only looks for the public methods which are inherited from ApiController class. If the method is private or not inherited by the APIController, framework doesn't consider them as API methods and returns an error.
• If an Action Method does not satisfy the naming convention nor it contains any HTTP verb attribute, then, by default the framework treats the action method as the HttpPost method. (In case the Controller has specified action name which matches the exact action key value of Route Dictionary.)
Now you know what is routing and Why routing is necessary let's come to our requirement, our student service is ready and we want the following URLs for our service
1. All Student :-
2. Course taken by a student:={studentName}/courses
Now, what do you think, our first step should be? obviously, we have to define the Route templates according to the URL structure we want and add them to the framework's Route table. Now, the question that arises is, where to define the route template and how to add it to the RouteCollection (route table), as we had RouteConfig class in MVC to define route templates, in Web API we have WebApiConfig class which has a static Register method which accepts HttpConfiguration instance, the HttpConfiguration class has a public property "Routes" of type HttpRouteCollection, which is extended to add various route templates, in short MapHttpRoute() is an extension method of RouteCollection (routes) where we define route templates like shown below.
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "AllStudent", routeTemplate: "api/students", defaults: new { controller = "StudentService" } ); config.Routes.MapHttpRoute( name: "StudentCourse", routeTemplate: "api/students/{StudentName}/courses", defaults: new { controller = "StudentService" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
Explanation:-
1. To get all students:- whenever a request comes that matches the URL template "api/students" the framework gets the controller's value from the default and save it to the route dictionary in key-value pair, the SelectController method gets the controller value from the dictionary and appends Controller string to it and invoke that controller, as the HTTP method is a get, the framework tries to invoke the method which starts with "Get" word, in our case both the method starts with the "Get" word but one is parameterless and other is parameterized, as the dictionary does not have any Key value pair for parameterized method, the parameterless method is invoked.
2. To get a student course:- whenever a request comes that matches the URL template "api/students/{StudentName}/courses" the framework gets the controller's value from the default and StudentName from the URL and save it to the route dictionary in key-value pair, notice here the dictionary also contains the StudentName, the SelectController method gets the controller value from the dictionary and appends Controller string to it and invoke that controller, as the HTTP method is a "Get" method, the framework tries to invoke the method which starts with the word "Get", in our case both the method starts with the word "Get" but one is parameterless and other is parameterized, as the dictionary does have StudentName: something as Key-value pair for parameter binding, the parameterized method is invoked.
Different ways of defining routes in Web API:-
Web API supports two types of routing:-
1.Convention based routing and
2.Attribute routing.
• Convention based routing is very much similar to MVC routing, here we define one or more route templates, which are basically parameterized strings, at one place that is in the WebApiConfig class. When the framework receives a request, it matches the URI against the route template, The only difference is that Web API uses the HTTP verb, not the URI path, to select the action. But we can also use MVC-style routing in Web API and can provide Action name in the route template, though from the "REST" point of view it is not recommended. In the above example, we have used convention-based routing.
• convention-based routing makes it difficult to achieve certain URI patterns that are common in RESTful services. For example, resources often contain child resources like Customers may contain a list of orders, movies have actors, books have authors, students have courses, and so forth. It's natural to create URIs that reflect these relations: students/1/courses. This type of URI pattern is very difficult to achieve using convention-based routing. even if it could be achieved, the results don't scale well if you have many controllers multi-levels of resources. That is why Web API 2 supports a new type of routing, called attribute routing. As the name implies, we use attributes to define routes. with Attribute routing we have more control over the URL patterns For example, we can easily create URIs that describe hierarchies of resources as shown in the below example.
[Route("api/students/{StudentName}/courses")]"); } }
Note:- In order to use attribute routing with Web API, we need to enable it in WebApiConfig.cs file by calling config.MapHttpAttributeRoutes() method.
At last, if anything is defined it must be called from somewhere in the application, we know the routes should be stored in the routing table before any requests hit the Web API, meaning when the application launches for the very first time the route templates should be added to the routing table, so the best place to call the Register method of WebApiConfig class is the application_Start event of global.asax as shown below.
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); }
Now , when you run the application you get the desired results when request is made through appropriate URLs. | https://www.sharpencode.com/article/WebApi/web-api-routing | CC-MAIN-2021-43 | refinedweb | 2,451 | 58.42 |
Updated by Linode Contributed by Linode
Use promo code DOCS10 for $10 credit on a new account.
The k8s-alpha CLI is deprecated. On March 31st, 2020, it will be removed from the linode-cli. After March 31, 2020, you will no longer be able to create or manage clusters created by the k8s-alpha CLI plugin, however, you will still be able to successfully manage your clusters using the Kubernetes Terraform installer for Linode Instances.
In This Guide
You will use the Kubernetes Terraform installer for Linode Instances to continue to manage and support clusters created using the k8s-alpha CLI plugin following the EOL date and beyond. You will learn how to:
Manage k8s-alpha Clusters
The k8s-alpha CLI plugin was based on Terraform. As a result, it created a number of Terraform configuration files whenever it created a cluster. These Terraform files are found within the
.k8s-alpha-linode directory. You can change into this directory using the following syntax:
cd $HOME/.k8s-alpha-linode
If you list the contents of this directory, you will see a subdirectory for each of the clusters you’ve created with the k8s-alpha CLI plugin. For any of your clusters, contents of these subdirectories will be as follows:
drwxr-xr-x 5 username staff 160 Dec 11 08:10 .terraform -rw-r--r-- 1 username staff 705 Dec 11 08:10 cluster.tf -rw-r--r-- 1 username staff 5456 Dec 11 08:14 example-cluster.conf -rw-r--r-- 1 username staff 5488 Dec 11 08:16 example-cluster_new.conf drwxr-xr-x 3 username staff 96 Dec 11 08:10 terraform.tfstate.d
- Both of the
.conffiles are kubeconfig files for this cluster.
terraform.tfstate.dis a Terraform state directory.
.terraformis a hidden directory which contains Terraform configuration files.
cluster.tfis the Terraform module file. This is the most important file here because it will allow you to scale, upgrade, and delete your cluster.
Note
Scale a Cluster
Open
cluster.tfwith the text editor of your choice. The contents will be similar to the following:
- cluster.tf
To scale your cluster, edit the value of the
nodesvariable. To resize the number of nodes from
3to
5, make the following edit and save your changes:
variable "nodes" { default = 5 }
Once your edit is made, move back to the
/.k8s-alpha-linode/clusternamedirectory and apply your changes with Terraform:
terraform apply
Note
You may need to use the original Terraform version used to deploy the cluster (either Terraform 0.11.X or Terraform 0.12.X). If you do not, you will see syntax errors.
Once this is completed, you’ll see a prompt reviewing your changes and asking if you would like to accept them. To proceed, type
yesand Terraform will proceed to make the changes. This process may take a few moments.
Note
When prompted, you may notice that one item in your plan is marked as
destroy. This is generally a “null resource” or a local script execution and is not indicative of an unintended change.
After Terraform has finished, your cluster will be resized. To confirm, enter the following command to list all nodes in your cluster, replacing the string
myclusterwith the name of the cluster you edited:
kubectl --kubeconfig=mycluster.conf get nodes
The output will then list an entry for each node:
kubectl --kubeconfig=mycluster.conf get nodes NAME STATUS ROLES AGE VERSION mycluster-master-1 Ready master 21m v1.13.6 mycluster-node-1 Ready <none> 18m v1.13.6 mycluster-node-2 Ready <none> 18m v1.13.6 mycluster-node-3 Ready <none> 18m v1.13.6 mycluster-node-4 Ready <none> 4m26s v1.13.6 mycluster-node-5 Ready <none> 4m52s v1.13.6
Upgrade a Cluster
You may have noticed that the Terraform module file,
cluster.tf, refers to a specific branch or git commit hash referencing the remote Kubernetes Terraform installer for Linode Instances module on GitHub. The following section will outline how to upgrade your cluster to the latest version.
For example, your
source variable may have a value that points to the git branch ref
for-cli. To perform an upgrade this must point to the latest commit history hash.
Visit the branch of the Terraform module you’re using on Github. Note the commit history and copy the latest hash by clicking on the clipboard next to the hash of the most recent commit. At the time of this writing, the most recent hash is as follows:
5e68ff7beee9c36aa4a4f5599f3973f753b1cd9e
Edit
cluster.tfto prepare for the upgrade. Update the following section using the hash you copied to appear as follows:
- cluster.tf
To apply these changes, re-initialize the module by running the following command:
terraform init
Once this has completed, apply your changes with the following command:
terraform apply
Note
Depending on the changes that have been configured, you may or may not see the upgrade perform actions. For example, in this case, because the only change was to the Kubernetes version, no actions were taken.
Delete a Cluster
To destroy a cluster, navigate to the directory containing your cluster’s files, and enter the
terraform destroy command:
cd ~/.k8s-alpha-linode/mycluster terraform destroy
Terraform will prompt you to confirm the action, and on confirmation will proceed to destroy all associated resources. If this process is interrupted for any reason, you can run the command again at any time to complete the process.
Create a Cluster
Create a new directory to house the new cluster’s configuration files in the
~/.k8s-alpha-linodedirectory. In this example the cluster name is
mynewcluster:
cd ~/.k8s-alpha-linode mkdir mynewcluster
Create a Terraform module file in this new directory called
cluster.tfwith your desired configuration. Replace the values for the variables
ssh_public_keyand
linode_tokenwith your own unique values and feel free to change the configuration values for the cluster itself. The example configuration below will create a cluster with a 4GB master, with a node pool with three 4GB Linodes, hosted in the us-east region:
- cluster.tf
Initialize and apply your new Terraform configuration:
terrform workspace new mynewcluster terraform init terraform apply
When prompted, review your changes and enter
yesto continue.
Once completed, you’ll see a kubeconfig file,
mynewcluster.conf, in this directory.
To complete your deployment, you will use this kubeconfig file and export it using the following syntax:
export KUBECONFIG=$(pwd)/mynewcluster.conf kubectl get pods --all-namespaces
Once completed, you should see your new cluster active and available with similar output:
NAMESPACE NAME READY STATUS RESTARTS AGE kube-system calico-node-4kp2d 2/2 Running 0 22m kube-system calico-node-84fj7 2/2 Running 0 21m kube-system calico-node-nnns7 2/2 Running 0 21m kube-system calico-node-xfkvs 2/2 Running 0 23m kube-system ccm-linode-c66gk 1/1 Running 0 23m kube-system coredns-54ff9cd656-jqszt 1/1 Running 0 23m kube-system coredns-54ff9cd656-zvgbd 1/1 Running 0 23m kube-system csi-linode-controller-0 3/3 Running 0 23m kube-system csi-linode-node-2tbcd 2/2 Running 0 21m kube-system csi-linode-node-gfvgx 2/2 Running 0 21m kube-system csi-linode-node-lbt5s 2/2 Running 0 21m kube-system etcd-mynewcluster-master-1 1/1 Running 0 22m kube-system external-dns-d4cfd5855-25x65 1/1 Running 0 23m kube-system kube-apiserver-mynewcluster-master-1 1/1 Running 0 22m kube-system kube-controller-manager-mynewcluster-master-1 1/1 Running 0 22m kube-system kube-proxy-29sgx 1/1 Running 0 21m kube-system kube-proxy-5w78s 1/1 Running 0 22m kube-system kube-proxy-7ptxp 1/1 Running 0 21m kube-system kube-proxy-7v8pr 1/1 Running 0 23m kube-system kube-scheduler-mynewcluster-master-1 1/1 Running 0 22m kube-system kubernetes-dashboard-57df4db6b-rtzvm 1/1 Running 0 23m kube-system metrics-server-68d85f76bb-68bl5 1/1 Running 0 23. | https://www.xpresservers.com/how-to-migrate-from-k8s-alpha-cli-to-terraform/ | CC-MAIN-2021-39 | refinedweb | 1,328 | 54.93 |
Python functions can be called from LabTalk, such as from Set Column Values dialog, Script Window, script associated with a button, or anywhere else in Origin with access to LabTalk scripting.
Python functions can be defined and accessed in the Set Values dialog for both Worksheets and Matrixsheets. The Python function should be defined in the Python Function tab. The function can then be called from the formula edit box or from the Before Formula Scripts tab.
If your Python function requires other packages, they need to be installed prior to defining and accessing the function from the Set Values dialog.
With column formula, the function should be defined to return a list of floats or strings in order to have optimal performance. If the function is defined to return a single float or a string, then the function will be called for each row involved in the calculation.
In this example, a Python function is used in column formula of column C to smooth noisy data from column B. The function is defined as:
import numpy as np
from scipy import signal
def smooth(y, npts, norder):
"""
F:Fii
"""
y=signal.savgol_filter(np.array(y), npts, norder)
return y
This function accepts a list of floats and two integers that specify the smoothing window and polynomial order, and returns a list of floats. The input and output types are specified using docstring as F:Fii. It is assumed here that NumPy and SciPy packages are already installed.
To access the function from the formula edit box, the function name needs to be pre-pended with py...:
py.smooth(B, 51, 2)
The image below shows the worksheet with the raw data and results, and the Set Values dialog with the Python Function tab.
In this example, a Python function is used to perform group statistics on data columns. The function accepts three columns of data and returns three columns with the results. The function therefore cannot be directly called from the Formula box. Instead, the Before Formula Scripts tab is used to call the function.
The function is defined as:
import pandas as pd
def groupstats(ID, x, y):
if len(ID) == len(x) and len(ID)==len(y):
df = pd.DataFrame({'ID':ID,'x':x,'y':y})
df1 = df.groupby('ID').mean()
return df1.index, df1.x, df1.y
else:
return [], [], []
Note that the input and output types are not explicitly defined in this function. The three input columns passed to the function are converted to lists. The computation is performed using dataframe, and the function returns three lists.
The values returned are placed in three output columns using the script command in the Before Formula Scripts tab:
col(D), col(E), col(F) = py.groupstats(col(A), col(B), col(C))
In the previous two examples, the Python function was defined in the Set Values dialog. The worksheet could then be saved as a template along with the Python function and then a new instance of the template can be opened for future use.
Python functions can also be defined in external files and then accessed in column or cell formula. In the following example, a function defined in the file labTalk.py is called. More details on defining functions in external files are available in the sections that follow.
You can create a custom import filter using Import Wizard where a Python function is used to parse the file and perform the import. For more information on this, please refer to this section on importing files using user-defined functions.
Python functions can be defined in external .py files. By default Origin will look for the function in a file named labtalk.py located in your User Files Folder (UFF). You can open this file from the Origin menu Connectivity: Open Default Python Functions....
Functions defined in the labtalk.py file can be called from LabTalk script using syntax such as:
col(B)=py.f1(col(A));
where f1 is the function name.
The file examples.py has several examples of defining Python functions. You can open this file from the Origin menu Connectivity: Open examples.py. Copy the desired function from this file to labtalk.py.
If you define functions in other .py files, you can access them with syntax such as:
col(b) = py.myfuncs.sort(col(a))
where the function sort() is defined in a file named myfuncs.py.
Origin will look for the .py file in the User Files Folder (UFF) by default. A different working directory can be set using the Python object property: Python.LTwd$.
The file name can be left out when calling functions by setting the Python object property: Python.LTwf$.
Python.LTwd$="D:\Python";
Python.LTwf$=MyFunctions.py;
col(B)=py.sort(col(A)); // call function sort from file MyFunctions.py located in D:\Pytyhon folder
The object properties used above are empty, and not set by default. The default python file location is internally set to UFF folder, and the default file name is internally set to labtalk.py Once you assign a value to either of these properties, the value is saved in the Origin.ini file located in the UFF.
Python functions can be defined with specific input and output argument types. There are two ways to specify types:
Here are several examples:
# Examples where function annotation is used to specify type
def a1(a, k:int):
return a + k
def a2(a, b)->int:
return a + b
def ss1(a:str, b:str)->str:
"""using function annotations"""
c = a + b
return c
def ss3(a:list)->list:
return [len(x) for x in a]
def ss2(a:list, b:list)->list:
c = [ x + y for x,y in zip(a, b)]
return c
# Examples where docstring is used to specify type
def s2(a,b):
"""
S:SS
concatenate strings, array version
"""
c = [ x + y for x,y in zip(a, b)]
return c
def s1(a, b):
"""
s:ss
concatenate strings, scaler version
"""
c = a + b
return c
def s3(a):
"""
F:S
intput string list and return float list
"""
return [len(x) for x in a]
def sin(a):
"""
F:F
return sine
"""
return np.sin(np.asarray(a))
This function accepts a list of float and two integers as input, and returns a list of float. It also uses NumPy and SciPy packages:
import numpy as np
from scipy import signal
def smooth(y,npts, norder):
"""
F:Fii
Perform Savitzky-Golay smoothing using scipy signal
"""
#npts: number of points for smoothing window
#norder: polynomial order
y=signal.savgol_filter( np.array(y), npts, norder )
return y
However whether the function can be accessed from column formula will depend on how the function is defined.
If it is defined as a scalar function and will be called for each row, the input/output type needs to be specified, such as:
def a1(a:float, b:int = 10)->float:
return a+b
If it is defined as a vector function, input/output type does not need to be specified, such as
def a1(a, b:int = 10):
return [x + b for x in a]
Here, the input/output type is assumed as list.
Either way, the function can be used in column formula or from script as in col(B)=py.a1(col(A)).
Multiple values or lists can be returned to LabTalk from Python functions.
This function accepts a list and two floats as input, and returns two lists:
def f3(a, b=5, c=10):
b = [x + b for x in a]
c = [x + c for x in a]
return b, c
In a new worksheet, fill col(A) with some numbers. Then from script, you can access the function such as:
col(b),col(c)=py.f3(col(a))
Tuple-returning example:
You could add the following to the file labtalk.py in your User Files Folder, then save the file:
def TestReturnTuple(arg1, arg2, arg3):
print('TestReturnTuple11: arg1 = ', arg1)
print('TestReturnTuple11: arg2 = ', arg2)
print('TestReturnTuple11: arg3 = ', arg3)
return ([arg1, 10*arg1, 100*arg1], [arg2, arg2/10., arg2/100., arg2/1000.], 1000 * arg3)
To run the example, do the following:
col(A), col(B), myvar= py.TestReturnTuple(3., 45., 66);
myvar=;
The function returns a tuple with two lists -- one to col(A) and one to col(B) -- and one numeric scalar that is written to the LabTalk variable, myvar.
myvar
Python functions can also be defined in .py file that are attached to the Origin project (OPJU). The functions in attached files can be accessed with the notation such as:
col(b)=py.@filename.func(col(a))
The @ character in front of the file name indicates to Origin that the file is attached to the project.
If there is only one .py file attached to the project, which is recommended, then the file name can be dropped when accessing the function, such as:
col(b)=py.@func(col(a)) | https://www.originlab.com/doc/python/Calling-Python-Functions-from-Column-Formula-and-LabTalk | CC-MAIN-2020-50 | refinedweb | 1,489 | 62.27 |
If. The town house we’re moving into is definitely larger than our previous condo, but it wasn’t until we had to pack everything, move it, and then unpack it that we realized how much stuff we had accumulated over the years. Yes, there was a reason for everything we had, but it was still a lot of stuff. Then we came to the realization that we prefer a more open, simpler environment with fewer pieces of furniture, fewer paintings covering the walls, and less clutter in general.
That is an interesting insight because it applies to many different things, including programming: There is a cost associated with having a complex, cluttered environment, whether it be the furniture in your house, your class hierarchy, or your build process. In particular it will create resistance to change, which can be in the form of a cross-country move, or a simple class refactoring.
Goals
The ultimate reason to write code is to have the computer carry out a sequence of instructions. In our case, that sequence of instructions is a game or a tool to help create the game. It is tempting to think of the computer as the “audience” for our program, but it is not a very good audience. It is way too forgiving, and as long as things compile, it’ll be happy with anything you throw at it. We can do better than that.
We can still write code that is correct, but with people in mind as the primary audience. The usual reason for choosing people as your audience is that software development is a team effort, and it’s very important that other people be able to understand and modify your code. True, but there’s more to it than that. Even if you were the only person writing code, you should still write for people, not computers. Assuming it’s more than a toy project, you will have to refactor your code as you learn new things about it. Probably not once, not twice, but many times over the course of the project’s lifetime. You will have to keep it up to date, fix bugs, add new features, etc. I am convinced that refactoring (or lack thereof) is one of the major influences on code quality, and, as a consequence, product quality, so anything to help with that is extremely important in my book.
Lately, I’ve been taking it a step further and thinking of my audience not just other programmers, but other people who are not programmers. If you manage to write some code that a non-programmer can more or less understand, then you know you’re there. The code should be simple and self-explanatory enough that should be a breeze to refactor in the future.
But wait, as if ease of refactoring wasn’t enough, there are more reasons for writing really simple code. Edsger W. Dijkstra in his lecture “The Humble Programmer” advocated the avoidance of clever tricks and urged programmers to be fully aware of the limitations of the human mind when writing programs.
“The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague.”
Dijkstra’s reason for keeping clever tricks away is not so much for ease of refactoring, but the quality of the program itself. Programmers are all too eager to tackle something too ambitious at once, without breaking it down into smaller, more understandable sub-problems, and, as a result, create a disastrous program that crashes often and doesn’t even implement all the required features.
Today, this sounds like a surprisingly modern attitude. After all, it’s right up the alley of agile development. But amazingly, this lecture took place in 1972. Talk about timeless advice (OK, OK, in the really short scale of computer history, not in the grand scheme of things).
Brian Kernighan had also something to contribute to the idea of writing simple code, but coming from a very different angle:
“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
While I totally agree with the sentiment, I feel it is not as important as the other two reasons for aiming towards code simplicity. Frankly, if you use test-driven development and take steps of the correct size, you should hardly ever find yourself knee-deep in the debugger trying to make sense of your program. However, a decade or two ago that made a lot more sense, especially given that debuggers were less sophisticated then as well. Still, anything that encourages programmers to keep things simple is a step in the right direction. So if that convinces some people, so be it.
Attaining Simplicity
Great. Simple is good. How do we write “simple” code? That’s not something they teach in school and it’s not something that is pushed for in the workplace, so it’s probably not something you’re used to thinking about. The rest of the article will be a series of suggestions and techniques on how to make code as simple as possible. Specific examples are given in C++, but the general techniques should apply to most object-oriented languages.
Avoid unnecessary language tricks.
Listen to Dijkstra and go easy on “clever code.” If you feel the need to write a comment to explain to other people what that cute line of code you just wrote does, you should very strongly consider re-writing it so a comment is not necessary. I’m not saying to avoid taking advantage of language features, just the ones that can be done in another, simpler way. For example, don’t use a template when a non-templated implementation is perfectly fine. Don’t rely on a clever arrangement of variables so they’re initialized in the correct order even though the language standard says it should work.
Avoid or postpone performance optimizations that obscure the meaning of the code for as long as possible.
You’re all familiar with the Donald Knuth quote: “Premature optimization is the root of all evil.” Programs have a way of twisting into evil, misshapen fiends when they’re optimized, and they usually become much harder to refactor afterwards. Specifically in this case, I suggest avoiding (or delaying at least) optimizations that affect how simple or readable a section of code is. There are many ways to skin a cat, and there are also many ways to optimize a program. I find that there is often a way to optimize things that doesn’t cause a major loss in code simplicity. But if that’s not possible, at least defer that optimization as long as possible. Maybe you won’t need it, and maybe the code will change before then and you’ll save yourself a lot of rework.
Functions should do one thing only.
The secret to a good function is that it should do one thing and one thing only. Functions that follow that rule are usually quite small (at most 10-15 lines in C++) and their whole meaning can be easily understood at a glance. Because the function has only one purpose, refactoring becomes very easy: No need to worry about how changes in that function will affect other parts of the function, no pesky local variables reused in many parts of the function, etc.
Maybe this is a bit extreme, but ideally, functions should be so simple that I should be able to look at a function, delete it and re-write it from scratch without any difficulty.
I follow two guidelines to keep functions as simple as possible:
- If a function goes over 10 to 15 lines of code, I look at it really hard and try to split it. Chances are it’s doing more than one thing.
- If I ever feel the need to write an explanatory comment about what a few lines of code do, I move those lines into a function of their own and give it a name that explains what it does (usually the same as the what the comment would have been). By following this rule, the only comments in my code are the ones that explain *why* the code does things the way it does, and deal with higher-level such as the purpose of a class or a library.
Classes should do one thing only.
This should come as no big surprise. If we want our functions to be small, simple, and just one thing, we also want the same qualities from our classes. When classes are left unchecked, they can easily grow into unmanageable blobs of many thousands of lines. The largest class I had the misfortune of encountering had a staggering 10,000 lines in it, and the problem was compounded by inheriting from another class with over 8,000 lines! As you can imagine, having to do any work near that class was quite a punishment.
Personally, I feel that C++ classes should ideally be no more than about 200-300 lines (remember, with virtually no other comments). Anything that goes beyond that, and I start thinking hard about what exactly the class does. If a class reaches 1000 lines, it’s time to get the axe out.
One technique I’ve been following to keep classes as simple as possible is to use the controversial suggestion from Scott Meyers on how to decide on the scope of a function. The quick summary is that functions should be pushed out of a class as much as possible: if a function can be implemented as a non-member function, then do it; if it can be a class static, make it so; otherwise, leave it as a member function.
One immediate consequence of following that advice is that a class is stripped of anything that is not essential. Helper functions (both public and private to the class) are pushed out, and the meaning of the class is made more clear. The second consequence is that refactoring is a lot easier. By using non-member functions in anonymous namespaces whenever possible, we avoid the need to edit any header files at all, which results in faster compile and iteration times. Also, since those functions are completely independent of the class, they’re trivial to move around, promote to higher levels, etc. while member functions require some massaging to move around.
I’m suggesting that we keep functions small, but also that we keep classes small. We’re not going to end up with any less code than we would have before, but we’re going to end up with many more classes scattered all over our program. We have pushed the complexity from the function and class level up to the program organization and architecture level. The next article in this series will deal with how to manage this newfound complexity, but here’s a preview: Use hierarchies.
Timings, logging, and error handling? We could argue that timings should be done with non-intrusive methods such as using profilers, but that’s not always possible or desirable. We often want very specific timings that only affect a particular section of the code (load times), or we want to continuously monitor performance of certain sections while the game is running. For example, we probably want to get an idea of how much time we’re spending each frame on each of the major tasks: entity updates, AI calculations, physics, animation, rendering, sound, etc. We need to wrap each of those areas in timing statements. The more detailed we want those timings to be, the more junk we’ll have to add to the code. We can try making that as clean as possible by using macros that only require one line, but it’s still junk that obscures the meaning.
Logging doesn’t even have a non-intrusive counterpart unless you want to automatically add prologue and epilogue code to every function (which would generate way too many messages and would affect performance too much). So we’re stuck writing messages by hand to the log system.
Error handling at least as has the possibility of using exceptions, which add a lot less clutter than returning and checking error codes. Unfortunately, we have to deal with several real-world issues which often make exception-handling impractical. The first one is performance. As much as I hate bringing this up, exception handling can easily have a significant performance impact even in modern hardware. This is something that will hopefully go away in the near future as PC hardware and consoles become more powerful. The second problem is compiler support. Even today, some console manufacturers are admitting that exception-handling support in their compilers is not usable and we shouldn’t rely on it. So much for that idea. Finally, and probably most importantly, is complexity and programmer knowledge. If you have read Exceptional C++ you how complicated it can be to write exception-safe code, and not every C++ programmer out there today is going to feel comfortable using exceptions. All of this is a vicious circle, because until programmers demand robust and efficient exception handling, compiler and system creators aren’t going to provide them, which means a lot of programmers are not going to be exposed to them, etc, etc.
So, what great solutions do I have to this problem? None, I’m afraid. This is where I’d like to hear from some of you. How do you deal with timing, logging, and error handling in a way to minimize the clutter and leave your code as clear as possible? Email me and I’ll edit this article or make a new one with any great solutions I receive.
Striking a balance
In the end, even if we have the best goals in mind about simplicity, we will be forced to make compromises. Error handling is one case. Another case is often performance. Sometimes, having many scattered functions can add up to a noticeable performance hit in some inner loop of a performance-critical section. In that case simplicity needs to give way to practicality and do whatever is necessary. Just make really sure that having many functions is the cause of the performance problems before you make any changes.
It is also important not to confuse code simplicity with algorithmic simplicity. Writing simple code doesn’t mean that you have to use a silly bubble sort to order a list. Always choose the most appropriate algorithm for the task at hand, just implement it with the simplest possible code. Implementing it in a very simple way will also make possible to easily change it down the line with a more efficient algorithm.
The next article will deal with how to manage all the complexity we’ve pushed up into the program structure. Until then, keep your functions short, your classes clean, and remember The Humble Programmer:
“. “
Performance Breakthrough!
Simple is Beautiful | http://gamesfromwithin.com/simple-is-beautiful/comment-page-1 | CC-MAIN-2020-10 | refinedweb | 2,538 | 59.94 |
Mark Trench Financial Accounting Standards Board (FASB) 401 Merritt 7 P. O. Box 5116 Norwalk, CT 06856-5116
Hans van der Veen International Accounting Standards Board (IASB) 30 Cannon Street London, EC4M 6XH United Kingdom
Dear Mark and Hans: The topic of discounting plays a key role in several conceptual accounting projects that are currently underway. The concept of “fair value” is also prominent in these discussions. A wide variety of methods have been, and continue to be, developed for discounting in the context of fair value measurements. Such methods combine both discounting and provision for the market price of risk in various ways. Concern has arisen among many actuaries, however, that when certain methods are specifically enumerated in accounting standards, it could imply a prohibition on the use of alternative methods that are consistent with stated valuation objectives, unless it is clearly stated that alternative methods are allowed. As accounting standards evolve, the need to allow the use of alternative methods that are consistent with a set of stated principles could be overlooked. The Financial Reporting Committee of the American Academy of Actuaries 1 (“Academy”) wishes to emphasize the importance of allowing flexibility in methodology for discounting and fair value measurement, subject to stated principles and valuation objectives. With that in mind, we have developed a White Paper, “Notes on the Use of Discount Rates in Accounting Present Value Estimates,” which is attached for your information. Current accounting standards provide some comfort with respect to the use of alternative methods. For example, Statement of Financial Accounting Concepts No. 7 (“CON 7”).” 1
The American Academy of Actuaries (“Academy”)
Similarly, Statement of Financial Accounting Standards No. 157 (“FAS 157”) includes the following statement in Appendix B: “This appendix neither prescribes the use of one specific present value technique nor limits the use of present value techniques to measure fair value to the techniques discussed herein.” Nearly identical wording appears in the current IASB Exposure Draft on Fair Value Measurement (“IASB ED 2009/5”) in the first paragraph of Appendix C. Our White Paper describes a number of valuation methods commonly used today that are consistent with the principles stated in CON 7, FAS 157, and IASB ED 2009/5. Several of the methods discussed in the White Paper are not explicitly mentioned in those documents. These include: certain methods for valuation of insurance liabilities with non-guaranteed investment elements; stochastic methods that use adjusted probabilities (rather than adjusted cash flows or adjusted discount rates); and stochastic methods that use discount rates that vary by scenario. Note that we do not advocate adding descriptions of these methods to future accounting standards. Instead, we hope that this sampling of currently applied methodologies will reinforce the need for future standards to continue the practice of explicitly stating that alternate approaches are allowed. If we can be of further assistance, please contact the Academy’s Senior Risk Management and Financial Reporting Policy Analyst, Tina Getachew, at getachew@actuary.org or +1 202.223.8196. Sincerely yours,
Stephen J. Strommen, FSA, MAAA Vice-Chair, Financial Reporting Committee American Academy of Actuaries Cc: Sam Gutterman (Chair, Insurance Accounting Committee, International Actuarial Association)
1850 M Street NW Suite 300
Washington, DC 20036
Telephone 202 223 8196
Facsimile 202 872 1948
Discussion on the use of Discount Rates in Accounting Present Value Estimates American Academy of Actuaries1 Financial Reporting Committee September 2009 This white.
The members of the Discounting Subgroup that are responsible for this white paper are as follows: Chairperson: Stephen Strommen, CERA,FSA,MAAA Steven Alpert, EA, FCA, FSA, MAAA, MSPA Mark Freedman, FSA, MAAA Burton Jay, FCA, FSA,MAAA Kevin Kehn, FSA,MAAA Ken LaSorella, FSA,MAAA Jeffrey Lortie, FSA,MAAA Robert Miccolis, FCAS, MAAA William Odell, FCA, FSA,MAA,ACAS Jeffrey Petertil, ASA, FCA, MAAA Leonard Reback, FSA,MAAA
1
The American Academy of Actuaries (“Academy�)
Introduction and Purpose At the time of writing (mid-2009), several conceptual accounting projects were underway that involve discussion of discount rates and present value estimates, including but not limited to the IASB/FASB joint project on Revenue Recognition and the IASB/FASB joint project on insurance contracts. When discount rates 1 and present value estimates have been discussed in these wider projects, the discussion has tended to be limited in scope. There is concern, however, that such limited discussions may result in accounting standards that limit the scope or breadth of techniques that are allowed when making present value estimates for accounting purposes. In this paper, we use the term “present value estimate” rather than the accounting term measurement to make a useful distinction. Present value estimates involve unknown (and in many cases unknowable) future outcomes; the estimating process thus aims to determine a single value (i.e., the present value) as representative of a range or distribution of potential future outcomes. By contrast, the term measurement is often used in the context of known or knowable fixed quantities. In the context of insurance, for example, the total of benefits actually paid is a measurement; the present value of benefit obligations is an estimate. Estimates are therefore needed for accounting measurement of items whose value is uncertain. Our focus in this document is on present value estimates that are intended to reflect market conditions on the valuation date 2 . There are several terms for such estimates, including fair value, fulfillment value, current value, and so on. These estimates share the common trait that similar methods of discounting can be used for any one of them, and it is those methods of discounting that we wish to discuss. 3 FASB Statement of Financial Accounting Concepts No. 7 (“CON7”) allows a broad range of valuation techniques when it.” The elements of fair value estimate in paragraph 23 are: “
1
In this white paper we use the term “discount rate” as it is used in FAS 157, somewhat interchangeably with “interest rate”. Texts on the theory of the time value of money draw a technical distinction between “discount rate” and “interest rate”, but for ease of understanding we ignore this technical issue. 2 The market conditions we are concerned with in this discussion of discounting are limited to market interest rates and items related to interest rates such as liquidity premiums, credit spreads, and market volatility. The definition of accounting measures such as fair value and fulfillment value sometimes differ in whether market-based or entityspecific assumptions are to be used when projecting the cash flows to be discounted, but we are not concerned with those differences in this paper. 3 This means that amortized-cost methodologies for accounting valuation are outside the scope of this discussion.
2
a. An estimate of future cash flow, or in more complex cases, series of future cash flows at different times. b. Expectations about possible variations in the amount or timing of those cash flows. c. The time value of money, represented by the risk-free rate of interest. d. The price for bearing the uncertainty inherent in the asset or liability. e. Other, sometimes unidentifiable, factors including illiquidity and market imperfections.” Exactly the same elements of fair value are documented in the May 2009 IASB Exposure Draft (“IASB ED 2009/5”) on Fair Value Measurement, in Appendix C, paragraph 2. CON 7 was issued in February 2000. Some more recent accounting discussions that mention present values or discounting explicitly refer to the risk-free rate mentioned in paragraph 23c above, without putting it in the context of a complete valuation technique that must embody all five elements. Some readers interpret such mention as a proposed rule forbidding the use of valuation techniques which use discount rates that reflect the combined effect of several of the five elements above, including paragraph 23d (uncertainty) and paragraph 23e (illiquidity). In addition, some accounting discussions 4 mention the “expected cash flow approach” wherein several possible patterns of future cash flow are projected and then probability weighted to obtain “expected” future cash flows, which are then discounted to obtain the present value. Some readers interpret such mention as a proposed rule forbidding the use of path-specific discount rates that are commonly used in practice when future cash flows depend on the uncertain level of future interest rates. And, some readers lament the limited nature of discussion on how the market price of risk and uncertainty is incorporated into the “expected cash flow approach”. We are concerned that these discussions and others are potentially leading to valuation rules that may not reflect all the elements of fair value outlined above. This paper explains the basic theory behind some valuation techniques that reflect all five elements of fair value as listed in CON 7 paragraph 23. It is our hope that the Boards will reaffirm the relevance of all five elements in any valuation intended to reflect market interest rates on the valuation date, and will continue to use language like the following, which appears in both FAS 157 and IASB ED 2009/5, in the respective Appendices titled Present Value Techniques. “This appendix neither prescribes the use of one specific present value technique nor limits the use of present value techniques to measure fair value to the techniques discussed herein.” Section 1 of this white paper covers the use of discount rates other than the risk-free rate. Section 2 covers stochastic techniques, where multiple paths of future cash flows are projected and probability-weighted to obtain a single value. All of the techniques discussed in this paper would appear to be consistent with paragraph 57 of CON 7, since they reflect the five elements listed in paragraph 23. However, many of the discounting techniques discussed here differ from those specifically mentioned in FAS 157 and IASB ED 2009/5. The purpose of this paper is to explain these methods with a focus on how they reflect “the price for bearing the uncertainty inherent in the asset or liability”. The intent is
4
E.g., paragraph 46 of CON7
3
to clarify any discussion concerning the use of techniques like these under a broad interpretation of CON 7 paragraph 57.
Section 1 – The discount rate and provision for risk The time value of money is conceptually represented by the risk-free rate of interest 5 . But for accounting purposes one is often required to measure the value of an asset or liability that is not risk-free. There are many ways to adjust for risk in a present value calculation. One convenient and frequently used method is to adjust the discount rate, reflecting market-observable discount rates for cash flow streams with similar timing and risk characteristics. The very name of the term “risk-free rate” presumes that there exist other rates of interest that exist when risk is present. This concept can easily be illustrated using a simple corporate bond as an example. Our example bond has a market value of $100.00 today, and is scheduled to mature in one year for $107.00. No coupons or other cash flows will contractually occur between today and the maturity date one year from now. Assume that the risk-free rate for a one-year term is 5%, and also that this bond bears a default risk. Since the market value of the bond is $100.00, we don’t even need to pick a discount rate or evaluate the provision for risk. The market price implies that the risk-adjusted discount rate is 7.0%. However, it is instructive to examine the components that are embodied in the difference between the risk-adjusted and the risk-free rates. Note that the market’s provision for risk in the price of this bond can be dissected into two parts. First there is the market’s perception of the expected, or probability-weighted cost of default. Second, there is the risk of whether a default will or will not occur, and the price the market extracts for bearing that risk. In the case of a bond, it is not usually possible to separate these two elements; all that is observable is the total market price for the risky asset.
Example 1: Discount rate includes full provision for risk Discount rate = 7%. Under this method, the discount rate provides the full provision for both aspects of the risk. We discount the contractual cash flows at the market’s risk-adjusted discount rate of 7%. The present value of $107.00 at 7% interest is $100.00.
Example 2: Cash flows are adjusted for expected defaults; discount rate provides only for the cost of uncertainty about default. Discount rate= 5.93% In this example, we need to make an assumption about the expected rate of default. As noted earlier, the expected rate of default cannot be separately identified by market observations. For purposes of this example only, we assume that the expected rate of 5
As a practical matter, identifying the risk-free rate, or many of the other conceptual quantities that will be discussed in this paper, is not always easy. The purpose here is to focus on the conceptual framework that governs relationships between quantities. Estimation of the quantities themselves (such as the risk free rate) is a separate topic and is beyond the scope of this paper.
4
default is 1%. Under this method the discount rate provides only for the risk of whether default will occur, but does not adjust for the probability-weighted “expected” cost of default. The cash flows are adjusted to reflect the expected defaults. To adjust the cash flows, we subtract an amount reflecting 1% probability of total default, or $1.07, so the expected cash flow before discounting is $107.00 - $1.07 = $105.93 6 . Discounting the expected cash flow at 5.93% then provides the $100.00 market value. Observe that 5.93% is greater than the risk-free rate because it includes a provision for the risk of whether default will occur (that is, the assumed market price for bearing the default risk).
Example 3: Discount rate includes no provision for risk Discount rate = 5.00% Under this method the discount rate is the risk-free rate and all adjustment for risk is done by adjusting the cash flows. The adjustment to cash flows must include not only the $1.07 for expected defaults, but also a market-calibrated provision for the risk of whether default will occur. The cash flows must be adjusted to be “certainty equivalents”. The market-calibrated provision for risk in this case is $0.93, so the certainty equivalent cash flow is $107.00 – $1.07 – $0.93 = $105.00. Discounting at the risk-free rate of 5% then leads to the market price of $100.00.
IASB ED 2009/5 lists three methods for adjusting for risk in Appendix C, paragraph C6 (a), (b), and (c). Example 1 above is analogous to the “discount rate adjustment technique” from C6(a). Example 2 is analogous to “method 2 of the expected present value technique” from C6(c). Example 3 is analogous to “method 1 of the expected present value technique” from C6(b). These same three methods are outlined in FAS 157 Appendix B. When the purpose for a valuation is to obtain a market-based or market-consistent value for an item that includes risk or uncertainty, it is best to use the most directly applicable and readily available information concerning market pricing for similar risks. This information can take several forms, leading to several different valuation techniques for estimating the effects of risk. In the example above, the most readily available information on market pricing is the market spread over the risk-free rate, or 2% = 7% - 5%. This spread could be used as means of estimating the effect of risk when valuing other assets that have similar risk and payment characteristics. However, there are situations where cash flow adjustments are more directly related to observable market parameters than are discount rates. A variety of methods should be allowed, as the most direct method is likely to be the most reliable, and depends on the circumstances. Sections 1.1 to 1.3 present examples of risk adjustment methods for a variety of risks that are relevant to valuing insurance contract liabilities. It is understood that insurance contracts often involve many different risks, all of which must be reflected in the same valuation, so several adjustments often need to be combined together. Insurance contracts may also require assumptions and estimates to account for the difference between contract risks and marketobservable analogues used as inputs to the valuation.
6
Or, equivalently, take a weighed average of 107 x 99% [assumed probability of payment in full] + 0 x 1% [assumed probability of total default]. This simple example assumes no partial recovery on default.
5
1.1 Risks of own credit standing and liquidity: the financing rate When a customer pays money to initiate an insurance contract with an insurer, the customer takes on two risks: •
Credit risk: The risk that the insurer will not pay contractual benefits when due.
•
Liquidity risk: The loss of ready access to funds. The customer loses access to their funds between the time the contract is paid for and the time when contractual benefits are due. 7
These two risks are also present in a financing transaction wherein a lender provides funds to a borrower. The lender takes the credit risk and also loses access to the funds except under contractual terms. There is a clear analogy here – the insurance customer is in the position of the lender and the insurer is in the position of the borrower. As was mentioned earlier, provision for risk can be made in many forms. We now discuss how to provide for the credit and liquidity risks. We start from a valuation that does not provide for risk: the present value of certain cash flows at the risk-free rate. We note that risks to the insurer should increase the value, and risks to the customer should decrease the value. Since credit risk and liquidity risk are both risks to the customer, when taken into account they should decrease the value of the insurer’s liability 8 . A decrease in present value can be obtained by increasing the discount rate with some sort of interest rate spread. Let the risk-free rate be i rf ; let the spread for credit standing be s credit ; and, let the spread for liquidity risk be s liquidity . The adjusted discount rate is then irf + s credit + s liquidity 9 . As was noted above, these same two risks are present in a financing transaction. Therefore, one can think of this adjusted discount rate as a financing rate. For purposes of this document, we will symbolize the financing rate as: i f = irf + s credit + s liquidity .
1.2 Risk of the uncertain level of claims In the valuation of insurance liabilities, one of the most common risks is that of the unknown level of actual incurred claims and claim payments. A margin for this risk should increase the value of the liability so that it is greater than the discounted present value of expected claims taken at the financing rate 10 . 7
Even under contracts that contain a deposit element wherein the deposit is accessible, generally part of the customer’s funds do enter the deposit element and are used to pay for pure insurance protection. This part of the funds is subject to liquidity risk under such contracts. In addition, even when the deposit element is accessible, there is often a surrender charge that enforces a penalty for withdrawal, thereby reducing liquidity of the funds. 8 There is considerable debate concerning whether valuation of liabilities should reflect the credit risk of the liability holder (for example, the IASB has requested comments on exactly this issue for liability measurement). We take no position on this issue in this white paper, At the time of writing, the Academy is in the process of formulating its response to IASB Discussion Paper 2009/2, Credit Risk in Liability Measurement. 9 As noted earlier, in practice it may be difficult if not impossible to separately identify scredit and sliquidity, and a single market observation of a financing rate is used as a stand-in for both. 10 This risk margin might be included as part of the reported liability or it might be shown as a separate item in the financial statements, depending on evolving rules for financial statement presentation and disclosure.
6
Two of the most common methods of providing this margin are: 1) adjusting the cash flows by adding to them a “cost of capital 11 ” amount that represents the market price of risk; and 2) adjusting the discount rate downward. These two methods can, of course, yield exactly the same resulting value for the liability. To see this, assume that the amount of capital attributable to claims risks is 10% of the liability at any point in time, and the cost of capital rate is 8% of the amount of capital. The cash flow adjustment for any period would be 10% x 8% = 0.8% of the value of the liability at the beginning of the period. Exactly the same valuation is arrived at without making any adjustment to cash flows if one instead subtracts 0.8% from the discount rate used when determining the present value of expected cash flows 12 . We will call this discount rate adjustment s clm . The discount rate to be used would then be i f − s clm . While the above methods are simple enough mathematically, there can be some difficulty in estimating both the portion of an insurer’s total capital that is attributable solely to claims risks and the cost of capital rate. For example, although total capital may be more observable (and the total cost of capital easier to estimate), most insurers retain some investment risk in addition to the claims risks that they take on, and their total capital includes the amount attributable to investment risks. Some actuaries point out that an alternative methodology allows calibration of the discount rate adjustment by using two quantities that are sometimes easier to estimate – the insurer’s total cost of capital and its expected total investment return (i.e., the portfolio rate 13 ). The argument is that if one subtracts the full cost of capital (expressed as a yield spread) from the portfolio rate, the result is an appropriate discount rate for insurance liabilities and no cash flow adjustment is required to include a provision for risk. This “portfolio rate” methodology can be shown to fall within CON 7 guidelines as long as certain relationships are enforced. Essentially, the method assumes that: i portfolio − s capital cos t = i f − s clm
11
The cost of capital is the market price for obtaining capital that is to be put at risk. The providers of capital to an insurer expect an investment return higher than the risk free interest rate because their funds have been put at risk. The excess of the investor’s expected investment return over the risk free rate is the estimated cost of capital rate. The cost of capital in dollars (or appropriate currency) is the cost of capital rate times the amount of capital required. This amount can be added to liability cash flows in each future time period as a provision for the market price of risk. 12 This can be demonstrated by example. Suppose the liability at the beginning of the period is L, and the expected claim payment at the end of the period is C. Suppose the financing rate is 5.0%, and the cost of capital is 0.8% of the liability. The cost of capital can be treated as an addition to cash flow, in which case we have L = (C + .008L) / (1.05), using the financing rate as the discount rate. One can re-arrange this equation to be L = C / (1.05 - .008), in which case the cost of capital appears as a reduction to the discount rate rather than a cash flow adjustment. The liability value is the same no matter which formula is used. 13 Sometimes the term “portfolio rate” is used to refer to a measure of investment return on an amortized cost bais. The usage here is different; “portfolio rate” refers to the expected total return on market value for the portfolio. This estimate depends on current market conditions and is therefore appropriate for market-consistent valuation if used properly.
7
It is not at first obvious why this relationship should hold. To understand why, let us enumerate all of the risks that need to be reflected in the company’s cost of capital. The risks and the interest rate spreads that reflects their market prices are: s clm
spread for claims risks retained by the insurer (adds to cost of capital)
s inv
spread for investment risks taken by the insurer (adds to cost of capital)
s credit spread for credit risk accepted by the policyholder (this is the option to default, and if reflected, it reduces the cost of capital) s liquidity spread for liquidity risk accepted by the policyholder (reduces the cost of capital)
The total cost of capital is then s capital cos t = s clm + s inv − s credit − s liquidity . Financial economic theory tells us that the expected yield spread on a risky investment should be equal to the market price for accepting the risk of the investment. Since we assume the market price of investment risk is s inv , that could suggest that s inv = i portfolio − irf We can now write i portfolio − scapital cos t = i portfolio − ( sclm + sinv − scredit − sliquidity ) = i portfolio − ( sclm + (i portfolio − irf ) − scredit − sliquidity ) = irf − ( sclm − scredit − sliquidity ) = (i f − ( scredit + sliquidity )) − ( sclm − scredit − sliquidity ) = i f − sclm
to demonstrate the equality stated earlier. Objections to the use of the “portfolio rate method” have often been based on the idea that the value of an insurer’s liabilities should not depend on its investment strategy. Since the portfolio rate does depend on investment strategy, its use in any way suggests that the valuation depends on the strategy. However, the portfolio rate method as described here includes adjustment for the full investment risk through the cost of capital adjustment. Any increase in investment risk that would lead to a higher portfolio rate also leads to a higher cost of capital, so that the quantity i portfolio − s capital cos t does not change, at least in theory. As a practical matter, one can check whether i portfolio − s capital cos t < i f to determine whether the portfolio rate method is being applied in an appropriate way 14 . When properly applied, the “portfolio rate method” is conceptually consistent with CON7, and may have the advantage of calibrating to more easily estimated quantities.
14
An exception to this relationship occurs for insurance contracts that contain non-guaranteed investment elements, as described in the next section.
8
The cost of capital that is used as the provision for risk in the portfolio rate method is not always converted into an interest rate spread. In some cases it is applied as an addition to projected cash flows. Under this variation, the portfolio rate is used directly as the discount rate, but full provision for risk is made through the adjustment to cash flows.
1.3 Risks retained by the policyholder: non-guaranteed elements in insurance contracts Many insurance contracts include elements that are not guaranteed. For example, an insurer may guarantee that insurance coverage can always be renewed or extended for another time period, but may not guarantee the premium rate for the renewal period. Alternately, an insurer may offer a plan of insurance that returns a portion of that premium on a non-guaranteed basis at the end of the coverage period if and only if claims experience is favorable. The premium for such a plan would, of course, be higher than that for a plan that offers no such potential nonguaranteed benefit. One can readily see that such non-guaranteed elements tend to reduce the risk of the contract to the insurer. They do so by shifting some risk to the customer. In the latter example, the customer’s risk is the uncertainty about the size of the non-guaranteed payment to be received at the end of the coverage period. In our discussion concerning the discount rate, a special focus needs to be placed on nonguaranteed investment elements in insurance contracts. Many insurance contracts involve an investment (or deposit) element. The contract may include a deposit or fund amount that the customer owns and on which interest is credited. When the interest credited to the fund is not fully guaranteed but depends in some way on the performance of a portfolio of assets, we have a non-guaranteed investment element inside an insurance contract. To understand valuation of an insurance contract with a non-guaranteed investment element, it helps to start by thinking about a pure investment contract. A pure investment contract simply passes the results of an investment portfolio directly to the contract owner, so we will refer to it as a pure pass-through. The liability for such a contract is typically the current account balance 15 . In some cases, the investment element inside an insurance contract does operate very much like a pure pass-through. In the US, such contracts are called Variable or Separate Account contracts. In the UK, the term is unit-linked. 16 The more interesting case is an investment element that is not a pure pass-through. The insurer may provide a minimum guaranteed interest rate that will be credited, and then provide the customer with non-guaranteed additional interest credits if investment performance is good. The additional interest credits may be based directly on current market performance or may be spread over time based on an amortized-cost measure of return. In either case, the insurer will charge a fee for the guarantee of a minimum credited rate. The fee is conceptually related to the cost of 15
That is, before adjustments for fees, expenses, or other elements of the contract. These contracts typically include certain fees that are subtracted from the account value each period. So while they are not pure pass-throughs because part of the investment return is held back in the form of fees, they still have the characteristic that fluctuations in investment return (and the corresponding risk) are passed through to the account value. 16
9
the capital required to support the guarantee. The lower or weaker the guarantee, the lower the fee, and the closer we get to a pure investment pass-through contract. With this in mind, let’s revisit the “portfolio rate method” as described in the previous section. The discount rate including full adjustment for risk was i portfolio − s capital cos t and was to be strictly less than the financing rate, so we could check that i portfolio − s capital cos t < i f . However, when nonguaranteed elements are included in insurance contracts, they provide a means of reducing the insurer’s risk and therefore reducing its capital cost without necessarily reducing either the portfolio rate or the financing rate. As a result, we could have a discount rate that exceeds the financing rate so that i portfolio − s capital cos t ≥ i f . Now, even though the discount rate is based on the portfolio rate and may exceed the financing rate, this does not mean that the resulting liability value depends on the company’s investment strategy. There is an offset to the excess of the discount rate over the financing rate. The offset is the additional projected liability cash flows that arise from the non-guaranteed interest credited to the customer. The reduction in capital cost attributable to the non-guaranteed elements is typically passed through to the customer as an increase in expected (but non-guaranteed) benefits. Any change in investment strategy that increases the discount rate under this methodology is offset by an increase in projected cash flows from non-guaranteed benefits, so the liability value is at least theoretically not sensitive to the investment strategy. As a result, when non-guaranteed elements with some sort of investment return pass-through are present, it can be appropriate to use a discount rate in excess of the financing rate as long as the projected cash flows include the pass-through of the additional investment return net of capital cost. An alternative method for valuation of such contracts is to assume the portfolio earns the riskfree rate (or the financing rate) and to project the non-guaranteed benefit amounts that would be paid with that level of investment return. Such a method is consistent with the reasoning above and with CON 7, but is less realistic because it requires a projection that alters current nonguaranteed crediting rates away from the actual rates currently being paid. This is important, because the behavior of the owners of contracts with non-guaranteed investment elements depends on the level of non-guaranteed amounts being paid. If these amounts are not competitive, contract owners may terminate their contracts. Since contract-owner behavior is typically reflected in cash flow models used for valuation, a projection that alters current nonguaranteed crediting rates away from the actual rates being paid also alters assumed behavior, thereby distorting the cash flow projection used for valuation unless policy-owner behavior algorithms are adjusted. 17
17
This problem is frequently encountered in risk-neutral valuations of spread-managed business where the credited rate is assumed to be the portfolio rate less a spread. Since all assets are assumed to earn the risk-free rate(s), the resulting modeled credited rate will be below the risk free-rate. If policyholder behavior assumptions (such as surrender rates) are not appropriately translated into a risk neutral environment, excess surrenders and early exercise of policyholder options might be triggered even in the base scenario and in those scenarios that vary little from the base. It should be further noted that not all actuaries believe policyholder behavior algorithms should be altered in a risk-neutral valuation; these actuaries believe that any resulting anomalous policyholder activity is part of such a valuation.
10
Section 2 – Interest rate risk under stochastic valuation methods The accounting literature discusses valuation techniques that involve probability-weighting of several different future outcomes. In CON 7 this is called the “expected cash flows” method, and in the IASB exposure draft on fair valuation, this is called the “expected present value technique”. In both cases, the “expected” cash flows are determined as a probability-weighted average of the outcomes of various scenarios, and the valuation is done by discounting the “expected” cash flows. While CON 7 is silent on how to provide for risk under this method, the IASB exposure draft suggests two methods, one in which the discount rate is adjusted away from the risk-free rate and one in which the risk-free rate is used for discounting but the expected cash flows are adjusted to “certainty equivalents”. These methods are reasonable, but they are not the only methods that are in common use. We wish to explain two variations on these methods that are in common use. The variations are 1) the use of probabilities other than the “real” probabilities, and 2) the use of discount rates that vary by scenario.
2.1 Probabilities other than the “real” probabilities As noted above, IASB ED 2009/5 mentions two methods that can be used to include a provision for risk under the “expected present value technique”. The two methods involve either an adjusted discount rate (other than the risk-free rate) or adjustments to the expected cash flows. A third technique not mentioned in ED 2009/5 is to adjust the probabilities of the scenarios to give adverse outcomes greater probability weight. When this is done, the discount rate can be the risk-free rate because the provision for risk is provided through the probability weighting, which adjusts the cash flows to certainty equivalents. The adjustment of probabilities, in combination with discounting at the risk-free rate, is the theoretical basis of the widely-used Black-Scholes method for valuation of stock options. Consider the valuation of an option to buy a stock at a price of $100 per share any time within the next year. Suppose the current market price of the stock is $95 per share. The value of the option is based on the probability of the price rising over $100 per share within the coming year. This probability depends on the “volatility” of the stock price. Under the Black-Scholes method, one uses the observed market value of options to work backwards to determine the “implied” volatility that is consistent with the observed market price. That implied volatility, calibrated to market prices of options available in the market, can be used in valuation of options for which a market price is not available; say, options with different strike prices or options with different expiry dates. The important concept here is that the “implied” volatility is not the real volatility, and the probability of the option having value based on the “implied” volatility is not the real probability of the option having value. The “implied” volatility is a biased probability that includes an adjustment to reflect the market price of risk. One can use the “implied” volatility and the 11
associated biased probabilities to determine market-consistent prices that include provision for risk without ever needing to know what the real probabilities are. It should be noted that while valuations calibrated in this manner include a provision for risk, the exact size of the provision for risk is not known, and the method provides no way to determine it. Therefore, any accounting requirement to disclose the size of the provision for risk in the valuation can only be met via a rough approximation that can be less reliable that the estimated market-consistent price itself. The Black-Scholes method, and other methods that involve use of adjusted probabilities, can be considered variants of “method 1 of the expected present value technique” as outlined in FAS 157 Appendix B and IASB ED 2009/5 Appendix C. The adjusted probabilities are used to determine risk-adjusted expected cash flows, which are then discounted at the risk-free rate. The important aspect of this family of variants is that the method of calibration to market prices bypasses any need to determine or specify the size of the risk margin that is included.
2.2 Discount rates that vary by scenario An added variation on the “expected present value” method comes into play in valuation of items whose cash flows depend on the level of future interest rates. Common methods for valuation of such instruments involve not only adjusted probabilities, but also discount rates that depend on the scenario of future interest rates. A common example of such an item is a fixed-rate home mortgage that can be prepaid without penalty at any time. Such a mortgage is more likely to be prepaid if interest rates are low (allowing the mortgagor to re-finance at a lower rate) than if interest rates are high. Therefore the cash flows from such a mortgage are sensitive to the level of future interest rates. We will use an example based on a prepayable mortgage to illustrate how the combination of adjusted probabilities and scenario-specific discount rates is often used to include a provision for the market price of the prepayment risk. Similar techniques are often applied in valuation of insurance contracts with cash flows that depend on the level of future interest rates. However an example of such a contract would be much more complex. The same principles and methods can be illustrated much more simply in the context of a prepayable mortgage. For our example, we focus on a simple fixed-rate mortgage that requires annual payment of interest, with a balloon payment to repay the full principal at the end of its term. The mortgage will have a principal amount of $1000, an interest rate of 5.122%, and a maturity date of two years after the valuation date. The contractual cash flows are $51.22 at the end of one year and $1051.22 at the end of two years. We also assume that the risk-free yield curve on the valuation date is 5.0% for the first year and 5.25% for the second year. If there were no option to prepay, the present value at the risk-free yield curve of $51.22 due in one year and $1051.22 due in two years is $1000, and this would be the current value of the mortgage. However, if there is an option to prepay at the end of one year without penalty, one might expect that if market interest rates decline, many mortgage holders would prepay and refinance their 12
mortgage at the lower interest rate. This option to prepay is a risk to an institution that holds the mortgage as an asset. Market provision for this risk should reduce the market value of the prepayable mortgage below $1000. To value the prepayable mortgage we will, as a simplified example, use the expected present value technique with two scenarios. Under scenario 1 the risk-free rate rises from 5% to 6% after one year. Under scenario 2 the risk-free rate falls from 5% to 4% after one year. The first step in applying this technique is to calibrate the implied risk-neutral probability weights to market prices. The implied probability weights must be such that they properly price a fixed and certain cash flow at the end of two years, when path-specific discounting of the scenario cash flows is used. Exhibit 1 shows how this is done. Each line in Exhibit 1 corresponds to a present value calculation along a scenario. Example 1.1 shows a single scenario calculation of the present value of a fixed and certain cash flow of $1000 at the end of two years, with discounting at the current risk-free yield curve. The present value is $904.88. Example 1.2 shows what happens if we apply path-specific discounting using our two scenarios, and guess at the probabilities. As an initial guess we specify probabilities of 50% for each scenario. The probability-weighted present value is $907.11, which is incorrect. We therefore need to adjust the probabilities to produce the proper probability-weighted value of $904.88. Example 1.3 shows the corrected probabilities. Note that for the institution that holds a fixedrate instrument as an asset, an increase in market interest rates is an “adverse” scenario because the return on the asset is locked and does not rise with the market. The probability of the adverse scenario is increased to 62.9454% from 50%, thereby giving more weight to the adverse scenario. When these probability weights are used, the probability-weighted present value is $904.88, as it should be. These adjusted probabilities are often termed the “risk-neutral” probabilities. This process of calibrating the scenarios and probabilities to market prices is vitally important when including a provision for risk using “expected present value” techniques. Now that our scenarios and probabilities have been calibrated, we can use them to value the mortgage, first assuming no prepayment risk and then assuming significant prepayment risk. Examples 2.1 and 2.2 are valuations assuming no prepayment risk. Example 2.1 does not use path-specific discount rates, and Example 2.2 does use path-specific discounting. Since the cash flows are fixed and do not depend on the scenario, the probability-weighted present value is the same under both methods at $1000.00. Examples 2.3 and 2.4 are valuations assuming significant prepayment risk. We assume that if interest rates fall to 4% at the end of year 1, fully half of the mortgage principal will be prepaid, of a prepayment of $500. In that case the cash flows are $551.22 at the end of year 1 and $525.61 at the end of year 2. Example 2.3 does not use path-specific discounting, and obtains a probability-weighted present value of $1000.22. Clearly this result must be incorrect because it is greater than the value of the non-prepayable mortgage. The fundamental reason it is incorrect is that it includes no provision for risk. Example 2.4 uses path-specific discounting to obtain a value of $998.10. This clearly 13
does make provision for the prepayment risk. The value of the prepayment option is $1000 $998.10, or $1.90. This example is not intended to fully explain the theory behind use of scenario-specific discount rates. However, the reader should take away the following main ideas. • •
Scenario‐specific discounting is commonly used to include a provision for risk when future cash flows depend on the level of future interest rates. Scenario‐specific discounting is used only in combination with careful calibration of the scenarios and the implied risk‐neutral probability weights to market prices.
The second point above is particularly important because it is critical to the theory that supports scenario-specific discounting. There are many ways to calibrate the scenarios and the probability weights to market prices. A short description of a method commonly used in valuation of insurance liabilities may be helpful. In valuation of insurance liabilities whose cash flows depend on future interest rates, one frequently uses a very large number of interest rate scenarios for many months or years into the future. Rather than adjusting the probabilities of the scenarios, the calibration process adjusts the path of future interest rates in each scenario. This is done by adding a calibrated “drift” to the change in interest rates each period before any stochastic or random change is applied by the scenario generator. In that way, even though the probabilities of the scenarios are all treated as equal, the number of scenarios with increasing or decreasing interest rates is adjusted, thereby adjusting the overall probability that interest rates will rise or fall. The “drift” is calibrated so that the probability-weighted present value of a fixed and certain cash flow at any future date is equal to its current market price on the valuation date. To accomplish this for all future dates, the “drift” is not a constant, but a series of calibrated amounts for each future time period. Lastly, an important aspect of scenario-specific discounting is that the scenario-specific discount rate for each period in each scenario is the short-term one-period risk-free rate. While a scenario generator may provide a full yield curve at every point in time along each scenario, it is the path of the short-term one-period rates that needs to be used for discounting.
Summary The purpose of this paper has been to outline several methods that can be used in valuation of items that involve risk and uncertainty, emphasizing their compliance with the principles of fair valuation as outlined in such existing accounting pronouncements as CON 7. There has been concern among some actuaries that certain methods that we believe are consistent with CON 7 could, in future accounting standards, be disallowed. There has been particular concern over methods for valuation of insurance liabilities that involve scenario path-specific discounting, or use of the insurer’s portfolio rate, or methods used when non-guaranteed investment elements are present. These methods have been shown here to be consistent with CON 7 when properly applied. A short paper such as this cannot possibly cover all the valuation methods that are in use, and neither can an accounting standard. That is why CON 7 is so important – it states the principles that must be followed, yet allows flexibility in the application of those principles as needed and appropriate. It is our hope that future accounting standards continue the practice of explicitly stating that alternate approaches for discounting and fair valuation are allowed. 14
Exhibit 1 ‐ Valuation of a fixed and certain cash flow: Calibration of Risk‐Neutral Probability Weights Scenario
Cash flows End yr 1 End yr 2
Discount rate during Year 1 Year 2
Discount factor for: End yr 1 End yr 2
Scenario Present Value
0.952381 0.904875
$ 904.88
100.00%
$ 904.88
$ 898.47 $ 915.75
50.0% 50.0%
$ 449.24 $ 457.88
Total weighted present value:
$ 907.11 Incorrect!
Probability Weight
Weighted Present Value
Example 1.1 No path‐specific discounting 1
$ ‐
$ 1,000
5.00%
5.25%
Example 1.2 Path‐specific discounting, "real" probabilities 1 2
$ ‐ $ ‐
$ 1,000 $ 1,000
5.00% 5.00%
6.00% 4.00%
0.952381 0.898473 0.952381 0.915751
Example 1.3 Path‐specific discounting, "risk‐neutral" probabilities 1 2
$ ‐ $ ‐
$ 1,000 $ 1,000
5.00% 5.00%
6.00% 4.00%
0.952381 0.898473 0.952381 0.915751
$ 898.47 $ 915.75
62.9454% 37.0546%
$ 565.55 $ 339.33
Total weighted present value:
$ 904.88
When discounting using the scenario path of risk free rates, one must use calibrated "risk‐neutral" probability weights.
Exhibit 2 ‐ Valuation of $1000 mortgage Cash flows End yr 1 End yr 2
Discount rate during Year 1 Year 2
Discount factor for: End yr 1 End yr 2
Scenario Present Value
5.25% 5.25%
0.952381 0.904875 0.952381 0.904875
$ 1,000.00 62.9454% $ 1,000.00 37.0546% Total weighted present value:
$ 629.46 $ 370.55 $ 1,000.00
6.00% 4.00%
0.952381 0.898473 0.952381 0.915751
$ 993.27 62.9454% $ 1,011.44 37.0546% Total weighted present value:
$ 625.22 $ 374.78 $ 1,000.00
0.952381 0.904875 0.952381 0.904875
$ 1,000.00 $ 1,000.58
$ 629.46 $ 370.76
Probability Weight
Weighted Present Value
If cash flows have no prepayment risk: Example 2.1 No path‐specific discounting 1 2
$ 51.22 $ 1,051.22 $ 51.22 $ 1,051.22
5.00% 5.00%
Example 2.2 With path‐specific discounting 1 2
$ 51.22 $ 1,051.22 $ 51.22 $ 1,051.22
5.00% 5.00%
If cash flows have significant prepayment risk: Example 2.3 No path‐specific discounting 1 2
$ 51.22 $ 1,051.22 $ 551.22 $ 525.61
5.00% 5.00%
5.25% 5.25%
62.9454% 37.0546%
Total weighted present value: $ 1,000.22 Incorrect! No provision for risk.
Example 2.4 With path‐specific discounting 1 2
$ 51.22 $ 1,051.22 $ 551.22 $ 525.61
5.00% 5.00%
6.00% 4.00%
0.952381 0.898473 0.952381 0.915751
$ 993.27 $ 1,006.30
62.9454% 37.0546%
$ 625.22 $ 372.88
Total weighted present value: $ 998.10 Correct! The value of the option to prepay is $1.90.
15
Bibliography This bibliography lists some textbooks and a monograph relevant to the subject of this white paper. The material in these books provides an indication of the wide variety of methods that have been developed and are being used in valuations that involve risk and uncertainty.
Interest Rate Modeling, a textbook by Jessica James and Nick Webber. John Wiley & Sons, 2000. Part III of the book is titled “Valuation Methods”. Derivatives Markets, a textbook by Robert L. McDonald. Addison Wesley, 2006. Part 5 of the book is titled “Advanced Pricing Theory”. Models for Quantifying Risk, a textbook by Robin Cunningham, Thomas Herzog, and Richard L. London. ACTEX publications, 2005. This book covers a wide variety of models used to characterize and quantify insurance risks. Insurance Risk Models, a textbook by Harry H. Panjer and Gordon E. Willmot. Society of Actuaries, 1992. This is a classic educational text covering a wide variety of models used to characterize and quantify insurance risks. Fair Valuation of Insurance Liabilities: Principles and Methods. This 2002 public policy monograph by the American Academy of Actuaries provides an introductory-level survey of many of the methods described in textbooks and other literature. Measurement of Liabilities for Insurance Contracts: Current Estimates and Risk Margins. This 2009 International Actuarial Research Paper was prepared by the ad hoc Risk Margin Work Group of the International Actuarial Association.
16
Published on Jun 7, 2012
Current accounting standards provide some comfort with respect to the use of alternative methods. For example, Statement of Financial Accoun... | https://issuu.com/actuarypdf/docs/discount_0915091 | CC-MAIN-2017-39 | refinedweb | 8,780 | 50.67 |
lookup problemsGen.Java Feb 2, 2013 1:40 PM
Hi all,
Please check the following code:
1. The first lookup() prints null because of the dot (.). How can I lookup nodes whose ids have dots? I tried "#a\00002Eb", still no luck
2. The second lookup() prints null ? no idea why
Thank you
Please check the following code:
The previous code has two problems:The previous code has two problems:
package helloworld; import javafx.application.Application; import javafx.stage.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; public class HelloWorld extends Application { public static void main(String[] args) { launch(args); } public void start(Stage primaryStage) { Accordion accordion = new Accordion(); TitledPane t1 = new TitledPane("T1", new Button("B1")); t1.setId ( "t1" ); accordion.getPanes().addAll(t1); accordion.setId ( "a.b" ); Group root = new Group(); root.getChildren().add(accordion); System.out.println ( root.lookup("#a.b") ); System.out.println ( root.lookup("#t1") ); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } }
1. The first lookup() prints null because of the dot (.). How can I lookup nodes whose ids have dots? I tried "#a\00002Eb", still no luck
2. The second lookup() prints null ? no idea why
Thank you
This content has been marked as final. Show 6 replies
1. Re: lookup problemsshakir.gusaroff Feb 2, 2013 3:23 PM (in response to Gen.Java)
I think the node id should not contain a period because in css files class selectors are preceded by a period (.).
public Node lookup(java.lang.String selector)
>The second lookup() prints null ? no idea why
If you call lookup() after primaryStage.show() you can see the correct id.
primaryStage.show(); System.out.println(root.lookup("#t1"));
2. Re: lookup problemsGen.Java Feb 2, 2013 4:39 PM (in response to shakir.gusaroff)Thank you shakir:
I think the node id should not contain a period because in css files class selectors are preceded by a period (.).Yes. I checked CSS ID Specification and found that a period (.) is not allowed.
If you call lookup() after primaryStage.show() you can see the correct id.Ok. Is there any way you can lookup before calling show() ?
3. Re: lookup problemsshakir.gusaroff Feb 2, 2013 7:13 PM (in response to Gen.Java)I think it is a bug. There is a similar one:
Jira says:
Node.lookup() method does not expose children of TabPane(tabs) and SplitPane(items) . It only works when the scene is realized (shown). Resolution: Not an issue.I think it is still an issue.
4. Re: lookup problemsGen.Java Feb 4, 2013 10:47 AM (in response to shakir.gusaroff)
shakir.gusaroff wrote:Thank you shakir, I hope they can resolve this issue soon because lookup() is a great method that has no equivalent in Swing. I agree with you that it is an issue because in some situations, you do need to lookup components before realizing the scene.
I think it is still an issue.
5. Re: lookup problemsjsmith Feb 4, 2013 6:30 PM (in response to Gen.Java)1 person found this helpful
you do need to lookup components before realizing the scene.I am not sure that that is possible based on the current JavaFX architecture.
I also don't think that that is quite what the linked jira issue in the thread was referring to.
I do agree that if you execute code like the following:
That it is pretty counter-intuitive that the lookup would return null at that time.
parent.getChildren().add(new Button()); Node n = parent.lookup(".button");
It is, I think, notable that equivalent jQuery style lookups in the html allow you to lookup a change to the DOM after you modify it (perhaps html takes a huge efficiency penalty to allow such lookups to function).
Potential workarounds are:
1. Wrap your lookup calls in Platform.runLater
Often that will work for me as it gives the JavaFX system time to run a rendering pulse on the scene which gets the scenegraph all set up with appropriate nodes and css applied to it before you do your lookup.
2. Use an AnimationTimer and poll the scene with a lookup each time the timer is invoked, then stops polling once the lookup succeeds.
(I think this is a pretty rare case where this is needed). If the scenegraph changes take a couple of pulses to propagate (which for some weird reason some of the chart scenegraph changes seem to do - perhaps because charts can be animated), then this is like a more heavyweight solution to the Platform.runLater method, for which the lookups can work at a later time.
3. I think there are some private methods in the JavaFX API which I have never used which manually kick off a css processing pass (something like impl_processCss - though I haven't tried to find the actual name).
Perhaps if you manually trigger the css processing on the scene graph, then subsequent lookups will work without you having to resort to tricker like Platform.runLater.
I think overall, it is unclear whether using lookup functions extensively in JavaFX code is as good an idea as it is in jQuery code. My overall feeling is - no it is not and the lookup style should be avoided in favor of direct API calls or, if the purpose of the lookup is just related to applying style changes, applying style changes based on setting css styleclasses on components and making use of a css stylesheet.
I found that often I was able to replace dynamic code lookups with css styleclasses and stylesheets. So I'd advise you to look at the reason on why you are doing the lookup, and, if possible, just make use of the css stylesheet mechanism instead.
6. Re: lookup problemsGen.Java Feb 14, 2013 10:24 AM (in response to jsmith)Thank you jsmith for your explanation and advice. | https://community.oracle.com/message/10852949 | CC-MAIN-2017-39 | refinedweb | 985 | 74.9 |
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
>>>>> "Jan" == Jan Kratochvil <jan.kratochvil@redhat.com> writes: Jan> Compiler says: Jan> .C:13:6: error: call of overloaded âm()â is ambiguous Jan> .C:13:6: note: candidates are: Jan> .C:6:7: note: int N2::m() Jan> .C:2:7: note: int N1::m() Jan> and I think GDB should also say the same output as error. I agree for expressions. I think linespecs are different. For example, with ADL, a plain name like "function" may be looked up in the namespaces of the arguments. I don't see how linespec will ever handle this sanely. GDB is already inconsistent here, BTW. For example, "break k::m" will search superclasses of "k", but "break m" will not search superclasses of the class of *this. I have been thinking about this, though, and I think there is another approach that could work. Jan> One can store the available namespaces as strings with the Jan> breakpoint (instead of storing pointer to the block - where the Jan> block may disappear). Yeah. I would like to store as little context as possible, though. Or, rather, I would like all the context to appear in the linespec's canonical form. The way we could make this work is that we could have decode_line_full return sets of SALs, where each set is distinguished by its canonical name. So, in this case, we would return two sets, one "N1::m" and one "N2::m". Then, this would create two separate breakpoints -- one per set. This is more complicated than just rejecting this case, but it would let us preserve namespace searches.). My problem with this is that it adds more complexity to the user interface: some linespecs will create a single breakpoint with multiple locations, some will create multiple breakpoints once again, depending on the context. So, I am still against it, but I will take a stab at it if you think it is important. Tom | https://sourceware.org/legacy-ml/gdb-patches/2011-11/msg00195.html | CC-MAIN-2020-34 | refinedweb | 339 | 75 |
Moving Clips from Project Assets to a Folder within Project Assetsbakramer1202 Dec 19, 2014 3:20 PM
I am using PRE13. I have many clips in my project assets panel. I also have folders in my project assets panel. I want to move my used clips to a folder but the clips and folder are not visible on the screen the same time . If I try and do a cut and paste, elements tell me the clips will be deleted from my timeline. Any help would be appreciated
1. Re: Moving Clips from Project Assets to a Folder within Project AssetsA.T. Romano Dec 19, 2014 5:34 PM (in response to bakramer1202)
bakramer1202
I am not clear where you are running into problems managing Project Assets with its files and folders. So, let me give you some information
that might help us in the communications.
1. Project Assets offers two views Grid and List. Are you working in the Grid view or have you tried both for what you want to do?
See Project Assets/Panel Options icon/new folder - drag files into folder.
Double click the folder to see the files.
If you want the folder icon to return (files now in the folder no visible), click on the icon which has the name of the project followed by Folder 01 or whatever folder number it is.
2. In the List view, you can open the folder and see its contents without losing sight of the folder.
Are you OK on how to create folders in Project Assets whatever the view?
Please give more details. If necessary, I will post screenshot if you cannot find the details that I mentioned.
Looking forward to your follow up.
ATR
2. Re: Moving Clips from Project Assets to a Folder within Project Assetsbakramer1202 Dec 21, 2014 3:04 PM (in response to A.T. Romano)
Thanks for the response. My situation is as follows
1. I have hundreds of clips in project assets (no folder).
2. I have a few folders also in project assets. Let's call them folder1
and folder2.
3. I want to move clips from project assets (no folder) into folder1.
Here is my problem.
1. I cannot drag and drop the individual clips into folder1 since I can't
see both on the same screen even when I expand the project assets.
2. I cannot "cut and paste" since PRE tells me it will delete the items
from the timeline when I go to cut.
3. I CAN "copy and paste". That results in the items being in two places;
folder1 and individual clips in project assets (no folder). Not a good
result.
I hope that clarifies the issue.
Thanks for the help
Bryce Kramer
On Fri, Dec 19, 2014 at 8:34 PM, A.T. Romano <forums_noreply@adobe.com>
3. Re: Moving Clips from Project Assets to a Folder within Project AssetsA.T. Romano Dec 21, 2014 5:52 PM (in response to bakramer1202)
Bryce Kramer
From what you wrote this is not a planned ahead maneuver. Rather you are dealing with a project in full progress with lots of individual files and few folders in Project Assets and you want to order up Project Assets thumbnails into Folder 01 and Folder 02 in this example.
I see the points that you bring out in what you have been trying to do.
Let us focus on your selection (all at one time) of multiple files destined for a particular folder in Project Assets
Selecting all wanted files at one time...
a. holding down Ctrl and clicking on each of the files to go into the selection
or
b. Shift click on first file in a series, hold down the Shift and click on the last file in the series.
Then clicking (holding the click) and dragging the selection downward to one of your existing Folder 01 or 02.
Just click anywhere in the selection, holding the click as you drag the selection down to the bottom edge of Project Assets. There you hold the click at the bottom edge of Project Assets as it goes into an automatic scroll down situation.
You release the click only when the mouse cursor on the Folder 01 icon when you arrive there. You continue this routine with other files you want placed in Project Asset folders.
It works.
Please review and consider and then let me know if this works for you.
Thank you.
ATR
4. Re: Moving Clips from Project Assets to a Folder within Project Assetsbakramer1202 Dec 22, 2014 8:01 AM (in response to A.T. Romano)
Works perfectly. You are the best.
Thanks
On Sun, Dec 21, 2014 at 8:52 PM, A.T. Romano <forums_noreply@adobe.com>
5. Re: Moving Clips from Project Assets to a Folder within Project AssetsA.T. Romano Dec 22, 2014 8:58 AM (in response to bakramer1202)
bakramer1203
Great news.
I was not going to mention that suggestion because I thought that you had tried that already. So, glad that I did.
Thanks for the follow up which is appreciated by all.
Best wishes
ATR | https://forums.adobe.com/thread/1662995 | CC-MAIN-2018-13 | refinedweb | 857 | 82.04 |
Just
The actual bug is probably hit in _cairo_int32x32_64_mul or _cairo_uint32x32_64_mul.
I try to build cairo within pkgsrc and at the moment cannot switch to another compiler. I don't think that bugs in such old versions of GCC get fixed. So if there is any possibility to fix this problem here, that would be great.
NB: Only Sparc is affected. GCC 3.4.6 on i386 compiles this without any errors.
(In reply to comment #0)
> Just
Could you provide the full compiler output and the preprocessed file? explains how to do it (basically add "-v -save-temps"
to your CFLAGS).
This could make it possible to (try to) provide a workaround to the compiler bug.
We were aware of this bug but in the final rush to 1.10 decided it wasn't really worth pursuing internal compiler errors further, especially for gcc that old. Having looked at it some more now, it seems that the problem stems from gcc 3.4's buggy support for the __uint128_t datatype. The following code triggers the bug as well:
#include <stdlib.h>
#include <inttypes.h>
int
main(int argc, char **argv)
{
__uint128_t a = atol(argv[1]);
a *= a;
return 0;
}
As a workaround, you could disable using intrinsic 128 bit arithmetic in the cairo-wideint-type-private.h header by commenting out the block following the comment "/* gcc has a non-standard name */". The problem had been fixed in later gcc releases, but I'm told gcc 4.5 has regressed. A more robust fix (probably a link test for the wideint code) is needed avoid future regressions.
Use of freedesktop.org services, including Bugzilla, is subject to our Code of Conduct. How we collect and use information is described in our Privacy Policy. | https://bugs.freedesktop.org/show_bug.cgi?id=31677 | CC-MAIN-2018-22 | refinedweb | 294 | 67.86 |
Type: Posts; User: rbmazter
I am new programmer. In the first place I really like my job because they gave me project and then when I finished it they give me a new task that was fixing a bugs of others work. The programmer who...
I separate my interface. I am using MVC 3 .
So far I already solve the problem in sending emails.
Thanks so much. :)
Uhm are you the one develop this website?
Programmers: Need Help!
using System.Net.Mail;
namespace MvcMembership
{
public interface ISmtpClient
{
void Send(MailMessage mailMessage);
}
}
Thanks so much ssystems.....
Please help customizing user management system using MembershipUserCollection in asp.net/C#....
>List of all users
>Search,edit,delete user
>Change user roles
>Password recovery
......thanks
Hello guys,
Can you give a project. I am newly hired .Net Developer in the company and I don't have a project yet I want to make myself busy. Anyone could give me a simple website... | http://www.webdeveloper.com/forum/search.php?s=751780639422b29f83c10d974581c1ba&searchid=2426589 | CC-MAIN-2013-48 | refinedweb | 158 | 70.39 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
dialog box with value from py file
Hi friendz,
I am trying out buttons in OpenERP 7 in which I need to display the value of the result in a dialog box.
For Example,
Now I am trying to transfer money from one account to another account, when the transaction is done through clicking the button "Transfer money". I need to get a dialog box as Transaction Complete Your current balance is 3000 Help me with my situation.
There is a way that you can create one wizard and show the message when transaction is done.
You need to call that wizard from py after transaction is completed successfully.
Ex:
def my_transaction_done_method(... #Your code ... return { 'name': 'Transaction Confirmation', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'your_wizard_object_name', 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'new', }
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/dialog-box-with-value-from-py-file-22642 | CC-MAIN-2018-17 | refinedweb | 187 | 54.93 |
Activity
Posted in Multi tenant - will it help?
Here is the case , I got users and a few other models , most of them end up doing some action with one main table that contains around 15M rows.
I have an indexed foreign key between the main table and the user model , and plently of specific columns indexes to speed up various queries.
I recently added an Ajax-DataTable view which queries this table for each change , this caused a huge bottleneck in the application.
I think this is happening due to too many calls using the same table.
I'm thinking of migrating the existing application to a multi-tenant strucutre , where each user will have its own main table.
Thus having less locks on the same table.
Anyone have any expirience with anything similar?
Posted in Checking for uniqueness.
Posted in Checking for uniqueness
Create a unique index + add a scoped validation.
I didn't understand the problem once you change the iterator.
Are you having any issue with
<% user_stock.symbol %> or anything similar?
Add prints from inside the view
<% puts "user_id = #{@user.id} | current_user.id = #{current_user.id} | user_stock = #{user_stock.inspect}" %>to see what is the content in the view.
Your
usermodel should have
user_stocksassociation on it, did you create a
foreignkey reference?
Yeah ,
whereusualy works on some
ActiveRecordtypes. The various
find*methods are actually wrappers for
where. For example
find_by , although I'm missing a
limit(1)in those calls , that bothers me a little bit since if you know that you
takethe first only than you should also
limitthe
SQLcall.
Try #1 , to understand what's going on , the inconsistency must be in one of the 3 variables hence , start exploring them.
puts and
inspect are your friends :)
The easiest way is to mimmic the flow in your console.
Check
UserStock.last and compare its details to the one you're trying to find after the second time.
BTW a few things that will make your code cleaner (in my personal opinion)
I would replace
set_user_stock by:
def set_user_stock @user_stock= @user.user_stocks.find_by( id: params[:id]) if @user_stock.nil? # do something , for example: flash[:danger]= 'msg' redirect_to 'path' and return end end
This will also remove the need for the
if @user.id condition since if some other user tries to touch another user stock , he will get redirected.
No need to define
find_by_ticker simply use
Model.find_by( key_name: value) , it will return the model or
nil.
Also , you can add a
unique index +
validation on
ticker_symbol (or
ticker_symbol && user_id which make it easier to search/validate the checks you do.
Is this a typo?
<% if @user.id = current_user.id %>
You're assigning to
@user.id and not comparing
==.
Posted in Shrine vs. Carrierwave
I noticed in the screencasts that the first one is on Carrierwave , but later on they're on all Shrine.
I really like (not sure if it supports Shrine) hence I go for Carrierwave.
What am I missing?
Posted in Jquery destroy seems to fire twice.
I think the issue is that you're destroying
@line_item but in your
redirect_to you're using
@line_item.cart_id , that doesn't seem right.
Try to store the URL / id / cart you want to redirect to in some variable , and after the destroy use that to
redirect_to.).
I recommend using RubyMine , it's not free but worth the money.
Especially if you're taking Ruby/Rails as a serious job.
They also have a pretty good vim mode (coming from a vim only guy).
Posted in Recommended.
I'm not sure that I follow , can you write the query you warn from?
There is a Rails based Trello clone available on GitHub . | https://gorails.com/users/11157 | CC-MAIN-2021-43 | refinedweb | 615 | 67.45 |
/*
* Detail.java July.Constructor;
import java.util.List;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.NamespaceList;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;
/**
* The <code>Detail</code> object is used to provide various details
* for a type. Most of the data that can be acquired from this can
* also be acquired from the <code>Class</code>. However, in some
* environments, particularly Android, reflection and introspection
* is very slow. This class attempts to reduce the overheads by
* caching all the data extracted from the class for future use.
*
* @author Niall Gallagher
* @see org.simpleframework.xml.core.Support
interface Detail {
/**
*
*/
boolean isStrict();
* This is used to determine if the generated annotations are
* required or not. By default generated parameters are required.
* Setting this to false means that null values are accepted
* by all defaulted fields or methods depending on the type.
*
* @return this is used to determine if defaults are required
*/
boolean isRequired();
* This is used to determine if the class is an inner class. If
* the class is a inner class and not static then this returns
* false. Only static inner classes can be instantiated using
* reflection as they do not require a "this" argument.
* @return this returns true if the class is a static inner
boolean isInstantiable();
* This is used to determine whether this detail represents a
* primitive type. A primitive type is any type that does not
* extend <code>Object</code>, examples are int, long and double.
* @return this returns true if no XML annotations were found
boolean isPrimitive();
* This is used to acquire the super type for the class that is
* represented by this detail. If the super type for the class
* is <code>Object</code> then this will return null.
* @return returns the super type for this class or null
Class getSuper();
* This returns the type represented by this detail. The type is
* the class that has been scanned for annotations, methods and
* fields. All super types of this are represented in the detail.
* @return the type that this detail object represents
Class getType();
* This returns the name of the class represented by this detail.
*
String getName();
* This returns the <code>Root</code> annotation for the class.
* The root determines the type of deserialization that is to
* be performed and also contains the name of the root element.
Root getRoot();
* This returns the order annotation used to determine the order
* of serialization of attributes and elements. The order is a
* class level annotation that can be used only once per class
* XML schema. If none exists then this will return null.
* of the class processed by this scanner.
Order getOrder();
* This returns the <code>Default</code> annotation access type
* that has been specified by this. If no default annotation has
* been declared on the type then this will return null.
* @return this returns the default access type for this type
DefaultType getAccess();
* This returns the <code>Namespace</code> annotation that was
* declared on the type. If no annotation has been declared on the
* type this will return null as not belonging to any.
* @return this returns the namespace this type belongs to, if any
Namespace getNamespace();
* This returns the <code>NamespaceList</code> annotation that was
* declared on the type. A list of namespaces are used to simply
* declare the namespaces without specifically making the type
* belong to any of the declared namespaces.
* @return this returns the namespace declarations, if any
NamespaceList getNamespaceList();
* This returns a list of the methods that belong to this type.
* The methods here do not include any methods from the super
* types and simply provides a means of caching method data.
* @return returns the list of methods declared for the type
List<MethodDetail> getMethods();
* This returns a list of the fields that belong to this type.
* The fields here do not include any fields from the super
* @return returns the list of fields declared for the type
List<FieldDetail> getFields();
* This returns the annotations that have been declared for this
* type. It is preferable to acquire the declared annotations
* from this method as they are cached. Older versions of some
* runtime environments, particularly Android, are slow at this.
* @return this returns the annotations associated with this
Annotation[] getAnnotations();
* This returns the constructors that have been declared for this
* type. It is preferable to acquire the declared constructors
* @return this returns the constructors associated with this
Constructor[] getConstructors();
} | http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.core.Detail.html | CC-MAIN-2018-05 | refinedweb | 734 | 55.84 |
Classes are the irreplaceable ingredient of any .NET assembly. First, all executable code must be contained in a type, usually a class. Global functions and variables are not permitted in C#, preventing problematic dependences caused by disparate references to global entities. Second, classes published in the .NET Framework Class Library provide important services that are integral to any .NET application.
Classes are described in a class declaration. A class declaration consists of a class header and body. The class header includes attributes, modifiers, the class keyword, the class name, and the base class list. The class body encapsulates the members of the class, which are the data members and member functions. Here is the syntax of a class declaration:
attributes accessibility modifiers class classname : baselist { class body };
Attributes further describe the class. If a class is a noun, attributes are the adjectives. For example, the Serializable attribute identifies a class that can be serialized to storage. There is an assortment of predefined attributes. You can also define custom attributes. Attributes are optional, and there are no defaults. Further details on attributes are contained in Chapter 11, "Metadata and Reflections."
Accessibility is the visibility of the class. Public classes are visible in the current assembly and assemblies referencing that assembly. Internal classes are visible solely in the containing assembly. The default accessibility of a class is internal. Nested classes have additional accessibility options, which are described later in this chapter.
Modifiers refine the declaration of a class. For example, the abstract keyword prevents instances of the class from being created. Modifiers are optional, and there is no default. Table 2-1 elucidates the modifiers.
A class can inherit the members of a single base class. Multiple inheritance is not supported in the Common Language Specification of .NET. However, a class can inherit and implement multiple interfaces. The baselist lists the class inherited and any interfaces to be implemented. By default, classes inherit the System.Object type. Inheritance and System.Object are expanded upon in Chapter 3, "Inheritance."
The class body encompasses the members of the class that entail the behavior and state of a class. The member functions are the behavior, whereas data members are the state. As a design goal, classes should expose an interface composed of the public functions of the class. The state of the class should be abstracted and described through the behavior of the class. You manage the state of an object through its public interface.
Classes do not require members. All members can be inherited. In addition, an empty class can function as a valuable marker or cookie at run time when ascertaining Run-time Type Information (RTTI).
The semicolon at the end of the class is optional.
XInt is a class and a thin wrapper for an integer:
internal sealed class XInt { .....public int iField=0; }
The XInt class has internal accessibility and visibility in the current assembly, but is not visible to an external assembly. The sealed modifier means that the class cannot be refined through inheritance.
The following code uses the new statement to create an instance of a class:
.....public void Func() { .........XInt obj=new XInt(); .........obj.iField=5; .....}
Classes are composed of members: member functions and data members. Use the dot syntax to access members. The dot binds an instance member to an object or a static member to a class. In the following code, Fred.name accesses the name field of the Fred object:
using System; namespace Donis.CSharpBook{ public class Employee{ public string name; } public class Personnel{ static void Main(){ Employee Jim=new Employee(); Fred.name="Wilson, Jim"; } } }
Table 2-2 describes the list of potential class members.
When a member is declared, attributes can be applied and accessibility defined. Members are further described with attributes. Accessibility sets the visibility as class member.
Members defined in a class are scoped to that class. However, the visibility of the member is defined by accessibility keywords. The most common accessibility is public and private. Public members are visible inside and outside of the class. The visibility of private members is restricted to the containing class. Private is the default accessibility of a class member. Table 2-3 details the accessibility keywords:
Attributes are usually the first element of the member declaration and further describe a member and extend the metadata. The Obsolete attribute exemplifies an attribute and marks a function as deprecated. Attributes are optional. By default, a member has no attributes.
Modifiers refine the definition of the applicable member. Modifiers are optional and there are no defaults. Some modifiers are reserved for classification of members. For example, the override modifier is applicable to member functions, not data members. Table 2-4 lists the available modifiers.
Members belong either to an instance of a class or to the class itself. Members bound to a class are considered static. Except for constants, class members default to instance members and are bound to an object via the this object. Constant members are implicitly static. Static members are classwise and have no implied this context. Not all members can be static or instance members; destructors and operator member functions are representative of this. Destructors cannot be static, whereas operator member functions cannot be instance members.
Instance members are qualified by the object name. Here is the syntax of a fully qualified instance member:
objectname.instancemember
Static members are prefixed with this class name:
classname.staticmember
The lifetime of static members is closely linked to the lifetime of the application. Instance members are inexorably linked to an instance and are accessible from the point of instantiation. Access to instance members ceases when the instance variable is removed. Therefore, the lifetime of an instance member is a subset of the lifetime of an application. Static members are essentially always available, whereas instance members are not. Static members are similar to global functions and variables but have the benefit of encapsulation. Static members can be private.
Your design analysis should determine which members are instance versus static members. For example, in a personnel application for small businesses, there is an Employee class. The employee number is an instance member of the class. Each employee is assigned a unique identifier. However, the company name member is static because all employees work for the same company. The company name does not belong to a single employee, but to the classification.
Static class A static class is a class that contains static members and no instance members. Because static classes have no instance data, a static class cannot be instantiated. This is a static class:
public static class ZClass { public static void MethodA() {} public static void MethodB() {} }
The this reference refers to the current object. Instance members functions are passed a this reference as the first and hidden parameter of the function. In an instance function, the this reference is automatically applied to other instance members. This assures that within an instance member function, you implicitly refer to members of the same object. In this code, GetEmployeeInfo is an instance member function referring to other instance members (the this reference is implied):
public void GetEmployeeInfo(){ PrintEmployeeName(); PrintEmployeeAddress(); PrintEmployeeId(); }
Here is the same code, except that the this pointer is explicit (the behavior of the function is the same):
public void GetEmployeeInfo(){ this.PrintEmployeeName(); this.PrintEmployeeAddress(); this.PrintEmployeeId(); }
In the preceding code, the this reference was not required. The this reference is sometimes required as a function return or parameter. In addition, the this reference can improve code readability and provide IntelliSense for class members when editing the code in Microsoft Visual Studio.
Static member functions are not passed a this reference as a hidden parameter. For this reason, a static member cannot directly access nonstatic members of the class. For example, you cannot call an instance method from a static member function. Static members are essentially limited to accessing other static members. Instance members have access to both instance and static members of the class.
The this reference is a read-only reference. As part of error handling, setting a this reference to null would sometimes be beneficial. Alas, it is not allowed.
Members are broadly grouped into data and function members. This chapter reviews constants, fields, and nested types, which are data members. Methods, constructors, destructors, and properties are member functions (and are covered in this chapter). The remaining members, such as events and delegates, are discussed in Chapter 8, "Delegates and Events."
Data members are typically private to enforce encapsulation and the principles of data hiding and abstraction. Abstraction abstracts the details of a class and restricts collaboration to the public interface. The developer responsible for the class obtains implementation independence and has the freedom to modify the implementation when required as long as the interface is unchanged. The interface is immutable—like a contract between the class and any client. As a best practice, data members should be private and described fully through the public interface. The class interface consists of the public member functions. Do not make every member function public; internal functionality should remain private.
Except for constructors and destructors, members should not have the same name as the containing class. As a policy, class names should differ from the surrounding namespace.
Constants are data members. They are initialized at compile time using a constant expression and cannot be modified at run time. Constants have a type designation and must be used within the context of that type. This makes a constant type-safe. Constants are usually a primitive type, such as integer or double. A constant can be a more complex type. However, classes and structures are initialized at run time, which is prohibited with a constant. Therefore, constant class and structures must be assigned null, which limits their usefulness. Following is the syntax of a constant member:
const syntax:
accessibility modifier const constname=initialization;
The only modifier available is new, which hides inherited members of the same name. Constants are tacitly static. Do not use the static keyword explicitly. The initialization is accomplished with a constant expression. You can declare and initialize several constants simultaneously.
The following code presents various permutations of how to declare and initialize a constant data member:
public class ZClass { public const int fielda=5, fieldb=15; public const int fieldc=fieldd+10; // Error public static int fieldd=15; }
The assignment to fieldc causes a compile error. The fieldd member is a nonconstant member variable and is evaluated at run time. Thus, fieldd cannot be used in a constant expression, as shown in the preceding code. Constant expressions are limited to literals and constant types.
As a data member, fields are the most prevalent. Instance fields hold state information for a specific object. The state information is copied into the managed memory created for the object. Static fields are data owned by the class. A single instance of static data is created for the class. It is not replicated for each instance of the class. Fields can be reference or value types. Here is the syntax for declaring a field:
accessibility modifier type fieldname=initialization;
Fields support the full assortment of accessibility. Valid modifiers for a field include new, static, read-only, and volatile. Initialization is optional but recommended. Uninitialized fields are assigned a default value of zero or null. Alternatively, fields can be initialized in constructor functions. Like constants, fields of the same type are declarable individually or in aggregate in the initialization list.
Initialization is performed in the textual order in which the fields appear in the class, which is top-down. This process is demonstrated in the following code:
using System; namespace Donis.CSharpBook{ internal class ZClass { public int iField1=FuncA(); public int iField2=FuncC(); public int iField3=FuncB(); public static int FuncA() { Console.WriteLine("ZClass.FuncA"); return 0; } public static int FuncB() { Console.WriteLine("ZClass.FuncB"); return 1; } public static int FuncC() { Console.WriteLine("ZClass.FuncC"); return 2; } } public class Starter{ public static void Main(){ ZClass obj=new ZClass(); } } }
Running this code confirms that FuncA, FuncC, and FuncB are called in sequence the textual order of the initialization. Avoid writing code dependent on the initialization sequence—writing code that way makes the program harder to maintain without clear documentation.
Private fields exposed through accessor functions, a get and set method, are read-write. Eliminate the get or set method to make the field read-only or write-only, respectively. However, this relies on programmer discipline. The read-only keyword is safer.
A read-only field is enforced by the run time. These fields are different from constants. Although constants can be initialized only at compile time, read-only fields can also be initialized in a constructor. Alternatively, read-only fields can be initialized with nonconstant expressions. These are subtle but important nuances and provide considerable more flexibility to a read-only field. In addition, read-only fields can be instance or static members, whereas constant are only static.
This code highlights read-only fields:
public class ZClass { public ZClass() { // constructor fieldc=10; } public static int fielda=5; public readonly int fieldb=fielda+10; public int fieldc; };
Because of the intricacy of program execution, writes and reads to a field might not be immediate. This latency can cause problems, particularly in a multithreaded application. Reads and writes to volatile fields are essentially immediate. Volatile makes automatic what locks do programmatically. Locks are explained in Chapter 9, "Threading."
Member functions contain the behavior of the class. Methods, properties, and indexers are the member functions. Methods are straightforward functions that accept parameters as input and return the result of an operation. Properties are accessor methods, a get and set method, masked as a field. An indexer is a specialized property. Indexers apply get and set methods to the this reference, which refers to the current object. The discussion of indexers is deferred to Chapter 6, "Arrays and Collections."
Functions encapsulate a sequence of code and define the behavior of the class. A function is not necessarily executed in sequential order and sometimes contains iterative and conditional transfer control statements. Return statements provide an orderly exit to a function. Void functions can simply fall through the end of the function. The compiler extrapolates the code paths of a function and uncovers any unreachable code, which is subsequently flagged by the compiler. All paths must conclude with an orderly exit. The following code includes both unreachable code and a code path without an orderly exit:
public static int Main(){ if(true) { Console.WriteLine("true"); } else { Console.WriteLine("false"); } }
The if statement is always true. Therefore, the else code is unreachable. Main returns int. However, the method has no return. For these reasons, the application generates the following errors when compiled:
unreachable.cs(10,17): warning CS0162: Unreachable code detected unreachable.cs(5,27): error CS0161: ' Donis.CSharpBook.Starter.Main()': not all code paths return a value
Keep functions relatively short. Extended functions are modestly harder to debug and test. A class comprised of several functions is preferable to class of a few convoluted functions. Remoted components are the exception: A narrower interface is preferred to minimize client calls and optimize network traffic. Comparatively, local invocations are relatively quick and efficient.
Methods own a code sequence, local variables, and parameters. The local variables and parameters represent the private state of the method.
Local variables and parameters represent the private state of the function. Local variables are reference or value types. Declare a local variable anywhere in a method. However, a local variable must be defined before use. Optionally, initialize local variables at declaration. There are competing philosophies as to when to declare local variables: Some developers prefer to declare local variables at the beginning of a method or block, where they are readily identifiable; other developers like to declare and initialize local variables immediately prior to use. They feel that local variables are more maintainable when situated near the affected code. Local variables are not assigned a default value prior to initialization. For this reason, using an unassigned local variable in an expression causes a compile error. This is the syntax of a local variable:
modifier type variablename=initialization;
The const modifier is the only modifier that is applicable. Variables that are const must be initialized at compile time.
The scope of a local variable or function parameter is the entire function. Therefore, local variables and function parameters must have unique names. Local variables of the same type can be declared individually or in aggregate.
Scope Local variables are declared at the top level or in a nested block within the method. Although the scope of a local variable is the entire function, the visibility of a local variable starts where the local variable is declared. Visibility ends when the block that the local variable is declared is exited. Local variables are visible in descendant blocks, but not ascendant blocks. Because local variables maintain scope throughout a function, names of local variable cannot be reused—even in a nested block. Figure 2-1 illustrates the relationship between scope and visibility of local variables.
Local variables of a value type are removed from the stack when a function is exited. Local references are also removed from the stack at that time, whereas the objects they referred to become candidates for garbage collection. This assumes that no other references to the object exist at that time. If other outstanding references exist, the object associated with the reference remains uncollectible. When a reference is no longer needed, assign null to the reference. This is a hint to the garbage collector that the related object is no longer needed.
Local variables are private to the current function. Functions cannot access private data of another function. Identically named local variables in different functions are distinct and separate entities, which are stored at different memory addresses. To share data between functions, declare a field.
Methods are the most common function member. Methods accept parameters as input, perform an operation, and return the result of the operation. Both parameters and the return result are optional. Methods are described through the method header, and implemented in the method body. Here is the syntax of a method:
Method syntax:
attributes accessibility modifiers returntype methodname(parameter list) { method body };
Any attribute that targets a method can prefix the method. The accessibility of methods included in the class interface is public. Methods not included in the interface are typically protected or private. Methods can be assigned the sealed, abstract, new, and other modifiers, as explained in Chapter 3. The return is the result of the method. Methods that return nothing stipulate a void returntype. The parameter list, which consists of zero or more parameters, is the input of the method. The method body contains the statements of the method.
Method Return Execution of a function starts at the beginning and ends at a return. The return keyword provides the result of function or an error code. A value or reference type can be returned from a method as defined by the return type. Functions can contain multiple returns, each on a separate code path. More than one return along a single code path results in unreachable code, which causes compiler warnings.
Functions with a void return type can be exited explicitly or implicitly. An empty return statement explicitly exits a function of a void return type. For an implicit exit, execution is allowed to exit the function without a return statement. At the end of the function block, the function simply exits. Implicit returns are reserved for functions that return void. A function can have multiple explicit returns but only one implicit return. The end of a function must be reached for an implicit return, whereas an explicit return can exit the function prematurely. In the following code, Main has both an explicit and implicit exit:
static void Main(string [] arg){ if(arg.Length>0) { // do something return; } // implicit return }
A function that returns void cannot be used in an assignment. This type of method evaluates to nothing and is thereby not assignable. This prevents a function that returns void from being used as a left- or right-value of an assignment. Other functions are usable in assignments and more generally in expressions. A function evaluates to the return value. When a reference type is returned, a function is available as a left- or right-value of an assignment. Functions that return a value type are restricted to right-values of an assignment. The following code demonstrates the use of methods in expressions:
public class ZClass { public int MethodA() { return 5; } public void MethodB() { return; } public int MethodC(){ int value1=10; value1=5+MethodA()+value1; // Valid MethodB(); // Valid value1=MethodB(); // Invalid return value1; } }
At the calling site, the return of a function is temporarily copied to the stack. The return is discarded after that statement. To preserve the return, assign the method return to something. Returns are copy by value. When returning a value type, a copy of the result is returned. For reference types, a copy of the reference is returned. This creates an alias to an object in the calling function. Look at the following code:
using System; namespace Donis.CSharpBook{ public class XInt { public int iField=0; } public class Starter{ public static XInt MethodA() { XInt inner=new XInt(); inner.iField=5; return inner; } public static void Main(){ XInt outer=MethodA(); Console.WriteLine(outer.iField); } } }
In the preceding code, MethodA creates an instance of XInt, which is subsequently returned from the method. The scope of the reference called inner, which is a local variable, is MethodA. After the return, outer is an alias and refers to the inner object, which prevents the object from becoming a candidate for garbage collection, even thought the inner reference is no longer valid.
A method returns a single item. What if you want to return multiple values? The solution is to return a structure containing a data member for each value. Structures are lightweight and appropriate for copying by value on the stack.
Function parameters Functions have zero or more parameters, where an empty function call operator indicates zero parameters. Parameter lists can be fixed or variable length. Use the param keyword to construct a variable length parameter list, which is discussed in Chapter 6. Parameters default to pass by value. When the parameter is a value type, changes to the parameter are discarded when the method is exited and the value is removed from the stack. In the following code, changes made in the function are discarded when the function returns:
using System; namespace Donis.CSharpBook{ public class Starter{ public static void MethodA(int parameter) { parameter=parameter+5; } // change discarded public static void Main(){ int local=2; MethodA(local); Console.WriteLine(local); // 2 outputted } } }
As a parameter, reference types are also passed by value. A copy of the reference, which is the location of the object, is passed by value. Therefore, the function now has an alias to the actual object, which can be used to change the object. Those changes will persist when the function exits.
This code revises the preceding code. An integer wrapper class is passed as a parameter instead of an integer value. Changes made to the object in MethodA are not discarded later.
using System; namespace Donis.CSharpBook{ public class XInt { public int iField=2; } public class Starter{ public static void MethodA(XInt alias) { alias.iField+=5; } public static void Main(){ XInt obj=new XInt(); MethodA(obj); Console.WriteLine(obj.iField); // 7 } } }
Pass a parameter by reference using the ref modifier. The location of the parameter is passed into the function. The ref attribute must be applied to the parameter in the function signature and at the call site. The function now possesses the location of the actual parameter and can change the parameter directly. The following code has been updated to include the ref modifier. Unlike the first revision of this code, changes made in MethodA are not discarded.
using System; namespace Donis.CSharpBook{ public class Starter{ public static void MethodA(ref int parameter) { parameter=parameter+5; } public static void Main(){ int var=2; MethodA(ref var); Console.WriteLine(var); // 7 } } }
What happens when a reference type is passed by reference? The function receives the location of the reference. Because a reference contains a location to an object, the location of the location is passed into the function. In the following code, a reference type is passed by value, which creates an alias. Because the reference is passed by value, changes to the alias are discarded when the function exits.
using System; namespace Donis.CSharpBook{ public class XInt { public int iField=2; } public class Starter{ public static void MethodA(XInt alias) { XInt inner=new XInt(); inner.iField=5; alias=inner; } // reference change lost public static void Main(){ XInt obj=new XInt(); MethodA(obj); Console.WriteLine(obj.iField); // 2 } } }
Next, the code is slightly modified to include the ref attribute. The assignment in MethodA is not discarded when the method exits. Therefore, obj is updated to reference the object created in the method.
using System; namespace Donis.CSharpBook{ public class XInt { public int iField=2; } public class Starter{ public static void MethodA(ref XInt alias) { XInt inner=new XInt(); inner.iField=5; alias=inner; } public static void Main(){ XInt obj=new XInt(); MethodA(ref obj); Console.WriteLine(obj.iField); // 5 } } }
Local variables must be initialized before use. The following code is in error. The obj reference is unassigned but initialized in the method. However, the compiler is unaware of this and presents an error for using an unassigned variable. The out parameter is a hint to the compiler that the parameter is being set in the function, which prevents the compiler error. The out parameter is not required to be initialized before the method call. These parameters are often used to return multiple values from a function.
using System; namespace Donis.CSharpBook{ public class XInt { public int iField=5; } public class Starter{ public static void MethodA(ref XInt alias) { XInt inner=new XInt(); alias=inner; } public static void Main(){ XInt obj; MethodA(ref obj); // Error } } }
In the following code, the parameter modifier is changed to out. The program compiles and runs successfully when the attribute is changed to out:
using System; namespace Donis.CSharpBook{ class XInt { public int iField=5; } class Starter{ public static void MethodA(out XInt alias) { XInt inner=new XInt(); alias=inner; } public static void Main(){ XInt obj; MethodA(out obj); Console.WriteLine(obj.iField); // 5 } } }
Function overloading permits multiple implementations of the same function in a class, which promotes a consistent interface for related behavior. The SetName method would be overloaded in the Employee class to accept variations of an employee name. Overloaded methods share the same name but have unique signatures. Parameter attributes, such as out, are considered part of the signature. (The signature is the function header minus the return type.) Because they are excluded from the signature, functions cannot be overloaded on the basis of a different return type. The number of parameters or the type of parameters must be different. With the exception of constructors, you cannot overload a function based on whether a member is a static or instance member.
The process of selecting a function from a set of overloaded methods is called function resolution, which occurs at the call site. The closest match to a specific function is called as determined by the number of parameters and the types of parameters given at function invocation. Sometimes a function call matches more than one function in the overloaded set. When function resolution returns two or more methods, the call is considered ambiguous, and an error occurs. Conversely, if no method is returned, an error is also manifested.
This sample code overloads the SetName method:
using System; namespace Donis.CSharpBook{ public class Employee { public string name; public void SetName(string last) { name=last; } public void SetName(string first, string last) { name=first+" "+last; } public void SetName(string saluation, string first, string last) { name=saluation+" "+first+" "+last; } } public class Personnel { public static void Main(){ Employee obj=new Employee(); obj.SetName("Bob", "Jones"); } } }
Functions with variable-length parameter lists can be included in the set of overloaded functions. The function is first evaluated with a fixed-length parameter list. If function resolution does not yield a match, the function is evaluated with variable-length parameters.
A constructor is a specialized function for initializing the state of an object. Constructors have the same name of the class. The main purpose of a constructor is to initialize the fields and guarantee that object is in a known state for the lifetime of the object. Constructors are invoked with the new operator. Here is the syntax of a constructor:
Constructor syntax:
accessibility modifier typename(parameterlist)
The accessibility of a constructor determines where new instances of the reference type can be created. For example, a public constructor allows an object to be created in the current assembly and a referencing assembly. A private constructor prevents an instance from being created outside the class. extern is the only modifier for constructors.
The parameter list of constructors has zero or more parameters.
This is the constructor for the Employee class:
using System; namespace Donis.CSharpBook{ public class Employee { public Employee(params string []_name) { switch(_name.Length) { case 1: name=_name[0]; break; case 2: name=_name[0]+" "+_name[1]; break; default: // Error handler break; } } public void GetName() { Console.WriteLine(name); } private string name=""; } public class Personnel{ public static void Main(){ Employee bob=new Employee("Bob", "Wilson"); bob.GetName(); } } }
Classes with no constructors are given a default constructor, which is a parameterless constructor. Default constructors assign default values to fields. An empty new statement invokes a default constructor. You can replace a default constructor with a custom parameterless constructor. The following new statement calls the default constructor of a class:
Employee empl=new Employee();
Constructors can be overloaded. The function resolution of overloaded constructors is determined by the parameters of the new statement. This Employee class has overloaded constructors:
using System; namespace Donis.CSharpBook{ public class Employee { public Employee(string _name) { name=_name; } public Employee(string _first, string _last) { name=_first+" "+_last; } private string name=""; } public class Personnel { public static void Main(){ Employee bob=new Employee("Jim", "Wilson"); // 2 arg c'tor } } }
In the preceding code, this would cause a compile error:
Employee jim=new Employee();
This is the error message:
overloading.cs(20,26): error CS1501: No overload for method 'Employee' takes '0' arguments
Why? Although the statement is syntactically correct, the Employee class has lost the default constructor. Adding a custom constructor to a class removes the default constructor. If desired, also add a custom parameterless constructor to preserve that behavior.
A constructor can call another constructor using the this reference, which is useful for reducing redundant code. A constructor cannot call another constructor in the method body. Instead, constructors call other constructors using the colon syntax, which is affixed to the constructor header. This syntax can be used only with constructors and not available with normal member functions. In this code, all constructors delegate to the one argument constructor:
class Employee { public Employee() : this(""){ } public Employee(string _name) { name=_name; } public Employee(string _first, string _last) : this(_first+" "+_last){ } public void GetName() { Console.WriteLine(name); } private string name=""; }
Constructors can also be static. Create a static constructor to initialize static fields. The static constructor is invoked before the class is accessed in any manner. There are limitations to static constructors, as follows:
Static constructors cannot be called explicitly.
Accessibility defaults to static, which cannot be set explicitly.
Static constructors are parameterless.
Static constructors cannot be overloaded.
Static constructors are not inheritable.
The return type cannot set explicitly. Constructors always return void.
As mentioned, static constructors are called before a static member or an instance of the classes is accessed. Static constructors are not called explicitly with the new statement. In the following code, ZClass has a static constructor. The static constructor is stubbed to output a message. In Main, the time is displayed, execution is paused for about five seconds, and then the ZClass is accessed. ZClass.GetField is called to access the class and trigger the static constructor. The static constructor is called immediately before the access, which displays the time. It is about five seconds later.
using System; using System.Threading; namespace Donis.CSharpBook{ public class ZClass{ static private int fielda; static ZClass() { Console.WriteLine(DateTime.Now.ToLongTimeString()); fielda=42; } static public void GetField() { Console.WriteLine(fielda); } } public class Starter{ public static void Main(){ Console.WriteLine(DateTime.Now.ToLongTimeString()); Thread.Sleep(5000); ZClass.GetField(); } } }
Singleton Singletons provide an excellent example of private and static constructors. A singleton is an object that appears once in the problem domain. Singletons are limited to one instance, but that instance is required. This requirement is enforced in the implementation of the singleton. A complete explanation of the singleton pattern is found at.
The singleton presented in this chapter has two constructors. The private constructor means that an instance cannot be created outside the class. That would require calling the constructor publicly. However, an instance can be created inside the class. The single instance of the class is exposed as a static member, which is initialized in the static constructor. The instance members of the class are accessible through the static instance. Because the static constructor is called automatically, one instance—the singleton—always exists.
A chess game is played with a single board—no more or less. This is the singleton for a chess board:
using System; namespace Donis.CSharpBook{ public class Chessboard { private Chessboard() { } static Chessboard() { board=new Chessboard(); board.start=DateTime.Now.ToShortTimeString(); } public static Chessboard board=null; public string player1; public string player2; public string start; } public class Game{ public static void Main(){ Chessboard game=Chessboard.board; game.player1="Sally"; game.player2="Bob"; Console.WriteLine("{0} played {1} at {2}", game.player1, game.player2, game.start); } } }
In Main, game is an alias for the ChessBoard.board singleton. The local variable is not another instance of Chessboard. The alias is simply a convenience. I preferred game.player1 to Chess-Board.board.player1.
An application can clean up unmanaged resources of an object in the destructor method. Destructors are not directly callable and called by the run time prior to garbage collection removing the object from the managed heap. Garbage collection is nondeterministic. A destructor is invoked at an undetermined moment in the future. Like a constructor, the destructor has the same as the class, except a destructor is prefixed with a tilde (~). The destructor is called by the Finalize method, which is inherited from System.Object. In C#, the Finalize method cannot be used directly. You must use a destructor for the cleanup of object resources. For deterministic garbage collection, inherit the IDisposable interface and implement IDisposable.Dispose. Call dispose to relinquish managed or unmanaged resources associated with the object. Implementing a disposable pattern is one of the topics found in Chapter 16.
Destructors differ from other methods in the following ways:
Destructors cannot be overloaded.
Destructors are parameterless.
Destructors are not inherited.
Accessibility cannot be applied to destructors.
Extern is the sole destructor modifier.
The return type cannot be set explicitly. Destructors return void.
Here is the syntax of a destructor.
Destructor syntax:
modifier ~typename()
Destructors have performance and efficiency implications. Understand the ramifications of destructors before inserting a destructor in a class. These topics are also covered in Chapter 16.
The WriteToFile class is a wrapper for a StreamWriter object. The constructor initializes the internal object. The Dispose method closes the file resource. The destructor delegates to the Dispose method. The Main method tests the class.
using System; using System.IO; namespace Donis.CSharpBook{ public class WriteToFile: IDisposable { public WriteToFile(string _file, string _text) { file=new StreamWriter(_file, true); text=_text; } public void WriteText() { file.WriteLine(text); } public void Dispose() { file.Close(); } ~WriteToFile() { Dispose(); } private StreamWriter file; private string text; } public class Writer{ public static void Main(){ WriteToFile sample=new WriteToFile("sample.txt", "My text file"); sample.WriteText(); sample.Dispose(); } } }
Properties are get and set methods exposed as properties. Public fields do not adhere to encapsulation. Private fields are good policy where the fields are exposed through accessor methods. A property combines the convenience of a public field and the safety of access methods. For clients of the public interface of a class, properties are indistinguishable from fields. The client appears to have direct access to the state of the class or object. There several benefits of properties:
Properties are safer than public fields. Use the set method to validate the data.
Properties can be computed, which adds flexibility. Fields represent a data store and never a calculation.
Lazy initialization can be used with properties. Some data is expensive to obtain. A large dataset is an ideal example. Deferring that cost until necessary is a benefit.
Write- and read-only properties are supported. Public fields are fully accessible.
Properties are valid members of an interface. As part of the interface contract, a class can be required to publish a property. Interfaces do not include fields.
A property is a get and set method. Neither method is called directly. Depending on the context of the property, the correct method is called implicitly. As a left-value of an assignment, the set method of the property is called. When used as a right-value, the get method of the property is called. When a property is the target of an assignment, the set method of the property is invoked. The get method is called if a property is used within an expression. Here is the syntax of a property:
Property syntax:
accessibility modifier type propertyname { attributes get {getbody} attributes set {setbody} }
The accessibility and any modifier included in the property header apply to both the get and set method. However, the set or get method can override the defaults of the property. Type is the underlying type of the property. Neither the get nor set method has a return type or parameter list. Both are inferred. The get method returns the property type and has no parameters. The set method returns void and has a single parameter, whi | http://etutorials.org/Programming/programming+microsoft+visual+c+sharp+2005/Part+I+Core+Language/Chapter+2+Types/Classes/ | crawl-001 | refinedweb | 6,364 | 50.53 |
Hi,
I've queried an EventLog using ManagementObjectSearcher (System.Management namespace for WMI access). So far I was able to retrieve log entries by querying the Win32_NTLogEvent instances.
But when I tried mapping the ManagementObject instances, the TimeGenerated and TimeWritten properties are in String form and not in DateTime type as documented (see MSDN:). I can't convert the String directly to DateTime. A sample value I'm getting is:
20060907105310.000000+480
It's the first time I've tried using the System.Management namespace, especially to access Event Logs. Please let me know if I'm doing something wrong here. Thanks.
use the management dateTime converter:
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.
Would you like to participate? | https://social.msdn.microsoft.com/Forums/vstudio/en-US/0d94b9a3-4f94-4ea7-bd03-6994f9384473/wmi-win32ntlogevent-class-time-properties-not-datetime?forum=netfxbcl | CC-MAIN-2015-14 | refinedweb | 148 | 59.8 |
In part 1 of this post, I described the possible approaches/frameworks for unit testing of web applications. In this post, I concentrate on one framework, which is JBoss Arquillian. The contents of this post will be:
- What about JBoss Arquillian?
- Use Arquillian to Unit Test inside EClipse and JBoss 6
- Secrets behind Scene: How Arquillian handles the Test?
Since the contents of this post is a little bit long, I will explain the following remained contents in part 3:
- Using Arquillian for Unit Test from Apache Ants
- Is Arquillian Really Good? Let's Evaluate it
Before jumping to details, I should mention that I am not a member of Arquillian project or JBoss. This post is only persoanl exprience of me on this framework, as a community member. So, it is not official ...
What about JBoss Arquillian?
As it is mentioned in official site of Arquillian:
Arquillian enables you to test your business logic in a remote or embedded container. Alternatively, it can deploy an archive to the container so the test can interact as a remote.
In four words, Arquillan is in-container test framework. For concept of in-container test, please refer to part 1 of this post.
Arquillian is a well-designed and easy-to-use framework, that makes the difficult task of web application unit test/integration test very easy.
You just write test cases using well-known tools of JUnit 4 or TestNG 5, and then add a few metadata to your test code specific to Arquillian, and you are done. Just need to run the test. The following difficult jobs are handled by Arquillian:
- Build deployable archive files (jar, war, ...) containing your test case classes.
- Deploy built test archive files to web application container, and after test, undeploy it automatically.
- After deploy, run the test inside container, and capture test results/failure.
- If necessary, Arquillian can handle start/stop web application container.
At the time of this post, it is still in 1.0.0.Alpha 5 release, and as a JBoss project, an active community and many team members are extending it to make it ready for final release. Its official site is as following:
Use Arquillian to Unit Test inside EClipse and JBoss 6
OK, introduction is enough. Let's see how to use Arquillian in a typical unit test case. Arquillian has many rich funcationalites and support different scenarios. But, for understanding it, let's concentrate on a simple situation (although it is simple, I guess it will be enough for many test situations). Let's assume our test situation is as following:
- As a sample, Target code to be tested is a business logic class to manage users of our web application with a simple CRUD interface like following sample code (typically, these kind of information are stored/retrieved to/from database):
public class UserLogic { public User add( User user ){ ... } public User get( Long id ){ ... } public Boolean update( User user ){ ... } public Boolean delete( Long id ){ ... } }
- Our application's classes/resources (including above business logic class) have been already deployed into web application server, which is JBoss 6, and the server is running (don't worry, if you are using different application server, we will talk about it too in few lines lower).
- We are using EClipse IDE as development/coding environment, and we can deploy/debug/run the web appliction into above web application server. The meaning of this assumption is that EClipse already knows how to access into application server. (I think other IDE tools should be the same, and EClipse is only a sample. However, I have not tested other IDEs).
- Your have necessary JUnit 4 or TestNG 5 plugin already installed into your EClipse, and you can use it. In recent versions of EClipse, these plugins have already been installed, and you shouldn't need any additional plugin.
That's all for the assumptions. Let's start preparing unit test items and do the test. The steps are very easy, and as following:
STEP (1): Write Unit Test Classes: For this step, you don't care about Arquillian, and just need knowledge of how to use JUnit 4 or TestNG 5. I assume that you already know how to do it. If not, you can find many good tutorials on web, for example, this link. Let's consider that our unit test case class will be something like following code (for JUnit 4):
public class UserLogicTest { ) } }
For this step, be careful about one important point. For JUnit, you should use JUnit 4.8.2 or higher. If using TestNG, you should use TestNG 5.14.9 or higher. Please confirm that your classpath library in EClipse for JUnit or TestNG is pointing out proper version, otherwise, when you run the test, you may face exception.
STEP (2): Add Arquillian Libraries to Your EClipse Project: Same as other Java frameworks, to use them, you need to add the necessary libraries to the library classpath of your project in EClipse. Same is for Arquillian, and you need to add Arquillian JAR files. Technically, this step should be the easiest, but, actually, this one is the most difficult step.
If you are using Apache Maven in your project, you can refer to this page of Arquillian's documentation. But, if, same as me, you are not fan of Apache Maven, logically you should be able to find the necessary JAR files in the download page of Arquillian, in this link. However, in this link, you can find it is mentioned:
Right now, Arquillian releases only consist of individual binary and source JARs published to the JBoss Community Nexus repository (see above). We'll make distributions available for download once Arquillian enters beta.
If you ca't wait for Beta release of Arquillian, then you can refer to following table to download the necessary JAR files. Sorry if I can't summarize all of them in one ZIP file to make this step easy for you.
As you can see in category 4 of above table, for different web application servers, the only difference is that you just need to include the related client libraries of target application server. Other steps are exactly same for all types of server.
STEP (3): Add Arquillian Meta-Data to Unit Test Classes: We have already included the Arquillian libraries in classpath, and we are ready to modify the unit test class we prepared in above STEP (1). The modification is very easy, and you can see the final test code in following.
@RunWith(Arquillian.class) public class UserLogicTest { @Deployment public static JavaArchive createTestArchive() { return ShrinkWrap.create(JavaArchive.class, "test.jar"); } ) } }
The @RunWith(Arquillian.class) means to use the Arquillian's test runner, instead of default JUnit's test runner.
And, the static @Deployment method, means to deploy the test code to web application server, as a "test.jar" archive file.
That's all for this step. Huh, it is easy, isn't it?
STEP (4): Run Test Classes: Last step is to run your test cases. It is easy, and exactly same as the way you run other test case classes inside EClipse. Nothing special for Arquillian. For JUnit, you can refer to this link.
Enjoy it. Your test should be running and show you the results, hopefully no error.
Secrets behind Scene: How Arquillian handles the Test?
We have seen how to create and run the unit test classes. But, how Arquillian run the test inside container? Run your test case inside the EClipe again, and when the test is running, have a look at: /server/serverName/deploy folder of your JBoss. While unit test is running, you can see a file called "test.war" is created in the deploy folder. And when the unit test is finished, this war file is deleted automatically.
Huh? In the static @Deployment method (mentioned in STEP (3)), the code says that test file should be "test.jar", but, the deploy file is "test.war". Why?
The answer is very easy. If you unzip the "test.war" file, you can see that a "test.jar" file exists inside it, which contains your test case class. But, in addition to "test.jar", some other Arquillian JAR files also exist within "test.war" file. That is logical. Arquillian needs to run the test cases inside the application server, so, the Arquillian libraries also should be deployed into server.
In order to run in-container test, Arquillian do following tasks sequentially for each test case:
- Bundle the test class and related Arquillian library JAR files into an archive file (according to static @Deployment method)
- Deploy the test archive into web application server
- Enhance/enrich the test class (e.g., resolving @Inject, @EJB and @Resource injections) and run the test class within server, and return the test results
- Undeploy the test archive from web application server
To be exact, other than "enhance/run/return results of test classes", other tasks are all done by JBoss ShrinkWrap. You have already seen in above STEP (2), that ShrinkWrap JAR libraries are necessary. To be more exact, ShrinkWrap internally uses the SPI (Service Provider Interface) to support deploy/undeploy archive files into/from web application server. You can read about SPI more in details in this link. Anyway, let's thank develppers of the Arquillian framework who have done good job to handle such difficult implementations internally, that we don't need to learn SPI.
OK. This long post is reaching to the end. By reading this post, I think you have found enough knowledge of how to use Arquillian. Arquillian has many advanced functionalities, that you can read in the documentation page. In part 3, I will explain about how to run Arquillian test cases from Apache Ant's xml files. | https://developer.jboss.org/blogs/mousavi/2011/09/09/web-application-unit-testintegration-test-which-framework-part-2 | CC-MAIN-2017-43 | refinedweb | 1,629 | 64.3 |
Hello, I am asp.net C# developer. I decided to tackle C++, so I started today. This is probably something simple I am sure but I cannot figure out what the problem is. I would appreciate if someone could show me what is wrong and why.
The error is happening on the last output operator, just before the jumble variable on the last line.The error is:The error is happening on the last output operator, just before the jumble variable on the last line.The error is:Code:: " << jumble;
I understand what its saying, but jumble is a std::stringI understand what its saying, but jumble is a std::stringCode:
Intellisense: no operator"<<" matches these operands
operand types are: std::basic_ostream<char, std::char_traits<char> <<std::string
Here are my preprocessor directives and using statements
Thanks in advance!Thanks in advance!Code:
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std; | http://forums.codeguru.com/printthread.php?t=530995&pp=15&page=1 | CC-MAIN-2016-18 | refinedweb | 155 | 58.58 |
parser.c File Reference
Channel protocol parser and commands. More...
#include "parser.h"
#include "cfg/cfg_parser.h"
#include <io/kfile.h>
#include <struct/hashtable.h>
#include <stdlib.h>
#include <string.h>
Go to the source code of this file.
Detailed Description
Channel protocol parser and commands.
This file contains the channel protocol parser and the definition of the protocol commands. Commands are defined in a "CmdTemplate" type array, containing:
- the name of the command,
- the arguments it expects to receive,
- the output values,
- the name of the function implementing the command.
The arguments and results are passed to command function using an union: the element of the union to use for each argument is determined by format strings present in the CmdTemplate table.
Definition in file parser.c.
Function Documentation
Tokenize one word at a time from a text.
This function is similar to strtok, but does not use any implicit context, nor it does modify the input buffer in any form. The word is returned as a STL-like [begin,end) range.
To extract the first word, make both begin and end point at the start of the text, and call the function. Then, subsequent calls will return the following words (assuming the begin/end variable are not modified between calls).
- Parameters:
-
- Returns:
- True if a word was extracted, false if we got to the end of the string without extracting any word.
Definition at line 92 of file parser.c. | http://doc.bertos.org/2.7/parser_8c.html | crawl-003 | refinedweb | 242 | 67.86 |
Answered by:
Issue with lambda expression Compile() and [HostType("Pex")].
- Here's an interesting one. The following simplified unit test in MSTest gets an exception if the [HostType("Pex")] attribute is present:
[TestMethod] [HostType("Pex")] public void testname3() { int x = 5; Expression<Func<int>> expression = () => x; var func = expression.Compile(); int y = func(); }
If I remove the attribute, it runs fine. If I debug through, it will jump from the Compile line to the end } and then the test will fail with the following exception:
Test method testname3 threw exception: System.ArgumentNullException: Value cannot be null.
Parameter name: field.
System.Reflection.Emit.DynamicIL.GenerateMemberAccess(ILGenerator gen, Expression expression, MemberInfo member, StackType ask)
System.Linq.Expressions.ExpressionCompiler.GenerateMemberAccess(ILGenerator gen, MemberExpression m, StackType ask)
System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
System.Linq.Expressions.ExpressionCompiler.GenerateLambda(LambdaExpression lambda)
System.Linq.Expressions.ExpressionCompiler.CompileDynamicLambda(LambdaExpression lambda)
System.Linq.Expressions.ExpressionCompiler.Compile(LambdaExpression lambda)
System.Linq.Expressions.LambdaExpression.Compile()
Compile()
PlayWithMoles.testname3() in PlayWithMoles.cs: line 42
If I change the expression to () => 5; then it works fine. I'm actually only using the Compile in my unit tests so it isn't a big deal but I would bet this will blow up and cause many weird questions. I am using Compile for my own Assert statements that I stole the idea from MBUnit. :-) If you care, the project is on CodePlex at. My Assert statements look like this:
AssertEx.That(() => x == 5);
Which are much easier to read once you get over the lambda expressions. The other neat thing is that the assert failures can look like "x was not equal to 5".
In any case, (I never thought I would say this but,) I love your Moles and your Stubs! Keep up the incredible work!
Saturday, September 19, 2009 9:06 PM
- Changed type PeliMicrosoft employee, Owner Saturday, September 19, 2009 11:33 PM tracking
Question
Answers
-
All replies
- Did you create your project through the project wizard? It might have added a special attribute to the project. Look for:
[assembly:PexLinqPackage]
This attribute loads a special rewritter for the Expression compiler and it might well be the reason for the crash.
Regarding the new AssertEx.That(...) method, why not simply have a AssertEx.That(bool) method so your example for read
AssertEx.That(x == 5);
If you only care about readability, this is much better than using the lambda. I suppose that the reason for using ExpressionTrees is really to be able to generate nice errors message. I guess you have some visitor that takes an expression tree and does pattern matching to create a english sentence (have you tought about showing the actual value of x?).
I can see the automated error message being useful but it comes with an ugly price. Instance of 3 MSIL instruction to evaluate the equality, you have millions of instructions being executed through the Expression compiler code path. If you plan to use Pex in the future, you should know that this overhead comes as a burden on the Pex whitebox analysis (Pex analyses every executed MSIL instruction).
So could you have the best of both worlds: lean and mean code + nice error messages? Yes this is possible. Instead of doing the compilation at runtime, do it at compilation time. For example, you could use CCI ( ) to rewrite the compiled test assembly. CCI could be used to visit the AST, create a string and embed it in the assembly. When running the test, in case of an error, you would simply have to load the string.
> In any case, (I never thought I would say this but,) I love your Moles and your Stubs! Keep up the incredible work!
Thanks. We've got a lof of good stuff in that space coming up. Stay tuned.
Jonathan "Peli" de HalleuxSunday, September 20, 2009 4:29 AMOwner
I was just playing with Moles so this was an existing project that used TypeMock before. I was replacing the TypeMock code with Moles. In any case I didn't have the [assembly: PexLinqPackage] attribute. I added it and now I get the following exception:
Test method testname3 threw exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: con.
System.Reflection.Emit.ModuleBuilder.GetFieldTokenNoLock(FieldInfo field)
System.Reflection.Emit.ModuleBuilder.GetFieldToken(FieldInfo field)
System.Reflection.Emit.IL.GenerateArgs(ILGenerator gen, ParameterInfo[] pis, ReadOnlyCollection`1 args)
System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall(ILGenerator gen, MethodInfo mi, ReadOnlyCollection`1 args, Type objectType)
System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall(ILGenerator gen, MethodCallExpression mc, StackType ask)
System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
System.Linq.Expressions.ExpressionCompiler.GenerateConvert(ILGenerator gen, UnaryExpression u)
System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
__Substitutions.System.Linq.Expressions.ExpressionCompiler.InternalGenerateLambda(Object receiver, LambdaExpression lambda)
__Substitutions.System.Linq.Expressions.ExpressionCompiler.CompileDynamicLambda(Object receiver, LambdaExpression lambda)
__Substitutions.System.Linq.Expressions.ExpressionCompiler.Compile(Object receiver, LambdaExpression lambda)
System.Linq.Expressions.LambdaExpression.Compile()
Compile()
testname3() in PlayWithMoles.cs: line 21
As I mentioned, this isn't fatal for me because the projects I'm testing are in VS 2005 so no lambdas. I'm using VS 2008 for all my unit testing since thats when MSTest became part of VS Professional.
About the lambda assertions. I understand I can replace my AssertEx.That(() => x == 5) statement with Assert.IsTrue(x == 5). The main reason for using the lambdas is to be able to parse the expression tree and create a good failure message. For example, AssertEx.That(() => Console.ReadLine() == null) would tell me that "ReadLine method returned <xxx> instead of the expected null" instead of saying the value "<xxx> is not null". I find the extra hint at what's going on very helpful.
I know very well that I'm replacing a couple IL instructions with thousand or millions. My first computer only had 4K of memory so I'm aware of the evil I do. But like all evil, it feels so good when I do it! In normal unit tests this makes almost no visible time different. If I were to do something like compare two bitmaps pixel by pixel I would drop back to the regular Assert.AreEqual(pixel1, pixel2). I'm also aware of how bad this is for Pex. I'm working on legacy code that wasn't built for unit testing so it's a challenge to write unit tests in the first place. I'm trying to us Pex against the new functionality I write.
I've worked with both Cecil (Mono open source project) and CCI for rewriting assemblies. The problem with both is that they don't handle updating the .pdb files. (I would love to find out I'm wrong in either of these cases.) That means I can't single step through my unit tests. This is a deal breaker for me. My hope is that .Net 5.0 has enough of the "Compiler as a Service" in it that I can do something like what you are talking about. I've seriously considered converting my unit tests to the Boo language because it lets you rewrite the AST (Abstract Syntax Tree) as its being compiled. I don't think this is part of .Net 5.0 Compiler as a Service feature.
Thanks for the quick response. BTW, I think its cool having such "direct" communications with you!Sunday, September 20, 2009 3:21 PM
- I'm pretty sure CCI handles pdbs correctly. It is used by the Code Contracts.NET rewritter which handles pdbs :). Have you raised the issue on the CCI forums?
Jonathan "Peli" de HalleuxMonday, September 21, 2009 1:35 AMOwner
- The project I was going to use this on was basically the same as Moles except I was going to rewrite the referenced assemblies to insert callbacks at the start. I was using Cecil and had it working pretty well except the pdb would get wacked 1/2 the time. Probably because I didn't know what I was doing. :-)
In any case, I was going to get back to playing with the project this weekend but you released Moles so I didn't have to. I can easily change my unit tests so I don't have this problem. We are putting our house on the market Monday so I really don't have time to play anyway!
Maybe I will get lucky and the stuff we would be using IL rewriting for could be done in the compiler in .Net 5.0. Having Code Contracts ship with VS 2010 is a good sign that it's needed or at least useful. Of course if it does make it into .Net 5.0, I'm sure many people will do evil with it.
Thanks for all your help!Monday, September 21, 2009 2:45 AM
- > IL rewriting for could be done in the compiler in .Net 5.0.
Code Contracts.NET uses CCI, which you can download today from . It does not use the 'Compiler As Service' component.
Jonathan "Peli" de HalleuxMonday, September 21, 2009 3:52 AMOwner
- I understand CCI (used by Code Contracts) and .Net 5.0 "Compiler as a Service" are different things. I was pointing out that Code Contracts would probably move to "Compiler as a Service" if it allowed AST (Abstract Syntax Tree) modification like Boo's implementation. Currently the Boo language will let you modify the AST while the code is compiling. If Code Contracts would ONLY have to support Boo then they would have used Boo's AST instead of IL rewriting. I haven't heard much about "Compiler as a Service" but I did hear that the Boo like AST rewriting might be part of .Net 5.0. If I recall it was a very weak might.Monday, September 21, 2009 2:28 PM
The Code Contracts questions should really go into the Contrats forum :).
Jonathan "Peli" de HalleuxMonday, September 21, 2009 3:30 PMOwner
- Hi,
Could you copy the instrumentation instruction you are using for your project? I cannot reproduce the issue.
Thanks,
Peli
Jonathan "Peli" de HalleuxTuesday, September 22, 2009 5:22 AMOwner
- I made a nice zip file but couldn't see a way to attach it...
I started from zero and created a new Console project. Created a new empty public method. Right-clicked on the method and chose "Create Unit Tests...". (The method isn't important, just showing I created everything "legal".) Modified the resulting test class as follows:
namespace TestPlayWithMoles { using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass()] public class ProgramTest { public TestContext TestContext { get; set; } [TestMethod] [HostType("Pex")] public void testname3() { int x = 5; Expression<Func<int>> expression = () => x; var func = expression.Compile(); int y = func(); } } }Added the two following attributes to the AssemblyInfo.cs file:
[assembly: PexLinqPackage()] [assembly: PexInstrumentAssembly(typeof(Program))]Single stepping on the expression.Compile() line cause the focus to move to the last } of the method. Another single step finished the test run and get the error we saw above. Adding/removing the PexLinqPackage attribute still causes the test to fail in the same fashion.
Other potentially important stuff. I'm running Windows 7 Ultimate 64-bit RTM from MSDN (installed new, not upgraded), Quad Core Intel, 8GB memory. I tried the following with no differences:
* run single test or all tests.
* compile in x86 mode and 64-bit mode.
* debug vs release mode.Tuesday, September 22, 2009 2:34 PM
- Ok, I could reproduce the issue. Investigating.
Jonathan "Peli" de HalleuxTuesday, September 22, 2009 3:16 PMOwner
-
- Excellent! Next version is fine. I can easily work around the problem for now. Thanks for your help.Tuesday, September 22, 2009 7:05 PM
- Don't forget to post your feedback at . Cheers, Peli
Jonathan "Peli" de HalleuxTuesday, September 22, 2009 8:22 PMOwner | https://social.msdn.microsoft.com/Forums/en-US/b2e90f00-7a94-4859-bd0f-40ae84ba9ce8/issue-with-lambda-expression-compile-and-hosttypepex?forum=pex | CC-MAIN-2015-22 | refinedweb | 2,050 | 50.73 |
> I.
If you are going to use Plone I can't offer advice - I have looked at Plone on three separate occasions, and recently read The Definitive Guide to Plone, and have stil decided not to use it. I only say this to make it clear that many applications are built without CMS and Plone.
> 1> the district name and their users come from 2 seperate Mysql > tables. the users are unique in each district.
Two separate tables with User information is awkward! The user folders I know of expect user information to come from one source. So you either have to create two folders, each with its own acl_users (provided by one of the User Folder Products), or you have to hack the User Folder product to put in a Union select statement in place of a simple Select.
> Now the qusetion is how do build this district user folder structure > using the database? > Hope not manually, because there are 22 districts and about 15 users > in each of them pluys head quarters.
You have not said whether the people in the different districts do completely different things with different forms, or identical things but specifying the district. If the former then it is no big deal to create the folders manually, although it can be done programmtically. You could set a Local Role equal to the district name and get that role for users from the database. That way, users can only enter their own district folder. If the latter, then you could retrieve the Username and District from the User object for use in the forms (include the District as a role).
> i dint get to know much about coding ZPT's and Script(Python) for > them, from the ZPT refs and Zopebook. So wanted some simple working > examples.
Try working on the rest of your application to build up ZPT and Python experience. As I said, managing users is tricky. Also, be aware that Zope experts advise developers to produce file system based Products. There are lots of simple Products that you can use and browse the code to see how they work.
Cliff
_________________________________________________________________________
prabuddha ray wrote:
______________________________________________________________________________________________Hi list, never before i got such a holistic advice. thanks so much Cliff.
About the 1st mail,
On Sat, 02 Apr 2005 17:03:56 +0100, Cliff Ford <[EMAIL PROTECTED]> wrote:
Customisation of the login sequence is quite difficult for Newbies because there are lots of different ways to approach the problem - you have already tried some. I suspect that trying to match what was done in PHP may be part of your problem. It would be helpful to know if your lists of users are coming from one source, like a database table, or multiple sources, like multiple tables or different databases, and whether users are unique in each district
I. But now as you say i think I should go the way Zope does it . only that i'm finding it hard to customize it in Zope.
1> the district name and their users come from 2 seperate Mysql tables. the users are unique in each district.
From there you decide your zope folder structure. It could be like this:
site_home |__acl_users |__district1 |__district2
or like this:
site_home |__district1 | |__acl_users |__district2 | |__acl_users
In the second case you would not have to worry about asking the user for the district name. In the first case you would get a district name or a user defined role for that district from a supplementary data source, like a database.
So i think 2nd structure is abetter fit. Now the qusetion is how do build this district user folder structure using the database? Hope not manually, because there are 22 districts and about 15 users in each of them pluys head quarters.
A combination of exUserFolder and MySQL would do.
i don know about them, something like mysqluserfolder or simpleuserfolder components ?
You can get information on the logged in user (Username and Roles) from
the User object, so you don't need to expicitly use sessions at this
stage. You should certainly not store passwords - that would be a serious breach of confidentiality.
Maybe you should say what you do with the District parameter after the
user has logged in.
I dont need the password but do need the username and district for following pages to decide the access rights and the stores available inthe districts , also for some report labels.
Giving advice or examples on ZPT and Python for an approach that is probably wrong is just too time-consuming.
Cliff
i dint get to know much about coding ZPT's and Script(Python) for them, from the ZPT refs and Zopebook. So wanted some simple working examples.
About 2nd mail,
On Sun, 03 Apr 2005 09:39:01 +0100, Cliff Ford <[EMAIL PROTECTED]> wrote:
I have been trying to think of ways of providing specific pointers, So, assuming you have a custom login page and a custom python script that processes that page:
In the Python script you could set a cookie for the District:
context.REQUEST.RESPONSE.setCookie('District', district)
where district is the name of the District field in the form. The District parameter is then always available to your page templates and scripts in the REQUEST object.
At the end of your login script you would typically redirect to some specific page like this:
return context.REQUEST.RESPONSE.redirect('aURL')
in exUserFolder you don't have to do anything else - the login works by magic, which is very confusing.
Are these above said things not possible in exUserFolder. how do i customize it for my problem?
Now for the problems:
If the login is wrong the system will call /standard_error_message, so you have to customise that to send the user back to the login form with a Login failed message.
If the user bookmarks a protected page and tries to jump to it without being logged in, the system will call the login sequence starting in acl_users, so you have to customise that to call your own login page.
After the user has logged in, whenever you need to get the Username you would typically use a python script like this:
from AccessControl import getSecurityManager return getSecurityManager().getUser().getUserName()
HTH
Cliff
So this is what can be done if I use exUserFolder ? Hope a reply soon.
Zope maillist - Zope@zope.org
** No cross posts or HTML encoding! **
(Related lists - ) | https://www.mail-archive.com/zope@zope.org/msg15285.html | CC-MAIN-2021-25 | refinedweb | 1,075 | 70.02 |
Constructive and Non-Constructive Proofs in Agda (Part 2): Agda in a Nutshell
Last week, we started a new blog series to introduce you to creating constructive and non-constructive proofs in Agda.
In our previous post, we took a look on logic in itself, we considered classical and intuitionistic logical calculi. It will come in handy today when we start tackling theorem proving in Agda based on a constructive logical framework.
In this article, we will introduce the reader to dependently typed programming and theorem proving in Agda. We will compare our examples of Agda code with their Haskell counterparts. After that, we will consider an example use of Agda in the formalisation of algebra.
General words on Agda
Agda is a dependently typed functional programming language based on a variant of Martin-Löf type theory. This type theory is a constructive proof-theoretic formal system, so Agda doesn’t have the default features for writing classical logic based proofs in contrast to HOL or Isabelle.
Agda has a Haskell-like syntax and a much richer type system (but we’re working on bringing Haskell to the same level), so we may use Agda as a proof-assistant based on the propositions-as-types paradigm. In other words, Agda is a programming language that allows providing formal proofs within constructive mathematics.
In this section, we will make a brief introduction to the syntax and possibilities of Agda.
See here for a more detailed introduction.
Basic stuff
Types in Agda
Datatypes
Datatypes in Agda are introduced as generalized algebraic datatypes (GADT):
Trivial example: a datatype of writers and a datatype of their works.
data Writers : Set where Wilde Shelley Byron Sartre Camus : Writers
data Literature : Set where DorianGrey Alastor ChildeHarold LaNausée L’Étranger : Literature
The typical example is a datatype of unary natural numbers:
data ℕ : Set where zero : ℕ suc : ℕ → ℕ
In Haskell we define these types as follows:
data Writers = Wilde | Shelley | Byron | Sartre | Camus data Literature = DorianGrey | Alastor | ChildeHarold | LaNausée | L’Étranger data ℕ = Zero | Suc ℕ
These datatypes are so-called simple datatypes.
Parameterized and indexed datatypes
See to read about parameterized and indexed datatypes in more detail.
A parameterized datatype is a datatype that depends on some parameter that should remain the same in the types of constructors. For instance,
List is a datatype parameterized over a type
A.
data List (A : Set) : Set where Nil : List A Cons : A → List A → List A
Datatypes also can have indexes that could differ from constructor to constructor in contrast to parameters. These datatypes are so-called datatype families. Example:
data Vec (A : Set) : ℕ → Set where Nil : Vec A zero Cons : {n : ℕ} → A → Vec A n → Vec A (suc n)
Vec (vector) is a datatype that is applied to another type
A and a natural number
n. We also say that
Vec is parameterized by
A and indexed by
ℕ.
Nil is an empty vector.
Cons is a constructor adding a new element to a given vector increasing the length counter. Here
n is an implicit argument of the constructor.
Cons is also an example of a dependent function, as will be seen below.
In Haskell, we would have the following GADT via
DataKinds,
PolyKinds and
GADTs extensions:
import Data.Kind (Type) data Vec :: Type -> ℕ -> Type where Nil :: Vec a 'Zero Cons :: a -> Vec a n -> Vec a ('Succ n)
Another example:
Fin is a type that describes finite types, in other words, types of finite cardinality. Informally,
Fin is a type of finite sets:
data Fin : ℕ → Set where zero : {n : ℕ} → Fin (suc n) suc : {n : ℕ} → Fin n → Fin (suc n)
Fin is a datatype indexed by a natural number.
zero reflects an empty set which is an element of any finite set.
suc is a constructor that applies the finite set
i and yields a new finite set, which is a larger than
i on one element.
In Haskell, we define
Fin using
DataKinds and
KindSignatures extensions as with vectors above:
import Data.Kind (Type) data Fin :: Nat -> Type where Fzero :: forall (n :: ℕ). Fin ('Succ n) Fsucc :: forall n. Fin n -> Fin ('Succ n)
Note that, datatypes
Vec and
Fin implemented in Agda are also examples of dependent types, these types depend on values (in particular, on natural numbers), not only on types.
On the other hand, their counterparts in Haskell are not dependent types in a strict sense, because
forall (n :: ℕ) in Haskell does not introduce a value, therefore
Fin does not depend on any values.
See here for an introduction to type level programming in Haskell.
Functions
Functions in Agda are arranged similarly to Haskell, using pattern matching:
bookToWriter : Literature → Writers bookToWriter DorianGrey = Wilde bookToWriter Alastor = Shelley bookToWriter ChildeHarold = Byron bookToWriter LaNausée = Sartre bookToWriter L’Étranger = Camus
We will discuss dependent functions in more detail. A dependent function is a function that takes a term
a of type
A and returns some result of type
B, where
a may appear in
B. We consider a simple example, where
a is a type itself.
const₁ : (A B : Set) → A → B → A const₁ A B x y = x
Here types
A and
B are explicit arguments. If we don’t need to mention these types explicitly, we may take them implicitly:
const₂ : {A B : Set} → A → B → A const₂ x y = x
We may compare this function in Agda with a similar function implemented in Haskell with the help of the
RankNTypes extension that allows writing the universal quantifier on types explicitly:
const₁ :: forall a b. a -> b -> a const₁ x y = x
We introduce the following datatypes to consider the next example:
data Ireland : Set where Dublin : Ireland
data England : Set where London : England
data France : Set where Paris : France
After that, we construct a function that returns some country datatype for a given writer.
WriterToCountry : Writers → Set WriterToCountry Wilde = Ireland WriterToCountry Shelley = England WriterToCountry Byron = England WriterToCountry Sartre = France WriterToCountry Camus = France
WriterToCity : (w : Writers) → WriterToCountry w WriterToCity Wilde = Dublin WriterToCity Shelley = London WriterToCity Byron = London WriterToCity Sartre = Paris WriterToCity Camus = Paris
WriterToCity is an example of a dependent function, because the type of the result depends on the argument. The type of a dependent function is the so-called -type. More generally, suppose we have some function
P: A → Set, then -type is a type of the function that assigns to every term
t : A some object of type
P t. In Agda notation, we write this type as
(t : A) → P t for some
{A : Set} {P : A → Set} in context.
Logically -type encodes intuitionistic universal quantifier. In other words,
P is a predicate and some function of a type
(t : A) → P t is a proof that for each
t : A the property
P has established.
In Haskell, we don’t have dependent quantification at term level, but we have it at type level. Therefore, we implement comparable functions as closed type families. Similarly, we promote values of type
Writers into the type level via
DataKinds in both cases:
data Ireland = Dublin data France = Paris data England = London type family WriterToCountry (a :: Writers) :: Type where WriterToCountry 'Wilde = Ireland WriterToCountry 'Shelley = England WriterToCountry 'Byron = England WriterToCountry 'Sartre = France WriterToCountry 'Camus = France
Also, we declare
WriterToCity type family that is similar to
WriterToCity function implemented in Agda. In contrast to Agda, we should enable the language extension called
TypeInType. You may implement this function via
PolyKinds since GHC 8.6.
type family WriterToCity (a :: Writers) :: WriterToCountry a where WriterToCity 'Wilde = 'Dublin WriterToCity 'Shelley = 'London WriterToCity 'Byron = 'London WriterToCity 'Camus = 'Paris WriterToCity 'Sartre = 'Paris
Dependent pairs
We introduce the dependent pair type (-type) through a simple example.
Let us consider the following inductive predicate on two lists as a GADT:
data IsReverse {A : Set} : (xs ys : List A) → Set where ReverseNil : IsReverse [] [] ReverseCons : (x : A) (xs ys : List A) → IsReverse xs ys → IsReverse (x ∷ xs) (ys ++ [ x ])
IsReverse xs ys denotes that the list
ys is equal to reversed
xs.
IsReverse is a datatype parameterized over a type
A and indexed over two lists of elements of type
A.
We prove the theorem that for all list
xs there exists list
ys such that
ys is a reversed list
xs. In other words, we should produce a dependent pair, where the first projection of this pair is some list
ys and the second one is a proof that
ys is reversed list
xs.
We use the dependent pair type to prove existence:
theoremReverse₁ : {A : Set} (xs : List A) → Σ (List A) (λ ys → IsReverse xs ys) theoremReverse₁ [] = [] , ReverseNil theoremReverse₁ (z ∷ zs) = let ys = proj₁ (theoremReverse₁ zs) in let ysProof = proj₂ (theoremReverse₁ zs) in ys ++ [ x ] , ReverseCons z zs ys ysProof
We should read the signature
{A : Set} (xs : List A) → Σ (List A) (λ ys → IsReverse xs ys) as “let
A be type and
xs be a list with elements of the type A, then there exists list
ys, such that
ys is the reversed list
xs”.
We prove this theorem by induction on
xs and build
ys for every case. If
xs is empty, then we present an empty list as the desired list
ys and
ReverseNil is a proof that
ys is equal to reversed list
xs, because both of them are empty. Thus, we have proved the base case.
The inductive step is a case when
xs is a non-empty list, i.e.
xs = z :: zs. List
zs is smaller than
z :: zs, so we can apply induction hypothesis to
zs and show that
:: preserves the desired property using the
ReverseCons constructor.
Generally, -type is defined in Agda as follows:
record Σ {a b} (A : Set a) (B : A → Set b) : Set (a ⊔ b) where constructor _,_ field fst : A snd : B fst
This record is defined for arbitrary universes, and we consider below what universes are in more detail. The given record has two fields. The first field called
fst is an object of a type A. The second one is an application
B to the argument from the first field.
From a logical point of view, we read
Σ A B as “there exists some element of a type
A, such that this element satisfies property
B”, i.e. -type encodes constructive existential quantifier. As we have told before, to prove the existence of some object with desired property constructively, then we should present the particular object and prove this object satisfies this considered property.
Universes
A hierarchy of types is a quite old idea that initially belongs to the logician and philosopher Bertrand Russell. The basic types such as
Nat or
Bool have a type called
Set, but
Set is not
Set itself.
Set has a type
Set₁, etc. Otherwise, we could infer Russell’s paradox, so our system would be inconsistent in that case.
Universe polymorphism also allows defining functions that can be called on types of arbitrary levels. Let us show how universe polymorphism works on the following example. Suppose we have this function called
s:
s : {A B C : Set} → (A → B → C) → (A → B) → A → C s f g x = f x (g x)
We implement a similar function in Haskell via
RankNTypes:
s :: forall a b c. (a -> b -> c) -> (a -> b) -> a -> c s f g x = f x (g x)
We can indicate that types
A,
B,
C are types of arbitrary level
a:
s₁ : {a : Level} {A B C : Set a} → (A → B → C) → (A → B) → A → C s₁ f g x = f x (g x)
We generalize
s further, because
A,
B and
C in
s₁ belong to the same level, but these types may generally belong to different levels :
s₂ : {a b c : Level} {A : Set a} {B : Set b} {C : Set c} → (A → B → C) → (A → B) → A → C s₂ f g x = f x (g x)
We would implement something similar as closed type family in Haskell:
type family S₂ (f :: a -> b -> c) (g :: a -> b) (x :: a) :: c where S₂ f g x = f x (g x)
By the way, the most general version of
s in Agda is an universe polymorphic dependent function:
S : {a b c : Level} {A : Set a} {B : A → Set b} {C : (x : A) → B x → Set c} → (f : (x : A) → (y : B x) → C x y) → (g : (x : A) → B x) → (x : A) → C x (g x) S f g x = f x (g x)
Records
Records in Agda are arranged similarly to Haskell. This record implemented in Haskell
data Person = Person { name :: String , country :: String , age :: Int }
may be translated to Agda as follows via keyword
record:
record Person : Set where field name : String country : String age : Int
Typeclasses are introduced in Agda as records. For example, we implement typeclass called
Functor:
record Functor {a} (F : Set a → Set a) : Set (suc a) where field fmap : ∀ {A B} → (A → B) → F A → F B
Instances may be declared either by constructing a record explicitly or by using copatterns:
instance ListFunctor₁ : Functor List ListFunctor₁ = record { fmap = map }
instance ListFunctor₂ : Functor List fmap {{ListFunctor₂}} = map
Propositional equality
The identity type is a datatype that reflects equality of terms in predicate logic. This type is defined as follows:
data _≡_ {a} {A : Set a} (x : A) : A → Set a where refl : x ≡ x
We consider a few examples where propositional equality is used. The first one is a proof of distributivity of natural number multiplication over addition.
*-+-distr : ∀ a b c → (b + c) * a ≡ b * a + c * a *-+-distr a zero c = refl *-+-distr a (suc b) c = begin (suc b + c) * a ≡⟨ refl ⟩ a + (b + c) * a ≡⟨ cong (_+_ a) (*-+-distr a b c) ⟩ a + (b * a + c * a) ≡⟨ sym (+-assoc a (b * a) (c * a)) ⟩ suc b * a + c * a ∎
This property is proved by induction on
b. When
b equals zero, the equality holds trivially. Otherwise, if
b is a non-zero number, then equality is proved using the induction hypothesis.
Propositional equality in Haskell
See the relevant part of the Haskell Prelude documentation.
We have propositional equality in Haskell as well:
data a :~: b where Refl :: a :~: a
Unlike in Agda, this datatype is defined on types of arbitrary kinds, not on terms. In other words,
(:~:) :: k -> k -> *, where
k is an arbitrary kind.
Algebraic example
We consider a few more examples in Agda to better understand its possibilities. Remember the abstract algebra, especially ring theory. We provide some algebraic definitions below:
Definition 3 A ring is an algebraic system , where is a non-empty set, , , are binary operations on and is a unary operation on such that:
- ;
- ;
- ;
- ;
- ;
- .
We define a ring in Agda similarly by declaring a record called
Ring.
Ring is a type
R with additional operations:
record Ring (R : Set) : Set₁ where constructor mkRing infixr 7 _·_ infixr 6 _+_ field θ : R -_ : R → R _+_ : R → R → R _·_ : R → R → R
After that, we formulate the axioms of a ring having declared operations above:
+-assoc : (a b c : R) → (a + b) + c ≡ a + (b + c) +-commute : (a b : R) → a + b ≡ b + a +-inv₁ : (a : R) → - a + a ≡ θ +-θ : (a : R) → a + θ ≡ a ·-distr-right : (a b c : R) → (a + b) · c ≡ (a · c) + (b · c) ·-distr-left : (a b c : R) → a · (b + c) ≡ (a · b) + (a · c) open Ring {{...}} public
It is easy to see that the definition of a ring in Agda is similar to the informal definition of a ring proposed above.
Suppose we need to extend a ring with additional axioms. Consider a Lie ring that generalizes Lie algebra, which is a well-known construction in linear algebra widely applied in mathematical physics and quantum mechanics. Initially, we suggest the following informal definition:
Definition 4 A Lie ring is a ring with two additional axioms:
- (Alternation) ;
- (Jacobi identity) .
We extend a ring to a Lie ring in Agda by declaring a new record, but we need to tell somehow that a given type
R is already a ring. We pass an additional instance argument in a signature of a record called
LieRing for this purpose:
record LieRing (R : Set){{ring : Ring R}} : Set₁ where
Then we add the special axioms of a Lie ring as usual:
constructor mkLeeRing field alternation : (a : R) → a · a ≡ θ jacobiIdentity : (a b c : R) → (a · b) · c + b · (c · a) + c · (a · b) ≡ θ
Lie ring is anticommutative, in other words:
Lemma 1 Let be Lie ring, then forall , .
Proof Firstly, we prove this fact informally. For convenience, we prove this useful proposition.
Proposition 1 If is a Lie ring, then forall , .
Thus by proposition above and alternation.
Formalisation of this proof completely preserves the reasoning above. The first lemma is the sequence of equalities applied sequentially via transitivity of propositional equality:
lemma : (a b : R) → (a + b) · (a + b) ≡ (a · b) + (b · a) lemma a b = begin ((a + b) · (a + b) ≡⟨ ·-distr-right a b (a + b) ⟩ a · (a + b) + b · (a + b) ≡⟨ cong₂ _+_ (·-distr-left a a b) (·-distr-left b a b) ⟩ (a · a + a · b) + (b · a + b · b) ≡⟨ cong (_+_ (a · a + a · b)) (cong₂ _+_ refl (alternation b)) ⟩ (a · a + a · b) + (b · a + θ) ≡⟨ cong (_+_ (a · a + a · b)) (+-θ (b · a)) ⟩ (a · a + a · b) + (b · a) ≡⟨ cong₂ _+_ (cong₂ _+_ (alternation a) refl) refl ⟩ (θ + a · b) + (b · a) ≡⟨ cong₂ _+_ (trans (+-commute θ (a · b)) (+-θ (a · b))) refl ⟩ (a · b + b · a) ∎)
Anticommutativity is proved in the same way using the obtained lemma:
anticommutativity : (a b : R) → (a · b + b · a) ≡ θ anticommutativity a b = (a · b + b · a) ≡⟨ sym $ lemma a b ⟩ (alternation (a + b))
Conclusion
In this post, we have briefly described basic concepts of dependently typed programming and theorem proving in Agda via examples. In the next post, we will introduce negation with classical postulates and play with non-constructive proofs in Agda.
Follow Serokell on Twitter and Facebook to keep in touch!
.jpg)
| https://serokell.io/blog/agda-in-nutshell | CC-MAIN-2021-43 | refinedweb | 3,017 | 52.33 |
Timeline
Jul 28, 2008:
- 3:25 PM Ticket #1635 (0 Z-Index for Map Div) created by
- FF2 and FF3 deal with zindexing differently. FF2: no specified …
- 2:16 PM Ticket #1607 (add methods for managing css class names) closed by
- fixed: (In [7579]) Adding functions to manage dom element class names. Use …
- 2:16 PM Changeset [7579] by
- Adding functions to manage dom element class names. Use …
- 2:10 PM Ticket #1390 (svg flicker at end of pan) closed by
- fixed: (In [7578]) Confirmed with Tim Coulter that forcing the reflow here …
- 2:10 PM Changeset [7578] by
- Confirmed with Tim Coulter that forcing the reflow here leads to a …
- 1:55 PM Ticket #1634 (draw feature control should pass temporary rendering intent to sketch ...) created by
- Currently, the sketch handlers check a style property that is expected …
- 1:47 PM Changeset [7577] by
- MultiMap's API seems to have all-but-disappeared from where we were …
- 1:40 PM Ticket #1116 (In IE7 Google layer doesn't work in parent <div> with right align) closed by
- fixed: (In [7576]) Fixes the issue where a container div around the map is …
- 1:40 PM Changeset [7576] by
- Fixes the issue where a container div around the map is setting the …
- 12:25 PM sprint0708 edited by
- (diff)
- 12:09 PM Changeset [7575] by
- Added drag / resize support
- 11:54 AM Ticket #1329 (service as customizable property in Format.WFS) closed by
- invalid
- 11:28 AM Ticket #688 (Mouse cursor = "wait" on WFS loading) closed by
- wontfix: once #1607 is in, then the correct way to do this will be to listen to …
- 10:00 AM Ticket #1104 (explicitly support versions for various formats) closed by
- duplicate
- 9:59 AM Ticket #1102 (margin on html element messes with mouse position) closed by
- duplicate: #1179
- 9:52 AM Ticket #1633 (remove dependency on popup from vector feature) created by
- I'll take this on.
- 9:49 AM Ticket #1505 (Strange popup autosizing behavior with floated content?) closed by
- duplicate: Dupe of #1469.
- 9:45 AM Ticket #1448 (zoomToScale does not exactly zoom to the given scale) closed by
- duplicate: Dupe of #1250
- 9:40 AM Ticket #1113 (wfs filter: generated URL should not have a bbox if a filter is enabled) closed by
- duplicate: This will be fixed in vector behavior (#1606) but not fixed in the …
- 9:38 AM Ticket #493 (Text Layer not shown in IE if meta description tag is present) closed by
- invalid
- 9:06 AM Ticket #897 (color correction on navtoolbar) closed by
- wontfix: You can override these in CSS. We won't change the default.
- 9:01 AM Ticket #1016 (Layerselector has incorrect style for IE6.) closed by
- duplicate: We currently are not interested in doing this directly this way: it …
- 9:00 AM Ticket #1374 (Customizing LayerSwitcher font color) closed by
- duplicate: We currently are not interested in doing this directly this way: it …
- 8:59 AM Ticket #1632 (Theme LayerSwitcher with CSS) created by
- The LayerSwitcher currently uses a lot of hardcoded styles in the …
- 8:24 AM sprint0708 created by
-
- 8:09 AM Ticket #1594 (FireBug detection) closed by
- invalid: I can't reproduce this at all. I don't understand what this problem …
- 7:50 AM Changeset [7574] by
- Parsing multilinestring correctly.
- 7:46 AM Changeset [7573] by
- Updated wfs example.
- 7:31 AM Changeset [7572] by
- Making wfs protocol work with featureType (unprefixed) and featureNS.
- 7:27 AM Changeset [7571] by
- Only trigger refresh if in range and visible. Trigger featuresremoved …
- 6:27 AM Ticket #1631 (SVG viewbox problem with minScale) created by
- I use Firefox. Of what I understand, each time I zoom in or out a …
Jul 26, 2008:
- 5:47 AM Changeset [7570] by
- here is the new playground folder
- 5:47 AM Changeset [7569] by
- removing empty folder
- 5:46 AM Changeset [7568] by
- moved one level up; will replace the playground folder
- 5:44 AM Changeset [7567] by
- point track without Layer.PointTrack
- 5:14 AM Changeset [7566] by
- Removing no longer needed styleMap sandbox
- 5:11 AM Changeset [7565] by
- Filling playground with current trunk
- 5:10 AM Changeset [7564] by
- Creating playground
Jul 25, 2008:
- 2:57 PM Changeset [7563] by
- fixes and renaming for MIS
- 1:21 PM Changeset [7562] by
- Started working on drag/drop
- 1:21 PM Changeset [7561] by
- Updated map config
- 10:19 AM Ticket #1630 (test) closed by
- invalid: this was just a test
- 10:18 AM Ticket #1630 (test) created by
-
- 9:51 AM Ticket #1629 (testing) closed by
- invalid
- 9:51 AM Ticket #1629 (testing) created by
- Test ticket as Openlayers:openlayers
- 9:17 AM Changeset [7560] by
- bug fix: not depending on global 'items' variable in MIS
- 12:52 AM Styles edited by
- changed Util.extend to Util.applyDefaults for style hash creation (diff)
Jul 24, 2008:
- 2:20 PM Changeset [7559] by
- control for elaborate widget
- 10:09 AM CLA edited by
- oops, guillaume's CCLA was for tilecache (diff)
- 10:07 AM CLA edited by
- adding guillaume lathoud of alpstein tourismus (diff)
- 2:20 AM UserRecipes edited by
- Gwennaël: sorting examples (diff)
- 1:50 AM Ticket #1628 (removeLayer may break feature selection) created by
- Removing a layer may prevent feature selection from working. Example …
Jul 23, 2008:
- 4:47 PM Ticket #1627 (OpenLayers.Layer.Vector.destroyFeatures() is not destroying features) created by
- Following the discussion from the list at …
- 10:15 AM Changeset [7558] by
- AfricaMap OpenLayers build.
- 7:23 AM Changeset [7557] by
- Pull in fix from #830. svn merge -r 7299:7300 trunk/openlayers/ .
- 7:20 AM Changeset [7556] by
- Copy 2.6 in order to create am-specific OL with Google fix
- 2:05 AM Ticket #1626 (Format.GML: parse srsName) created by
- This ticket is to track parsing srsName on the geometries of a GML …
Jul 22, 2008:
- 1:39 PM Ticket #1625 (Gazetteer service) created by
- Please create a gazetteer service client. OGC has specs for it as a …
Jul 21, 2008:
- 7:43 AM Changeset [7555] by
- added a moveend event at the layer level to handle visibility ranges …
- 7:37 AM Ticket #1624 (cursor "inherit" on a vector feature causes IE to load cursor file ...) closed by
- fixed: (In [7554]) don't set the cursor to "inherit" in the VML renderer. …
- 7:37 AM Changeset [7554] by
- don't set the cursor to "inherit" in the VML renderer. r=pgiraud …
- 7:00 AM Ticket #1624 (cursor "inherit" on a vector feature causes IE to load cursor file ...) created by
- Obviously VML does not recognize the "inherit" keyword from css. In …
- 6:59 AM Changeset [7553] by
- added requirements
- 6:57 AM Ticket #1623 (geometry bounds should be cleared while using path handler) closed by
- fixed: (In [7552]) handlers test are not reflecting the reality, we now …
- 6:57 AM Changeset [7552] by
- handlers test are not reflecting the reality, we now simulate a click, …
- 5:38 AM Ticket #1623 (geometry bounds should be cleared while using path handler) created by
- Since r7546, the tests are failing in IE6. In this revision, we …
- 3:03 AM Ticket #1602 (Vector features won't draw in IE if features are very far outside the ...) closed by
- invalid: The failing of the tests for Handler.Path and Handler.Polygon is not …
- 2:38 AM Changeset [7551] by
- the Composer strategy no longer exists
- 2:06 AM Ticket #1602 (Vector features won't draw in IE if features are very far outside the ...) reopened by
- I may be wrong but it seems like tests are breaking with this patch on IE6.
- 1:24 AM Ticket #1622 (Mapguide Layer http served tile support) created by
- It is possible to bypass the mapguide server mapagent and expose the …
Jul 18, 2008:
- 1:40 PM Changeset [7550] by
-
- 12:08 PM Changeset [7549] by
- yahoo geocoder takes appid *optionally*
- 11:45 AM Changeset [7548] by
-
- 9:17 AM Changeset [7547] by
-
- 5:24 AM Ticket #1602 (Vector features won't draw in IE if features are very far outside the ...) closed by
- fixed: (In [7546]) "Vector features won't draw in IE if features are very far …
- 5:24 AM Changeset [7546] by
- "Vector features won't draw in IE if features are very far outside the …
- 2:53 AM Changeset [7545] by
- callback for event to unregister doesn't correspond to the registered one
- 2:13 AM Changeset [7544] by
- zooming out or in the map called the moveTo method with incorrect …
- 2:09 AM Changeset [7543] by
- as proposed in a recent message in the dev list, we want to know when …
- 12:18 AM Ticket #1621 (Geometries of type "Collection" are not erased by renderer) closed by
- fixed: (In [7542]) we forgot to take Geometry.Collection into account when …
- 12:18 AM Changeset [7542] by
- we forgot to take Geometry.Collection into account when erasing …
Jul 17, 2008:
- 10:28 PM Changeset [7541] by
- Adding basic measure control.
- 12:23 PM Changeset [7540] by
- ND comment fix, no functional change
- 9:10 AM Changeset [7539] by
- Updated control / panel integration
- 8:23 AM Ticket #1520 (Util.modifyAlphaImageDiv makes hidden elements reappear in IE6.) closed by
- fixed: (In [7538]) the number of tests were wrong while launched in IE6, …
- 8:23 AM Changeset [7538] by
- the number of tests were wrong while launched in IE6, r=tschaub …
- 8:07 AM Changeset [7537] by
- sync with vector-behavior
- 7:59 AM Ticket #1520 (Util.modifyAlphaImageDiv makes hidden elements reappear in IE6.) reopened by
- I still don't think that the number of tests is correct. In the …
- 7:35 AM Changeset [7536] by
- removed extra comma (IE complains), no functional change
- 7:17 AM Ticket #1621 (Geometries of type "Collection" are not erased by renderer) created by
- In the renderer eraseGeometry method, Collection geometries are not …
- 6:58 AM Changeset [7535] by
- improve HTTP protocol test coverage
- 6:21 AM Ticket #1610 (add a text-align css rule) closed by
- fixed: (In [7534]) add a specific text-align css rule so that we don't have …
- 6:21 AM Changeset [7534] by
- add a specific text-align css rule so that we don't have weird …
- 5:51 AM Changeset [7533] by
- two fixes: destroy the appropriate features, make sure tiles reference …
Jul 16, 2008:
- 6:04 PM Changeset [7532] by
- copying trunk to sandbox
- 6:03 PM Changeset [7531] by
- Creating sandbox
- 2:02 PM Changeset [7530] by
- Controls and panels are working more in harmony
- 1:14 PM Changeset [7529] by
- requires; shorter property name
- 11:11 AM Changeset [7528] by
- Removing dependency on ajax.
- 11:01 AM Changeset [7527] by
- Adding console and select feature control to build.
- 9:41 AM Changeset [7526] by
- Replacing featuresdestroyed with the already available featuresremoved …
- 8:35 AM Changeset [7525] by
- shorter property names are nicer
- 7:23 AM Changeset [7524] by
- YahooGeocoder now parses response, transforms projection, and returns …
- 6:30 AM Changeset [7523] by
- Only trigger refresh on layer if in range and visible.
- 6:26 AM Changeset [7522] by
- Only trigger protocol read when layer is in range and visible.
- 6:15 AM Changeset [7521] by
- oh, so the new OL.Request stuff does proxying automagically. Sweet.
Jul 15, 2008:
- 4:00 PM Changeset [7520] by
- Updating profile and build.
- 3:06 PM Changeset [7519] by
- Updated build profile and single file build.
- 3:05 PM Changeset [7518] by
- This will soon need reworking, but for now the bbox strategy passes …
- 3:03 PM Changeset [7517] by
- Docs and requirements for WFS protocol.
- 3:01 PM Changeset [7516] by
- This will eventually be broken into versions.
- 1:33 PM Changeset [7515] by
- updated example
- 1:19 PM Changeset [7514] by
- Separating featureType (local), featureNS (namespace uri), and …
- 1:17 PM Changeset [7513] by
- and pointMember for multipoint
- 1:15 PM Changeset [7512] by
- Parsing polygonMember elements in multipolygon.
- 1:13 PM Changeset [7511] by
- correctly parsing multilinestring
- 1:04 PM Changeset [7510] by
- work towards a Yahoo geocoding control (with example)
- 2:43 AM Ticket #1620 (overviewmap does not support "reprojection") created by
- The overview map control currently can't deal with the situation where …
- 1:07 AM Changeset [7509] by
- remove the Composer strategy, it's no longer relevant
- 12:45 AM Changeset [7508] by
- OpenLayers.Class is a regular function, not a constructor
Jul 14, 2008:
- 8:34 PM Ticket #1619 (Unable to delete feature) created by
- Dear OpenLayers team, I tested the example : modify-feature.html to …
- 1:25 PM Changeset [7507] by
-
- 12:13 PM Changeset [7506] by
- Breaking wfs protocol to make it work like I want - based on the …
- 10:46 AM Changeset [7505] by
-
- 7:59 AM Changeset [7504] by
-
- 7:44 AM Changeset [7503] by
-
- 7:09 AM Changeset [7502] by
-
- 7:06 AM Changeset [7501] by
-
- 7:05 AM Changeset [7500] by
-
Jul 13, 2008:
- 2:00 PM Changeset [7499] by
-
- 4:55 AM Ticket #1617 (Incorrect documentation) closed by
- fixed
- 4:54 AM Changeset [7498] by
- Closes #1617. Update docs to reflect correct property name for marker …
- 1:16 AM Ticket #1618 (readme.txt mention an inexisting docs.sh script) created by
- The readme.txt at the root of openlayers says: « Dcumentation is …
- 1:13 AM Ticket #1617 (Incorrect documentation) created by
- The documentation about Layers.Text is incorrect. It says that the …
Jul 12, 2008:
- 2:36 PM Ticket #888 (Draw Polygon Features) closed by
- fixed
- 2:35 PM Ticket #1081 (OpenLayers.Handler.Path / Polygon 'point' property callback suggestion ...) closed by
- invalid: I don't get it. There's is the 'done' callback for exactly that, isn't …
Jul 11, 2008:
- 1:44 PM Changeset [7497] by
- Updating built script.
- 1:41 PM Changeset [7496] by
- merge changes from behavior branch
- 1:30 PM Changeset [7495] by
- And preferably the compressed version.
- 1:29 PM Changeset [7494] by
- Including XML format in build.
- 12:32 PM Ticket #1601 (French dictionary could use some more entries.) closed by
- fixed: (In [7493]) fixing tests/Lang.html, p=fvanderbiest, r=me (closes #1601)
- 12:32 PM Changeset [7493] by
- fixing tests/Lang.html, p=fvanderbiest, r=me (closes #1601)
- 12:08 PM Changeset [7492] by
- options passed to this.update() and this.delete() cannot be reused
- 11:57 AM Changeset [7491] by
- Add xhr and renderers to build.
- 10:38 AM Changeset [7490] by
- merge r7354:HEAD from trunk
- 7:54 AM Changeset [7489] by
- merge -r7352:HEAD from trunk/openlayers
- 7:47 AM Changeset [7488] by
- tiles must remove their reference to feature being removed
- 4:44 AM Changeset [7487] by
- typo, strokeRadius doesn't exist, it's meant to be strokeWidth no …
- 12:12 AM Ticket #1616 ([REGRESSION] extra '?' is added to the URL by the LoadURL method.) created by
- some URL like this : …
Jul 10, 2008:
- 9:38 AM Ticket #1615 (GeoRSS feature doesn't work with content:encoded tags) created by
- Using the GeoRSS feature to display points on a map rendered by …
Jul 9, 2008:
- 11:56 AM History edited by
- (diff)
- 11:53 AM History edited by
- (diff)
- 11:30 AM History edited by
- (diff)
- 11:27 AM History edited by
- (diff)
- 10:54 AM History edited by
- (diff)
- 10:51 AM History edited by
- (diff)
- 9:36 AM History edited by
- Dates for and links to the past Where 2.0 conferences, from the … (diff)
- 8:56 AM Changeset [7486] by
- point features, therefore set the grid strategy safe option to false …
- 8:44 AM Changeset [7485] by
- destroy things in correct order; in particular destroy strategies …
- 8:29 AM Changeset [7484] by
- deal with features spanning multiple tiles
- 7:51 AM Ticket #1614 (GeoRSS, States Misplaced) created by
- David Winslow at TOPP stumbled across this one while doing some GeoRSS …
- 7:50 AM Changeset [7483] by
- OpenLayers.Grid calls tile.moveTo with 3 arguments, the third …
- 7:07 AM Changeset [7482] by
- do not add features to the layers if there are not
- 6:07 AM Changeset [7481] by
- in destroy() deactivate the strategy before setting this.layer to …
- 1:29 AM Changeset [7480] by
- add to proxy.cgi allowedHosts, and fix URL to proxy in …
Jul 8, 2008:
- 1:08 PM Changeset [7479] by
- Add Grid Strategy. With this strategy features are added and removed …
- 7:58 AM Changeset [7478] by
- Correcting doc bug for elements renderer. Thanks zarn.
- 5:47 AM Changeset [7477] by
- not sure if this is right, but adding in a link to the metadata about …
- 12:36 AM Ticket #1601 (French dictionary could use some more entries.) reopened by
- Eric told me tests went wrong due to this patch. I'm terribly sorry. A …
- 12:24 AM Ticket #1613 (enhance Format.GML to parse gml:boundedBy) created by
- This is e.g. handy when you want to zoom to the full featureCollection.
Jul 7, 2008:
- 5:35 PM Changeset [7476] by
- change link to new gallery.
- 3:29 PM Ticket #1609 (Traditional Chinese Translation) closed by
- fixed: (In [7475]) Adding Traditional Chinese dictionary from Jian Ding Chen …
- 3:29 PM Changeset [7475] by
- Adding Traditional Chinese dictionary from Jian Ding Chen …
- 3:23 PM Changeset [7474] by
- Build configurations with include sections don't need exclude sections.
- 3:04 PM CreatingPatches edited by
- adding link to coding standards (diff)
- 2:56 PM CodingStandards edited by
- adding a page outline (diff)
- 2:54 PM CodingStandards edited by
- adding instructions for creating new examples (diff)
- 2:34 PM Ticket #1612 (Layer.Yahoo and Layer.WFS don't play well together) created by
- Carole Zieler reported an error with a map using a Yahoo layer and a …
- 1:39 PM Changeset [7473] by
- Looking a little harder for ElementTree.
- 9:49 AM Changeset [7472] by
- Adding a few example descriptions, removing a redundant example.
- 7:34 AM Changeset [7471] by
- Unused function.
- 7:32 AM Changeset [7470] by
- Adding title, id, updated, and author elements for valid atom.
- 6:44 AM Changeset [7469] by
- No additional markup in title or shortdesc please.
- 3:57 AM Ticket #1611 (DeleteVertex does not work in non-Mozilla browsers) created by
- tested with "Delete" and "d" keys on the OpenLayers ModifyFeature …
- 12:02 AM Ticket #1600 (getChildValue() on GeoRSS format is slow) closed by
- fixed: (In [7468]) getChildValue() on GeoRSS format is slow, p=edgemaster, …
- 12:02 AM Changeset [7468] by
- getChildValue() on GeoRSS format is slow, p=edgemaster, r=me,crschmidt …
Jul 6, 2008:
- 8:28 PM Ticket #1506 (Change cursor in subclass of OpenLayers.Handler.Drag) closed by
- duplicate
- 1:44 PM Changeset [7467] by
- v2-bbox-wfs-gml.html is broken. In an attempt to fix it I discovered a …
- 1:37 PM Changeset [7466] by
- applyDefaults requires a non-null from argument
- 1:16 PM Changeset [7465] by
- vector layer must activate the strategy
- 1:07 PM Changeset [7464] by
- remove unused "parser" property
Jul 4, 2008:
- 12:26 PM Ticket #1399 (Improve License Accessibility) closed by
- fixed: link to the ClearBSD license is on the homepage now
- 5:00 AM Ticket #1610 (add a text-align css rule) created by
- Some users pulled their hair by trying to find out why they had weird …
Jul 3, 2008:
- 11:57 PM Ticket #1087 (null exceptions in vector layer when reloading in IE6) closed by
- worksforme: i can confirm that this is no longer happenning in trunk at r7463. …
- 11:52 PM Ticket #1075 (BaseTypes/Element causing IE to die) closed by
- invalid: this doesn't seem to be a problem for anyone anymore. maybe we fixed …
- 11:47 PM Ticket #956 (Create Larger Navigation Control for use in non-draggable maps) closed by
- fixed: I think tim's example here is good enough to call this ticket fixed. …
- 11:24 PM Ticket #1423 (restrictedExtent allows to zoomout even if bounds constraints are not ...) closed by
- wontfix: sounds like (from tim's explanation) this is an issue that has been …
- 11:19 PM Ticket #1315 (Polygon moving when drawing a new one in IE) closed by
- invalid: this ticket has sat here unattended for 5 months. Given fredj's …
- 9:25 PM Ticket #1277 (Give OpenLayers.Ajax classes proper destroy() methods) closed by
- wontfix: I'm going to close this ticket since, AFAICT, the Ajax.js code is now …
- 8:16 PM Ticket #1609 (Traditional Chinese Translation) created by
- I've translated the localization strings to Traditional Chinese (the …
- 1:48 PM Changeset [7463] by
- Googlebot doesn't seem to like these relative urls.
- 1:09 PM Release/2.6/Announce/RC1 created by
-
- 11:02 AM Ticket #1601 (French dictionary could use some more entries.) closed by
- fixed: ok. CLA procured and on file. carry on, carry on
- 11:00 AM CLA edited by
- adding francois van der biest (diff)
- 10:21 AM Ticket #1608 (handler box doesn't remove box if user right clicks) created by
- When zooming in with shift key down, you can draw a box. If you press …
- 9:42 AM CLA edited by
- adding Chen, Jian Ding -- if it should be Jian Ding, Chen, some let me know (diff)
Jul 2, 2008:
- 11:19 PM Ticket #1569 (provide a working alternative to the wfs layer feature tile format) closed by
- duplicate: seems to me this is a duplicate of #1606 reopen if this is not the case
- 6:45 PM Ticket #1519 (Patch for the Brazilian Portuguese dictionary) closed by
- fixed: ICLA for pedro simonetti now on file. Thanks for the quick turnaround …
- 6:40 PM CLA edited by
- adding pedro simonetti (diff)
- 5:36 AM Ticket #1199 (if scales is set on the map, you cannot use minScale and maxScale on ...) reopened by
- This patch doesn't look entirely good to me. What if we don't want to …
- 1:33 AM Ticket #1607 (add methods for managing css class names) created by
- These can go in OpenLayers.Element and be named things like …
- 12:00 AM Ticket #864 (KeyboardDefaults broken in IE) closed by
- duplicate: looks like pedro's #1108 is more thorough, let's go with it.
Jul 1, 2008:
- 12:51 PM Changeset [7462] by
- SLD format now requires Filter format.
- 12:45 PM Changeset [7461] by
- merge r7368:HEAD from behavior sandbox
- 12:26 PM Ticket #1606 (Add cluster and paging strategy) created by
- Add a cluster strategy to group nearby features into clusters and a …
- 12:16 PM Ticket #1605 (Create a filter format and extend the SLD format to use it) created by
- Create versioned filter formats. Use the readers/writers from the SLD …
- 10:42 AM Ticket #1598 (Translation for norwegian bokmål) closed by
- fixed: it's true! sorry about that. oversight on my part. this ticket is …
Jun 30, 2008:
- 6:30 PM Ticket #1601 (French dictionary could use some more entries.) reopened by
- can we be sure to get a CLA from francois?
- 5:36 PM Ticket #1598 (Translation for norwegian bokmål) reopened by
- let's get a CLA from bobkare?
- 2:46 PM Ticket #1519 (Patch for the Brazilian Portuguese dictionary) reopened by
- as far as i can see, we still don't have a CLA for pedro, and he …
- 7:58 AM Ticket #1604 (alphahack image src may be wrong) created by
- If the image src contains "'" (quotes) the alphahack breaks. The …
- 7:09 AM Ticket #1603 (Controls location problems in Internet Explorer) created by
- Hi, The position of some of my controls (drawing features, loading …
Jun 28, 2008:
- 5:35 AM Ticket #1602 (Vector features won't draw in IE if features are very far outside the ...) created by
- According to …
Note: See TracTimeline for information about the timeline view. | http://trac.osgeo.org/openlayers/timeline?from=2008-07-28T09%3A52%3A55-0700&precision=second | CC-MAIN-2016-36 | refinedweb | 3,947 | 52.94 |
Hello!
I have collected my own dataset and trying to run random forrest on it but fastai complains that there are labels in my validation set that do not appear in the training set. How do I prepare and split my data?
The data is collected from a web site selling used cars. My columns is brand, model, type (sedan…), gear, fuel, model_year and milage. I have some 150k rows. I have left out the brand feature because I think I need to make it less diverse in the future. I have also tried leaving out all brands not being one of the top 20.
The error message does not help me figure out which feature is containing the missing category. It just says:
Exception: Your validation data contains a label that isn't present in the training set, please fix your data.
Here is my code running fastai v1.0x
from pathlib import Path from fastai.tabular import * path = Path('/my_path') df = pd.read_csv(path/'data.csv') procs = [FillMissing, Categorify, Normalize] valid_idx = range(len(df)-2000, len(df)) dep_var = 'price' cat_names = ['brand','model_year','gear','fuel','type'] cont_names = ['milage'] data = TabularDataBunch.from_df(path, df, dep_var, valid_idx=valid_idx, procs=procs, cat_names=cat_names, cont_names=cont_names)
Is there any good tools to do this split? Is there any good guides on how to prepare data for training?
Thanks! | https://forums.fast.ai/t/split-my-dataset/33691 | CC-MAIN-2022-21 | refinedweb | 225 | 66.23 |
MELEZHIK/CPAN-Repo-v0.0.5 - 27 Dec 2011 08:08:34 GMT - 08 Aug 2014 22:52:57 GMT GMT
CPAN::Audit is a module and a database at the same time. It is used by cpan-audit command line application to query for vulnerabilities....VTI/CPAN-Audit-0.15 - 09 Mar 2019 09:48:06 GMT GMT
C63 - 03 Oct 2017 09:37:08 GMT GMT
SZABGAB/CPAN-Digger-0.08 - 14 Jan 2013 07:14:12 GMT
Following.217 - 30 Jan 2019 02:38:40 GMT g...ANDK/CPAN-2.27 - 03 Jul 2019 20:15:40 GMT
This module is a plugin loader for CPAN commands in the "CPAN::Commmand::*" namespace. # sudo perl -MCPAN::Command -e 'CPAN::shell()' will load all command plugins in that namespace, then run the CPAN shell as usual. The pluggable commands are now av...MARCEL/CPAN-Command-1.100840 - 25 Mar 2010 19:52:04 GMT
This module allows to apply custom patches to the CPAN distributions. See "patch" and "update_debian" for a detail description how. See <> for example generated Debian patches set folder....JKUTEJ/CPAN-Patches-0.05 - 05 Jun 2015 12:31:31 GMT
SZABGAB/CPAN-Porters-0.03 - 08 Mar 2008 22:53:51
GMT | https://metacpan.org/search?p=2&q=module%3ACPAN%3A%3AModule | CC-MAIN-2019-51 | refinedweb | 207 | 68.26 |
Let's imagine you are playing a game of Twenty Questions. Your opponent has secretly chosen a subject, and you must figure out what he/she chose. At each turn, you may ask a yes-or-no question, and your opponent must answer truthfully. How do you find out the secret in the fewest number of questions?
It should be obvious some questions are better than others. For example, asking "Can it fly?" as your first question is likely to be unfruitful, whereas asking "Is it alive?" is a bit more useful. Intuitively, you want each question to significantly narrow down the space of possibly secrets, eventually leading to your answer.
That is the basic idea behind decision trees. At each point, you consider a set of questions that can partition your data set. You choose the question that provides the best split and again find the best questions for the partitions. You stop once all the points you are considering are of the same class. Then the task of classification is easy. You can simply grab a point, and chuck it down the tree. The questions will guide it to its appropriate class.
IMPORTANT TERMS
Decision tree is a type of supervised learning algorithm that can be used in both regression and classification problems. It works for both categorical and continuous input and output variables.
Let’s identify important terminologies on Decision Tree, looking at the image above:
Root Node represents the entire population or sample. It further gets divided into 2 or more homogeneous sets.
Splitting is a process of dividing a node into 2 or more sub-nodes.
When a sub-node splits into further sub-nodes, it is called a Decision Node.
Nodes that do not split is called a Terminal Node or a Leaf.
When you remove sub-nodes of a decision node, this process is called pruning. The opposite of pruning is splitting.
A sub-section of an entire tree is called a branch.
A node, which is divided into sub-nodes is called a Parent Node of the sub-nodes; whereas the sub-nodes are called the Child of the parent node.
HOW IT WORKS
Here I only talk about classification tree, which is used to predict a qualitative response. Regression tree is the one used to predict quantitative values.
In a classification tree, we predict that each observation belongs to the most commonly occurring class of training observations in the region to which it belongs. In interpreting the results of a classification tree, we are often interested not only in the class prediction corresponding to a particular terminal node region, but also in the class proportions among the training observations that fall into that region. The task of growing a classification tree relies on using one of these 3 methods as a criterion for making the binary splits:
1 - Classification Error Rate: We can define the “hit rate” as the fraction of training observations in a particular region that don't belong to the most widely occurring class. The error is given by this equation:
E = 1 - argmax_{c}(π̂ mc)
in which π̂ mc represents the fraction of training data in region R_m that belong to class c.
2 - Gini Index: The Gini Index is an alternative error metric that is designed to show how “pure” a region is. "Purity" in this case means how much of the training data in a particular region belongs to a single class. If a region R_m contains data that is mostly from a single class c then the Gini Index value will be small:
3 - Cross-Entropy: A third alternative, which is similar to the Gini Index, is known as the Cross-Entropy or Deviance:
The cross-entropy will take on a value near zero if the π̂ mc’s are all near 0 or near 1. Therefore, like the Gini index, the cross-entropy will take on a small value if the m-th node is pure. In fact, it turns out that the Gini index and the cross-entropy are quite similar numerically.
When building a classification tree, either the Gini index or the cross-entropy are typically used to evaluate the quality of a particular split, since they are more sensitive to node purity than is the classification error rate. Any of these 3 approaches might be used when pruning the tree, but the classification error rate is preferable if prediction accuracy of the final pruned tree is the goal.
IMPLEMENTATION FROM SCRATCH
Let’s walk through the decision tree–building algorithm, with all its fine details. To build a decision tree, we need to make an initial decision on the dataset to dictate which feature is used to split the data. To determine this, we must try every feature and measure which split will give us the best results. After that, we’ll split the dataset into subsets. The subsets will then traverse down the branches of the first decision node. If the data on the branches is the same class, then we’ve properly classified it and don’t need to continue splitting it. If the data isn’t the same, then we need to repeat the splitting process on this subset. The decision on how to split this subset is done the same way as the original dataset, and we repeat this process until we’ve classified all the data.
How do we split our dataset? One way to organize this messiness is to measure the information. Using information theory, we can measure the information before and after the split. The change in information before and after the split is known as the information gain. When we know how to calculate the information gain, we can split our data across every feature to see which split gives us the highest information gain. The split with the highest information gain is our best option.
In order to calculate the information gain, we can use the Shannon Entropy, which is the expected value of all the information of all possible values of our class. Let’s see the Python code for it:
from math import log
def ShannonEntropy(data):
# Number of instances in the dataset
labelCounts = {}
# Create a dictionary of all possible classes
for featVec in data:
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEntropy = 0.0
for key in labelCounts:
# Probability of a label in our dataset
prob = float(labelCounts[key]) / len(data)
# Calculate the Shannon Entropy
shannonEntropy -= prob * log(prob, 2) # logarithm base 2
return shannonEntropy
As you can see, we first calculate a count of the number of instances in the dataset. Then we create a dictionary whose keys are the values in the final column. If a key was not encountered previously, one is created. For each key, we keep track of how many times this label occurs. Finally, we use the frequency of all the different labels to calculate the probability of that label. This probability is used to calculate the Shannon entropy, and we sum this up for all the labels.
After figuring out a way to measure the entropy of the dataset, we need to split the dataset, measure the entropy on the split sets, and see if splitting it was the right thing to do. Here’s the code to do so:
def splitDataset(data, axis, value):
# Create a separate list
retData = []
for featVec in data:
if featVec[axis] == value:
# Cut out the feature to split on
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
retData.append(reducedFeatVec)
return retData
This code takes 3 input: the data to be split on, the feature to be split on, and the value of the feature to return. We create a new list at the beginning each time because we’ll be calling this function multiple times on the same dataset and we don’t want the original dataset modified. Our dataset is a list of lists; as we iterate over every item in the list and if it contains the value we’re looking for, we’ll add it to our newly created list. Inside the if statement, we cut out the feature that we split on.
Now, we’re going to combine 2 functions: ShannonEntropy and splitDataset to cycle through the dataset and decided which feature is the best to split on.
def chooseBestFeatureToSplit(data):
numFeatures = len(data[0]) - 1
baseEntropy = ShannonEntropy(data)
bestInfoGain = 0.0
bestFeature = -1
for i in range(numFeatures):
# Create unique list of class labels
featList = [example[i] for example in data]
uniqueVals = set(featList)
newEntropy = 0.0
# Calculate entropy for each split
for value in uniqueVals:
subData = splitDataset(data, i, value)
prob = len(subData) / float(len(data))
newEntropy += prob * ShannonEntropy(subData)
infoGain = baseEntropy - newEntropy
if (infoGain > bestInfoGain):
# Find the best information gain
bestInfoGain = infoGain
bestFeature = 1
return bestFeature
Let’s quickly examine the code:
We calculate the Shannon entropy of the whole dataset before any splitting has occurred and assign the value to variable baseEntropy.
The 1st for loop loops over all the features in our data. We use list comprehensions to create a list (featList) of all the i-th entries in the data or all the possible values present in the data.
Next, we create a new set from a list to get the unique values out (uniqueVals).
Then, we go through all the unique values of this feature and split the data for each feature (subData). The new entropy is calculated (newEntropy) and summed up for all the unique values of that feature. The information gain (infoGain) is the reduction in entropy (baseEntropy - newEntropy).
Finally, we compare the information gain among all the features and return the index of the best feature to split on (bestFeature).
Now that we can measure how organized a dataset is and we can split the data, it’s time to put all of this together and build the decision tree. From a dataset, we split it based on the best attribute to split. Once split, the data will traverse down the branches of the tree to another node. This node will then split the data again. We’re going to use recursion to handle this.
We’ll only stop under the following conditions: (1) Run out of attributes on which to split or (2) all the instances in a branch are the same class. If all instances have the same class, then we’ll create a leaf node. Any data that reaches this leaf node is deemed to belong to the class of that leaf node.
Here’s the code to build our decision trees:
def createTree(data, labels):
classList = [example[-1] for example in data]
# Stop when all classes are equal
if classList.count(classList[0]) == len(classList):
return classList[0]
# When no more features, return majority
if len(data[0]) == 1:
# A function that returns the class that occurs with the greatest frequency
# You can write your own
return majorityCount(classList)
bestFeat = chooseBestFeatureToSplit(data)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel:{}}
# Get list of unique values
del(labels[bestFeat])
featValues = [example[bestFeat] for example in data]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = createTree(splitDataset(data, bestFeat, value), subLabels)
return myTree
Our code takes 2 inputs: the data and a list of labels:
We first create a list of all the class labels in the dataset and call this classList. The first stopping condition is that if all the class labels are the same, then we return this label. The second stopping condition is the case when there are no more features to split. If we don’t meet the stopping conditions, then we use the function chooseBestFeatureToSplit to choose the best feature.
To create the tree, we’ll store it in a dictionary (myTree). Then we get get all the unique values from the dataset for our chosen feature (bestFeat). The unique value code uses sets (uniqueVals).
Finally, we iterate over all the unique values from our chosen feature and recursively call createTree() for each split of the dataset. This value is inserted into myTree dictionary, so we end up with a lot of nested dictionaries representing our tree.
IMPLEMENTATION VIA SCIKIT-LEARN
Now that we know how to implement the algorithm from scratch, let’s make use of scikit-learn. In particular, we’ll use the DecisionTreeClassifier class. Working with the iris dataset, we first import the data and split it into a training and a test part. Then we build a model using the default setting of fully developing the tree (growing the tree until all leaves are pure). We fix the random_state in the tree, which is used for tie-breaking internally:
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Generate the iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
# Build a model using the default setting of fully developing the tree
tree = DecisionTreeClassifier(random_state=0)
# Fit the classifier on training set
tree.fit(X_train, y_train)
# Make the predictions on test set
predictions = tree.predict(X_test)
print("Test set predictions: {}".format(predictions))
# Evaluate the model
accuracy = tree.score(X_test, y_test)
print("Test set accuracy: {:.2f}".format(accuracy))
Running the model should gives us a test set accuracy of 95%, meaning the model predicted the class correctly for 95% of the samples in the test dataset.
STRENGTHS AND WEAKNESSES.
Another huge advantage is such the algorithms are completely invariant to scaling of the data. As each feature is processed separately, and the possible splits of the data don’t depend on scaling, no pre-processing like normalization or standardization of features is needed for decision tree algorithms. In particular, decision trees work well when we have features that are on completely different scales, or a mix of binary and continuous features.
However, decision trees generally do not have the same level of predictive accuracy as other approaches, since they aren't quite robust. A small change in the data can cause a large change in the final estimated tree. Even with the use of pre-pruning, they tend to overfit and provide poor generalization performance. Therefore, in most applications, by aggregating many decision trees, using methods like bagging, random forests, and boosting, the predictive performance of decision trees can be substantially improved.
Reference Sources:
Introduction to Statistical Learning by Gareth James, Daniela Witten, Trevor Hastie, and Robert Tibshirani (2014)
Machine Learning In Action by Peter Harrington (2012)
Introduction to Machine Learning with Python by Sarah Guido and Andreas Muller (2016) | https://www.experfy.com/blog/decision-trees-how-to-optimize-my-decision-making-process | CC-MAIN-2019-35 | refinedweb | 2,444 | 60.65 |
Desire S: don't
If I had known a week ago about the lengths to which HTC are now going to prevent people from using their phones, I would have bought some other phone (like maybe the the LG Optimus 2X) instead – and if you are the kind of person who prefers to choose your own software than to let device manufacturers and mobile phone networks do it for you, I would recommend that you don’t buy it either.
That’s right, as far as I can determine it’s not (currently, at least) rootable. Finding this out is made harder than it needs to be because for any conceivable relevant search term, Google seems to prefer the xda-dev forum – by volume, 98% composed of script kiddies saying “OMG LOLZ” – over any results from people who know what they’re talking about. But here’s the summary:
- as delivered, there is no root access. Well, so far so perfectly standard
- there are a couple of promising-sounding exploits which work on other similar devices. The psneuter exploit – or at least the binary copy of psneuter of unknown provenance that I downlaoded from some ad-filled binaries site - doesn’t work, erroring out with
failed to set prot mask. GingerBreak, though, will get you a root shell. Or at least it will if you get the original version that runs from the command line and not the APK packaged version that a third party has created for the benefit of xda-dev forum users.
- the problem is that GingerBreak works by exploiting bugs in
voldand as the side-effect is to render vold unusable, you can’t get access to your sd card after running it. So, you think, “no problem, I’ll remount
/systemas writable and install
suor some setuid backdoor program that will let me back in”. This doesn’t work although it looks like it did right up until you reboot and notice your new binary has disappeared.
- (incidentally, if you run GingerBreak again after rebooting the phone and it fails, it’s because you need to remove
/data/local/tmp/{sh,boomsh}by hand.)
- The explanation for this freakiness is that
/systemis mounted from an eMMC filesystem which is hardware write-protected in early boot (before the Linux kernel starts up) but Linux doesn’t know this, so the changes you make to it are cached by the kernel but don’t get flushed. There is a kernel module called wpthis designed for the G2/Desire Z whih attempts to remove the write-protect flag by power-cycling the eMMC controller, but it appears that HTC have somehow plugged this bug on the Desire S. For completeness sake, I should add that every other mounted partition has
noexecand/or
nosuidsettings, so
/systemis the only possible place to put the backdoor command.
- Um.
Avenues to explore right now: (1) the write-protect-at-boot behaviour
is apparently governed by a “secu flag” which defaults to S-ON on
retail devices but can be toggled to S-OFF using a hardware device
called the “XTC Clip”, available in some phone unlocking shops. (2)
Perhaps it is possible to become root without calling
setuid by
installing an APK containing a started-on-boot service and hacking
/data/system/packages.xml so that the service launches with uid
0. (3) wait and see if anyone else has any good ideas. (4)
study the Carphone Warehouse web site carefully and see if they have
an option to return the phone for exchange, bearing in mind that I’ve
been using it for seven days. Obviously those last two options are
mutually incompatible.
Summary of the summary: HTC, you suck.
Incidentally, if you want to build the wpthis module for yourself
there’s not a lot of useful documentation on building Android kernels
(or modules for them) for devices: everything refers to a page on
sources.google.com which appears to be 404. The short answers: first,
the gcc 4.4.0 cross-compiler toolchain is in the NDK; second, the kernel
source that corresponds to the on-device binary, at the time I write
this, can be had from
<>
(linked from <>); third,
<> doesn’t compile cleanly anyway:
you’ll need to scatter
#include <linux/slab.h> around a bit and to
copy/paste the definition of
mmc_delay from
linux/drivers/mmc/core/core.h
Incidentally (2): <> has lots of interesting stuff.
At this point, though, my advice remains that you should buy a different phone. Even if this one is rooted eventually (and I certainly hope it will be), HTC have deliberately made it more difficult than it needs to and why reward that kind of anti-social behaviour?
Syndicated 2011-05-15 13:10:27 from diary at Telent Netowrks | http://www.advogato.org/person/dan/diary.html?start=146 | CC-MAIN-2015-06 | refinedweb | 801 | 55.68 |
/************************************************ FINANCIAL SIMULATION You have a bank account whose annual interest rate depends on the amount of money you have in your account at the beginning of each year. Your annual rate starts at 3%, and grows by an additional half a percent for each thousand dollars in your account up to, but not exceeding 8%. Interest in this account is compounded monthly at the annual rate. Each year you also make a deposit (before the bank figures out what your rate is, fortunately). Write a program that simulates these financial interactions. It should first ask the user how many years he wants to simulate, and at the beginning of each year it should ask the user how much he wants to deposit. ***************************************************/ #include <iostream> using namespace std; int main() { //Get number of years int Y; cout << "How many years would you like to simulate: "; cin >> Y; /*************************************************/ /******** S I M U L A T E Y Y E A R S ********/ /*************************************************/ double B = 0; for(int k = 0; k < Y; k++) { //Get payment amount & adjust balance double P; cout << "Payment for year " << k+1 << " : "; cin >> P; B = B + P; //Compute annual rate R int T = B / 1000; //Get number of 1000's double R = 3 + 0.5*T;//Compute rate if (R > 8.0) //Correct for 8% cap R = 8.0; //Compute new balance with interest for the year double r = R/100; for(int i = 0; i < 12; i++) B = B*(1 + r/12); } //Print final balance cout << "Final balance is " << B << " dollars" << endl; return 0; } | https://www.usna.edu/Users/cs/wcbrown/courses/F15IC210/lec/l13/TE2.html | CC-MAIN-2018-09 | refinedweb | 256 | 63.63 |
1 /*2 * @(#)RuntimeException.java 1.13 03/12/193 *4 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.6 */7 8 package java.lang;9 10 /**11 * <code>RuntimeException</code> is the superclass of those 12 * exceptions that can be thrown during the normal operation of the 13 * Java Virtual Machine. 14 * <p>15 * A method is not required to declare in its <code>throws</code> 16 * clause any subclasses of <code>RuntimeException</code> that might 17 * be thrown during the execution of the method but not caught. 18 *19 *20 * @author Frank Yellin21 * @version 1.13, 12/19/0322 * @since JDK1.023 */24 public class RuntimeException extends Exception {25 static final long serialVersionUID = -7034897190745766939L;26 27 /** Constructs a new runtime exception with <code>null</code> as its28 * detail message. The cause is not initialized, and may subsequently be29 * initialized by a call to {@link #initCause}.30 */31 public RuntimeException() {32 super();33 }34 35 /** Constructs a new runtime exception with the specified detail message.36 * The cause is not initialized, and may subsequently be initialized by a37 * call to {@link #initCause}.38 *39 * @param message the detail message. The detail message is saved for 40 * later retrieval by the {@link #getMessage()} method.41 */42 public RuntimeException(String message) {43 super(message);44 }45 46 /**47 * Constructs a new runtime exception with the specified detail message and48 * cause. <p>Note that the detail message associated with49 * <code>cause</code> is <i>not</i> automatically incorporated in50 * this runtime exception's detail message.51 *52 * @param message the detail message (which is saved for later retrieval53 * by the {@link #getMessage()} method).54 * @param cause the cause (which is saved for later retrieval by the55 * {@link #getCause()} method). (A <tt>null</tt> value is56 * permitted, and indicates that the cause is nonexistent or57 * unknown.)58 * @since 1.459 */60 public RuntimeException(String message, Throwable cause) {61 super(message, cause);62 }63 64 /** Constructs a new runtime exception with the specified cause and a65 * detail message of <tt>(cause==null ? null : cause.toString())</tt>66 * (which typically contains the class and detail message of67 * <tt>cause</tt>). This constructor is useful for runtime exceptions68 * that are little more than wrappers for other throwables.69 *70 * @param cause the cause (which is saved for later retrieval by the71 * {@link #getCause()} method). (A <tt>null</tt> value is72 * permitted, and indicates that the cause is nonexistent or73 * unknown.)74 * @since 1.475 */76 public RuntimeException(Throwable cause) {77 super(cause);78 }79 }80
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | https://kickjava.com/src/java/lang/RuntimeException.java.htm | CC-MAIN-2021-21 | refinedweb | 443 | 58.58 |
Introduction
Declaring namespaces at the top of your COBOL.NET code can greatly simplify coding and streamline your syntax by eliminating unnecessary namespaces in your code and the Class Repository. This is identical in concept to the using directive in C#. The using directive in C# permits the use of types in a namespace so you do not have to qualify the use of a type or class in that namespace.
In this article I will show the use of
the ILUSING compiler directive in
Micro Focus COBOL.NET. To do this, I will also provide two additional examples
of what the code would look like when not declaring a namespace so you can have
a better idea of the advantages of this feature. This very basic sample program
gets the current time, waits 5000 milliseconds, gets the current time again,
and then calculates the elapsed time. In all examples elapsedStr is defined as
a String which is a pre-defined type in COBOL.NET that equates to a .NET System.String. i.e. there is no need to
declare a namespace for it or use the Type keyword.
Example 1:
Using a Class by declaring it in the Class RepositoryUsing a Class by declaring it in the Class Repository
The code below uses the Class Repository to declare each class that will be used in the program. Each Class in the repository associates a name (think of it as an alias) to an actual Class.
In this example the Thread class, which is in the .NET Framework System.Threading namespace, is associated with the name ThreadClass.
Likewise, DateTime and TimeSpan, which are both in the .NET Framework System namespace, are associated with "DateTimeClass" and "TimeSpanClass" respectively. In the COBOL application code, it is the alias names that are actually used, not the true .NET type or class names.
repository.
class ThreadClass as "System.Threading.Thread"
class DateTimeClass as "System.DateTime"
class TimeSpanClass as "System.TimeSpan"
.
working-storage section.
01 begTime DateTimeClass.
01 endTime DateTimeClass.
01 elapsedTime TimeSpanClass.
01 elapsedStr String.
procedure division.
set begTime to DateTimeClass::"Now"
invoke ThreadClass::"Sleep"(5000)
set endTime to DateTimeClass::"Now"
set elapsedTime to endTime::"Subtract"(begTime)
set elapsedStr to elapsedTime::"ToString"()
While the Class respository makes it convenient to declare individually each Class or type that will be used in your program. It is a convention that .NET programmers in general would not be familiar with. Furthermore, if a COBOL programmer were to look at a C# or VB.NET program as an example of how to do something they would also see that this convention is not is not used and is not necessary in other .NET languages. It could also lead to using non-standard or inconsistent class and type names throughout your application code. This could make it a little more difficult for a .NET programmer to maintain the code later...i.e. always having to look in the Class Repository to see which class is actually being used.(Classes and Enumerators) to be consistent, but this is also somewhat redundant b. The actual program code would then also be using Class names or aliases that are not standard. If another person later had to maintain this code, they would always have to look in the Class Repository sections to confirm which actual type is being used.
Example 2:
Using a Class without declaring it in the Class Repository or declaring a Namespace
The code below uses Classes or Types without having to declare them in the Class Repository. However, because no namespace was declared, the fully qualified type including the namespace is required. Notice the use of the type keyword followed by the fully qualified type (including the namespace) to specify a type in the working-storage section or in the code.
In this example the Thread class or type, which is in the .NET Framework System.Threading namespace, is fully qualified everywhere it used by specifying System.Threading.Thread.
Likewise, DateTime and TimeSpan, which are in the .NET Framework System namespace, are also fully qualified as System.DateTime and System.TimeSpan respectively. In the COBOL application, the actual fully qualified class or type names are used including the namespace that contains the type...NOT names declared in the Class Repository.
working-storage section.
01 begTime2 type "System.DateTime".
01 endTime2 type "System.DateTime".
01 elapsedTime2 type "System.TimeSpan".
01 elapsedStr String.
procedure division.
set begTime2 to type "System.DateTime"::"Now"
invoke type "System.Threading.Thread"::"Sleep"(5000)
set endTime2 to type "System.DateTime"::"Now"
set elapsedTime2 to endTime2::"Subtract"(begTime2)
set elapsedStr to elapsedTime2::"ToString"()
The downside to this technique is that it can get rather cumbersome while coding if you always have to specify the fully qualified class or type including the namespace. This takes us to our final example and the purpose of this How-To article.
Example 3:
Using Classes contained in Namespaces that have been declared
The code below uses Classes or Types without having to declare them in the Class Repository. However, the difference between this and example 2 is the namespaces that contain the types have been declared with the ILUSING directive. Because of this, it is not necessary to fully qualify the types in the COBOL data definitions or business logic. The type keyword is still required, but you only need to specify the Class or Type name in double quotes.
In this example the Thread, DateTime, and TimeSpan classes are used without their respective namespaces in the code. Their namespaces are declared once at the top of the program with the ILUSING directive. This is identical in concept to the USING directive in C# or IMPORTS in VB.NET. $set is a feature of the Micro Focus compiler that allows you to set compiler directives directly in the source code. In this example it is used to specify the ILUSING directive.
1st lines of the COBOL program or Class ($set begins in column 7):
$set ilusing"System"
$set ilusing"System.Threading"
working-storage section.
01 begTime3 type "DateTime".
01 endTime3 type "DateTime".
01 elapsedTime3 type "TimeSpan".
01 elapsedStr String.
procedure division.
set begTime3 to type "DateTime"::"Now"
invoke type "Thread"::"Sleep"(5000)
set endTime3 to type "DateTime"::"Now"
set elapsedTime3 to endTime3::"Subtract"(begTime3)
set elapsedStr to elapsedTime3::"ToString"()
The advantages of declaring the namespaces of the types or classes used in your COBOL.NET program are:
1. Promotes streamlined coding by allowing the use of types or classes with their exact names...without having to fully specify the namespace in the name everytime those classes are used.
2. Eliminates the need to use the Class Repository to specify each individual class and type used in your program. The combination of the ILUSING directive and the Type keyword allow you to specify the exact names of types directly in your code.
3. Because naming is more consistent and standardized, it makes the classes and types in use more recognizable to other .NET programmers looking at your code. | https://mobile.codeguru.com/csharp/csharp/net30/article.php/c16385/Declaring-Namespaces-with-Micro-Focus-for-COBOLNET.htm | CC-MAIN-2018-34 | refinedweb | 1,167 | 57.57 |
An exercise is to write a program that shows how memory is allocated to stack variables compared to heap variables. I ran the following code.
#include "../../std_lib_facilities.h" int main () { char c = ' '; char ch0[10]; char *ch = new char[10]; char *init_ch = ch; cout << "Enter characters separated by a space.\nUse the '!' to indicate the end of your entries." << endl; int i = 0; while (cin >> c) { if (c == '!') { break; } else { *ch = c; ch0[i] = c; ch++; i++; } } ch = init_ch; for (int i = 0; i < 10; i++) { cout << *ch << " " << reinterpret_cast<void*>(ch) << endl; cout << ch0[i] << " " << reinterpret_cast<void*>(&ch0[i]) << endl; cout << endl; ch++; } ch = init_ch; delete[] ch; keep_window_open(); return 0; }
The output I get is an address of 00345A48 for the first element of the ch (heap) array, and an address of 0012FF48 for the first element of the ch0 (stack) array. The addresses of the other elements increase by 1 unit in both arrays.
The illustration in my book of the memory layout shows stack memory 'below' heap memory. I am guessing that means stack memory addresses will have smaller numbers than heap memory addresses, as my output shows.
Is that supposed to happen?
Thanks in advance for explanations. | https://www.daniweb.com/programming/software-development/threads/322173/stack-vs-heap-memory | CC-MAIN-2018-13 | refinedweb | 200 | 70.94 |
This reference provides cmdlet descriptions and syntax for all Windows Deployment Services cmdlets. It lists the cmdlets in alphabetical order based on the verb at the beginning of the cmdlet.
Adds an existing driver package to a driver group or injects it into a boot image.
Approves clients.
Copies install images within an image group.
Denies approval for clients.
Disables a boot image.
Disables a driver package in the Windows Deployment Services driver store.
Disables an install image.
Disconnects a multicast client from a transmission or namespace.
Enables a boot image.
Enables a driver package in the Windows Deployment Services driver store.
Enables an install image.
Exports an existing boot image from an image store.
Exports an existing install image from an image store.
Gets properties of boot images from the image store.
Gets client devices from the pending device database, or pre-staged devices from Active Directory or the stand-alone server device database.
Gets properties of driver packages from the Windows Deployment Services driver store.
Gets properties of install images from an image store.
Gets properties of install image groups.
Gets a list of clients connected to a multicast transmission or namespace.
Imports a boot image to the image store.
Imports a driver package into the Windows Deployment Services driver store.
Imports an install image to an image store.
Creates a pre-staged client.
Creates an install image group.
Removes a boot image from the image store.
Removes a pre-staged client from AD DS or the stand-alone server device database, or clears the Pending Devices database.
Removes a driver package from a driver group or removes it from all driver groups and deletes it.
Removes an install image from an image store.
Removes an install image group.
Modifies settings of a boot image.
Modifies a pre-staged client device.
Modifies the properties of an install image.
Modifies the name and access permissions of an install image group. | https://docs.microsoft.com/en-us/powershell/module/wds/index?view=win10-ps | CC-MAIN-2017-43 | refinedweb | 321 | 62.04 |
Hi guys, I’m an old time Rhino user since it was a public beta.
I noticed that Rhino is using IronPython 2.7. Unfortunately, I recently finished up a Python 3.x instruction so I’m wondering if there is a way to update IronPython separately, if not will I have to start learning Python 2…x vs. 3.x differences.
Hi guys, I’m an old time Rhino user since it was a public beta.
Hi Stephan
there is no 1-click or easy method to update to the next version of Python. And yes, there are quite some differences between the two. Rhino uses 2.7 because that was the only available version when Rhino 5 was shipping, and I think still a few steps are still missing before IP3 is released.
I think the best idea is to write forward-compatible code today. Here is how*. Also, IronPython already supports strings better than CPython 2.7, and
from __future__ import division is already the default in Rhino’s editor.
I hope this helps,
Giulio
Giulio Piacentino
for Robert McNeel & Associates
giulio@mcneel.com
*The difference is really not that large.
Hi Giulio - is IronPython 2.7 installing with Rhino 5 automatically these days? Or is it still required to download IronPython separately? Thanks.
Brian
This is installed automatically in Rhino 5 for Windows. This is still a separate download in Rhino for Mac.
I really doubt you are going to have problems understanding the 2.7 syntax if you have taken a course on 3.x
Thanks Steve! | https://discourse.mcneel.com/t/ironpython-is-2-7-will-i-be-able-to-update-for-python-3-4/8372 | CC-MAIN-2020-40 | refinedweb | 262 | 69.07 |
Are there differences between Streams, Java Streams and Reactive Streams?
Streams and observables are often used interchangeably, but some say there is a difference between them. So what is it all about?
>>IMAGE. After a lot of digging through various online sources, I’ll summarize my final understanding of Streams and Observables here in this article.
If you’re in a hurry, you can scroll down a bit to “So where’s the difference between all these streams?”. But before we get to that part, I’ve provided some basic information about the Observer pattern and reactive programming to help you better understand the technical details.
The Observer Pattern
With the Observer Pattern, objects can subscribe to a subject and get informed, whenever there is an update in the subject. Essentially, the subject maintains a list of its observers and automatically notifies them when any state is changed.
To understand the observer pattern, imagine an online movie platform (like Netflix). You eagerly wait for your favorite movie to come out on netflix so you can watch it immediately.
- You could check Netflix every day to see if the movie is already online, but that would be a waste of time, since the movie wouldn’t be online for a long time.
- Netflix could also send an email to every user as soon as your favorite movie is online. You would be very happy about that, but most people would be annoyed by their full inbox.
- You could click the “notify me” button and sign up for movie news. That way, only you (and a few other users who clicked the button) are subscribed to receive a notification when the movie is online. This is an analogy for the observer pattern. The movie is the subject that can notify the subscribers and you (the user) are the observer.
Reactive Programming
Reactive programming means that you program using — and relying on — events, rather than based on the order of your lines of code (that would be imperative programming).
Usually, there are several events involved, occurring at indeterminate times. Some of these events may occur in the future, for example. The sequence of events that happen over time is called a “stream”.
Andre Staltz defines it like this (here on GitHub):
Reactive programming is programming with asynchronous data streams.
You can think of it like a meeting between the two friends Alice and Bob. Alice invites Bob for watching a movie and a pizza.
- Synchronous: Alice is finished with work. She goes to the restaurant, orders the pizza and waits until it is ready. After she gets the pizza, she picks up Bob and they go home to watch the movie.
- Asynchronous: Alice orders the pizza online while she is still at work. She calls Bob and invites him to come over. She goes home, has the pizza delivered, and starts eating it. She also starts watching the movie without waiting for Bob.
- Reactive: Alice orders the pizza online while still at work. She calls Bob and invites him to come over. She goes home and has the pizza delivered, but waits until Bob comes over so they can start eating the pizza and watching the movie. Here, Alice waits until all the asynchronous actions are complete, and then continues with other actions.
So where’s the difference between all these “streams”?
The term “stream” does not really say much. A stream is simply “a sequence of data elements made available over time” (source: wikipedia). So the word “stream” does not imply any technical details, just that there is data and we can use it over time. It is a generic term that applies to Java Streams, Observables and even Iterators.
In my research I read a lot that “streams are pull-based” but this something very specific for Java Streams. And the library XStream uses the word “stream” instead of “observable” simply because the creator prefers the word stream to observable (issue at GitHub).
So when people use the word “stream”, they can mean different things that differ in their technical details. They could be talking about either Java Streams or Observables or something else.
1. Java Streams
Java streams can only be used once and are pull-based. Pull and push are just two different protocols which describe how data producers communicate with consumers. The data-consumer can decide when it gets the data from the data-producer. JS functions are pull-based too. The function produces data and the function can be called, “pulling” a value out of the function.
This approach is synchronous, because when we want to pull a value it has to be available the time we pull it.
2. Observables
An observable is simply an object that has a function
registerObserver(observer)(or with different naming in RxJS:
subscribe(observer)).
This means, that the observable is the
Subject being observed/subscribed to (see in the observer pattern above). You can also put it into other words: The stream is the “observable” being observed.
You can subscribe to an observable (stream) and get updates on changes on the observable.
For example, in RxJS an observable is an instance of the
Observable type and it has the method
subscribe(observer), which returns a subscription. (Important: RxJS has different types of observables and calls one of the types “Subject” — this is something RxJS-specific)
import { Observable } from 'rxjs';const observable = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
});observable.subscribe(result => console.log(result));
I think that this image (which looks quite the same as the image below) describes the differences between the synchronous vs the asynchronous world very good.
3. (Functional) Reactive Streams/Observable Streams/Observable Sequence
When someone is talking about reactive streams, reactive functional streams, observable streams or observable sequences they basically mean the same. With libraries like RxJS, XStream or RxJava you can introduce reactive programming (Rx is an acronym for “reactive extension”). Not many languages have built-in support for reactive streams, so those Rx-.. libraries help you with that. Since Java 9 there also exists the built-in
Flow interface, which lets you work with reactive streams natively.
In difference to the previously mentioned Java Streams, those Observable Streams are push-based. This means that the data-producer decides when the data-consumer (the subscriber) gets the data. This is an asynchronous approach, as the data-producer pushes the value to the consumers when it is available.
Conclusion
As the word “stream” does not have a special, definitive meaning in the software context, I would suggest to always differentiate between Java Streams and Observable Streams when talking about streams to prevent confusion.
The main differences between the most common streams are following:
- Java Streams: pull-based and synchronous
- Observable Streams: push-based and asynchronous
I hope I could clarify some views on streams and if you are interested in this topic I have some great resources for you:
What the hell is Reactive Programming anyway?
My recent article How React is not reactive, and why you shouldn't care opened up a much larger debate on the…
dev.to
Streams for reactive programming - surma.dev
Can you use WHATWG Streams for reactive programming? It seems so. But is it a good idea? The Reactive Programming (RP)…
dassur.ma
How streams can simplify your life - LogRocket Blog
In the land of web development, streams (and their building blocks, observables) are an increasingly popular topic…
blog.logrocket.com | https://s1gr1d.medium.com/are-there-differences-between-streams-java-streams-and-reactive-streams-82fb4565488a?source=post_internal_links---------4---------------------------- | CC-MAIN-2021-25 | refinedweb | 1,244 | 63.49 |
#include <stdio.h>
char *strstr(char *string2, char string*1);
The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence.
The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in src a null pointer is returned.
#include <stdio.h>
int main() {
char s1 [] = "My House is small";
char s2 [] = "My Car is green";
printf ("Returned String 1: %s\n", strstr (s1, "House"));
printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}
It will proiduce following result:
Returned String 1: House is small
Returned String 2: Car is green | http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=ansi_c&file=c_strstr.htm | CC-MAIN-2014-41 | refinedweb | 117 | 68.64 |
In the training process, I need to read array data from
.npy file and get a part of it:
import numpy as np data = np.load("sample1.npy") sound1 = data[start1: end1] sound2 = data[start2: end2]
Since the
.npy files are large, it became slowly to read a large file but only get some small parts of it. Is there a simple way to let us only read these small parts?
Yes, it’s just a simple line change
mmap_mode:
import numpy as np data = np.load("sample1.npy", mmap_mode="r") # just change this line sound1 = data[start1: end1] sound2 = data[start2: end2]
Now, the
load() function will not generate any IO for disk. But when we process the segment (like
sound1 or
sound2), it will load and only load the pages that contains the segment, which decrease the total IO tremendously.
After I change this line of code, the reading bandwidth dropped from 300MB/s to less than 100MB/s | https://donghao.org/2021/03/18/accelerate-reading-of-numpy-array-from-files/ | CC-MAIN-2021-39 | refinedweb | 161 | 80.31 |
C | String | Question 14
Assume that a character takes 1 byte. Output of following program?
Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
(A) 9
(B) 10
(C) 20
(D) Garbage Value
Answer: (C)
Explanation: Note that the sizeof() operator would return size of array. To get size of string stored in array, we need to use strlen(). The following program prints 9.
#include <stdio.h> #include <string.h> int main() { char str[20] = "GeeksQuiz"; printf ("%d", strlen(str)); return 0; }
My Personal Notes arrow_drop_up | https://www.geeksforgeeks.org/c-string-question-14/?ref=lbp | CC-MAIN-2021-43 | refinedweb | 111 | 77.64 |
Hi Gurus
I'm working through the Consultants Cookbook for Interaction Center (IC) Webclient CRM 5.0 SP03.
I'm having a huge problem with the CRM_IC.xml in my customers namespace.
My customers namespace is /XYZ/.
Therefore when I try to modify the CRM_IC/xml file I'm hitting errors because the replacement Include file name is being determined incorrectly.
<%@include file="..//<b>XYZ/CRM_IC_DT_REP</b>/CRM_IC_All_Viewsets.xml" %>
/XYZ/CRM_IC_DT_REP needs to be viewed as one value.
What escape characters should I use to resolve this.
An example would be appreciated greatly
Max points for the right answer.
Many Thanks
Panduranga | https://answers.sap.com/questions/3225765/crm-50---ic-webclient---bsp-error-due-to-no-escape.html | CC-MAIN-2022-27 | refinedweb | 102 | 61.43 |
First, a version of the code that will compile on a modern g++:
#include <iostream>
template<int N> struct fib {
static const int result = fib<N-1>::result + fib<N-2>::result;
};
template<> struct fib<0> {
static const int result = 0;
};
template<> struct fib<1> {
static const int result = 1;
};
int main(int ac, char *av[])
{
std::cout << "Fib(10) = " << fib<10>::result << std::endl;
return 0;
}
It might be worth exploring why exactly the above program is linear in compile time rather than exponential. After all, if the computation is being done at compile time, and the run-time of the algorithm is expected to be exponential, then compiling the program should be exponential, right? Let's take a look.
First, let's consider what fib(n) depends on, in this algorithm. Obviously, fib(10) (to continue with the example above) depends on fib(9) and fib(8). But fib(9) depends on fib(8) as well! (It also depends on fib(7)). Obviously, there's some repeated work here; in fact, the repeated work is the source of the expected exponential run-time. If, instead, we cached the value of fib for each n after the first time we computed it, we would only need to do n computations for fib(n), giving us a linear run-time (this type of algorithm is known as dynamic programming).
fib(n)
fib(10)
fib(9)
fib(8)
fib(7)
fib
Now, let's examine what your C++ compiler does when faced with the above code. Firstly, fib is a struct (i.e., a type) parametrized over an integer N. Just like templates using type parameters, fib is code for which a certain detail is left open until the code is used; the only difference is that detail is a value instead of a type. When using such a template, you specify the value explicitly, and the resulting code gets instantiated. So in main(), when you access fib<10>::result, fib gets instantiated with the value 10. However, to do so, because of the way fib is defined, fib<9> and fib<8> must also be instantiated. Recall that fib<9> also needs fib<8>; but at this point, fib<8> has already been instantiated, so the compiler doesn't need to do any extra work, and just emits code to read fib<8>::result. This is exactly like caching the value of fib(n), like we discussed above! And thus compilation time is linear in n.
struct
main()
fib<10>::result
fib<9>
fib<8>
fib<8>::result
One final C++ detail that's worth exploring: how does the recursion stop? In a normal recursive function fib(n), you'd have some sort of conditional at the top that exited the recursion when presented with a base case. It turns out C++ templates have a little feature called partial specialization. The idea, going back to type templates, is that maybe you want your templated class or function to do something different for a particular type than the normal case. In the case of fib, we have it specialized for the value 0 and 1, for which result is not defined recursively, but rather initialized with a constant. Thus, when the compiler reaches fib<2> and has to access fib<1>::result and fib<0>::result, it just outputs code to access the constants we wrote in those specializations of fib. (ML hackers will notice that this looks a awful lot like pattern matching arguments).
result
fib<2>
fib<1>::result
fib<0>::result
Need help? accounthelp@everything2.com | https://everything2.com/user/nyte/writeups/C%252B%252B%253A+computing+Fibonacci+numbers+at+compile+time | CC-MAIN-2018-43 | refinedweb | 598 | 60.04 |
Node.js and Kafka in 2018
Yes, Node.js has support for all of the Kafka features you need.
>>IMAGE?
node-rdkafkawraps the
librdkafkalibrary, which is widely used by the Kafka community, particularly as the basis of clients in other languages.
kafka-nodeis a pure JavaScript implementation of the Kafka protocol.
Is Kafka 2.0 Supported?
Yes, for both clients. I've been testing with
node-rdkafka using the Confluent Enterprise Kafka 5.0 Docker image:
I am 99.9% certain this is also true for
kafka-node whose documentation says it supports v0.8 and above.
Can I use SSL and SASL with Kafka?
Absolutely; SSL is supported by both brokers. In terms of authentication, SASL_PLAIN is supported by both, and I believe
node-rdkafka theoretically supports "GSSAPI/Kerberos/SSPI, PLAIN, SCRAM" by virtue of passing configuration directly to
librdkafka (but I haven't personally verified this).
In
node-rdkafka, it's as simple as:
import { KafkaConsumer } from 'node-rdkafka' import { hostname } from 'os' const consumer = new KafkaConsumer({ // My syntax highlighter doesn't support template strings...🙁 'client.id': ['myserver', hostname()].join('-'), 'group.id': 'myconsumegroup', 'rebalance_cb': true, 'metadata.broker.list': 'localhost:9091', 'security.protocol': 'SASL_SSL', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'myclient', 'sasl.password': 'clientpassword', // Note: librdkafka does not access a string with the certificate/key 'ssl.key.location': './etc/security/client.key', // This is only necessary if your key file is protected with a password 'ssl.key.password': 'mysupersecretpassword', 'ssl.certificate.location': './etc/security/client.certificate.pem', 'ssl.ca.location': './etc/security/ca.pem', }, { 'auto.offset.reset': 'beginning', })
Managing Kafka is scary, are there good hosted options?
Yaaaas.
- Confluent Cloud:
- Aiven Kafka:
- Cloudkarafka:
- Heroku Kafka:)
Confluent Cloud I'm going to assume is the gold standard. This is a service offering by the founders and core contributors of Kafka. Unfortunately, I can't tell you much about it because I've never had a chance to use it. I'm assuming they are targeting big enterprises because getting a simple price from the company requires you to go through an army of sales engineers who want to "talk about your Kafka implementation."
Aiven Kafka and Cloudkarafka are straightforward, multi-cloud Kafka providers. Aiven specifically is easy to set up and use in AWS, GCP, Azure, and Digital Ocean. From the documentation, it appears Cloudkarafka is hosted in AWS, but it may also support other public clouds (IDK). One distinguishing feature of Aiven was the ability to store messages indefinitely (other offerings forced users into 30-day event storage limits unless they upgraded to "enterprise plans"). Either way, I do enjoy the pricing models both vendors CLEARLY DISPLAY on their marketing pages.
To be fair to Cloudkarafka, we didn't research the offering as thoroughly as Aiven. Aiven has other database offerings (specifically Postgres with the TimescaleDB extension) that really convinced us.
Finally, if you are on the Heroku platform, it probably makes sense to use Heroku Kafka. Heroku has a great reputation for providing stable products, so I imagine the same goes for this offering.
Conclusion
I hope this answers some of your questions. Kafka can be daunting for the uninitiated but is certainly worth the effort. More importantly, Node.js is a completely viable language for using the Kafka broker. If you do plan on choosing Kafka, consider using one of the hosted options. Confluent Cloud is probably the safest bet, but it's considerably more expensive. Aiven is a great alternative, especially if you are just testing out the platform.
Stumbling my way through the great wastelands of enterprise software development. | https://rclayton.silvrback.com/node-js-and-kafka-2018 | CC-MAIN-2021-17 | refinedweb | 593 | 50.94 |
Problems with QGraphicsView subclassing
Hi everybody,
I'm having some problems subclassing QGraphicsView. I'm trying to reimplement the following functions:
QGraphicsView::mouseMoveEvent(QMouseEvent *event)
QGraphicsView::paintEvent(QPaintEvent *)
I have a Dialog and what I have to do is display a chart and some other buttons, and when I move the mouse on the chart I want to draw a Cursor. I have read in some topics that the best way to do that is subclassing QGraphicsView and reimplement the two functions above. So here is my code. I take example from this topic for the subclass
@
customgv.h
@
#include <QGraphicsView>
#include <QMouseEvent>
class QWidget;
class customgv : public QGraphicsView
{
Q_OBJECT
public:
QPoint mousePoint;
void mouseMoveEvent(QMouseEvent * event);
void paintEvent(QPaintEvent *);
public:
customgv(QWidget *parent= NULL);
~customgv();
};
@
customgv.cpp
@
#include <QtGui>
#include "customgv.h"
customgv::customgv(QWidget* parent)
: QGraphicsView(parent)
{
setGeometry(5,5,500,500); setMouseTracking(true);
}
customgv::~customgv()
{
}
void customgv::mouseMoveEvent(QMouseEvent *event)
{
mousePoint = event->pos(); update();
}
void customgv::paintEvent(QPaintEvent *)
{
QPainter painter(this); painter.setPen(QPen(Qt::black, 1)); painter.drawLine(mousePoint.x(),this->geometry().bottom() , mousePoint.x(),this->geometry().top());
}
@
chart.cpp
@
//in the constructor of my new dialog chart.cpp i simply do this
//custom is defined as a pointer to my subclass in chart.h like customgv *custom
custom = new customgv(this);
QChartView *chartView = new QChartView(chart,custom);
@
The problem is that the mouseMoveEvent is not working, when I move the mouse on the chart nothing happens and in debugging it never entries in the function. The only error qt gives me is the following:
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
this error appears only when I open the dialog that includes my QGraphicsView subclass.
Of course I am missing something but I can't understand what.
Thank you all in advance.
- raven-worx Moderators
@davidesalvetti
your biggest mistake is that you do not call the base class implementation which (basically - unless you know what you are doing) you always should do when subclassing event-handlers - or virtual functions.
void customgv::mouseMoveEvent(QMouseEvent *event) { mousePoint = event->pos(); update(); QGraphicsView::mouseMoveEvent(event); }
Also i think reimplementing drawForeground() is more what you want rather than paintEvent():
void customgv::drawForeground(QPainter * painter, const QRectF & rect) { QGraphicsView::drawForeground(painter, rect); painter.setPen(QPen(Qt::black, 1)); painter.drawLine(mousePoint.x(),this->geometry().bottom() , mousePoint.x(),this->geometry().top()); }
Thanks for your anwer.
I'm sorry, I forgot to say that I already tried adding the base class implementation, but the mouseMoveEvent didn't work, that's why I tried without that line, but of course it's not correct.
I understand your second advice, I will use drawForeground() instead of paintEvent() in the future.
Anyway I tried to modify all my code as you said, but mouseMoveEvent doesn't work. I tried debugging and putting a break in the mouseMoveEvent function, but it never breaks.
I'm wondering if subclassing QGraphicsView is correct for my purpose. Maybe I have to subclass QChartView?
- Asperamanca
If you want a specific cursor while over the chart, it would make sense to have the chart as a separate GraphicsItem. Create your own QGraphicsItem for the chart with your paint code, and use "setCursor" to define which cursor should be visible.
Subclassing QGraphicsView should not be necessary at all in this case.
@Asperamanca
Thank you for the answer.
what I really need is not only to change the cursor while i'm over the chart, I need to draw a vertical Line on the chart that follow the mouse position, and when i click the mouse the line has to be fixed at that particular position.
For this purpose I think I need a QGraphicsView that contain the QChartView, create the QChart and then create a GraphicsItem to draw the line. Am I wrong? Shoul I do something different?
Any advice is appreciated.
- Asperamanca
@davidesalvetti
QChart derives from QGraphicsWidget and thus indirectly from QGraphicsItem. I personally don't know QChart (so I don't know whether it's the right class for you to display what you want to display), but in any case, I would much rather suclass QChart (always making sure you call the base class methods when you replace a method), and put your logic in there.
For example, reimplement paint, call the base class painting code first, then draw the vertical line where you need it.
Thank you a lot for your answer. I will try to find a solution based on your advices. Thanks again! | https://forum.qt.io/topic/83672/problems-with-qgraphicsview-subclassing | CC-MAIN-2018-09 | refinedweb | 760 | 53.92 |
It's often needed to have some sort of login functionality in an app so users can save data or create their own profiles. Or maybe only authenticated users can have access to reserved content. In a modern app, users expect to have standard login-related features like email verification, password reset, multi-factor authentication, etc. These features, though necessary, are not easy to get right and usually not the app's main business.
On the user side, they don't want to go through the lengthy registration process neither as they need to create and remember yet another email/password. Without a proper password manager, users tend to reuse the same password which is terrible in terms of security.
SSO (Single sign-on), mostly known to the public by the everywhere Login with Facebook/Google/Twitter buttons, was invented as a solution for this issue. For users, they don't have to go through the painful registration process: one click is all it needs. For developers, removing friction for users is always a huge win and in addition, all login-related features are now delegated to the Identity provider (i.e. Facebook/Google/Twitter). Your app simply trusts the Identity provider of doing its job of verifying user identity.
SSO is usually powered by OIDC (OpenId Connect) or SAML protocol. SAML is used mostly in enterprise application. OIDC is built on top of OAuth2 and used by social identity providers like Facebook, Google, etc. In this post, we'll focus on the OIDC/OAuth2 protocol.
This post presents a step-by-step guide to add a SSO Login button into a Flask application with SimpleLogin and Facebook as Identity provider. This can be done without using any external library but in order not to worry too much about the OAuth details, we'll use Requests-OAuthlib, a library to integrate OAuth providers. If you are interested in implementing a SSO login from scratch, please check out Implement SSO Login the raw way.
At the end of this article, you should have a Flask app that has the following pages:
- Home page: that only has the login button
- User information page: upon successful login, the user will be able to see information such as name, email, avatar.
All steps of this tutorial can be found on flask-social-login-example repository.
A demo is also available at, feel free to remix the code on Glitch 😉.
Step 1: Bootstrap Flask app
Install
flask and
Requests-OAuthlib. You can also use
virtualenv or
pipenv to isolate the environment.
pip install flask requests_oauthlib
Create
app.py and the route that displays a login button on the home page:
import flask app = flask.Flask(__name__) @app.route("/") def index(): return """ <a href="/login">Login</a> """ if __name__ == '__main__': app.run(debug=True)
Let's run this app and verify everything is working well:
python app.py
You should see this page when opening. The full code is on step1.py
Step 2: Identity provider credential
There are currently hundreds (if not thousands) identity providers with the most popular ones being Facebook, Google, Github, Instagram, etc. For this post, SimpleLogin is chosen because of its developer-friendliness. The same code will work with any OAuth2 identity provider (Facebook, Google, etc) though. Disclaimer: I happen to be SimpleLogin co-founder so this choice is obviously subjective.
As going through the setup of Facebook, Google, Twitter login is a bit complex (everyone uses Google Cloud Console can feel the pain 😅) and requires additional steps that are beyond the scope of this post like setting up SSL, choosing right scopes, etc. the section Login with Facebook is rather provided as an appendix at the end of the post.
Please head to SimpleLogin and create an account if you do not have one already, then create a new app in Developer tab.
On app detail page, please copy your AppID and AppSecret and save them into variable environment. In OAuth terminology, client actually means a third-party app, i.e. your app. We can put these values directly in the code but it's a good practice to save credentials into variable environments. This is also the third factor in the The Twelve Factors.
export CLIENT_ID={your AppID} export CLIENT_SECRET={your AppSecret}
In
app.py please add these lines on top of the file to get
client id and
client secret
import os CLIENT_ID = os.environ.get("CLIENT_ID") CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
Please also add these OAuth URLs on the top of
app.py that are going to be used in the next step. They can also be copied on the OAuth endpoints page.
AUTHORIZATION_BASE_URL = "" TOKEN_URL = "" USERINFO_URL = ""
As we don't want to worry about setting up SSL now, let's tell
Requests-OAuthlib that it's OK to use plain HTTP:
# This allows us to use a plain HTTP callback os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
As usual, the code for this step is on step2.py
Step 3: Login redirection
When a user clicks on the login button:
The user will be redirected to the identity login provider authorization page asking whether user wants to share their information with your app.
Upon user approval, they will be then redirected back to a page on your app along with a
codein the URL that your app will use to exchange for an
access tokenthat allows you later to get user information from the service provider.
We need therefore two routes: a
login route that redirects the user to the identity provider and a
callback route that receives the
code and exchanges for
access token. The callback route is also responsible for displaying user information.
@app.route("/login") def login(): simplelogin = requests_oauthlib.OAuth2Session( CLIENT_ID, <br> <a href="/">Home</a> """
Clicking on Login button should bring you through the following flow. The full code can be found on Github - step3.py
Conclusion
Congratulations 🎉 you have successfully integrated SSO login into a Flask app!
For the sake of simplicity, this tutorial doesn't mention other OAuth concepts like scope and state, important to defend against *Cross Site Request Forgery * attack. You would also probably need to store the user info in a database which is not covered in this article.
The app also needs to be served on https on production, which can be quite easily done today with Let’s Encrypt.
Happy OAuthing!
Appendix: Login with Facebook
As promised earlier, please find below the steps to integrate Login with Facebook button 🙂. Apart from a quite sophisticated UI, the hardest part about integrating Facebook might be finding a way to serve your web app on https locally as the new version of Facebook SDK doesn't allow local plain HTTP. I recommend using Ngrok, a free tool to have a quick https URL.
Step 1: Create a Facebook app:
Please head to and create a new app
Then choose "Integration Facebook Login" on the next screen
Step 2: Facebook OAuth credential
Click on "Settings/Basic" on the left and copy the App ID and App Secret, they are actually OAuth client-id and client-secret.
Update the client-id and client-secret
export FB_CLIENT_ID={your facebook AppId} export FB_CLIENT_SECRET={your facebook AppSecret}
Update the AUTHORIZATION_BASE_URL and TOKEN_URL:
FB_AUTHORIZATION_BASE_URL = "" FB_TOKEN_URL = ""
The home page
@app.route("/") def index(): return """ <a href="/fb-login">Login with Facebook</a> """
Step 3: Login and callback endpoints
If the app is served behind
ngrok using
ngrok http 5000 command, we need to set the current url to the ngrok url
# Your ngrok url, obtained after running "ngrok http 5000" URL = ""
Please make sure to add the url to your Facebook Login/Settings, Valid OAuth Redirect URIs setting:
In order to have access to a user email, you need to add
scope
FB_SCOPE = ["email"] @app.route("/fb-login") def login(): facebook = requests_oauthlib.OAuth2Session( FB_CLIENT_ID, redirect_uri=URL + "/fb-callback", scope=FB_SCOPE ) authorization_url, _ = facebook.authorization_url(FB_AUTHORIZATION_BASE_URL) return flask.redirect(authorization_url)
The
callback route is a bit more complex as Facebook requires a compliance fix:
from requests_oauthlib.compliance_fixes import facebook_compliance_fix @app.route("/fb-callback") def callback(): facebook = requests_oauthlib.OAuth2Session( FB_CLIENT_ID, scope=FB_SCOPE, redirect_uri=URL + "/fb-callback" ) # we need to apply a fix for Facebook here facebook = facebook_compliance_fix(facebook) facebook.fetch_token( FB_TOKEN_URL, client_secret=FB_CLIENT_SECRET, authorization_response=flask.request.url, ) # Fetch a protected resource, i.e. user profile, via Graph API facebook_user_data = facebook.get( "{url}" ).json() email = facebook_user_data["email"] name = facebook_user_data["name"] picture_url = facebook_user_data.get("picture", {}).get("data", {}).get("url") return f""" User information: <br> Name: {name} <br> Email: {email} <br> Avatar <img src="{picture_url}"> <br> <a href="/">Home</a> """
Now when clicking on Login with Facebook, you should be able to go through the whole flow.
The full code is on facebook.py
Integrating
Login with Google/Twitter/... is quite similar. Please let me know in the comment if you would like to have similar sections for these social login providers!
Discussion (0) | https://dev.to/simplelogin/create-a-flask-application-with-sso-login-f9m | CC-MAIN-2021-17 | refinedweb | 1,480 | 54.22 |
Scan formatted input from stdin
#include <stdio.h> int scanf( const char* format, ... );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The scanf() function scans input from stdin under control of the format argument, assigning values to the remaining arguments.
Format control string
The format control string consists of zero or more format directives that specify what you consider to be acceptable input data. Subsequent arguments are pointers to various types of objects that the function assigns values to as it processes the format string.
A format directive can be a sequence of one or more whitespace characters or:
As each format directive in the format string is processed, the directive may successfully complete, fail because of a lack of input data, or fail because of a matching error as defined by the directive.
If end-of-file is encountered on the input data before any characters that match the current directive have been processed (other than leading whitespace, where permitted), the directive fails for lack of data.
If end-of-file occurs after a matching character has been processed, the directive is completed (unless a matching error occurs), and the function returns without processing the next directive.
If a directive fails because of an input character mismatch, the character is left unread in the input stream.
Trailing whitespace characters, including newline characters, aren't read unless matched by a directive. When a format directive fails, or the end of the format string is encountered, the scanning is completed, and the function returns.
When one or more whitespace characters (space, horizontal tab \t, vertical tab \v, form feed \f, carriage return \r, newline or linefeed \n) occur in the format string, input data up to the first non-whitespace character is read, or until no more data remains. If no whitespace characters are found in the input data, the scanning is complete, and the function returns.
An ordinary character in the format string is expected to match the same character in the input stream.
Conversion specifiers
A conversion specifier in the format string is processed as follows:
Type length specifiers
A type length specifier affects the conversion as follows:
Conversion type specifiers
The valid conversion type specifiers are:
When an l ("el") qualifier is present, a sequence of characters are converted from the initial shift state to wchar_t wide characters as if by a call to mbrtowc(). The conversion state is described by a mbstate_t object.
If the sequence contains more than 8 digits, the conversion is performed only on the last 8 digits in the sequence.
When an l ("el") qualifier is present, a sequence of characters are converted from the initial shift state to wchar_t wide characters as if by a call to mbrtowc(). The conversion state is described by a mbstate_t object.
When an l ("el") qualifier is present, a sequence of characters are converted from the initial shift state to wchar_t wide characters as if by a call to mbrtowc() with mbstate set to 0. The argument is assumed to point to the first element of a wchar_t array of sufficient size to contain the sequence and a terminating NUL character, which the conversion operation adds.
The conversion specification includes all characters in the scanlist between the beginning [ and the terminating ]. If the conversion specification starts with [^, the scanlist matches all the characters that aren't in the scanlist. If the conversion specification starts with [] or [^], the ] is included in the scanlist. (To scan for ] only, specify %[]].)
A - in the scanlist that isn't the first character, nor the second where the first character is a ^, nor the last character, defines a range of characters to be matched. This range consists of characters numerically greater than or equal to the character before the -, and numerically less than or equal to the character after the -.
A conversion type specifier of % is treated as a single ordinary character that matches a single % character in the input data. A conversion type specifier other than those listed above causes scanning to terminate, and the function to returns with an error.
The number of input arguments for which values were successfully scanned and stored, or EOF if the scanning stopped by reaching the end of the input stream before storing any values.
The line:
scanf( "%s%*f%3hx%d", name, &hexnum, &decnum )
with input:
some_string 34.555e-3 abc1234
copies "some_string" into the array name, skips 34.555e-3, assigns 0xabc to hexnum and 1234 to decnum. The return value is 3.
The program:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main( void ) { char string1[80], string2[80]; memset( string1, 0, 80 ); memset( string2, 0, 80 ); scanf( "%[abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWZ ]%*2s%[^\n]", string1, string2 ); printf( "%s\n", string1 ); printf( "%s\n", string2 ); return EXIT_SUCCESS; }
with input:
They may look alike, but they don't perform alike.
assigns "They may look alike" to string1, skips the comma (the "%*2s" matches only the comma; the following blank terminates that field), and assigns " but they don't perform alike." to string2.
To scan a date in the form "Friday March 26 1999":
#include <stdio.h> #include <stdlib.h> #include <string.h> int main( void ) { int day, year; char weekday[10], month[12]; int retval; memset( weekday, 0, 10 ); memset( month, 0, 12 ); retval = scanf( "%10s %12s %d %d", weekday, month, &day, &year ); if( retval != 4 ) { printf( "Error reading date.\n" ); printf( "Format is: Friday March 26 1999\n" ); return EXIT_FAILURE; } printf( "weekday: %s\n", weekday ); printf( "month: %s\n", month ); printf( "day: %d\n", day ); printf( "year: %d\n", year ); return EXIT_SUCCESS; } | http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/s/scanf.html | CC-MAIN-2019-51 | refinedweb | 941 | 60.45 |
How String equals Method Works
How String equals Method Works
Join the DZone community and get the full member experience.Join For Free
Take 60 minutes to understand the Power of the Actor Model with "Designing Reactive Systems: The Role Of Actors In Distributed Architecture". Brought to you in partnership with Lightbend.
The equals method is declared in Object class and hence is inherited by all classes in Java. The purpose of equals method is to provide logical equality. The default implementation of equals method is:
public boolean equals(Object obj) { return (this == obj); }Thus the default behavior of equals method is same as == operator.
equals method in String class checks if the two strings have same characters or not. But this check is performed intelligently. The algorithm for checking the Strings for equality involves:
a) If the String objects are equals as per == operator, true is returned.
b) If the == returns false then each character of both the strings are compared and if a difference if found, immediately false is returned.
c) If after comparing all characters of both the strings, no difference is found in characters and length of strings, true is returned.
Please note that the equals method in String class in Java is case-sensitive. The complete code for equals method is reproduced here for reference:; }
Also the compareTo method in String class is consistent with equals method.
Learn how the Actor model provides a simple but powerful way to design and implement reactive applications that can distribute work across clusters of cores and servers. Brought to you in partnership with Lightbend.
Published at DZone with permission of Sandeep Bhandari . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/how-string-equals-method-works | CC-MAIN-2018-13 | refinedweb | 299 | 55.13 |
This. I started of with some of the basics, advantages and disadvantages of user controls.
User Control:
User Control is the custom, reusable controls. User Controls offers a way to partition and reuse User Interface (UI) functionality across ASP.NET Applications.
Advantages of User Control:
Disadvantages of User Control:
Adding User Controls to an WebForms Page:
At the top of the .aspx page, add the below line above <Html> tag.<%@ Register TagPrefix="Test" TagName="TestControl" Src="Test.ascx" %>
Declare user controls like
<
Accessing and Setting User Controls Values in the .aspx Page:
User can access and set the values of the User Control from .aspx page through properties,using javascript and in code-behind of aspx page.The details of it are shown below
1) Using Properties
If the test.ascx control has two textboxes and submit button.You can access the values of the textboxes in the control from an .aspx page by declaring public property in the .ascx page.
public
TestControl.FirstName
You can set the FirstName of the control from aspx page using
TestControl.FirstName = "Suzzanne"
2) Using Javascript
You can set the values of the controls declared in the .ascx page by
document.forms[0]['TestControl:txtFirstName'].
TestControl objTestControl = (TestControl)Page.FindControl("TestControl");TextBox objTextBox = objTestControl.FindControl("txtFirstName");
<%
namespace
{
Passing Values between User Controls and ASPX Page
Formatting Chemical Formulae in DataGrid
Create a form in your code and you can past via get or post and do a request string in your aspx page.
I am trying to pass a variable in a web page using the param tag. What changes do I need to make in my c# user control so I can read this value from the same web page. | http://www.c-sharpcorner.com/UploadFile/Santhi.M/PassingValuesfrmUCtoASPX11212005050040AM/PassingValuesfrmUCtoASPX.aspx | crawl-003 | refinedweb | 287 | 58.69 |
Upgrading a Reverse Proxy from Netty 3 to 4
Tracon is our reverse HTTP proxy powered by Netty. We recently completed an upgrade to Netty 4 and wanted to share our experience.
Written by Chris Conroy and Matt Davenport.
Tracon: Square’s reverse proxy
Tracon is our reverse HTTP proxy powered by Netty. Several years ago, as we started to move to a microservice architecture, we realized that we needed a reverse proxy to coordinate the migration of APIs from our legacy monolith to our rapidly expanding set of microservices.
We chose to build Tracon on top of Netty in order to get efficient performance coupled with the ability to make safe and sophisticated customizations. We are also able to leverage a lot of shared Java code with the rest of our stack in order to provide rock-solid service discovery, configuration and lifecycle management, and much more!
Tracon was written using Netty 3 and has been in production for three years. Over its lifetime, the codebase has grown to 20,000 lines of code and tests. Thanks in large part to the Netty library, the core of this proxy application has proven so reliable that we’ve expanded its use into other applications. The same library powers our internal authenticating corporate proxy. Tracon’s integration with our internal dynamic service discovery system will soon power all service-to-service communication at Square. In addition to routing logic, we can capture a myriad of statistics about the traffic flowing into our datacenters.
Why upgrade to Netty 4 now?
Netty 4 was released three years ago. Compared to Netty 3, the threading and memory models have been completely revamped for improved performance. Perhaps more importantly, it also provides first class support for HTTP/2. Although we’ve been interested in migrating to this library for quite a while, we’ve delayed upgrading because it is a major upgrade that introduces some significant breaking changes.
Now that Netty 4 has been around for a while and Netty 3 has reached the end of its life, we felt that the time was ripe for an overhaul of this mission-critical piece of infrastructure. We want to allow our mobile clients to use HTTP/2 and are retooling our RPC infrastructure to use gRPC which will require our infrastructure to proxy HTTP/2. We knew this would be a multi-month effort and there would be bumps along the way. Now that the upgrade is complete, we wanted to share some of the issues we encountered and how we solved them.
Issues encountered
Single-threaded channels: this should be simple!
Unlike Netty 3, in Netty 4, outbound events happen on the same single thread as inbound events. This allowed us to simplify some of our outbound handlers by removing code that ensured thread safety. However, we also ran into an unexpected race condition because of this change.
Many of our tests run with an echo server, and we assert that the client receives exactly what it sent. In one of our tests involving chunked messages, we found that we would occasionally receive all but one chunk back. The missing chunk was never at the beginning of the message, but it varied from the middle to the end.
In Netty 3, all interactions with a pipeline were thread-safe. However, in Netty 4, all pipeline events must occur on the event loop. As a result, events that originate outside of the event loop are scheduled asynchronously by Netty.
In Tracon, we proxy traffic from an inbound server channel to a separate outbound channel. Since we pool our outbound connections, the outbound channels aren’t tied to the inbound event loop. Events from each event loop caused this proxy to try to write concurrently. This code was safe in Netty 3 since each write call would complete before returning. In Netty 4, we had to more carefully control what event loop could call write to prevent out of order writes.
When upgrading an application from Netty 3, carefully audit any code for events that might fire from outside the event loop: these events will now be scheduled asynchronously.
When is a channel really connected?
In Netty 3, the SslHandler “redefines” a channelConnected event to be gated on the completion of the TLS handshake instead of the TCP handshake on the socket. In Netty 4, the handler does not block the channelConnected event and instead fires a finer-grained user event:SslHandshakeCompletionEvent. Note that Netty 4 replaces channelConnected with channelActive.
For most applications, this would be an innocuous change, but Tracon uses mutually authenticated TLS to verify the identity of the services it is speaking to. When we first upgraded, we found that we lacked the expected SSLSession in the mutual authentication channelActive handler. The fix is simple: listen for the handshake completion event instead of assuming the TLS setup is complete on channelActive
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws if (evt.equals(SslHandshakeCompletionEvent.SUCCESS)) { Principal peerPrincipal = engine.getSession().getPeerPrincipal(); // Validate the principal // ... } super.userEventTriggered(ctx, evt); }
Recycled Buffers Leaking NIO Memory
In addition to our normal JVM monitoring, we added monitoring of the size and amount of NIO allocations by exporting the JMX bean *java.nio:type=BufferPool,name=direct *since we want to be able to understand and alert on the direct memory usage by the new pooled allocator.
In one cluster, we were able to observe an NIO memory leak using this data. Netty provides a leak detection framework to help catch errors in managing the buffer reference counts. We didn’t get any leak detection errors because this leak was not actually a reference count bug!
Netty 4 introduces a thread-local Recycler that serves as a general purpose object pool. By default, the recycler is eligible to retain up to 262k objects. ByteBufs are pooled by default if they are less than 64kb: that translates to a maximum of 17GB of NIO memory per buffer recycler.
Under normal conditions, it’s rare to allocate enough NIO buffers to matter. However, without adequate back-pressure, a single slow reader can balloon memory usage. Even after the buffered data for the slow reader is written, the recycler does not expire old objects: the NIO memory belonging to that thread will never be freed for use by another thread. We found the recyclers completely exhausted our NIO memory space.
We’ve notified the Netty project of these issues, and there are several upcoming fixes to provide saner defaults and limit the growth of objects:
- Allow to limit the maximum number of WeakOrderQueue instances per Thread
- Introduce allocation / pooling ratio in Recycler
- Port SendBufferPooled from netty 3.10 and use it if non pooled ByteBufAllocator is used.
We encourage all users of Netty to configure their recycler settings based on the available memory and number of threads and profiling of the application. The number of objects per recycler can be configured by setting -Dio.netty.recycler.maxCapacity *and the maximum buffer size to pool is configured by -Dio.netty.threadLocalDirectBufferSize. It’s safe to completely disable the recycler by setting the -Dio.netty.recycler.maxCapacity* to 0, and for our applications, we have not observed any performance advantage in using the recycler.
We made another small but very important change in response to this issue: we modified our global UncaughtExceptionHandler to terminate the process if it encounters an error since we can’t reasonably recover once we hit an OutOfMemoryError. This will help mitigate the effects of any potential leaks in the future.
class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger logger = Logger.getLogger(LoggingExceptionHandler.class); /** Registers this as the default handler. */ static void registerAsDefault() { Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler()); } @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof Exception) { logger.error("Uncaught exception killed thread named '" + t.getName() + "'.", e); } else { logger.fatal("Uncaught error killed thread named '" + t.getName() + "'." + " Exiting now.", e); System.exit(1); } } }
Limiting the recycler fixed the leak, but this also revealed how much memory a single slow reader could consume. This isn’t new to Netty 4, but we were able to easily add backpressure using the channelWritabilityChanged event. We simply add this handler whenever we bind two channels together and remove it when the channels are unlinked.
/** * Observe the writability of the given inbound pipeline and set the {@link ChannelOption#AUTO_READ} * of the other channel to match. This allows our proxy to signal to the other side of a proxy * connection that a channel has a slow consumer and therefore should stop reading from the * other side of the proxy until that consumer is ready. */ public class WritabilityHandler extends ChannelInboundHandlerAdapter { private final Channel otherChannel; public WritabilityHandler(Channel otherChannel) { this.otherChannel = otherChannel; } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { boolean writable = ctx.channel().isWritable(); otherChannel.config().setOption(ChannelOption.AUTO_READ, writable); super.channelWritabilityChanged(ctx); } }
The writability of a channel will go to not writable after the send buffer fills up to the high water mark, and it won’t be marked as writable again until it falls below the low water mark. By default, the high water mark is 64kb and the low water mark is 32kb. Depending on your traffic patterns, you may need to tune these values.
If a promise breaks, and there’s no listener, did you just build /dev/null as a service?
While debugging some test failures, we realized that some writes were failing silently. Outbound operations notify their futures of any failures, but if each write failure has shared failure handling, you can instead wire up a handler to cover all writes. We added a simple handler to log any failed writes:
@Singleton @Sharable public class PromiseFailureHandler extends ChannelOutboundHandlerAdapter { private final Logger logger = Logger.getLogger(PromiseFailureHandler.class); @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { promise.addListener(future -> { if (!future.isSuccess()) { logger.info("Write on channel %s failed", promise.cause(), ctx.channel()); } }); super.write(ctx, msg, promise); } }
HTTPCodec changes
Netty 4 has an improved HTTP codec with a better API for managing chunked message content. We were able to remove some of our custom chunk handling code, but we also found a few surprises along the way!
In Netty 4, every HTTP message is converted into a chunked message. This holds true even for zero-length messages. While it’s technically valid to have a 0 length chunked message, it’s definitely a bit silly! We installed object aggregators to convert these messages to non-chunked encoding. Netty only provides an aggregator for inbound pipelines: we added a custom aggregator for our outbound pipelines and will be looking to contribute this upstream for other Netty users.
There are a few nuances with the new codec model. Of note, LastHttpContent is also a HttpContent. This sounds obvious, but if you aren’t careful you can end up handling a message twice! Additionally, a FullHttpResponse is also an HttpResponse, an HttpContent, and a LastHttpContent. We found that we generally wanted to handle this as both an HttpResponse and a LastHttpContent, but we had to be careful to ensure that we didn’t forward the message through the pipeline twice.
Don’t do this
if (msg instanceof HttpResponse) { ... } if (msg instanceof HttpContent) { ... } if (msg instanceof LastHttpContent) { … // Duplicate handling! This was already handled above! }
Another nuance we discovered in some test code: LastHttpContent may fire after the receiving side has already received the complete response if there is no body. In this case, the last content is serving as a sentinel, but the last bytes have already gone out on the wire!
Replacing the engine while the plane is in the air
In total, our change to migrate to Netty 4 touched 100+ files and 8k+ lines of code. Such a large change coupled with a new threading and memory model is bound to encounter some issues. Since 100% of our external traffic flows through this system, we needed a process to validate the safety of these changes.
Our large suite of unit and integration tests was invaluable in validating the initial implementation.
Once we established confidence in the tests, we began with a “dark deploy” where we rolled out the proxy in a disabled state. While it didn’t take any traffic, we were able to exercise a large amount of the new code by running health checks through the Netty pipeline to check the status of downstream services. We highly recommend this technique for safely rolling out any large change.
As we slowly rolled out the new code to production, we also relied on a wealth of metrics in order to compare the performance of the new code. Once we addressed all of the issues, we found that Netty 4 performance using the UnpooledByteBufAllocator is effectively identical to Netty 3. We’re looking forward to using the pooled allocator in the near future for even better performance.
Thanks
We’d like to thank everyone involved in the Netty project. We’d especially like to thank Norman Maurer / @normanmaurer for being so helpful and responsive!
References
- New and Noteworthy in Netty 4.0:
- Netty Best Practices a.k.a Faster == Better:
- Netty in Action: | https://developer.squareup.com/blog/upgrading-a-reverse-proxy-from-netty-3-to-4/ | CC-MAIN-2022-40 | refinedweb | 2,195 | 54.63 |
In this program, we first input the number (Say num = 12345). Next the control reaches the while loop where it checks the condition (num>0) which is true as (12345>0) so the body of the loop is executed.
On First pass, x=5 Sum=0+5=5 num = 1234
On Second pass, x=4 Sum=5+4= 9 num = 123
On Third pass, x=3 Sum=9+3=12 num = 12
On Fourth pass, x=2 Sum=12+2=14 num = 1
On Fifth pass, x=1 Sum=14+1=15 num = 0
Finally, when the condition becomes false, the control reaches out of the loop and finally displays the sum of digits of a number. In this program, the number of times the loop will be executed is unknown in advance.
//program to Find Sum of Digits of a Number
import java.util.Scanner; //program uses Scanner class
public class SumDigits
{
public static void main(String[] args)
{
long num,x,sum=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number :");
num=input.nextInt();
while(num>0)
{
x = num%10;
sum += x;
num /=10;
}
System.out.println("Sum of Digits of Number is :" | http://ecomputernotes.com/java/control-structures-in-java/sum-of-digits-of-a-number | CC-MAIN-2019-39 | refinedweb | 197 | 70.84 |
Palindrome checker is a better basic example of test-driven development
A commonly given basic example for test-driven development (TDD) is a function that is supposed to add up two integers. The stub always returns a specific number, like 0, instead of actually adding up its two parameters.
Of course that fails a test that expects something like 1 + 1 = 2. So you change the stub to return 2. But now that fails a test that expects something like 2073 + 125 = 2198. So you change the function to
return a + b.
If people conclude from this that TDD is dumb and pointless, can you blame them? It’s an example simple enough that anyone with a computer can follow along, but it doesn’t do anything to convey the sense of accomplishment one can feel in making a previously failing test now pass.
A better example, I think, would be the palindrome checker. We’re going to use a Java IDE (like NetBeans or IntelliJ) to write in Java a command line palindrome checker utility.
It’s barely more useful than wrapping plain old addition in a new function, but I think the palindrome checker TDD exercise would do much more to convince TDD skeptics that TDD’s the way to go.
Also, the palindrome checker exercise provides more opportunities for follow-up exercises than trying to reinvent the wheel on basic integer arithmetic.
Although this example is going to be specifically in Java, I think you can follow along with almost any other programming language with a reliable and established testing framework.
The command line tool will take in the command line arguments as an array of
String instances, and report which ones of them are palindromes and which ones are not.
A palindrome is a word, phrase or number that reads the same backwards as forwards. For example, “kayak” and 121 are palindromes, “canoe” and 122 are not (122 backwards is 221, and “canoe” backwards is not even a valid word as far as most spellcheckers is concerned.).
So our palindrome checker will have a standard
public static void main(String[] args) procedure which puts each of the
args through a Boolean function that ought to return
true for palindromes only.
I’m putting the
PalindromeChecker class in the
basicexercises package of my Basic Exercises project. Here’s what I’ve got so far (license header and Javadoc placeholders omitted):
package basicexercises;public class PalindromeChecker {
public static boolean isPalindromic(String s) {
return false;
}
public static void main(String[] args) {
// TODO: Write arg : args loop
}
}
Some people prefer to write the test first, before absolutely anything else. But since you’re going to need some kind of stub before you can even run the test, I think it’s still proper TDD to write the stub first. I might get some disagreement in the comments on this point.
I’m going to let NetBeans take care of the test class boilerplate for me. Then I write this test for
isPalindromic():
@Test
public void testIsPalindromic() {
System.out.println("isPalindromic");
String word = "kayak";
String msg = "\"" + word +
"\" should be considered palindromic";
assertTrue(msg, PalindromeChecker.isPalindromic(word));
}
This test should fail. And indeed it does fail.
Testcase: testIsPalindromic(basicexercises.PalindromeCheckerTest): FAILED
"kayak" should be considered palindromic
junit.framework.AssertionFailedError: "kayak" should be considered palindromic
at basicexercises.PalindromeCheckerTest.testIsPalindromic(PalindromeCheckerTest.java:48)
The easiest way to make this test pass is to change
isPalindromic() so that it returns
true instead of
false. Okay, now the test passes. Big deal, no one is impressed by this.
But this next test should fail:
@Test
public void testIsNotPalindromic() {
String word = "canoe";
String msg = "\"" + word +
"\" should NOT be considered palindromic";
assertFalse(msg, PalindromeChecker.isPalindromic(word));
}
We could revert
isPalindromic(), but then
testIsPalindromic() would fail. So now we actually need to figure out how to tell if
s is palindromic or not.
The most obvious algorithm consists of reversing
s and seeing if that’s the same as
s. Easy, right?
Problem is,
String doesn’t have a
reverse() function. But
StringBuilder does (and we don’t need to import anything extra to use it).
public static boolean isPalindromic(String s) {
StringBuilder intermediate = new StringBuilder(s);
return s.equals(intermediate.reverse().toString());
}
Cross our fingers, run the tests… okay, they both pass now. It’s time now for the refactoring step of TDD.
You might be thinking that there’s a more elegant way to do this, one that doesn’t use
StringBuilder. If you can think of it, you should try it out. If it works, both of the tests will pass. If it doesn’t, one or both of the tests will fail and you will know you need to go back to the drawing board.
However, the point of the refactoring step of TDD is only to improve the function that passes the tests we’ve got so far, not to come up with a completely different function that might make our tests fail again.
But at the same time, the refactoring step isn’t really for minor things like tweaking indentation and spacing. Though such “linting” might help you find something more worthwhile to refactor.
At this early stage, we’re unlikely to have anything that needs refactoring. As the program grows more complex, so do the opportunities for refactoring, generally speaking.
So now we know that
isPalindromic() should work correctly for any
String consisting of lowercase ASCII letters. Should it be case sensitive? Maybe, maybe not. Whatever we decide, we should write a test for it.
Let’s say we decide that we don’t want it to be case sensitive. Then something like “Kayak” should be recognized as a palindrome, even though backwards it would not be capitalized.
As for “Canoe,” that should not be considered palindromic regardless. You can certainly write a test for it if you want, I wouldn’t bother. The tests should be running so fast that the “Canoe” test shouldn’t be a drag on performance.
However, the “Canoe” test is a low-information test. Can you think of any situation in which the “canoe” test would pass but the “Canoe” test would fail? So the “Canoe” test could be seen as cluttering up the test class.
Here’s the “Kayak” test:
@Test
public void testIsPalindromicNotCaseSensitive() {
String word = "Kayak";
String msg = "\"" + word +
"\" should be considered palindromic";
assertTrue(msg, PalindromeChecker.isPalindromic(word));
}
At this point, this test should be failing. The “Canoe” test, if you have it, should be passing.
If you still have
StringBuilder in your implementation of
isPalindromic(), it should be very easy to get it to pass the “Kayak” test.
String does not have a reversing function, but it does have a lowercase function.
public static boolean isPalindromic(String s) {
String lowerCased = s.toLowerCase();
StringBuilder intermediate = new StringBuilder(lowerCased);
return lowerCased.equals(intermediate.reverse().toString());
}
String also has an uppercase function, which you can use instead if you prefer. Neither function should affect characters without a case property. But if you have the slightest doubt, you can write a test, e.g., “7*7,” “l33t.”
How do you feel about palindromes with spaces, punctuation? For example, “A man, a plan, a canal… Panama!” If you want that recognized as a palindrome, don’t think about implementation yet. Write a test first.
And what about emoji? I’ve read that in the Java Virtual Machine, Unicode characters beyond the Basic Multilingual Plane (such as most emoji) are represented by surrogate pairs.
This might possibly mean that something like “😁😁😁” could be misunderstood as a non-palindromic sequence of six characters rather than three instances of the same emoji, which is trivially palindromic.
Again, don’t think about how to implement it just yet. Write a test first.
@Test
public void testIsPalindromicEmoji() {
String emojiSeq = "😁😁😁";
String msg = "\"" + emojiSeq +
"\" should be considered palindromic";
assertTrue(msg, PalindromeChecker.isPalindromic(emojiSeq));
}
If you don’t see the three instances of the emoji in your IDE’s source code editor, you can use the surrogate pair “
\uD83D\uDE01” thrice instead.
You might find that
isPalindromic() passes this test as is, and so you don’t actually need to do anything. It should indeed pass the test, if you stuck with
StringBuilder, rather than try to implement your own reversal function.
The problem has to do with the fact that the
char primitive is limited to the 16-bit characters of Unicode’s Basic Multilingual Plane (BMP). But Unicode did set aside some space in the BMP for “surrogate characters.”
The surrogates work in pairs. On its own, any particular “leading surrogate” is meaningless. But followed by a “trailing surrogate,” it becomes a character in one of Unicode’s extra planes.
In reversing the sequence of characters,
StringBuilder takes care of keeping the surrogate pairs together in the “leading” then “trailing” order as it moves them to a different part of the character sequence.
So, if your custom reversal function doesn’t take care of this detail, you’re going to wind up with a sequence of an unmatched low surrogate, two instances of a valid surrogate pair, and an unmatched high surrogate.
To indicate the presence of unmatched surrogates, your system might display the sequence as “?😁😁?”, and clearly that looks different from “😁😁😁”. For this reason, the palindromic emoji test is worthwhile, even if you don’t see it fail before you see it pass.
Generally, you want to see a test fail and then make it pass. That way, you can be confident that when you run your tests in the future, they will all pass when your program is working correctly according to your specifications, and at least one test will fail if your program is not working correctly.
Some of you might be wondering about the empty
String test. I think that one’s necessary only if you think you might want to use an algorithm that might be thrown off by an empty character sequence, like the comparative algorithm Rosetta Code gives for the R programming language.
Though maybe it’s better to have some tests that seem unnecessary than to not have tests for something that later on breaks in production.
This points up another advantage of TDD. If you’re testing “after the fact,” you could forget to test for some important case that later arises in production. But with TDD, if you thought about it during the design phase and you wrote a test for it, it’s covered now.
Once you’ve got
isPalindromic() working to your satisfaction, turn the program into a command line utility.
public static void main(String[] args) {
for (String arg : args) {
System.out.print("\"" + arg + "\" is");
if (!isPalindromic(arg)) {
System.out.print(" NOT");
}
System.out.println(" palindromic");
}
}
On the DOS command line under Windows, you will probably be limited to a small subset of Unicode characters that you can use to pass
args on to
main(). But you can be confident that
isPalindromic() will work as you expect it to.
So, was this demonstration of TDD better than the wrapped addition example? Please let me know in the comments. | https://alonso-delarte.medium.com/palindrome-checker-is-a-better-basic-example-of-test-driven-development-239a01d11fc8 | CC-MAIN-2021-21 | refinedweb | 1,847 | 63.8 |
One of the important functions of a database administrator is to manage storage structures to optimize performance in a relational database. Admins use tables, views, index, and cubes to tune the database as well as control the behavior of users (e.g., discourage full table scans and cross joins).
There are similar well-known techniques in the big data world. Two factors make it hard to use these techniques in the Hadoop ecosystem. First, none of the open source analytic engines support these techniques natively. This means data engineers need to create these optimizations manually and then document, communicate, and train end users on the data structures to use. This doesn’t scale well for large enterprises. Second, it is very common to use more than one technology or analytic engine to improve performance and accessibility. For example, base tables optimize for scale, so they are hosted in S3 and managed through Apache Hive, while materialized views are stored in a data warehouse like Redshift for fast access.
Quark solves both these problems and helps data engineers manage these storage structures in their big data ecosystem. Before we describe Quark further, let’s first walk through the internal data architecture at Qubole, and where Quark fits in.
The diagram above shows a simplified version of the data infrastructure at Qubole. It is representative of the typical infrastructure we help to run for our customers. The data engineers generate derived datasets of the core transactional data for each type of analysis – ad hoc, reporting and advanced data modeling. In Quark, they are registered as materialized views. Quark then automatically chooses the best dataset and SQL engine for the queries submitted by analysts. This significantly simplifies the model for our analysts and they don’t need to know the underlying data structures when writing SQL queries.
Quark
We have developed and released Quark as an open source project. Quark enables the following use cases:
- Create & manage optimized copies of base tables:
- Narrow tables with important attributes only.
- Sorted tables to speed up filters, joins and aggregation
- Denormalized tables wherein tables in a snowflake schema have been joined.
- OLAP Cubes: Quark supports OLAP cubes on partial data (last 3 months of sales reports for example). It also supports incremental refresh.
- Bring your own database: Quark enables you to choose the technology stack. For example, optimized copies or OLAP cubes can be stored in Redshift or HBase or ElasticSearch and base tables can be in S3 or HDFS and accessed through Hive. This is a powerful feature and data teams can choose the stack best suited to their architectural and cost constraints.
- Rewrite common bad queries: A common example is to miss specifying partition columns which leads to a full table scan. Quark can infer the predicates on partition columns if there are related columns or enforce a policy to limit the data scanned.
We designed Quark with some specific features in mind:
- Compatibility with BI tools: Quark supports ANSI SQL and provides a JDBC driver so that your analyst can use your favorite BI tool, such as Tableau.
- Complex Data Structures: like Maps and Arrays. Useful for mapping JSON.
- SQL Dialects: Quark has to work with multiple SQL engines. We have built the ability to morph the SQL query to match the SQL engine where the dataset is available.
In the future, we hope to build an ETL system that will use metadata in Quark to guide ETL processes.
Architecture
From a user’s perspective, Quark acts like a typical database. It consists of a server and a JDBC client. The JDBC client allows Quark to be used with any BI tool that can submit queries using the JDBC protocol.
Database Administrators
Database administrators are expected to register datasources, define views and cubes. Quark can pull metadata from a multitude of data sources through an extensible Plugin interface. Once the data sources are registered, the tables are referred to as data_source.schema_name.table_name. Quark adds an extra namespace to avoid conflicts. DBAs can define or alter materialized views with DDL statements such as:
create view page_views_partition as select * from hive.default.page_views where timestamp between “Mar 1 2016” and “Mar 7 2016” and group in (“en”, “fr”, “de”) stored in data_warehouse.public.pview_partition
Quark stores its catalog in a database such as MySQL, Postgres or SQLite.
Analysts
Analysts will submit SQL queries to Quark through a command line utility or BI tools like Tableau or notebook interfaces like Apache Zeppelin. The SQL queries should refer to a canonical set of tables. Typically these are tables defined in the Apache Hive metastore.
Internals
Quark’s capabilities are similar to a database optimizer. Internally it uses Apache Calcite which is a cost-based optimizer. It uses the Avatica a sub-project of Apache Calcite to implement the JDBC client and server.
Quark parses, optimizes and routes the query to the most optimal dataset. For example, if the last months of data in
hive.default.page_views are in a data warehouse, Quark will execute queries in the data warehouse instead of the table in Apache Hive.
Community
Quark has already proved useful for internal uses cases at Qubole as well as at a few of Qubole’s customers. However, there is much more work to be done, and we’d love for you to get involved. Quark is fully open source software, licensed under the Apache Software License 2.0.
Resources for getting involved:
- Source Code:
- Mailing List: [email protected]groups.com
- Gitter:
Summary
Quark is a system that can manage metadata of datasets for ETL engineers. It also helps analysts to use the right dataset for their reports. Quark supports JDBC. It is designed to work well with current investments made by the data team both for data storage systems and reporting tools. We welcome feedback and suggestions and also for developers to get involved in the open source project. | https://www.qubole.com/blog/quark-control-and-optimize-sql-across-hadoop-and-rdbms/ | CC-MAIN-2021-43 | refinedweb | 985 | 64.2 |
On 06 October 2005 18:46, Krasimir Angelov wrote: > 2005/10/6, Simon Marlow <simonmar at microsoft.com>: >> --bindirrel=<dir> >> --libdirrel=<dir> >> --datadirrel=<dir> >> --libexecdirrel=<dir> > > bindirrel, libdirrel, ... looks a little bit verbose. Why not just > bindir/libdir? Because bindir/libdir are already used by autoconf with a different meaning. >>. > >) Yes, in fact it is: getDataDir :: IO FilePath getDataDir = do mb_path <- getPrefix binDirRel return (fromMaybe prefix mb_path `joinFileName` dataDirRel) > I think that is better to add these templates to Paths.hs-inc. Fine by me. One problem is that I need to use stuff from Distribution.Compat.FilePath, which isn't available outside Cabal, and in any case we don't want every package to depend on Cabal. I might have to include a definition of joinFileName in Paths.hs-inc too. >. A library cannot be prefix-independent, only an executable. That was the assumption I was working with, sorry for not making it clear. >> That's sounds like a reasonable default. The current defaults for a library on Windows are: prefix = C:\Program Files\ bindirrel = $package libdirrel = Haskell\$package\$compiler datadirrel = $package libexecdirrel = $package you suggest changing datadirrel to: datadirrel = Common Files\$package and on Unix, for completeness: prefix = /usr/local bindirrel = bin libdirrel = lib/$package/$compiler datadirrel = share/$package libexecdirrel = libexec > This might sense for Unix too. For some libraries it might be prefered > to use /etc/<package>, so the datadir isn't necessary relative to the > prefix. No, I think we want datadir to be relative to prefix. It should be possible to install a library in your home directory, for example. Cheers, Simon | http://www.haskell.org/pipermail/libraries/2005-October/004414.html | CC-MAIN-2014-35 | refinedweb | 267 | 57.37 |
The Python Standard Library: Data Structures
- 2.
import collections print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) print collections.Counter({'a':2, 'b':3, 'c':1}) print collections.Counter(a=2, b=3, c=1)
The results of all three forms of initialization are the same.
$ python collections_counter_init.py Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1})
An empty Counter can be constructed with no arguments and populated via the update() method.
import collections c = collections.Counter() print 'Initial :', c c.update('abcdaab') print 'Sequence:', c c.update({'a':1, 'd':5}) print 'Dict :', c
The count values are increased based on the new data, rather than replaced. In this example, the count for a goes from 3 to 4.
$ python collections_counter_update.py Initial : Counter() Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1}) Dict : Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})
Accessing Counts
Once a Counter is populated, its values can be retrieved using the dictionary API.
import collections c = collections.Counter('abcdaab') for letter in 'abcde': print '%s : %d' % (letter, c[letter])
Counter does not raise KeyError for unknown items. If a value has not been seen in the input (as with e in this example), its count is 0.
$ python collections_counter_get_values.py a : 3 b : 2 c : 1 d : 1 e : 0', 'x']
Use most_common() to produce a sequence of the n most frequently encountered input values and their respective counts.
import collections c = collections.Counter() with open('/usr/share/dict/words', 'rt') as f: for line in f: c.update(line.rstrip().lower()) print 'Most common:' for letter, count in c.most_common(3): print '%s: %7d' % (letter, count)
This example counts the letters appearing in all words in the system dictionary to produce a frequency distribution, and then prints the three most common letters. Leaving out the argument to most_common() produces a list of all the items, in order of frequency.
$ python collections_counter_most_common.py Most common: e: 234803 i: 200613 a: 198938
Arithmetic
Counter instances support arithmetic and set operations for aggregating results.
import collections c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) c2 = collections.Counter('alphabet') print 'C1:', c1 print 'C2:', c2 print '\nCombined counts:' print c1 + c2 print '\nSubtraction:' print c1 - c2 print '\nIntersection (taking positive minimums):' print c1 & c2 print '\nUnion (taking maximums):' print c1 | c2
Each time a new Counter is produced through an operation, any items with zero or negative counts are discarded. The count for a is the same in c1 and c2, so subtraction leaves it at zero.
$ python collections_counter_arithmetic.py C1: Counter({'b': 3, 'a': 2, 'c': 1}) C2: Counter({'a': 2, 'b': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1}) Combined counts: Counter({'a': 4, 'b': 4, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1}) Subtraction: Counter({'b': 2, 'c': 1}) Intersection (taking positive minimums): Counter({'a': 2, 'b': 1}) Union (taking maximums): Counter({'b': 3, 'a': 2, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1}), as list,)): 4 Right: 3 Left: 1 Right: 2 Left done Right done
Rotating:
-. | https://www.informit.com/articles/article.aspx?p=1719315&seqNum=8 | CC-MAIN-2021-10 | refinedweb | 532 | 61.97 |
Not logged in
Log in now
Recent Features
LWN.net Weekly Edition for May 24, 2012
A uTouch architecture introduction
LWN.net Weekly Edition for May 17, 2012
Tasting the Ice Cream Sandwich
Highlights from the PostgreSQL 9.2 beta
ChangeSet@1.664, 2002-09-30 23:56:34-07:00, torvalds@home.transmeta.com
Linux v2.5.40
TAG: v2.5.40
ChangeSet@1.661.1.6, 2002-09-30 19:33:46-07:00, david@gibson.dropbear.id.au
[PATCH] Squash warning in fs/devfs/base.c
This removes an unused label in fs/devfs/base.
ChangeSet@1.660.1.8, 2002-09-30 16:40:06-07:00, greg@kroah.com
USB: fix typo from previous schedule_task() patch..
ChangeSet@1.660.1.6, 2002-09-30 16:11:26-07:00, greg@kroah.com
USB: allow /sbin/hotplug to be called for the main USB device.
ChangeSet@1.660.1.5, 2002-09-30 16:09:50-07:00, greg@kroah.com
USB: Fix the name of usb hubs in driverfs.
ChangeSet@1.660.1.4, 2002-09-30 16:09:11-07:00, greg@kroah.com
USB: add a lot more driverfs files for all usb devices..
ChangeSet@1.660.1.2, 2002-09-30 16:05:03-07:00, greg@kroah.com
USB: added Palm Zire id to the visor driver, thanks to Martin Brachtl
ChangeSet@1.620.10.10, 2002-10-01 00:04:09+01:00, rmk@flint.arm.linux.org.uk
[ARM] iPAQ updates from Jamey Hicks
ChangeSet@1.620.10.9, 2002-09-30 23:57:43+01:00, rmk@flint.arm.linux.org.uk
[ARM] General cleanups/missed bits in previous csets
This corrects spelling mistakes, adds missed configuration for
cpufreq, corrects free_irq comment, etc.
ChangeSet@1.660.1.1, 2002-09-30 15:54:02-07:00, greg@kroah.com
USB: queue_task() fixups
ChangeSet@1.661.1.3, 2002-09-30 15:46:51-07:00, davej@codemonkey.org.uk
[PATCH] include fix
Trivial include file fix..
ChangeSet@1.661.1.2, 2002-09-30 15:46:24-07:00, davej@codemonkey.org.uk
[PATCH] Various trivial module related fixes.
More bits from 2.5.39-dj sucked out by Adrian Bunk.
- drivers/char/toshiba.c: add
MODULE_{PARM_DESC,AUTHOR,DESCRIPTION,SUPPORTED_DEVICE}
- drivers/mtd/nand/nand_ecc.c: add MODULE_{AUTHOR,DESCRIPTION}
- drivers/net/skfp/skfddi.c: add MODULE_AUTHOR
- drivers/net/tokenring/olympic.c: remove "\n" at the end of
MODULE_DESCRIPTION
- fs/driverfs/inode.c: add MODULE_LICENSE
- fs/nls/nls_cp1250.c: correct MODULE_LICENSE
- include/linux/module.h: add "GPL v2" to the list of free software
licenses
ChangeSet@1.661.1.1, 2002-09-30 15:45:33-07:00, davej@codemonkey.org.uk
[PATCH] trivial bits.
Adrian Bunk went through .39-dj, and pulled out a bunch of
trivial bits (docs changes, whitespace fixes etc)
- CREDITS: update the web-address of Tigran A. Aivazian
- Documentation/Changes: higher minimum version of reiserfsprogs
- s/ in:
- Documentation/DocBook/sis900.tmpl
- Documentation/kernel-docs.txt
- Documentation/scsi-generic.txt
- Documentation/scsi.txt
- Documentation/sound/oss/PAS16
- Documentation/filesystems/isofs.txt: document where to get ISO 9660
docs from
- Documentation/networking/00-INDEX: document that e100.txt and e1000.txt
are present
- typo fixes in:
- Documentation/networking/ip-sysctl.txt
- Documentation/s390/Debugging390.txt
- drivers/ide/Config.help
- MAINTAINERS:
- update location of the emu10k1-devel and linux-mips lists
- Remy Card is no longer ext2 maintainer
- list Andrew Morton instead of Remy Card as second ext3 maintainer
- update mail addresses of Riley H. Williams and Jack Hammer
- misc whitespace -> tab fixes
- arch/mips/kernel/time.c: correct the location of a README
- whitespace -> tab fixes in
drivers/net/{3c505,3c509,arcnet/arcnet,at1700,hamradio/scc,ni65,
pcmcia/aironet4500_cs}.c and drivers/net/wan/lmc/lmc_var.h
- drivers/pci/quirks.c: update URL
- remove tabs/whitespace at the end of lines in:
- drivers/tc/lk201-map.map
- drivers/tc/lk201-remap.c
- drivers/tc/zs.h
- fs/jfs/jfs_logmgr.c: remove two extra empty lines
- include/linux/auto_fs.h: s/__x86_64/__x86_64__/
ChangeSet@1.620.10.8, 2002-09-30 23:15:45+01:00, rmk@flint.arm.linux.org.uk
[ARM] Prevent namespace clash with IRq numbering
Add "IRQ_" prefix to these sa1111 irq numbers.
ChangeSet@1.620.10.7, 2002-09-30 22:57:26+01:00, rmk@flint.arm.linux.org.uk
[ARM] Fix sa1111 IRQ handling
We must clear down all currently pending IRQs before servicing any
IRQ on the chip. This prevents immediate recursion into the
interrupt handling paths when we service the first IRQ.
ChangeSet@1.620.10.6, 2002-09-30 22:45:29+01:00, rmk@flint.arm.linux.org.uk
[ARM] Update cpufreq related sa1100 related drivers and CPU code
This cset updates sa1100 code for the now merged cpufreq next-gen.
ChangeSet@1.620.16.4, 2002-09-30 17:43:45-04:00, andmike@us.ibm.com
Error handler general clean up
ChangeSet@1.620.16.3, 2002-09-30 17:41:12-04:00, fokkensr@fokkensr.vertis.nl
[PATCH] sg.c and USER_HZ, kernel 2.5.37
Hi!
Since the introduction of USER_HZ the SG_[GS]ET_TIMEOUT ioctls may have
a serious BUG as userspace uses a different HZ from the HZ in kernelspace.
In x86 HZ=1000 and USER_HZ=100, resulting in confusing timouts as the
kernel measures time 10 times as fast as userspace.
This patch is an attempt to fix this by transforming USER_HZ based timing to
HZ based timing before storing it in timeout. To make sure that SG_GET_TIMEOUT
and SG_SET_TIMEOUT behave consistently a field timeout_user is added which
stores the exact value that's passed by SG_SET_TIMEOUT and it's returned on
SG_GET_TIMEOUT.
Rolf Fokkens
fokkensr@fokkensr.vertis.nl
P.S. this is the second post of this patch
ChangeSet@1.620.16.2, 2002-09-30 17:39:32-04:00, jejb@mulgrave.(none)
[SCSI 53c700] flag as able to do I/O from highmem
ChangeSet@1.620.16.1, 2002-09-30 17:38:52-04:00, akpm@zip.com.au
scsi_initialise_merge_fn() will only set highio if ->type == TYPE_DISK.
But it's called from scsi_add_lun()->scsi_alloc_sdev() before the type
is known. The type is -1 all the time in scsi_initialise_merge_fn()
and scsi always bounces.
This patch makes it do the right thing - just enable block-highmem for
all scsi devices.
Jens had this to say:
"I guess that block-highmem has been around long enough, that I can
use the term 'historically' at least in the kernel sense :-)
This extra check was added for IDE because each device type driver
(ide-disk, ide-cd, etc) needed to be updated to not assume virtual
mappings of request data was valid. I only did that for ide-disk,
since this is the only one where bounce buffering really hurt
performance wise. So while ide-cd and ide-tape etc could have been
updated, I deemed it uninteresting and not worthwhile.
Now, this was just carried straight into the scsi counter parts,
conveniently, because of laziness. A quick glance at sr shows that it
too can aviod bouncing easily (no changes needed). st may need some
changes, though. So again, for scsi it was a matter of not impacting
existing code in 2.4 too much.
So TYPE_DISK check can be killed in 2.5 if someone does the work of
checking that it is safe. I'm not so sure it will make eg your SCSI
CD-ROM that much faster :-)"
ChangeSet@1.620.10.5, 2002-09-30 22:20:40+01:00, rmk@flint.arm.linux.org.uk
[ARM] sa1100fb updates
Update sa1100fb for recent fbcon changes, and move stork LCD power
handling into machine specific file.
ChangeSet@1.661, 2002-09-30 14:10:35-07:00, linux@brodo.de
[PATCH] cpufreq crashes on P4
In two drivers a wrong size of memory was allocated for cpufreq_driver: as
it must include NR_CPUS times a struct cpufreq_policy (and not struct
cpufreq_freqs). Thanks to Petr Vandrovec for this patch.
ChangeSet@1.660, 2002-09-30 13:23:37-07:00, willy@debian.org
[PATCH] Remove QDIO_BH
QDIO_BH was never actually used anyway, and won't do much good now BHs
are gone.
ChangeSet@1.659, 2002-09-30 13:22:56-07:00, viro@math.psu.edu
[PATCH] alloc_disk/put_disk
Beginning of proper refcounting. New helpers introduced, several drivers
switched to using them for dynamic allocation of gendisks. Once everything
is switched (and that will be way easier than per-drive gendisks series)
we will be able to add sane reference counts on gendisk, at which point
we can safely put pointer to gendisk in struct block_device / struct request
and we had pretty much won - from that point it's pretty straightforward
crapectomy in drivers.
ChangeSet@1.658, 2002-09-30 13:21:56-07:00, viro@math.psu.edu
[PATCH] ->major_name inlined
char *major_name replaced with char disk_name[16]; All uses of ->major_name
replaced with those of ->disk_name and (obviously) simplified big way. Bunch
of arrays, kmallocs, etc. is gone.
ChangeSet@1.620.10.4, 2002-09-30 21:04:23+01:00, rmk@flint.arm.linux.org.uk
[ARM] Remove "struct device" from sa1111_init() callers
This didn't follow the LDM model correctly. The SA1111 is always
a device on the root bus.
ChangeSet@1.657, 2002-09-30 12:42:46-07:00, viro@math.psu.edu
[PATCH] register_disk() unexported
... now it can be done. We also drop almost all arguments - there is only
one caller and everything is determined by the first argument.
ChangeSet@1.656, 2002-09-30 12:42:14-07:00, viro@math.psu.edu
[PATCH] ubd fixes
Cleans the handling of partitioning up. More or less the same story as with
other drivers...
ChangeSet@1.655, 2002-09-30 12:41:46-07:00, viro@math.psu.edu
[PATCH] floppy fixes
corrected handling of sizes. Ugh.
ChangeSet@1.654, 2002-09-30 12:41:32-07:00, viro@math.psu.edu
[PATCH] get_gendisk() prototype change
get_gendisk() now takes dev_t (instead of kdev_t) and gets an additional
argument - int *part. Set to 0 for non-partitioned, partition number
for partititoned. Callers updated. Yes, I hate passing return values
that way ;-/ We need that since old "minor(dev) - disk->first_minor"
doesn't work for stuff with non-trivial numbers (e.g. floppy) and
get_gendisk() really has to return both gendisk and partition number.
Fortunately, amount of callers of gendisk() is about to drop RSN big way...
ChangeSet@1.653, 2002-09-30 12:41:00-07:00, viro@math.psu.edu
[PATCH] gendisks list switched to list_head
The list used to generate /proc/partitions turned into list_head one;
we also restore the old order of elements (originally we added to the end
of list; recent changes had reverted that, now we are back to original
order).
ChangeSet@1.652, 2002-09-30 12:36:06-07:00, axboe@suse.de
[PATCH] set ide pci dma mask
Make IDE set the dma mask to full 32-bit dma.
ChangeSet@1.651, 2002-09-30 12:35:48-07:00, axboe@suse.de
[PATCH] loop clear q->queuedata on exit
Just for niceness, loop should clear queue queuedata when it exits.
ChangeSet@1.650, 2002-09-30 12:35:16-07:00, axboe@suse.de
[PATCH] raid5 BIO_UPTODATE set
These days we only require a clear of BIO_UPTODATE on -EIO, we don't set
it on success. This breaks raid5. It appears to clear BIO_UPTODATE fine
but doesn't start out with it set.
ChangeSet@1.649, 2002-09-30 12:34:45-07:00, axboe@suse.de
[PATCH] make loop set right queue restrictions
This makes loop honor the queue restrictions by basically stacking all
of those, and mirroring the merge_bvec_fn() on the target queue. It also
switches loop to use per-loop device queues, since that is the only sane
way to do this from a performance POV. Also, in principle I find it to
be much nicer if every distinct block device has its own queue.
ChangeSet@1.648, 2002-09-30 12:34:11-07:00, axboe@suse.de
[PATCH] don't BUG() on too big a bio
There's really no reason to BUG() out on a bio that is too big, the
gentleman thing to do would be to print a warning and just end the bio
with -EIO quietly.
ChangeSet@1.647, 2002-09-30 12:33:53-07:00, axboe@suse.de
[PATCH] add function to set q->merge_bvec_fn
Add a function to set queue merge_bvec_fn to mimic the rest of the api,
and also add documentation for that and blk_queue_prep_rq().
ChangeSet@1.646, 2002-09-30 12:33:22-07:00, axboe@suse.de
[PATCH] request_irq() use GFP_ATOMIC
The might_sleep() thing caught ide, which calls request_irq() with a
lock held. It can be argued that this is a bad thing, however I think it
can also validly be argued that requesting an irq should not be a
blocking operation. This might even remove some driver bugs where usage
count is not incremented during init...
It can also be argued, that the very first irq requests cannot be
blocking for io anyways, for good reason :-)
ChangeSet@1.620.10.3, 2002-09-30 20:32:40+01:00, rmk@flint.arm.linux.org.uk
[ARM] Add LDM suspend/resume support to SA1100 suspend code.
ChangeSet@1.620.10.2, 2002-09-30 20:23:43+01:00, rmk@flint.arm.linux.org.uk
[ARM] Update SA1111 core and related drivers for LDM.
This cset updates the SA1111 core, PCMCIA, OHCI and keyboard drivers,
allowing them to take advantage of the Linux device manager code;
this implements initial suspend/resume support for the SA1111 in the
core. Many existing drivers currently rely on the old PM-based
interface for suspend/resume support.
ChangeSet@1.645, 2002-09-30 12:02:20-07:00, bzeeb-lists@lists.zabbadoz.net
[PATCH] fix endless loop walking the MADT
Too trivial to see the first time when debugging on weekends ;-))
ChangeSet@1.644, 2002-09-30 11:48:41-07:00, torvalds@penguin.transmeta.com
Merge
into penguin.transmeta.com:/home/penguin/torvalds/repositories/kernel/linux
ChangeSet@1.620.1.37, 2002-09-30 10:25:00-07:00, mingo@elte.hu
[PATCH] sigfix-2.5.39-D0, BK-curr
This fixes a procfs crash noticed by Anton Blanchard.
The procfs code can have a reference even to an already exited task, so
it needs to follow special rules accessing p->sig. The atomic-signals
patch made this bug happen at a much higher frequency, but procfs i
believe was buggy ever since, it potentially used the freed signal
structure - which just did not result in a crash like it does today.
The proper fix is to take the tasklist read-lock in
collect_sigign_sigcatch(), this excludes __exit_sighand() freeing the
signal structure prematurely.
ChangeSet@1.620.14.6, 2002-09-30 01:29:41-07:00, davem@nuts.ninka.net
sound/pci/cs46xx/dsp_spos.c: Include linux/vmalloc.h
ChangeSet@1.620.14.5, 2002-09-30 01:13:24-07:00, davem@nuts.ninka.net
sound/sparc/cs4231.c: Include sound/pcm_params.h
ChangeSet@1.640, 2002-09-30 01:09:05-07:00, davem@nuts.ninka.net
drivers/net/ethertap.c: Use C99 initializers.
ChangeSet@1.620.14.4, 2002-09-29 23:57:49-07:00, davem@nuts.ninka.net
drivers/input/keyboard/sunkbd.c: queue_task --> schedule_task
ChangeSet@1.620.14.3, 2002-09-29 23:24:24-07:00, davem@nuts.ninka.net
[SPARC]: Rename private init_timers to sparc{,64}_init_timers.
ChangeSet@1.618.1.7, 2002-09-30 03:18:40-03:00, acme@conectiva.com.br
. LLC: kill mac_send_pdu, use plain dev_queue_xmit
With this we avoid doing skb_clone on skbs that will not be kept on
unacked lists.
ChangeSet@1.620.14.2, 2002-09-29 23:14:16-07:00, davem@nuts.ninka.net
[SPARC]: sigmask_lock --> sig->siglock
ChangeSet@1.620.14.1, 2002-09-29 23:10:41-07:00, davem@nuts.ninka.net
Resolve conflicts with recent ALSA merge.
ChangeSet@1.620.1.36, 2002-09-30 02:09:09-04:00, jgarzik@mandrakesoft.com
Replace local var in 8139cp net driver that was accidentally removed,
due to synchronize_irq() becoming a no-op when !CONFIG_SMP.
ChangeSet@1.603.2.11, 2002-09-29 23:05:28-07:00, davem@nuts.ninka.net
arch/sparc64/kernel/pci_schizo.c: Enable error interrupts in correct PBM.
ChangeSet@1.620.1.35, 2002-09-29 22:13:32-07:00, david@gibson.dropbear.id.au
[PATCH] Fix: Orinoco driver update
Crud. Looks like my patch making script was borken, so orinoco_pci.c
wasn't updated properly. The patch below should fix that, and adds
some other minor updates (driver version 0.13a) as well.
ChangeSet@1.620.1.34, 2002-09-29 22:08:07-07:00, david-b@pacbell.net
[PATCH] Sleeping function called from illegal context...
Fix pci_pool_create() from calling device_create_file() under
pools_lock.
Found by the new "may_sleep" infrastructure.
ChangeSet@1.620.1.33, 2002-09-29 22:07:56-07:00, torvalds@home.transmeta.com
All .tmp* files are auto-generated
ChangeSet@1.620.7.4, 2002-09-30 00:02:33-04:00, jdike@uml.karaya.com
main.o needed to be added to the vmlinux dependencies so it would build.
ChangeSet@1.618.1.6, 2002-09-30 00:11:19-03:00, acme@conectiva.com.br
o LLC: make sure llc.o is linked before the datalink protos when !module
Thanks do Andries Brouwer for reporting the problem and suggesting a
way to fix it.
ChangeSet@1.620.1.30, 2002-09-29 21:59:54-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move dial/hangup related stuff to isdn_net_dev
Keeping track of dialing / auto hangup is per ISDN channel, so should
go into isdn_net_dev.
ChangeSet@1.620.7.3, 2002-09-29 22:43:05-04:00, jdike@uml.karaya.com
Moved the linker script from vmlinux.lds.S, which will be empty, to
uml.ld.S.
ChangeSet@1.620.1.29, 2002-09-29 21:19:12-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move ppp-specifics to isdn_net_dev
Again, ipppd has one kernel connection per channel in a MPPP
setting, so we should keep track in isdn_net_dev.
ChangeSet@1.579.15.5, 2002-09-29 22:18:25-04:00, jdike@uml.karaya.com
Added CONFIG_HIGHMEM to defconfig.
ChangeSet@1.579.15.4, 2002-09-29 22:02:45-04:00, jdike@uml.karaya.com
One last fix to make the non-highmem build work.
ChangeSet@1.620.12.3, 2002-09-29 21:56:46-04:00, jgarzik@mandrakesoft.com
Use do_gettimeofday() in ATM drivers
(contributed by Francois Romieu)
ChangeSet@1.620.9.72, 2002-09-29 18:49:07-07:00, davidm@napali.hpl.hp.com
[PATCH] avoid reference to struct page before it's declared
GCC currently warns when page-flags.h gets included before struct page
is declared. Declare it.
ChangeSet@1.620.12.2, 2002-09-29 21:47:38-04:00, jgarzik@mandrakesoft.com
Include linux/tqueue.h in orinoco[_cs] net drvrs, fixing build
(contributed by James Blackwell)
ChangeSet@1.620.12.1, 2002-09-29 21:45:44-04:00, jgarzik@mandrakesoft.com
Use schedule_task() in tlan net driver, fixing build
ChangeSet@1.620.9.71, 2002-09-29 18:22:17-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/cramfs
ChangeSet@1.620.9.70, 2002-09-29 18:22:12-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/ufs
ChangeSet@1.620.9.69, 2002-09-29 18:22:07-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/isofs
ChangeSet@1.620.9.68, 2002-09-29 18:22:02-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/proc
ChangeSet@1.620.9.67, 2002-09-29 18:21:57-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/romfs
ChangeSet@1.620.9.66, 2002-09-29 18:21:53-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializer patch for fs/devpts.
ChangeSet@1.620.9.65, 2002-09-29 18:21:48-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializer patch for fs/exportfs
ChangeSet@1.620.9.64, 2002-09-29 18:21:41-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializer patch for fs/ramfs
ChangeSet@1.620.9.63, 2002-09-29 18:21:36-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializer patch for fs/openpromfs
ChangeSet@1.620.9.62, 2002-09-29 18:21:31-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/efs
ChangeSet@1.620.9.61, 2002-09-29 18:21:26-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializers for fs/minix
ChangeSet@1.620.9.60, 2002-09-29 18:21:21-07:00, ahaas@neosoft.com
[PATCH] C99 designated initializer for fs/bfs
ChangeSet@1.620.9.59, 2002-09-29 18:19:33-07:00, torvalds@home.transmeta.com
Make sure the "devices" list is initialized in isapnp_device_driver
ChangeSet@1.620.9.58, 2002-09-29 18:10:37-07:00, wim@iguana.be
[PATCH] i810-tco update
i810-tco: Upgrade to version 0.05 .
Fix possible timer_alive race, add expect close support,
clean up ioctls (WDIOC_GETSTATUS, WDIOC_GETBOOTSTATUS and
WDIOC_SETOPTIONS), made i810tco_getdevice __init,
removed boot_status, removed tco_timer_read,
added support for 82801DB and 82801E chipset, general cleanup.
ChangeSet@1.620.9.57, 2002-09-29 18:10:32-07:00, wim@iguana.be
[PATCH] i8xx: new PCI ids
Add defines to pci_ids.h for 82801E and 82801DB I/O Controller Hub PCI-IDS.
ChangeSet@1.620.9.56, 2002-09-29 18:10:27-07:00, wim@iguana.be
[PATCH] i8xx documentation
Make i810_rng documentation the same as in 2.4.19
ChangeSet@1.620.9.55, 2002-09-29 18:06:43-07:00, rmk@arm.linux.org.uk
[PATCH] free_irq
Fix free_irq() comment - it definitely is not callable
from interrupt context..
ChangeSet@1.636, 2002-09-29 18:01:58-07:00, bart.de.schuymer@pandora.be
net/bridge/br_input.c: Missing read_unlock.
ChangeSet@1.620.9.54, 2002-09-29 18:01:34-07:00, hirofumi@mail.parknet.co.jp
[PATCH] remove fat_search_long() in vfat_add_entry()
This removes the fat_search_long() in the vfat_add_entry(). This path
is already checked by the vfs layer whether file/directory exists. So,
we don't need the fat_search_long() in vfat_add_entry().
The following is the result of created the 1000 files,
2.5.39
root@devron (a)[1007]# time ../../create
real 0m2.761s
user 0m0.006s
sys 0m2.752s
root@devron (a)[1008]#
2.5.39 + patch
root@devron (a)[1007]# time ../../create
real 0m1.601s
user 0m0.008s
sys 0m1.575s
root@devron (a)[1008]#
ChangeSet@1.620.9.53, 2002-09-29 18:01:29-07:00,.
[Randy Dunlap, I appreciate your help.]
ChangeSet@1.635, 2002-09-29 17:56:52-07:00, schoenfr@gaaertner.de
net/ipv4/proc.c: Dont print dummy member of icmp_mib.
ChangeSet@1.603.2.10, 2002-09-29 17:49:03-07:00, zaitcev@redhat.com
[sparc] Suppress warnings in srmmu printks.
ChangeSet@1.603.2.9, 2002-09-29 17:47:21-07:00, zaitcev@redhat.com
[sparc] Stalingrad for kbuild army.
ChangeSet@1.620.9.52, 2002-09-29 17:07:54-07:00, linux@brodo.de
[PATCH] cpufreq bugfixes
- incorrect pointer calculation spotted by Gerald Britton
- speedstep.c cleanup (Gerald Britton)
ChangeSet@1.620.9.51, 2002-09-29 17:07:01-07:00, torvalds@home.transmeta.com
Fix broken whitespacing in PPC Makefile
ChangeSet@1.620.9.50, 2002-09-29 16:47:05-07:00, perex@suse.cz
[PATCH] ALSA update [10/10] - 2002/08/05
- CS46xx
- fixed capture with new DSP firmware
- multiple pcm playback streams
- pcm playback instance is allocated dynamically
- fixed detection of secondary codec
- changed ctl/rawmidi/timer read() code to follow POSIX standard - when some data are ready, return immediately
- RME96 - added 32 bit sample formats for ADAT
ChangeSet@1.620.9.49, 2002-09-29 16:47:00-07:00, perex@suse.cz
[PATCH] ALSA update [9/10] - 2002/08/01
- CS46xx - added support for the new DSP image
- S/PDIF and dual-codec support
- sequencer
- fixed deadlock at snd_seq_timer_start/stop
ChangeSet@1.620.9.48, 2002-09-29 16:46:55-07:00, perex@suse.cz
[PATCH] ALSA update [8/10] - 2002/07/31
- AC'97 codec
- added reset callback to do reset and skip the standard procedure
- added limited_regs flag to avoid to touch unexpected registers
- Fixes for AD1981A and added a special patch for an intel motherboard
- sequencer
- check the possible infinite loop in priority queues
- reset the timer at continue if not initialized yet
- changed synchronize_irq() for new api with an argument
- NM256 driver - fixes the lock up on NM256 ZX
- VIA8233 - implementation of SG buffer
ChangeSet@1.620.9.47, 2002-09-29 16:46:44-07:00, perex@suse.cz
[PATCH] ALSA update [7/10] - 2002/07/24
- renamed snd-dt0197h to snd-dt019x
- added support for DT0196, DT0197h and ALS007 to snd-dt019x
- searial-u16550 - added support for generic adapter type
- pcm.c
- fixed the initialization of runtime->status
- removed unnecessary check of n_register callback
- timer.c
- fixed kmod behaviour
- Opti92x/93x fixes by Michael Corlett
- fixed compilation of YMFPCI driver (PPC)
ChangeSet@1.620.9.46, 2002-09-29 16:46:11-07:00, perex@suse.cz
[PATCH] ALSA update [6/10] - 2002/07/20
- added vfree_nocheck()
- PCM midlevel & EMU10K1 - added support for SG buffer
- CS4236 - added new ISA PnP ID
- HDSP - fixed rate rules (OSS emulation works)
ChangeSet@1.620.9.45, 2002-09-29 16:46:02-07:00, perex@suse.cz
[PATCH] ALSA update [5/10] - 2002/07/17
- AD1816A - fixed MIC playback volume
- OPL3SA2 - fixed non-ISA PnP build
- AC'97 code - 1st version of separated codec specific code
ChangeSet@1.620.9.44, 2002-09-29 16:45:57-07:00, perex@suse.cz
[PATCH] ALSA update [4/10] - 2002/07/14
- seq_virmidi - exported snd_virmidi_receive() for processing the incoming events from the event handler of a remote virmidi port.
- pcm_lib.c - fixed wrong spinlock
- AC'97 code
- added VIA codecs, fixed order
- added S/PDIF support for Conexant CX20468
- ALI5451 - fixed wrong spinlock
- ES1968 - fixed wrong mutex
- ICE1712 - fixed SMP dead-lock
- HDSP driver update
- RME9652 - fixed wrong spinlock
ChangeSet@1.620.9.43, 2002-09-29 16:45:51-07:00, perex@suse.cz
[PATCH] ALSA update [3/10] - 2002/07/03
- added support for spdif on coexant cx20468 chip
- fixed compilation without CONFIG_PROC_FS
- YMFPCI driver
- fixed GPIO read/write
- a new module option snd_rear_switch
- ioctl32 - added support for old hw_params ioctl
- ES1968 driver
- enabled hw control IRQ
- calling es1968_reset() in free()
- VIA8233 driver - fixes for mono playback
ChangeSet@1.620.9.42, 2002-09-29 16:45:46-07:00, perex@suse.cz
[PATCH] ALSA update [2/10] - 2002/06/26
- Enhanced bitmasks in PCM - added support for more formats by Takashi and me
- RME32 driver - added support for ADAT (Digi 32/8)
ChangeSet@1.620.9.41, 2002-09-29 16:45:41-07:00, perex@suse.cz
[PATCH] ALSA update [1/10] - 2002/06/24
- ioctl32 emulation update
- intel8x0 driver
- fixed PCI ID of AMD8111
- compilation fixes for HDSP
- fixes for PCI memory allocation
ChangeSet@1.620.9.40, 2002-09-29 16:20:47-07:00, akpm@digeo.com
[PATCH] topology API updates
From Matthew Dobson.
Leaves any functions which architectures haven't defined as undefined,
rather than using non-NUMA functions where users would expect
NUMA-functions.
This will cause compilation errors if someone tries to use an undefined
function, hopefully causing them to actually define those functions.
Also removes lingering topology-like macros that aren't being used, and
a couple typo fixes.
ChangeSet@1.620.9.39, 2002-09-29 16:20:40-07:00, akpm@digeo.com
[PATCH] in-kernel topology API
From Matthew Dobson <colpatch@us.ibm.com>
"This patch adds a 'simple' in-kernel topology API. This API allows
for three primary topology elements: CPUs, memory blocks, and nodes.
The API allows for the discovery of which CPUs/Memory Blocks reside on
which nodes, and vice versa. Also implemented is a macro to get a
bitmask of CPUs on a particular node. This API is platform neutral."
We need this API for per-node-kswapd - without it there is no means by
which each kswapd can be bound to its node's CPUs. And we rather need
per-node-kswapd...
The patch also uses the new API to bind each kswapd instance to its
node's CPUs
ChangeSet@1.620.9.38, 2002-09-29 16:20:34-07:00, akpm@digeo.com
[PATCH] per-node kswapd instances
Patch from David Hansen.
Start one kswapd instance for each NUMA node. That kswapd instance
only works against the pages which are local to that node.
We need to bind that kswapd to that node's CPU set, but the
infrastructure for this is not yet in place.
ChangeSet@1.620.9.37, 2002-09-29 16:20:30-07:00, akpm@digeo.com
[PATCH] remove free_area_t typedef
typedef eradication.
ChangeSet@1.620.9.36, 2002-09-29 16:20:25-07:00, akpm@digeo.com
[PATCH] add /proc/buddyinfo
From David Hansen, Bill Irwin, Martin Bligh.
"It's easier to cat /proc/buddyinfo than to beg users to press
shift-scrolllock on a machine millions of miles away. Order 1 and 2
memory allocations are common. Memory fragmentation is a problem
under some workloads, and this is a useful tool for helping diagnose
these problems."
The following patch exports some information about the buddy allocator.
Each column of numbers represents the number of pages of that order
which are available. In this case, there are 5 chunks of
2^2*PAGE_SIZE available in ZONE_DMA, and 101 chunks of 2^4*PAGE_SIZE
availble in ZONE_NORMAL, etc... This information can give you a good
idea about how fragmented memory is and give you a clue as to how big
an area you can safely allocate.
Node 0, zone DMA 0 4 5 4 4 3 ...
Node 0, zone Normal 1 0 0 1 101 8 ...
Node 0, zone HighMem 2 0 0 1 1 0 ...
ChangeSet@1.620.9.35, 2002-09-29 16:20:20-07:00, willy@debian.org
[PATCH] remove GFP_NFS
GFP_NFS has been obsolete for a while now. Kill its only remaining
user, its definition and the SLAB_NFS define too.
ChangeSet@1.620.9.34, 2002-09-29 16:20:15-07:00, akpm@digeo.com
[PATCH] fix uninitialised vma list_head
From Zach Brown. Lots of places forget to initialise list_heads in
vm_area_structs, and other places then go and test the state of those
list_heads.
Plug the gaps for now, Zach is working on a broader cleanup.
ChangeSet@1.620.9.33, 2002-09-29 16:20:10-07:00, akpm@digeo.com
[PATCH] move_one_page kmap atomicity fix
move_one_page() is calling alloc_one_pte_map() while holding an atomic
kmap for the source pte's page. But alloc_one_pte_map() can sleep in
the page allocator.
So change move_one_page() to take a peek at the destination pagetables
to work out whether the alloc_one_pte_map() will need to perform page
allocation. If so, drop the atomic kmap and retake it after allocating
the pte.
ChangeSet@1.620.9.32, 2002-09-29 16:20:05-07:00, akpm@digeo.com
[PATCH] get_user_pages PageReserved fix
From David Miler.
get_user_pages() needs to avoid running page_cache_get() against
PageReserved pages. Things like video driver and audio driver
remap_page_range() mappings.
ChangeSet@1.620.9.31, 2002-09-29 16:20:01-07:00, akpm@digeo.com
[PATCH] Documentation/vm/hugetlbpage.txt
From Rohit
Creates Documentation/vm/hugetlbpage.txt
ChangeSet@1.620.9.30, 2002-09-29 16:19:56-07:00, akpm@digeo.com
[PATCH] kmem_cache_destroy fix
Slab currently has a policy of buffering a single spare page per slab.
We're putting that on the partially-full list, which confuses
kmem_cache_destroy().
So put it on cachep->slabs_free, which is where empty pages go.
ChangeSet@1.620.9.29, 2002-09-29 16:19:51-07:00, akpm@digeo.com
[PATCH] additional might_sleep checks
- Dave says that lock_sock() inside locks is a popular bug. Put a
check there.
- Also in wait_for_completion().
- Add the text "Debug" to the warning message so people are less
likely to think that they've oopsed.
ChangeSet@1.620.9.28, 2002-09-29 16:15:35-07:00, Kai.Makisara@kolumbus.fi
[PATCH] SCSI tape driver locking fixes
This contains the following changes for the SCSI tape driver in 2.5.39:
- move driverfs file creation and removal outside the st_dev_arr_lock
spinlock
- change page pointer array allocation from GFP_ATOMIC to GFP_KERNEL
ChangeSet@1.620.9.27, 2002-09-29 16:15:30-07:00, urban@teststation.com
[PATCH] might_sleep fixes
+ Fixes 2 cases caught by might_sleep testing.
+ Replace sleep_on with wait_event.
+ MOD_INC_USE_COUNT to prevent module unload vs smbiod thread exit race.
ChangeSet@1.618.1.5, 2002-09-29 20:05:05-03:00, acme@conectiva.com.br
o LLC: make it clear that Appletalk and IPX needs LLC
Thanks to Andries Brouwer for providing a patch.
ChangeSet@1.620.9.25, 2002-09-29 16:02:49-07:00, urban@teststation.com
[PATCH] SMB Unix Extensions
This patch adds symlinks, hardlinks, device nodes, uid/gid, unix
permissions vs servers that support it (ie samba). Most of this is the
work of John Newbigin, I just modified it for 2.5.
There are issues with what samba allows (eg you can't make arbitrary
symlinks) and room for improvements (use the servers value for ino?). But
it doesn't affect "normal" users.
ChangeSet@1.620.9.24, 2002-09-29 16:02:42-07:00, urban@teststation.com
[PATCH] wait_event_interruptible_timeout
smbfs wants a wait_event_interruptible_timeout to be able to replace
interruptible_sleep_on_timeout.
ChangeSet@1.620.1.28, 2002-09-29 17:56:14-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move dial/channel related members to isdn_net_dev
Dialing happens per channel / isdn_net_dev, so the move the
corresponding members there.
ChangeSet@1.618.1.4, 2002-09-29 19:49:15-03:00, acme@conectiva.com.br
o LLC: CONFIG_LLC_UI is really a bool, not a tristate
ChangeSet@1.620.11.2, 2002-09-29 15:44:39-07:00, mingo@elte.hu
[PATCH] tq_struct removal fixups..
Update radeon_irq.c and reiserfs for tq simplifications
ChangeSet@1.620.11.1, 2002-09-29 15:36:10-07:00, mingo@elte.hu
[PATCH] tq-cleanup module compile
This removes some more old symbols from ksyms.c. This makes the kernel
compile with modules enabled.
ChangeSet@1.620.1.27, 2002-09-29 17:10:26-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move "name" member from isdn_net_local to isdn_net_dev
This is the first step of a long series moving members between
isdn_net_local and isdn_net_dev.
Today, a one-to-one relationship between these both structures exist, so
it does not really matter where the members live. However, the goal
is to get a correspondence like
net_device -> isdn_net_local -> master isdn_net_device
|
slave isdn_net_device
|
slave isdn_net_device
where more than one isdn_net_device can exist per actual net_device,
due to channel bundling.
ChangeSet@1.620.1.26, 2002-09-29 16:48:28-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Add close()/open() callbacks to ISDN net interface implementation
X25 needs notification if an interface is brought up or down, and
ethernet over ISDN creates a fake MAC address at open time, so put this
into appropriate callbacks as well.
ChangeSet@1.620.1.25, 2002-09-29 16:24:57-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use ether_setup() for ethernet over ISDN only
The ->init() callback can be used for calling ether_setup() in case
of encapsulation "ISDN over ethernet", for the other cases it does not
make sense anyway.
ChangeSet@1.620.10.1, 2002-09-29 22:21:45+01:00, rmk@flint.arm.linux.org.uk
Merge
into flint.arm.linux.org.uk:/usr/src/linux-bk-2.5/linux-2.5-rmk
ChangeSet@1.620.1.24, 2002-09-29 15:53:40-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Introduce generic init/cleanup callbacks
X25 needs notification when encapsulation is set to X25 and when
it is changed to something else again, so let's have some callbacks
for init/cleanup.
ChangeSet@1.497.2.22, 2002-09-29 21:45:42+01:00, rmk@flint.arm.linux.org.uk
[ARM] Fix assabet backlight and power supply settings.
ChangeSet@1.620.1.23, 2002-09-29 15:35:00-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use a struct to describe types of ISDN net interfaces
Use a struct of methods and parameters to describe the
different kinds of network interfaces supported by isdn_net.c
and friends.
ChangeSet@1.497.2.21, 2002-09-29 21:31:19+01:00, rmk@flint.arm.linux.org.uk
[ARM] Fix clps711x and ftvpci LEDs initialisation.
ChangeSet@1.497.2.20, 2002-09-29 21:23:36+01:00, rmk@flint.arm.linux.org.uk
[ARM] Add kmap_types.h and percpu.h
ChangeSet@1.497.2.19, 2002-09-29 21:12:12+01:00, rmk@flint.arm.linux.org.uk
[ARM] Cleanup Ceiva merge.
ChangeSet@1.497.2.18, 2002-09-29 21:04:50+01:00, rscott@attbi.com
[ARM PATCH] 1243/1: Add support for Ceiva Photoframe, part2: machine specifics (fixed)
Adds machine specific support for Ceiva Photoframe. Affects:
arch/arm/mach-clps711x/Makefile
arch/arm/mach-clps711x/ceiva.c (new)
include/asm-arm/arch-clps711x/hardware.h
include/asm-arm/arch-clps711x/memory.h
Differences from 1st patch:
Removed redundant static I/O mapping for flash from hardware.h
Reverted to original CONFIG_DISCONTIGMEM enabling in memory.h
Added PHYS_TO_NID definition, when DISCONTIG undefined in memory.h
ChangeSet@1.620.9.22, 2002-09-29 14:49:09-05:00, kai@tp1.ruhr-uni-bochum.de
Merge
into tp1.ruhr-uni-bochum.de:/home/kai/src/kernel/v2.5/linux-2.5.make
ChangeSet@1.620.9.21, 2002-09-29 14:45:14-05:00, kai@tp1.ruhr-uni-bochum.de
kbuild: Make KBUILD_VERBOSE=0 work better under emacs
(slightly modified to unconditionally add the relative path to the subdir)
Rusty Russel wrote:
"M-x compile" in emacs stars a compilation and can jump to the next
error. With KBUILD_VERSBOSE=0 (as I have in my env, great work Kai)
it can't figure out the directory, since it doesn't see the make[XXX]
markers.
This makes it work.
ChangeSet@1.497.2.17, 2002-09-29 20:41:42+01:00, rmk@flint.arm.linux.org.uk
[ARM] Fix up export-objs for clps711x, integrator and sa1100
(From Thunder)
ChangeSet@1.620.9.20, 2002-09-29 14:30:10-05:00, kai@tp1.ruhr-uni-bochum.de
kbuild: Fix typo for 'tags' target
by Aristeu Sergio Rozanski Filho
ChangeSet@1.620.9.19, 2002-09-29 14:27:29-05:00, kai@tp1.ruhr-uni-bochum.de
kbuild: Make scripts/Configure follow the definition of 'int'
Currently, scripts/Configure has code for the 'int' verb to take a
min/max. This violates the spec described in
Documentation/kbuild/config-language.txt. It also requires that if a
default is outside of +/- 10,000,000 that defaults be provided, or
'config' and 'oldconfig' will get stuck. The following removes the
support for a min/max from scripts/Configure.
(by Tom Rini)
ChangeSet@1.497.2.16, 2002-09-29 20:21:59+01:00, nico@cam.org
[ARM PATCH] 1293/1: fix to the ARM optimized strchr()
Two bugs here:
1) The return value of strchr("foo",0) should be the start address of
"foo" + 3, not NULL.
2) Since the second argument for strchr() is defined as an int, some
characters such as 'é' might validly end up to be the value -23 due to
signedness issues. Corectly handle those.
ChangeSet@1.497.2.15, 2002-09-29 20:16:12+01:00, rmk@flint.arm.linux.org.uk
[ARM] Don't return a value from ptrace_set_bpt()
The return value from ptrace_set_bit() is never used. This cset
makes it a void function.
ChangeSet@1.497.2.14, 2002-09-29 20:06:15+01:00, rmk@flint.arm.linux.org.uk
[ARM] Update PCI host bridge drivers for GregKH PCI cleanups.
ChangeSet@1.620.9.18, 2002-09-29 11:21:51-07:00, linux@brodo.de
[PATCH] CPUfreq i386 drivers update
This add-on patch is needed to abort on Dell Inspiron 8000 / 8100 which
would lock up during speedstep.c and to resolve an oops (thanks to Hu Gang
for reporting this)
ChangeSet@1.620.9.17, 2002-09-29 11:21:46-07:00, linux@brodo.de
[PATCH] (5/5) CPUfreq /proc/sys/cpu/ add-on patch
CPUFreq 24-API add-on patch for 2.5.39:
kernel/cpufreq.c cpufreq-24-API
include/linux/cpufreq.h cpufreq-24-API
arch/i386/config.in Transmeta LongRun does not work well with cpufreq-24-API
arch/i386/Config.help help text for CONFIG_CPU_FREQ_24_API
ChangeSet@1.497.2.13, 2002-09-29 19:21:43+01:00, rmk@flint.arm.linux.org.uk
[ARM] Correct the usage of __FUNCTION__ to make gcc happy.
ChangeSet@1.620.9.16, 2002-09-29 11:21:40-07:00, linux@brodo.de
[PATCH] (4/5) CPUfreq Documentation
CPUFreq documentation for 2.5.39:
CREDITS one further CREDIT entry
Documentation/cpufreq documentation of CPU frequency and voltage scaling
support in the Linux kernel.
MAINTAINERS one further MAINTAINERS entry
arch/i386/Config.help Config.help texts for i386 CPUFreq drivers
ChangeSet@1.620.9.15, 2002-09-29 11:21:35-07:00, linux@brodo.de
[PATCH] (3/5) CPUfreq i386 drivers
CPUFreq i386 drivers for 2.5.39:
arch/i386/config.in Necessary config options
arch/i386/kernel/cpu/Makefile allow for compilation of the CPUFreq subdirectory
arch/i386/kernel/cpu/cpufreq/Makefile Makefile for CPUFreq drivers
arch/i386/kernel/cpu/cpufreq/elanfreq.c CPUFreq driver for AMD Elan processors
arch/i386/kernel/cpu/cpufreq/longhaul.c CPUFreq driver for VIA Longhaul processors
arch/i386/kernel/cpu/cpufreq/longrun.c CPUFreq driver for Transmeta Crusoe processors
arch/i386/kernel/cpu/cpufreq/p4-clockmod.c CPUFreq driver for Pentium 4 Xeon processors (using clock modulation)
arch/i386/kernel/cpu/cpufreq/powernow-k6.c CPUFreq driver for mobile AMD K6-2+ and mobile AMD K6-3+ processors
arch/i386/kernel/cpu/cpufreq/speedstep.c CPUFreq drivers for ICH2-M and ICH3-M chipsets and Intel Pentium 3-M and 4-M processors.
ChangeSet@1.620.9.14, 2002-09-29 11:21:30-07:00, linux@brodo.de
[PATCH] (2/5) CPUfreq i386 core
CPUFreq i386 core for 2.5.39:
arch/i386/kernel/i386_ksyms.c export cpu_khz
arch/i386/kernel/time.c update various i386 values on frequency
changes
include/asm-i386/msr.h add Transmeta MSR defines
ChangeSet@1.620.9.13, 2002-09-29 11:21:25-07:00, linux@brodo.de
[PATCH] (1/5) CPUfreq core
CPUFreq core for 2.5.39
include/linux/cpufreq.h CPUFreq header
kernel/Makefile add cpufreq.c if necessary
kernel/cpufreq.c CPUFreq core
ChangeSet@1.620.9.12, 2002-09-29 11:11:33-07:00, pwaechtler@mac.com
[PATCH] oss sound cli cleanup
More cleanups for the OSS sound modules
ChangeSet@1.497.2.12, 2002-09-29 19:10:32+01:00, rmk@flint.arm.linux.org.uk
[ARM] Bring asm/setup.h and asm/unistd.h into line with main ARM tree
This removes some minor differences between Linus' tree and the main
ARM tree; comment clarification and some weird formatting.
ChangeSet@1.620.9.11, 2002-09-29 11:00:25-07:00, mingo@elte.hu
[PATCH] smptimers, old BH removal, tq-cleanup
This is the smptimers patch plus the removal of old BHs and a rewrite of
task-queue handling.
Basically with the removal of TIMER_BH i think the time is right to get
rid of old BHs forever, and to do a massive cleanup of all related
fields. The following five basic 'execution context' abstractions are
supported by the kernel:
- hardirq
- softirq
- tasklet
- keventd-driven task-queues
- process contexts
I've done the following cleanups/simplifications to task-queues:
- removed the ability to define your own task-queue, what can be done is
to schedule_task() a given task to keventd, and to flush all pending
tasks.
This is actually a quite easy transition, since 90% of all task-queue
users in the kernel used BH_IMMEDIATE - which is very similar in
functionality to keventd.
I believe task-queues should not be removed from the kernel altogether.
It's true that they were written as a candidate replacement for BHs
originally, but they do make sense in a different way: it's perhaps the
easiest interface to do deferred processing from IRQ context, in
performance-uncritical code areas. They are easier to use than
tasklets.
code that cares about performance should convert to tasklets - as the
timer code and the serial subsystem has done already. For extreme
performance softirqs should be used - the net subsystem does this.
and we can do this for 2.6 - there are only a couple of areas left after
fixing all the BH_IMMEDIATE places.
i have moved all the taskqueue handling code into kernel/context.c, and
only kept the basic 'queue a task' definitions in include/linux/tqueue.h.
I've converted three of the most commonly used BH_IMMEDIATE users:
tty_io.c, floppy.c and random.c. [random.c might need more thought
though.]
i've also cleaned up kernel/timer.c over that of the stock smptimers
patch: privatized the timer-vec definitions (nothing needs it,
init_timer() used it mistakenly) and cleaned up the code. Plus i've moved
some code around that does not belong into timer.c, and within timer.c
i've organized data and functions along functionality and further
separated the base timer code from the NTP bits.
net_bh_lock: i have removed it, since it would synchronize to nothing. The
old protocol handlers should still run on UP, and on SMP the kernel prints
a warning upon use. Alexey, is this approach fine with you?
scalable timers: i've further improved the patch ported to 2.5 by wli and
Dipankar. There is only one pending issue i can see, the question of
whether to migrate timers in mod_timer() or not. I'm quite convinced that
they should be migrated, but i might be wrong. It's a 10 lines change to
switch between migrating and non-migrating timers, we can do performance
tests later on. The current, more complex migration code is pretty fast
and has been stable under extremely high networking loads in the past 2
years, so we can immediately switch to the simpler variant if someone
proves it improves performance. (I'd say if non-migrating timers improve
Apache performance on one of the bigger NUMA boxes then the point is
proven, no further though will be needed.)
ChangeSet@1.620.9.10, 2002-09-29 11:00:15-07:00, mingo@elte.hu
[PATCH] atomic-thread-signals
Avoid racing on signal delivery with thread signal blocking in thread
groups.
The method to do this is to eliminate the per-thread sigmask_lock, and
use the per-group (per 'process') siglock for all signal related
activities. This immensely simplified some of the locking interactions
within signal.c, and enabled the fixing of the above category of signal
delivery races.
This became possible due to the former thread-signal patch, which made
siglock an irq-safe thing. (it used to be a process-context-only
spinlock.) And this is even a speedup for non-threaded applications:
only one lock is used.
I fixed all places within the kernel except the non-x86 arch sections.
Even for them the transition is very straightforward, in almost every
case the following is sufficient in arch/*/kernel/signal.c:
:1,$s/->sigmask_lock/->sig->siglock/g
ChangeSet@1.620.9.9, 2002-09-29 11:00:08-07:00, mingo@elte.hu
[PATCH] thread-group SIGSTOP handling
Fix thread-group SIGSTOP handling - the SIGSTOP notification was not
propagated to the parent of the thread group leader. Now Ctrl-Z-ing of
thread groups works again.
ChangeSet@1.620.9.8, 2002-09-29 11:00:03-07:00, mingo@elte.hu
[PATCH] signal delivery to thread groups bugfix
Fix thread group signal sending
ChangeSet@1.620.9.7, 2002-09-29 10:59:58-07:00, mingo@elte.hu
[PATCH] futex-fix-2.5.39-A1
This fixes one more race left in the new futex hashing code, which
triggers if a futex waiter gets a signal after it has been woken up but
before it actually wakes up.
ChangeSet@1.620.9.6, 2002-09-29 10:59:53-07:00, mingo@elte.hu
[PATCH] sigfix-2.5.39-A1
This fixes the bug reported by David Mosberger, force_sig_info() dropped
the siginfo structure, which broke things like SIGFPU or alignment-error
exceptions. This bug was introduced by the threading signal changes.
(The patch also fixes signal declaration whitespaces in sched.h.)
ChangeSet@1.497.2.11, 2002-09-29 17:42:34+01:00, rmk@flint.arm.linux.org.uk
[ARM] Remove keyboard.h includes and some generic ARM keyboard bits.
This keeps ARM in line with the continued transition to the input
layer.
ChangeSet@1.497.2.10, 2002-09-29 17:34:05+01:00, rmk@flint.arm.linux.org.uk
[ARM] NWFPE updates for new entry conditions.
ChangeSet@1.497.2.9, 2002-09-29 17:22:33+01:00, gilbertd@treblig.org
[ARM PATCH] 1260/1: Fix comment in nwfpe
Hi,
I believe the comment in the nwfpe fpopcodes is slightly wrong -
although a 2nd pair of eyes on this would be a good idea.
ChangeSet@1.497.2.8, 2002-09-29 17:20:50+01:00, gilbertd@treblig.org
[ARM PATCH] 1257/1: Helpful comment in stat.h
Hi,
For reasons of great complexity I found out the hard way that the
kernel must (and does) zero the pad sections in the stat structures.
Here is a comment that states this for the next person who needs to
know.
ChangeSet@1.497.2.7, 2002-09-29 17:16:01+01:00, rmk@flint.arm.linux.org.uk
[ARM] Unify integer register usage passed into FP module.
This allows the FP module to perform some extra optimisations.
ChangeSet@1.497.2.6, 2002-09-29 17:12:05+01:00, rmk@flint.arm.linux.org.uk
[ARM] 2.5.34 update
Update for changes in mainline 2.5.3[01234].
ChangeSet@1.536.24.36, 2002-09-29 07:25:30-03:00, acme@conectiva.com.br
o lapbether: get rid of cli/sti, use refcnts for devs, etc
ChangeSet@1.603.2.8, 2002-09-29 03:19:20-07:00, zaitcev@redhat.com
[sparc]: defconfig update
ChangeSet@1.620.9.5, 2002-09-29 05:58:08-04:00, jgarzik@mandrakesoft.com
[net drivers] update hamachi.c and starfire.c to use MII lib
ChangeSet@1.603.2.7, 2002-09-29 02:55:15-07:00, davem@nuts.ninka.net
[SPARC64]: Rework all EBUS DMA support.
- Add EBUS DMA layer so the same code does not need to
be debugged/duplicated several times.
- Convert Parport/Floppy/CS4231 to use new EBUS DMA layer.
ChangeSet@1.620.9.4, 2002-09-29 04:17:00-04:00, jgarzik@mandrakesoft.com
[net drivers] add optional duplex-changed arg to generic_mii_ioctl helper
ChangeSet@1.620.9.3, 2002-09-29 03:54:55-04:00, jgarzik@mandrakesoft.com
[net drivers] Remove 'dev' argument from generic_mii_ioctl helper
ChangeSet@1.620.8.4, 2002-09-29 02:30:29-04:00, jgarzik@mandrakesoft.com
Use new MII lib helper generic_mii_ioctl in several net drivers:
8139too, epic100, fealnx, sundance and via-rhine.
In the process, several of these net drivers gained MII ioctl
locking fixes simply by virtue of being brought in line with
standardized code.
ChangeSet@1.632, 2002-09-28 23:24:18-07:00, yoshfuji@linux-ipv6.org
net/ipv6/ip6_fib.c: Default route support on router.
ChangeSet@1.620.1.22, 2002-09-29 00:52:54-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Introduce generic bind/unbind callbacks
PPP wants callbacks at the time a connection between ISDN channel
and network interface is established, i.e. before dialing to
avoid dialing when no ipppd is present, so use generic
bind/unbind callbacks.
ChangeSet@1.620.1.21, 2002-09-29 00:30:21-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: unclutter isdn_net_find_icall()
The method to find out if an incoming call is addressed to
any of the ISDN network interfaces is horrible. A bit of splitting
and dropping the swap channels if exclusive logic makes it a bit
better at least.
ChangeSet@1.620.8.3, 2002-09-29 01:07:35-04:00, jgarzik@mandrakesoft.com
Add helper function generic_mii_ioctl to MII lib, use it in 8139cp net drvr
ChangeSet@1.536.24.35, 2002-09-29 02:07:09-03:00, acme@conectiva.com.br
o LAPB: use refcounts and rwlock to protect lapb_cb and list
Also some CodingStyle code reformatting.
Ah, killed the typedef for lapb_cb.
ChangeSet@1.620.1.20, 2002-09-28 23:46:14-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Remove ISDN_NET_CONNECTED flags
The same information is present as (->isdn_slot >= 0), so don't
duplicate it (and risk it getting out of sync)
ChangeSet@1.620.1.19, 2002-09-28 23:38:00-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use net/ethernet/eth.c eth_rebuild_header()
No need to duplicate that function privately.
ChangeSet@1.620.1.18, 2002-09-28 23:32:07-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Share code for initiating dial out
ChangeSet@1.620.8.2, 2002-09-29 00:07:56-04:00, jgarzik@mandrakesoft.com
[net drivers] Rename MII lib API member, s/duplex_lock/force_media/,
and update all drivers that reference this struct member.
ChangeSet@1.620.1.17, 2002-09-28 23:04:07-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: exclusive handling in isdn_net_force_dial_lp()
When using exclusive mode, we already reserved our channel
at the time that mode was set, so no need to get a free channel
in this case.
Also, indent cleanups to isdn_net_start_xmit().
ChangeSet@1.620.1.16, 2002-09-28 22:53:01-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Put slot index of reserved channel into ->exclusive
We will need the index of the channel we reserved later, so override
the meaning of ->exclusive.
ChangeSet@1.620.1.15, 2002-09-28 22:30:30-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: inline function for testing if interface is bound
Put the test for lp->flags & ISDN_NET_CONNECTED into an inline
function called isdn_net_bound(), which more accurately names what
we are testing for, i.e. the interface being bound to a hardware
ISDN channel, which however is not necessarily online yet.
ChangeSet@1.620.9.1, 2002-09-28 20:13:44-07:00, akpm@digeo.com
[PATCH] Fix uninitialized swapper_space lists
ChangeSet@1.536.24.34, 2002-09-29 00:09:19-03:00, acme@conectiva.com.br
o X25: x25_wait_for_{data,connection_establishemnt} and the death of the last cli/sti pair in X.25
ChangeSet@1.620.8.1, 2002-09-28 22:53:46-04:00, jgarzik@mandrakesoft.com
[net drivers] MII lib update:
* add boolean 'init_media' arg to mii_check_media
* update all callers (just 8139cp, for now)
ChangeSet@1.620.7.2, 2002-09-28 22:28:25-04:00, jdike@uml.karaya.com
Updated to build with the 2.5.39 kbuild.
ChangeSet@1.620.7.1, 2002-09-28 22:23:28-04:00, jdike@uml.karaya.com
Took the 2.5.39 Makefile changes.
ChangeSet@1.620.2.16, 2002-09-28 19:09:34-07:00, torvalds@home.transmeta.com
Fix "make mrproper" that broke when the files pattern matched
a directory pattern. Clean directories _first_, then files.
ChangeSet@1.536.24.33, 2002-09-28 22:36:04-03:00, acme@conectiva.com.br
o X25: protect x25 sockets and list with refcnt and rwlock
ChangeSet@1.620.1.12, 2002-09-28 21:21:06-04:00, jgarzik@mandrakesoft.com
sis900 net driver update:
* fix eeprom accesses
* fix tx desc overflow
* fix tx timeout bug
* add sis963 support
ChangeSet@1.620.1.11, 2002-09-28 21:05:26-04:00, jgarzik@mandrakesoft.com
[net drivers] fix MII lib force-media ethtool path
(contributed by Edward Peng @ D-Link)
ChangeSet@1.620.1.10, 2002-09-28 21:00:19-04:00, jgarzik@mandrakesoft.com
sundance net drvr: bump version to LK1.05
ChangeSet@1.620.1.9, 2002-09-28 20:31:35-04:00, jgarzik@mandrakesoft.com
sundance net drvr: fix DFE-580TX packet drop issue, further reset_tx fixes
(contributed by Edward Peng @ D-Link)
ChangeSet@1.620.1.8, 2002-09-28 20:26:47-04:00, jgarzik@mandrakesoft.com
sundance net drvr: fix reset_tx logic
(contributed by Edward Peng @ D-Link, cleaned up by me)
ChangeSet@1.536.24.32, 2002-09-28 21:23:09-03:00, acme@conectiva.com.br
o X25: use refcnts and protect x25_neigh structs and list
Simplify some other code.
ChangeSet@1.620.1.7, 2002-09-28 20:10:17-04:00, edward_peng@dlink.com.tw
update sundance driver to support building on older kernel:
conditionally include crc32.h, ethtool.h, mii.h, and compat.h
if built outside the stock 2.4.x kernel.
ChangeSet@1.620.1.6, 2002-09-28 20:01:27-04:00, achirica@ttd.net
airo wireless net drvr: add Cisco MIC support
Conditionally enabled when out-of-tree, but open source, crypto lib
is present.
ChangeSet@1.579.15.3, 2002-09-28 15:45:58-04:00, jdike@uml.karaya.com
Missed a change to fixmap.h in the highmem update.
ChangeSet@1.579.15.2, 2002-09-28 15:31:57-04:00, jdike@uml.karaya.com
Fixed highmem support for 2.5.
ChangeSet@1.627, 2002-09-28 02:44:05-07:00, yoshfuji@linux-ipv6.org
net/ipv6/ndisc.c: Add missing credits.
ChangeSet@1.618.1.3, 2002-09-28 06:36:52-03:00, acme@conectiva.com.br
o LLC: rename llc_sock.c to af_llc.c
To make it look like the other protocols.
ChangeSet@1.536.24.31, 2002-09-28 06:28:57-03:00, acme@conectiva.com.br
o X25: use refcounts and protect x25_route list
Also rename untypedefed x25_cb, renaming it to x25_opt, to make
it look like the other protocols.
Added some kerneldoc comments.
ChangeSet@1.536.24.30, 2002-09-28 02:39:50-03:00, acme@conectiva.com.br
o X25: Simplify ioctl code, CodingStyle cleanups
ChangeSet@1.620.6.17, 2002-09-28 00:31:10-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use a function pointer for type-specific disconnected() callback
Again, instead of a switch statement, just use a callback.
ChangeSet@1.618.1.2, 2002-09-28 02:16:50-03:00, acme@conectiva.com.br
o LLC: remove unused list_head from llc_opt & use rw_lock_init for rwlocks
ChangeSet@1.620.6.16, 2002-09-28 00:14:40-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use a function pointer for type-specific connected() callback
Again, instead of a switch statement, just use a callback.
ChangeSet@1.620.6.15, 2002-09-27 23:56:50-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Use a function pointer for type-specific receive
ChangeSet@1.620.6.14, 2002-09-27 23:46:23-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: finish separating out receive functions
Use the same form for the already existing PPP / X.25 receive functions
as for all the other ones, + small fixes.
ChangeSet@1.620.6.13, 2002-09-27 23:39:24-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: separate out IPTYP receive function
Another step in splitting isdn_net_receive into type specific functions.
ChangeSet@1.620.6.12, 2002-09-27 23:34:58-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: separate out CISCO HDLC receive function
Another step in splitting isdn_net_receive into type specific functions.
ChangeSet@1.620.6.11, 2002-09-27 23:19:42-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: separate out RAWIP receive function
Another step in splitting isdn_net_receive into type specific functions.
ChangeSet@1.620.6.10, 2002-09-27 23:16:02-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: separate out IPTYP receive function
Another step in splitting isdn_net_receive into type specific functions.
ChangeSet@1.620.6.9, 2002-09-27 23:12:32-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: separate out 'ethernet over ISDN' receive function
First step in splitting isdn_net_receive into type specific functions.
ChangeSet@1.620.6.8, 2002-09-27 23:01:09-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: net_device->header for IPTYP
ChangeSet@1.620.6.7, 2002-09-27 22:51:46-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: net_device->header for syncPPP and UI HDLC
Break syncPPP and UI HDLC specific parts out of isdn_net_header()
and move it to more appropriate places.
ChangeSet@1.620.6.6, 2002-09-27 22:39:47-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: net_device->header for CISCO HDLC
Break the CISCO specific part out of the generic isdn_net_header()
and move it to the CISCO code.
ChangeSet@1.620.6.5, 2002-09-27 22:25:03-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: 'ethernet over ISDN' cleanups
ChangeSet@1.620.6.4, 2002-09-27 21:46:51-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move net_device setup to a type-specific method
isdn_net handles all kind of interfaces, e.g. raw IP, ethernet over ISDN,
PPP - this is a cleanup making the setup of a net_device specific to the
type of interface.
ChangeSet@1.620.6.3, 2002-09-27 20:59:18-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: More cleanup to isdn_net.c (X.25 / PPP)
Again, instead of having stuff cluttered all over isdn_net.c, put
it into the files where it belongs and get rid of the
#ifdef CONFIG_ISDN_X25 / CONFIG_ISDN_PPP by using dummy stubs if
necessary.
Same thing for CONFIG_ISDN_PPP.
ChangeSet@1.620.2.15, 2002-09-27 18:32:41-07:00, torvalds@home.transmeta.com
Remove more tmp-file on clean (introduced with kallsyms)
ChangeSet@1.623, 2002-09-27 18:24:55-07:00, yoshfuji@linux-ipv6.org
net/ipv6/addrconf.c: Refine IPv6 Address Validation Timer.
ChangeSet@1.620.6.2, 2002-09-27 20:04:20-05:00, kai@tp1.ruhr-uni-bochum.de
ISDN: Move CISCO HDLCK protocol into separate file
SyncPPP and X25 are already (kind of) separated, so do the same for CISCO
HDLCK.
ChangeSet@1.497.2.5, 2002-09-28 00:04:28+01:00, rmk@flint.arm.linux.org.uk
[ARM] Add DC21285 decompressor debug support
ChangeSet@1.497.2.4, 2002-09-27 23:56:53+01:00, rmk@flint.arm.linux.org.uk
[ARM] Parse initrd information early
We need the initrd location before the normal command line parsing
occurs so we can reserve the right bits of memory, and not double-
free the initrd during userspace boot.
ChangeSet@1.497.2.3, 2002-09-27 23:23:20+01:00, rmk@flint.arm.linux.org.uk
[ARM] Don't continue to process pending interrupts after disable_irq()
This solves a problem whereby the generic interrupt code repeatedly
called an interrupt handler, even though the interrupt handler had
called disable_irq().
ChangeSet@1.620.2.14, 2002-09-27 14:47:36-07:00, torvalds@penguin.transmeta.com
Linux v2.5.39
TAG: v2.5.39
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/11337/ | crawl-003 | refinedweb | 10,794 | 61.43 |
Sometimes one may wish to query the database for objects matching any of several criteria specified in several form fields, some of which may be multiple choice. This function makes that easy:
def buildOrQuery(request, config): ''' Builds a django.db.models.query.QOr object based on HTTP request and a simple config dictionary, mapping field names to filter syntax. For example: config = { 'bar': 'foo__bar__exact', 'ham': 'spam__eggs__ham__icontains', } ''' query = None # A blank query here would be v bad for field in config.keys(): values = request.POST.getlist(field) for value in values: subquery = Q(**{config[field]: value}) if not query: query = subquery else: # Combine using OR: query = query | subquery if query: return query else: return Q() # Blank query -- it would break things to return None
Last modified 10 years ago Last modified on 08/14/2007 04:03:49 PM | https://code.djangoproject.com/wiki/OrQueryBuilder | CC-MAIN-2017-13 | refinedweb | 138 | 59.13 |
AWS News Blog Functions provides the callback pattern for us in this situation. Approval emails are a common use case in this category.
In this post, I show you how to create a Step Functions state machine that uses the sfn-callback-urls application for an email approval step. The app is available in the AWS Serverless Application Repository. The state machine sends an email containing approve/reject links, and later a confirmation email. You can easily expand this state machine for your use cases.
Solution overview
An approval email must include URLs that send the appropriate result back to Step Functions when the user clicks on them. The URL should be valid for an extended period of time, longer than presigned URLs—what if the user is on vacation this week? Ideally, this doesn’t involve storage of the token and the maintenance that requires. Luckily, there’s an AWS Serverless Application Repository app for that!
The sfn-callback-urls app allows you to generate one-time-use callback URLs through a call to either an Amazon API Gateway or a Lambda function. Each URL has an associated name, whether it causes success or failure, and what output should be sent back to Step Functions. Sending an HTTP GET or POST to a URL sends its output to Step Functions.
sfn-callback-urls is stateless, and it also supports POST callbacks with JSON bodies for use with webhooks.
Deploying the app
First, deploy the
sfn-callback-urls serverless app and make note of the ARN for the Lambda function that it exposes. In the AWS Serverless Application Repository console, select Show apps that create custom IAM roles or resource policies, and search for sfn-callback-urls. You can also access the application.
Under application settings, select the box to acknowledge the creation of IAM resources. By default, this app creates a KMS key. You can disable this by setting the DisableEncryption parameter to true, but first read the Security section in the Readme to the left. Scroll down and choose Deploy.
On the deployment confirmation page, choose CreateUrls, which opens the Lambda console for that function. Make note of the function ARN because you need it later.
Create the application by doing the following:
- Create an SNS topic and subscribe your email to it.
- Create the Lambda function that handles URL creation and email sending, and add proper permissions.
- Create an IAM role for the state machine to invoke the Lambda function.
- Create the state machine.
- Start the execution and send yourself some emails!
Create the SNS topic
In the SNS console, choose Topics, Create Topic. Name the topic ApprovalEmailsTopic, and choose Create Topic.
Make a note of the topic ARN, for example arn:aws:sns:us-east-2:012345678912:ApprovalEmailsTopic.
Now, set up a subscription to receive emails. Choose Create subscription. For Protocol, choose Email, enter an email address, and choose Create subscription.
Wait for an email to arrive in your inbox with a confirmation link. It confirms the subscription, allowing messages published to the topic to be emailed to you.
Create the Lambda function
Now create the Lambda function that handles the creation of callback URLs and sending of emails. For this short post, create a single Lambda function that completes two separate steps:
- Creating callback URLs
- Sending the approval email, and later sending the confirmation email
There’s an
if statement in the code to separate the two, which requires the state machine to tell the Lambda function which state is invoking it. The best practice here would be to use two separate Lambda functions.
To create the Lambda function in the Lambda console, choose Create function, name it ApprovalEmailsFunction, and select the latest Python 3 runtime. Under Permissions, choose Create a new Role with basic permissions, Create.
Add permissions by scrolling down to Configuration. Choose the link to see the role in the IAM console.
Add IAM permissions
In the IAM console, select the new role and choose Add inline policy. Add permissions for
sns:Publish to the topic that you created and
lambda:InvokeFunction to the
sfn-callback-urls
CreateUrls function ARN.
Back in the Lambda console, use the following code in the function:
import json, os, boto3 def lambda_handler(event, context): print('Event:', json.dumps(event)) # Switch between the two blocks of code to run # This is normally in separate functions if event['step'] == 'SendApprovalRequest': print('Calling sfn-callback-urls app') input = { # Step Functions gives us this callback token # sfn-callback-urls needs it to be able to complete the task "token": event['token'], "actions": [ # The approval action that transfers the name to the output { "name": "approve", "type": "success", "output": { # watch for re-use of this field below "name_in_output": event['name_in_input'] } }, # The rejection action that names the rejecter { "name": "reject", "type": "failure", "error": "rejected", "cause": event['name_in_input'] + " rejected it" } ] } response = boto3.client('lambda').invoke( FunctionName=os.environ['CREATE_URLS_FUNCTION'], Payload=json.dumps(input) ) urls = json.loads(response['Payload'].read())['urls'] print('Got urls:', urls) # Compose email email_subject = 'Step Functions example approval request' email_body = """Hello {name}, Click below (these could be better in HTML emails): Approve: {approve} Reject: {reject} """.format( name=event['name_in_input'], approve=urls['approve'], reject=urls['reject'] ) elif event['step'] == 'SendConfirmation': # Compose email email_subject = 'Step Functions example complete' if 'Error' in event['output']: email_body = """Hello, Your task was rejected: {cause} """.format( cause=event['output']['Cause'] ) else: email_body = """Hello {name}, Your task is complete. """.format( name=event['output']['name_in_output'] ) else: raise ValueError print('Sending email:', email_body) boto3.client('sns').publish( TopicArn=os.environ['TOPIC_ARN'], Subject=email_subject, Message=email_body ) print('done') return {}
Now, set the following environment variables TOPIC_ARN and CREATE_URLS_FUNCTION to the ARNs of your topic and the
sfn-callback-urls function noted earlier.
After updating the code and environment variables, choose Save.
Create the state machine
You first need a role for the state machine to assume that can invoke the new Lambda function.
In the IAM console, create a role with Step Functions as its trusted entity. This requires the
AWSLambdaRole policy, which gives it access to invoke your function. Name the role
ApprovalEmailsStateMachineRole.
Now you’re ready to create the state machine. In the Step Functions console, choose Create state machine, name it
ApprovalEmails, and use the following code:
{ "Version": "1.0", "StartAt": "SendApprovalRequest", "States": { "SendApprovalRequest": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke.waitForTaskToken", "Parameters": { "FunctionName": "ApprovalEmailsFunction", "Payload": { "step.$": "$$.State.Name", "name_in_input.$": "$.name", "token.$": "$$.Task.Token" } }, "ResultPath": "$.output", "Next": "SendConfirmation", "Catch": [ { "ErrorEquals": [ "rejected" ], "ResultPath": "$.output", "Next": "SendConfirmation" } ] }, "SendConfirmation": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Parameters": { "FunctionName": "ApprovalEmailsFunction", "Payload": { "step.$": "$$.State.Name", "output.$": "$.output" } }, "End": true } } }
This state machine has two states. It takes as input a JSON object with one field, “name”. Each state is a Lambda task. To shorten this post, I combined the functionality for both states in a single Lambda function. You pass the state name as the step field to allow the function to choose the block of code to run. Using the best practice of using separate functions for different responsibilities, this field would not be necessary.
The first state, SendApprovalRequest, expects an input JSON object with a name field. It packages that name along with the step and the task token (required to complete the callback task), and invokes the Lambda function with it. Whatever output is received as part of the callback, the state machine stores it in the output JSON object under the output field. That output then becomes the input to the second state.
The second state, SendConfirmation, takes that output field along with the step and invokes the function again. The second invocation does not use the callback pattern and doesn’t involve a task token.
Start the execution
To run the example, choose Start execution and set the input to be a JSON object that looks like the following:
{
"name": "Ben"
}
You see the execution graph with the SendApprovalRequest state highlighted. This means it has started and is waiting for the task token to be returned. Check your inbox for an email with approve and reject links. Choose a link and get a confirmation page in the browser saying that your response has been accepted. In the State Machines console, you see that the execution has finished, and you also receive a confirmation email for approval or rejection.
Conclusion
In this post, I demonstrated how to use the
sfn-callback-urls app from the AWS Serverless Application Repository to create URLs for approval emails. I also showed you how to build a system that can create and send those emails and process the results. This pattern can be used as part of a larger state machine to manage your own workflow.
This example is also available as an AWS CloudFormation template in the sfn-callback-urls GitHub repository. | https://aws.amazon.com/blogs/aws/using-callback-urls-for-approval-emails-with-aws-step-functions/ | CC-MAIN-2019-35 | refinedweb | 1,461 | 55.24 |
namespace fs = std::experimental::filesystem; std::vector<std::string> list_files_in_dir(string dirPath) { vector<string> r; for (auto & p : fs::directory_iterator(dirPath)) { std::cout << p.path().string() << std::endl; r.push_back(p.path().string()); } return r; }
7/20/2018
get file list in the folder (example code)
example code
7/04/2018
get files list in a directory in ubuntu
refer to below code:
..
..
std::vector<std::string> list_files_in_dir(const char* dirPath) { DIR *dir; std::vector<std::string> files; struct dirent *ent; if ((dir = opendir (dirPath)) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) { stringstream fullpath; fullpath << dirPath << "/" << ent->d_name; files.push_back(fullpath.str()); } } closedir (dir); } else { /* could not open directory */ perror (""); return files; } return files; }..
7/03/2018
opencv install on ubuntu
Simple and easy way
1. install opencv from the official site
2. download sh file
3. run sh file
cd build/bin
./example_cpp_edge ../../samples/data/fruits.jpg
That's all
Thank you.
more detail refer to here :
1. install opencv from the official site
sudo apt-get autoremove libopencv-dev python-opencv
2. download sh file
3. run sh file
bash install-opencv.sh4. test
cd build/bin
./example_cpp_edge ../../samples/data/fruits.jpg
That's all
Thank you.
more detail refer<< | https://study.marearts.com/2018/07/ | CC-MAIN-2021-31 | refinedweb | 218 | 54.59 |
In a rather old project I’m working on again now, there used to be a lot of Latin-1-encoded files. Yuck! I don’t even want to know why anybody ever created or used a character encoding other than UTF-8. So I thought, let’s get these old-school files a decent encoding.
iconv -f L1 -t UTF-8 filename >filename.converted
This will convert the file
filename from Latin-1 to UTF-8 and save it as
filename.converted.
To find all relevant files in the project directory, we use find, of course. The only issue with this is that a simple
for x in `find ...` loop will not handle filenames containing spaces correctly, so we apply
while read to it, as in:
find . -name '*.php' | while read x; #...
This will execute the rest with a variable
x being assigned every PHP filename in the current directory. (There are other approaches to this as well, of course.)
Now there’s only one problem left to deal with: Some files in the directory are already UTF-8-encoded. Of course, we don’t want to re-encode them again. (Decoding from Latin-1 and encoding to UTF-8 is not idempotent for characters beyond ASCII.) There might be other solutions, but I decided to use Python and the chardet package to determine whether a file is already UTF-8-encoded:
import chardet if chardet.detect(str)['encoding'].lower() == 'utf-8': print ('UTF-8') else: print ('L1')
This will print
UTF-8 if the string
str is encoded in UTF-8 and
L1 otherwise.
Adding some code to output the current file and to remove the original file and replace it by the converted one, we get the following script:
We can also assemble this into a bash one-liner if we prefer: | http://www.poeschko.com/2012/04/converting-text-files-to-utf-8/ | CC-MAIN-2013-48 | refinedweb | 305 | 63.49 |
2016-04-07 10:13:11 8 Comments
Lately, I have been working on this Huffman algorithm and it is finally done, though I think it is improvable due to the fact that people say you have got to use two priority queues but I ended up just using one, so maybe it is even not correctly implemented.
Code:
#include <iostream> #include <string> #include <map> #include <queue> #include <fstream> #include <functional> class HuffmanCoder{ struct TreeNode { char character; unsigned frequency, code; TreeNode* left, *right; friend bool operator>(const TreeNode& a, const TreeNode& b) { return a.frequency > b.frequency; } TreeNode() = default; TreeNode(char chara, int freq) : character(chara), frequency(freq), code(0u), left(nullptr), right(nullptr) {} } m_root; //recursive function that assigns codes for every char in the map passed as a reference in the parameters void assignCodes(std::map<char, std::string>& map, const TreeNode& rootNode, unsigned currWord, unsigned depth) { if (!rootNode.left && !rootNode.right) { std::string s; for (auto d = 0u; d < depth; ++d) { s.push_back('0' + (currWord & 1)); currWord >>= 1; } std::reverse(s.begin(), s.end()); map[rootNode.character] = std::move(s); } else { assignCodes(map, *rootNode.left, currWord << 1, depth + 1); assignCodes(map, *rootNode.right, (currWord << 1) | 1, depth + 1); } } public: HuffmanCoder() = default; std::string encodeMessage(const std::string& message) { std::map<char, int> frequencies; for (const auto& character : message) frequencies[character]++; std::priority_queue<TreeNode,std::vector<TreeNode>, std::greater<>> pairs; for (auto&& value : frequencies) pairs.push({ value.first, value.second }); //huffman algorithm while (pairs.size() > 1) { const auto pair1 = pairs.top(); pairs.pop(); const auto pair2 = pairs.top(); pairs.pop(); TreeNode temp('*', pair1.frequency + pair2.frequency); temp.left = new TreeNode(pair1); temp.right = new TreeNode(pair2); pairs.push(temp); } m_root = pairs.top(); std::map<char, std::string> map; assignCodes(map, m_root, 0u, 0u); std::string ret; for (auto&& character : message) ret += map[character]; return std::move(ret); } std::string decodeMessage(const std::string& binaryMessage) { std::string decodedStr; auto temp = m_root; for (auto&& character : binaryMessage) { if (character == '1') temp = *temp.right; else temp = *temp.left; if (!temp.left && !temp.right) { decodedStr += temp.character; temp = m_root; } } return std::move(decodedStr); } }; int main() { std::ifstream file("text.txt"); std::string message, line; while (std::getline(file, line)) message += line; HuffmanCoder hf; const auto& a = hf.encodeMessage(message); const auto& b = hf.decodeMessage(a); std::cout << a << "\n\n" << b; }
Input for the encoder: ?
Characters and their binds.
Related Questions
Sponsored Content
0 Answered Questions
Compression/decompression using Huffman Coding Algorithm
- 2018-05-27 08:23:32
- Harry Nguyen
- 1345 View
- 4 Score
- 0 Answer
- Tags: c++ beginner algorithm tree compression
3 Answered Questions
[SOLVED] Huffman code implementation
- 2014-03-15 22:07:16
- JavaDeveloper
- 58286 View
- 11 Score
- 3 Answer
- Tags: java algorithm compression
2 Answered Questions
[SOLVED] Huffman Coding in C++
- 2017-09-09 06:07:10
- coder
- 11902 View
- 4 Score
- 2 Answer
- Tags: c++ c++11 compression priority-queue
0 Answered Questions
Huffman encoding implementation -follow up
- 2017-06-06 00:30:26
- MAG
- 93 View
- 2 Score
- 0 Answer
- Tags: rust compression
1 Answered Questions
[SOLVED] C++ Huffman coder and decoder
- 2017-05-18 19:52:14
- Yksuh
- 1327 View
- 8 Score
- 1 Answer
- Tags: c++ compression
1 Answered Questions
[SOLVED] Huffman encoding implementation for Unicode
- 2016-12-23 21:57:33
- MAG
- 181 View
- 6 Score
- 1 Answer
- Tags: rust compression
2 Answered Questions
[SOLVED] Huffman compressor in C++
- 2016-12-02 06:55:07
- coderodde
- 903 View
- 4 Score
- 2 Answer
- Tags: c++ console compression
1 Answered Questions
[SOLVED] C++11 implementation of Huffman-encoding
- 2015-12-19 22:57:43
- DJMcMayhem
- 2925 View
- 12 Score
- 1 Answer
- Tags: c++ c++11 compression
1 Answered Questions
[SOLVED] Huffman tree Python implementation
- 2015-10-29 06:34:39
- CodeYogi
- 2363 View
- 3 Score
- 1 Answer
- Tags: python algorithm python-2.x compression
3 Answered Questions
[SOLVED] Huffman decoding for video
- 2011-08-29 11:51:39
- ronag
- 2848 View
- 12 Score
- 3 Answer
- Tags: c++ performance compression video
@Bizkit 2016-04-07 14:32:10
There's really no need to do all that bit manipulation when you can simply do:
and let the compiler worry about those kinds of "instead of multiplying by 2, shift by 1" optimizations and have it handle it for us. That version (to me at least) is much clearer than the one you previously had.
EDIT: I would also put parenthesis around the expression that the
*operator is supposed to dereference to make it clearer as I've done above. A similar syntactical fix needs to be done in
decodeMessage()too.
I think you're trying to force move semantics in areas where they aren't necessary. An example is the code snippet below:
There is no reason to have an r-value reference (and consequently moving characters out of the
messagestring) when you're updating the
ret string. You're passing in
messageby const reference so you should not be modifying the
messagein the function. This loop really should be:
This also applies for the similar loop in
decodeMessage().
Having
std::moveto move the return value out of the function may inhibit the compiler from performing RVO (which is even faster than move assignment). Just return the value normally and only add the
std::movewhen you have evidence that the return value is returned by a copy.
There is no need to have this line in the code:
The compiler generates the default constructor for you so there's no reason to declare it here.
In your
assignCodesfunction, you're creating a binary representation of the currWord number here:
I would be inclined to have this as a private member method to do this for me:
Now I can just simply call the function inside of
assignCodes():
You can avoid having to do a string reverse by doing this:
A similar transformation can be done for this code inside of
encodeMessage():
Turn that into a function that returns the priority_queue:
Finally, in your TreeNode() initializer list, you're initializing
frequency(which is an unsigned type) using a signed value. If you don't need negative numbers (and you don't), then use only unsigned numbers:
EDIT:
I can't believe I failed to mention this:
Your class dynamically creates Nodes using
newbut I don't see
deleteanywhere; as a result, your class will leak all that memory. Use
std::unique_ptrto avoid having to deal with memory management issues.
@Bizkit 2016-04-07 19:31:57
Oh, I see. I'll edit the answer then. Thanks for the clarification.
@Levon 2016-04-08 00:50:09
Thank you for answering! I just cannot get my head around move semantics so I use it when I feel to. I know this is not good practice but I felt like that would improve my code :/ . Also, what looked interesting since it could potentially speed up my algorithm was avoiding using reverse, however, the code that you put there does not work :P
@Bizkit 2016-04-08 13:25:06
@Levon Oops! Silly me... I forgot to add one more shift. I edited my answer :) This is why you should test code before posting it haha but I didn't have a compiler environment to work on at the time.
@Levon 2016-04-08 19:22:09
Are you sure it works? It does since num & (1 << shift) ALWAYS returns 0. I do not really know why it returns 0 every time, does not matter the number or what shift's value is
@Bizkit 2016-04-11 11:44:04
Yes, I'm sure it works. I let it run for all 4 billion integers in the
unsignedrange and it worked correctly. How are you testing the function? What values are you assigning to
depth?
@Levon 2016-04-11 20:07:24
It does not matter what parameters I give to that function, it always returns 0. For example, if I call the function like this numToBin(10u,5u). Am I doing something wrong? :P
@Bizkit 2016-04-20 14:00:12
For that particular input, keep in mind that
unsignedis 32 bits wide and that the
forloop in my function is conditioned on the
depthparameter. In the case where the depth is 5 and the number is 10, the 5 MSB of the value 10 represented in 32 bits are
00000. That's why you're getting 0. Try setting depth to 32 and testing the function separately from this program. | https://tutel.me/c/codereview/questions/125037/huffman+algorithm+implementation+in+c | CC-MAIN-2019-22 | refinedweb | 1,408 | 51.07 |
IBM Cloud Kubernetes Service Introduces the ALB OAuth Proxy Add-On
5 min read
Protect your applications running on an IBM Cloud Kubernetes Service cluster with IBM Cloud App ID.
When you create an IBM Cloud Kubernetes Service cluster, a default Application Load Balancer (ALB) is created for you in the new cluster. The ALB is an Ingress controller, in practice.
As of 24 August 2020, you can now choose to deploy the Kubernetes Ingress controller as the default ALB for your cluster. Please see the announcement here for more information.
The ALB takes care of the routing of the incoming HTTP(S) requests to your applications that are deployed in your cluster. In many cases, you may want to authenticate and authorize the clients that send those incoming requests. This article will show you how to use the new IBM Cloud Kubernetes Service ALB OAuth Proxy Add-On to integrate the Kubernetes Ingress controller with IBM Cloud App ID to protect your applications. For more information about IBM Cloud App ID please see this YouTube channel.
How it works
The IBM Cloud Kubernetes Service ALB OAuth Proxy Add-On deploys and manages an OAuth2-Proxy deployment in your cluster for each and every IBM Cloud App ID service instance that you want to use. The OAuth2-Proxy provides the OIDC Relying Party (Client) function for the Kubernetes Ingress controller (ALB).
The following figure presents the interactions of the different system components during an OIDC Authorization Code Flow:
- The User Agent sends a GET request to obtain the protected data from the Application.
- The IBM Cloud Kubernetes Service ALB is configured to authenticate such a request. The ALB sends an Authentication request to the OAuth2-Proxy, which has been deployed by the ALB OAuth Proxy Add-on previously.
- As there is no valid Access Token in the request, the OAuth2-Proxy sends a 401 Unauthorized response to the ALB.
- The ALB redirects the User Agent to the URL, which will trigger the start of the authorization flow. The URL’s host part points to the ALB.
- The User Agent sends a new request to the new URL. Due to the host of the URL, the request is routed to the ALB again.
- The ALB is configured to send this kind of request to the OAuth2-Proxy.
- The OAuth2-Proxy redirects the User Agent to the Authorization Endpoint of the IBM Cloud App ID Service.
- The IBM Cloud App ID Service executes the authentication of the End-User behind the User Agent. The IBM Cloud App ID Service uses the services of the Identity Provider, which has been configured for this IBM Cloud App ID Service instance to authenticate the End-User.
- If the authentication of the End-User is successful, the IBM Cloud App ID Service redirects the User Agent to the redirect URL, which has been registered in the IBM Cloud App ID Service instance. The host part of the redirect URL points to the ALB. The IBM Cloud App ID Service includes the Authorization Code into the redirection response.
- The User Agent sends a new request with the Authorization Code to the callback URL.
- The ALB is configured to route this kind of requests to the OAuth2-Proxy.
- The OAuth2-Proxy sends the Authorization Code to the Token endpoint of the IBM Cloud App ID Service.
- The IBM Cloud App ID Service responds with an Access Token, an ID Token, and (optionally) a Refresh Token.
- The OAuth2-Proxy redirects the User Agent to the original request URL. As we use the OAuth2-Proxy in stateless mode, the redirection response contains the Access Token, the ID Token, and the Refresh Token in cookies.
- The User Agent sends a new request to the original request URL, but this time, it includes the Access Token, the ID Token, and the Refresh Token in the request as cookies.
- The ALB is configured to authenticate such a request, so the ALB sends an Authentication request to the OAuth2-Proxy.
- The OAuth2-Proxy validates the tokens and it answers with a 202 Accepted response to the ALB.
- The ALB routes the request to the backend Application. The request may contain the Access Token, or the ID Token based on the ALB configuration.
Usage
Prerequisites
Create an IBM Cloud App ID service instance and bind that to the cluster:
- Navigate to IBM Cloud App ID in the service catalog.
- Select a deployment region and the pricing plan.
- Replace the auto-filled service name with your own unique name for the IBM Cloud App ID service instance. The service instance name must contain only alphanumeric characters or hyphens (-) and can't contain spaces.
- Click Create. The App ID management console will be displayed:
- In the IBM Cloud App ID management console, navigate to Manage Authentication:
- In the Identity providers tab, make sure that you have an Identity Provider selected. If no Identity Provider is selected, the user will not be authenticated but will be issued an access token for anonymous access to the app. Next, create a Cloud Directory user:
- Click Edit on the Cloud Directory card.
- In the left-hand navigation, click Users:
- Click Create User. Give the details of your user in the dialog box, and save the user:
- Navigate back to Manage Authentication, and select the Authentication settings tab:
- In the Authentication settings tab, add redirect URLs for your app. A redirect URL is the callback endpoint of your app. To prevent phishing attacks, IBM Cloud App ID validates the request URL against the allowlist of redirect URLs. A redirect URL shall have the following form:
- Bind the IBM Cloud App ID service instance to your IBM Cloud Kubernetes Service cluster. Be sure to bind the service instance to the same Kubernetes namespace that your Ingress resources will be created:
Usage of the ALB OAuth Proxy Add-on
- Enable the ALB OAuth Proxy Add-on for your cluster:
- In the IBM Cloud Kubernetes Service console, click your cluster and click the Add-ons tab. On the ALB OAuth Proxy card, click Install:
- From the IBM Cloud CLI, run the following command:
- Verify that the ALB OAuth Proxy Add-On has a status of
Addon Ready:
- In the Ingress resources for your app where you want to add IBM Cloud App ID authentication, add the following annotations to the
metadata.annotationssection:
- Verify that the IBM Cloud App ID authentication is enforced for your apps. Access your app's URL in a web browser. If IBM Cloud App ID is correctly applied, you are redirected to an IBM Cloud App ID authentication log-in page. Log in with the user you created in the Cloud Directory above. After a successful authentication, you are redirected to your app and you can see the response of your app in the browser.
More information
For more information, check out our official documentation.
Learn more about the Kubernetes Ingress controller in the IBM Cloud Kubernetes Service:
Follow IBM Cloud
Be the first to hear about news, product updates, and innovation from IBM Cloud.Email subscribeRSS | https://www.ibm.com/cloud/blog/announcements/ibm-cloud-kubernetes-service-alb-oauth-proxy-add-on | CC-MAIN-2021-49 | refinedweb | 1,176 | 59.94 |
hey guys.i have one realy big big problem.. My programming teacher gave my a task to get these functions to work, but i dont know python program so good.. thats why maybe someone of you could help me, and make these 3 functions to work .:).. please!! these lines are not in corect order, and they nedd to be in another place..
for j in range(i, 0, -1):
def bubble(l):
l[j], l[j-1] = l[j-1], l[j]
for j in range(len(l)-1, i, -1):
return l
k = j
def selection(l):
for i in range(0, len(l)):
if not swapped:
break
for i in range(0, len(l)):
if l[j] > l[j-1]:
break
k = i
def insertion(l):
for j in range(i+1, len(l)):
if l[j] < l[j-1]:
l[j], l[j-1] = l[j-1], l[j]
return l
swapped = True
if l[j] < l[k]:
for i in range(1, len(l)):
l, l[k] = l[k], l
return l
swapped = False
Edited by sikais17: n/a | https://www.daniweb.com/programming/software-development/threads/310130/please-help-me-with-these-python-algorytms | CC-MAIN-2018-17 | refinedweb | 183 | 76.29 |
CodePlexProject Hosting for Open Source Software
I would like to randomly show a content item from a list in the sidebar of my site. For example, I have a list of images and I would like to build off of the container widget to allow for options to only show 1 item and make it random.
Can I copy the Container Widget and just trim it down to just pulling a random item? I can't seem to find the Container Widget code in modules so this makes me think it is in Core?
It's defined in \src\Orchard.Web\Core\Containers\Migrations.cs. The relevant part you are probably looking for is the container part.
So if I wanted to build my own widget called "Random Container Item Widget" would I just copy and trim down this code for the most part?
Does it make sense to make a new content part called "Random Item Containers" and mimic everything except the data retrieval piece, or build a content part that can attach to the existing Container type and then do the filtering there?
I would do the second one, if you're on 1.x, because then you can just hide the normal list with placement and render your own shape.
Yes, I am on 1.3.
So I am fairly new to module development. But would I add some logic in my module's placement.info to hide the normal rendering : <Place Parts_ContainerWidget="Nowhere"/> ??
The rendering of my own shape, would that occur once my module was called in the request cycle after all the other content parts were called? I would get a list object and I could randomly return a single item?
To hide shapes use <Place Parts_ContainerWidget="-"/> - that's the nowhere zone (otherwise the rendering code will still run even tho your item doesn't display). Use shape tracing to find out the name of the shape you want to target.
Drivers render shapes in whatever order Autofac provides the dependencies, but that doesn't really matter, because of course you control the final position with placement.
The important thing to realise is that in your driver you have to wrap the code in a delegate function like this:
return ShapeResult("Parts_RandomContainerItem",()=>{
var item = part.(code to get your random item);
return _contentManager.BuildDisplay(item,"Summary");
});
By doing things this way, your code will only run if Placement actually finds a zone for your shape. This means you can have many complex shapes available for a part but only incur the overhead for the ones you actually use in your display.
Hello arock3,
I have been wanting to create a "randomizer" for Container items and am planning on working on it in the next week or so. I thought it would be really handy for Testimonials so they would pull through different every time. This has been a good discussion
and I like what you and randompete concluded about using a new contentpart. That is the approach I will plan on taking. If I have success before you are finished I will post my code up here on this thread. Thanks for doing likewise and I will
also keep watching this thread to see if others or you have success doing this.
So in order to avoid writing a content part (due to time) I added a Parts.ContainerWidget.cshtml file to my Theme\Views folder. I then put the following code in there:
@using Orchard.ContentManagement;
@using Orchard.Core.Containers.Models;
@{
IEnumerable<object> items = Model.ContentItems;
Model.ContentItems.Classes.Add("content-items");
Model.ContentItems.Classes.Add("list-items");
var rand = new Random();
var zone = ???
}
@if(zone == "AsideSecond")
{
@Display(items.ElementAt(rand.Next(0, (items.Count() - 1))))
else
@Display(items)
------------
This will randomly display elements from the list. The only thing I would like to fix is the statement in front of it to check the zone before I call this. I am not sure how to grab the zone name in this context. I know a content part would be best, rather
than filtering on the front end, but this is working now.
The wrapper is not a bad idea, my only concern is that (normally) a widget for a container item only returns the Top 10 or the Top 20 (depending on your setting). Therefore, if you exceed this many quantity in your List, I believe you would only be
randomizing the display order of the Top "XX" and not the whole list. Either way, I think (from using Shape Tracing) that you can find the name at:
Model.Child.Parent.Content.ZoneName
I have not tested it but this is how it shows under Shape Tracing Model tab. Hope it works for you and I look forward to hearing whether your randomizer only works on the Top "XX" or whether it is truly randomizing the whole list.
@jao28. Yea I set the count to return to something very large like 50 so this wouldn't happen to me. The statement Model.Child.Parent.Content.ZoneName does not seem to resolve in the Parts.ContainerWidget.cshtml. Ideally I could filter based on zone
name or even widget name so that this filtering was not applied everywhere. Right now it works, since I am not using lists anywhere else. Know anyway to get the widget name?
@arock3. Sorry, I was looking at a regular content item. According to Shape Tracing, it should be the following:
Model.Child.Parent.ContentItem.WidgetPart.Zone
HOWEVER, this is an easier way to get at it (and is the one I tested and found working):
Model.ContentItem.WidgetPart.Zone
Of course, this process should/will throw an error if no WidgetPart exists. Therefore, you could first check to see if the WidgetPart exists before grabbing the Zone from it. Of course, if your wrapper is for a widget it will :) so not likely
worth checking. I decided to actually test this so here is my working code (based off your code of course):
@using Orchard.ContentManagement;
@using Orchard.Core.Containers.Models;
@{
IEnumerable<object> items = Model.ContentItems;
// Threw an error for me
//Model.ContentItems.Classes.Add("content-items");
// Threw an error for me
//Model.ContentItems.Classes.Add("list-items");
var rand = new Random();
var zone = Model.ContentItem.WidgetPart.Zone;
}
@if(zone == "AsideSecond") {
@Display(items.ElementAt(rand.Next(0, (items.Count() - 1))))
}
else {
@Display(Model.Child)
}
Note that I had to use "@Display(Model.Child)" in the else statement as that is normally what get's rendered. Also, I only confirmed that the "zone" worked as expected (which is what you are really looking for). I don't have time right yet to confirm the
"@Display(items.ElementAt(rand.Next(0, (items.Count() - 1))))" functions as you are expecting - I just don't have a list/container item in place to test it on. However, I look forward to hearing back from you if it does.
@jao, Both of those statements do not return the zone name. The WidgetPart is null all of the time. I was thinking:
var zone = ((IContent) Model.ContentItem).As<ContainerWidgetPart>().Zone;
But it does not work either. Seems there is not much info at this point in the rendering.
Also the core template uses:
@Display(items);
Sooo I think it should be that.
My random rendering is working great....it is just if I ever add another container widget on the site, it will use this rendering too. Need something to switch on.
@arock3, that is because I am overriding "Widget.Wrapper.cshtml" where it looks like you are overriding "Parts.ContainerWidget.cshtml". It is possible you are at too low of a level and thus you cannot get back up to the Widget level to access the actual
zone information (which is on the WidgetPart). The code I provided does work as "Widget.Wrapper.cshtml". If you want to see what options you have, I HIGHLY recommend turning on the "Shape Tracing" module - it is a wonderful module that allows you
to view the Model and all the options that go with it.
By the way, I fully understand why you want to just override the "Parts.ContainerWidget.cshtml" as that obviously gaurantees you are on a Container item. The alternative is to use my example and check to see if the widget CONTAINS a Container Part.
This way you get access to higher level information (such as the Zone). Check the "Shape Tracing" first though as you might possibly have access to this... Keep me informed and I will help as I can.
Yea I mean I didn't think Widget.Wrapper was the right spot to do this, but you could filter the items at that higher level I guess. Hmmm I am not sure.
Yes, I use Shape Tracing a lot for this and am familiar with the module.
I think writing a content part would be the best solution obviously, I just am not proficient enough in writing them yet and needed a quick fix. It would be great to have an option in the container widget to randomize the item returned.
I think your solution would work if we did it in Widget.Wrapper.cshtml. I am going to investigate writing the content part this weekend.
Thanks for all your help!
I totally agree, a content type that can be added or removed at will and thus only target what you want is ideal. Please keep me informed as you are working on it because I would like to contribute. I am a little bit away from being able to tackle
it but it was on my list. I have not looked enough at what events a "Container" part has available to the developer, but if it had an "OnQuerying" event or something like that, this new content type that you are creating could catch that event and handle it
and thus return the data (randomized of course). It could likely even grab the "Top XX" setting from the actual widget so you only return the number of results that the user was expecting to see. It could be a great little content type - keep me informed.
Since this is a topic on randomness, for obvious reasons I want to help :)
Firstly, you don't need to write a content part (I never said this) - all you need is a driver. That's one single code file, as opposed to a whole part, which requires many files including a driver.
The problem with the solution you've currently got is that Orchard is performing a whole lot of work just to display one item: "I set the count to return to something very large like 50". This means you are loading up to 50 items from the database, running
them all through the whole rendering process (which isn't trivial) - only to use one of those resultant shapes.
This is why you need a driver - so you can have your own database code where you optimally read just a single item. By hiding the original Parts_ContainerWidget, you ensure
it won't load any items from the database. In your custom random select query, you can ignore the list length anyway and just read the whole table.
Here's the tricky part. It's actually not so easy to do a random select query in MSSQL.
See the following StackOverflow thread for reasons why
SELECT * FROM table ORDER BY RAND() LIMIT 1
and similar variants still have performance issues:
The way I eventually found to do it was to create a database View that generates a random number, then join your table to it and sort on that number. Just been searching for a reference to this and I can't find it anywhere now. Still, unless you're querying
100,000s of rows performance should be better than the current approach. There are much better ways to, say, select approx. x% of rows; but it seems generally quite bad for seeking specific numbers.
Hello @randompete, how could you help but join in - the name says it all :) Thanks for the reply and thanks for all your help on these forums, greatly appreciated.
Can you clear up some verbiage for me? When you say all you need is a driver, how would you create a driver and associate it with a Content Type if it were not wrapped up as a Content Part? Maybe that would not be possible and you are
saying just to hard code it (say by dropping the "driver.cs" it into the theme or something) instead of letting the user choose on what Content Type to apply this randomness. Thanks for helping me learn on this one.
And thanks for the great database references, I wonder if that can be done through NHibernate/LINQ... I was concerned about the difficulty of randomness and wanted to stay with native Orchard (i.e. without going into HQL or whatever that option
is for typing straight SQL). The only way I can think of would be to perform two queries. The first query would return a list of all the valid Content ID's back to the Driver. Then the driver (somehow) would have to extract a random set. Then (lot of
assumptions here) that could be somehow inner joined with NHibernate. If that was not feasible, then would somehow have to use "IN" as in SQL like "WHERE Id IN (XX, YY, ZZ)" - I am sure that would not be too speedy.
More than likely I did not use the correct terminology on some items above. Thanks for pointing this out (if you will) as I actively learning the product and want to be clear.
My guess if create a Drivers folder in your theme. Then add a file named ContainerWidgetPartDriver.cs. This would then override the existing driver? But if we don't have our own content part to attach to our own content type that has the container part,
how do we differentiate from normal rendering widgets and our RandomItemContainerWidget?
All ContentPartDrivers across the whole of Orchard execute sequentially, and in the base implementation they check if their part type exists and run if so. This means that you can have multiple drivers for a single ContentPart.
This means you can just create your own:
public class RandomContainerWidgetContentPartDriver : ContentPartDriver<ContainerWidgetPart> {
/// ... etc
It'll run as well as the core driver, and each will generate a shape result. But the construction delegates from each will only execute if Placement matches, so you just switch off Parts_ContainerWidget to stop it rendering or composing.
It also occurred to me once you have a proper random query, you can limit the query by the property ContainerWidgetPart.Record.PageSize - so it decides how many random items you want to show.
jao28: To clarify, I'm not talking about Content Types. A content type is kind of a template of which ContentParts to construct an item from, and settings to apply to those parts. Here I am talking about applying a driver to a single ContentPart (specifically
the ContainerWidgetPart, but you could just as easily also do this with normal ContainerPart).
Whichever way is chosen, I think this will involve first executing an SQL statement (which you can do thru Orchard already) which retrieves just a randomised list of Ids. Then perform a ContentManager.GetMany(..) to properly load all the content items. There
isn't a more efficient way to do it, due to the intricacies of content manager (although this might change with 1.4 / Projector).
I still think the method I previously used (joining/sorting on a random View) was actually much more efficient than the alternatives, for reasons which I dimly recall. The SQL to create the View looked like this:
CREATE VIEW [dbo].[RandomView]
AS
SELECT NEWID() As ID
GO
You can run that in a migration. You might want to use Orchard's table prefix to get a unique RandomView per tenant. Then finally compose an SQL to join the CommonPartRecords to it (filtering on CommonPartRecord.Container.Id) and sort on the RandomView.ID
column.
When I originally found this technique I was dealing with a really large content database, and we had to do this to make things remotely efficient. We were doing things like pulling out randomised adverts, recommended content, etc., but from a very large
pool, and from the same table as the rest of the content items.
@jao, you getting all of this? Any thoughts on writing the driver? In my case there would be no more than 20 items at any time, so querying all the items and then filtering in the app is not a big deal to me. Just finding the right extension point is good
enough for me.
Thanks so much for your insight RandomPete!
You're not just querying them, you're rendering also. This takes a surprising amount of time because all the handlers/drivers have to be called
all over again, it could easily slow your page down enough to feel it with just 20 items, especially if you had anything complex going on elsewhere on the page (and of course this does depend exactly what parts you have attached to your items). Still,
it might not be so bad that you can't put up with it, but it'd be great to have a random content module available that could cope with larger amounts of content. e.g. for a "quote of the day" system where you had 1,000 quotes stored as content items - that
kind of scenario would start causing serious performance issues.
@randompete, first off, THANKS, I did not you could have multiple drivers sor a single Content Part - that rocks... there have been many times I have wondered how I could "override" an existing Content Part that someone created in their module but I did
not want to hit their code (so that I could continue to use the future updates they made). VERY powerful. I am definitely going to work on a robust "Random Content" module - this could be very useful for the community as a whole. I have
built a number of modules, but never hosted on CodePlex. Time to get in the game - I will use all of these great ideas and start something and get it shared so many people can contribute.
@arock3, I am not sure I will be quick enough for your demands but I will try. As soon as I get something started I will post the link back here.
If you hide the normal ContainerPart in placement.info and then create your own driver, won't it always use this driver in all cases a container widget is used? For example, on my homepage in the Contnet zone I have a list of items I need normal rendering,
but then in the AsideSecond zone I want my container with a random image from a list to show up. Overriding Parts.ContainerWidget.cshtml in my theme I can access literally no information about what zone or widget title/id is being rendered. I would love to
be able to switch off of widget name or ideally zone here. I know this is not ideal(all the reasons above) but I need a quick fix here. Here is my code:
I need someway to check zone here or at least widget name.
Does the functionality described in this post now exist in the Widget Alternates module? Could I create a template called Parts.ContainerWidget-AsideSecond.cshtml
Doesn't seem to work
Use shape tracing to find what alternates are available. When I do, I see the following for body part in tripel second zone:
~/Themes/TheThemeMachine/Views/Parts.Common.Body.cshtml
~/Themes/TheThemeMachine/Views/Parts.Common.Body-10.cshtml
~/Themes/TheThemeMachine/Views/Parts.Common.Body-HtmlWidget.cshtml
~/Themes/TheThemeMachine/Views/Parts.Common.Body-HtmlWidget-TripelSecond.cshtml
~/Themes/TheThemeMachine/Views/Parts.Common.Body-TripelSecond.cshtml
Hello @bertrandleroy, @arock3, and @randompete:
As I am going through building this module, I am wondering what ability there is to have the Container Part NOT render WHEN it also has the new "Random Container Part" associated with it. For example, if I have a Content Type that contains both the
Container Part and this new Random Container Part, I want my Random Container Part to handle the display while the existing Container Part would not even generate a shape (i.e. don't want to waste time generating a shape that won't be used). I
know in the Placement.info I can do this, but I was wondering if there is a way via code as I would rather my module control all of this instead of relying on the user to modify their placement.info every time.
@bertrandleroy, I have read your blog article on controlling Placement.info at but
it seems I would need to inject the helper into the user's active theme (along with some other things). It seems that if I add my own Placement.info to my module that I could handle hiding the Container Part or Container Widget Part but this seems like
this would trickle down across either the whole page or the current zone I elect to hide it in (as @arock3 is experiencing). Ideally, I could return "false" in this part of the code telling all other ContentPartDriver<ContainerWidgetPart>
not to render but then 1. I don't know if this is possible 2. How do I know my driver would run first:
/// ... etc
Obviously one solution is just to build a Random Container Widget Part that does all the functionality of the Container Widget Part but likely then I would have to deal with the issue of whether, in Orchard, this would be recognized as a true "Container
Widget Part" such that containable items could be associated with it. I would like to avoid this and modify as little of the native functionality as possible.
Thanks again for any recommendations.
It seems like to me that the "Randomness" should just be a content part that attaches to the normal container. It then will modify at the query level to only return 1 random item. (or a configurable amount of items). Then all the pagination, filtering, and
sorting would come into play after that. It would just be an option that sits on the editor screen of the container widget.
Hi @arock3,
I don't disagree, I just don't know how to prevent the existing Driver (i.e. the ContainerWidgetPart or even the ContainerPart) from rendering it's shape. We cannot have both shapes (i.e. the ContainerWidgetPart and the RandomContainerWidgetPart shapes) rendered
otherwise you will have two shapes on screen... It does not seem right to build a module that requires a user to override their own Placement.info either. Thanks for your thoughts.
@jao28: you should not attempt to override the user's placement decisions. I'm not sure why I would want you to suppress the rendering of the container part when your stuff is active. But if you really want to make different decisions than the regular container,
I would advise creating a separate part. There is nothing magical about the regular container widget that you wouldn't be able to reproduce.
So why does your widget content type have ContainerWidgetPart at all?
Hello @bertrandleroy,
I may end up just creating a separate part. My concern was that, when in Orchard, for a Containable item to be used it has to be paired up with a "Container" part. So, I was not sure my "RandomContainerPart" would be eligible for this functionality.
In other words, is the "Container" part special because it implements a certain interface or because of something like the actual name "Container". If it is because of something like the name then I cannot simply create a RandomContainerPart and
expect it to work with the existing "ContainablePart". However, it seems from what you have written that this should not be a concern and that I should be able to pair my new "RandomContainerPart" up with "Containable" parts and get the effect I want
- time will tell. I jsut did not want to reinvent the wheel if I could simply extend existing functionality. However, sometimes it is quicker to just reinvent (in this case modify). Thanks for any additional comments you have
and if you don't that is fine. Thanks again.
Also, your part does not necessarily need to render anything, if all it does is modify the data that other parts are displaying.
Yeah, but there is no event (that I know of) to intercept the existing ContainerPart driver and deliver different data... That is my goal is to simply override the data request and use the "native" containerpart but I would have to deal with one of
the two problems:
Without replacing the complete module, is there anyway to get around either one of the two items above?
I don't think there's any way to hook into ContainerPart and modify the data that's displayed (especially since you only want it to display the random item in certain circumstances), I think the shape method is the best, if you want to leverage containers.
It's not hard for a user to switch shapes on or off in placement, have your shape not displayed by default so they still get the normal container placement, and can switch the random item version on for specific content types and display types.
*However* there's a completely different (and probably easier) way you can go about this.
Rather than using a container, just create a whole new content type for this behaviour, and a new widget. I'll call this content type "RandomItem" for example. Then in your widget just do a content query for "RandomItem" content type and pick a random one
to display it. Then any new "RandomItem" you create will automatically be in the random pool (and they can still interact with other containers if required). I think this is simpler, and I did a similar thing for Ad selection in a site I built ...
If you hide the original shape with placement, the database work is never done (because the shape implements the factory method) and therefore you can provide your own shape with your own data, but based on the existing part.
At a minimum, I have learned a lot just by having this conversation (and likely others who review this in the future will benefit also). I am going to target a dedicated (separate) widget.
The next big thing will be to see if I can push the randomization down to the database level. @randompete you have some good ideas on that and I will be trying them (using the View approach). The current process I have requires that I pull a list of unique
Id's (first database call) and then randomize the id's in order to select the final content I need (second database call). This is fine on small datasets but will baloon as soon as the amount of content increases. I will let you know...
Oh yeah, @arock3, I have never succeeded with the "Custom Field Filtering" - I am not sure they are tied off. I bet @bertrandleroy or @randompete will have a better reply though...
Hello Again @arock3,
I do believe @bertrandleroy has added value to Custom field filtering in his Vandelay Industries module. I have not tested it yet but as soon as I saw "Custom One", "Custom Two", and "Custom Three" options as a result of activating this module I
immediately thought of your question in regards to custom field filtering. Thanks @bertrandleroy for adding even more value.
It wasn't me :) The three custom fields come with the list feature iirc.
@bertandleroy "So why does your widget content type have ContainerWidgetPart at all?"
I figured it needed the functionality from container to hold and edit all of the items a user might add to a list.
I guess your right though, it really can be its own separate piece of functionality. In my example, I have random quotes appear on each page of the site. These quotes are organized as a List>Quotes (Created Content Type in Orchard Admin). Basically,
in summary view I wanted to only show 1 item and have it random. I added a container widget to my "default" layer and are controlling what appears through the view. (Got this working now and all is good. Even though it is pretty hacky.)
If you look at it again, it really could be a new widget type that just returns a random item of content of a specific type. RandomContentWidget, could just ask you to select the content type you want to randomize and then pull a random item from the
DB without even caring about a container at all. This may be easier for me to write as it is a much simpler concept than a content part to container type, etc, etc.
I will try this approach out. Thanks Bertrand.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/282075 | CC-MAIN-2017-30 | refinedweb | 4,895 | 71.04 |
How you approach a problem is to some extent your key to accomplishing good solid work. This walkthrough will guide you in the six most commonly used methods for button creation and show you in which situations they are best put to use.
The Button Making Dilemma
Let me tell you a little story about how all of this button interaction conflict started. One day Adam and Eve were out in the Garden of Eden.
ADAM: Hey Eve, you look different today, what's wrong?
EVE: I'm really thirsty, and we don't have fresh water anymore.
ADAM: Stay right here.
Adam went to a near by vending machine, saw an apple juice box, memorized its number, inserted a coin and pressed the button! Nothing happened. There was a bug.
You see, Adam started an event that should have triggered an action. Luckily, being a well versed ActionScript programmer, he plugged his USB ActionScript compiler into the vending machine's USB ActionScript programming slot and started to debug the code.
He had a shape lying on the stage that looked like a button, and nothing else. Someone had forgotten to make the code. It was now up to him to find the most appropriate method to approach this problem and code his way to the juice box.
Old School Method
When you first open Flash 5 you're prompted to view a few tutorials if you wish. One of these tutorials teaches you how to make simple button interaction and for the most part of your ActionScript 1 and beginning 2 you follow that path.
It works something like this:
- Create a button symbol.
- Inside the symbol set the states you want the button to have.
- Go to the timeline where you put the button, click to select it, open up the actions and write:
on(press){ trace("hihi that tickles"); }
Even though it's not standard practice anymore, there are a lot of designers that I know who still use this method. It's still quite useful if you're on a tight deadline, you're working on a banner restricted to Flash Player 5 or lower (yes there are still restrictions of that sort nowadays) and you have to rely on a designer to build and animate the banner. In the end all you need is a clickTag button.
Note: A clickTag is a variable that an ad host injects inside a swf object through html. It contains the url to which the banner should navigate. Check out Victor Jackson's clickTag tut for more information.
Download example 1 to see this method in action.
If I Could Just Tell the Target...
Later in your ActionScript life, when 2.0 came along, there was also the ability to associate functions to events inside MovieClip Objects. By using this method you could build your own button based on a movieclip and the best thing was that all your code could be stored in just one place. This is very useful for menus, too bad it was only made available in Flash Player 6.
Here's how that workflow looks.
- Create a movieclip symbol.
- For the states you can do whatever you want: you could add keyframes, you could create different movieclips, you could color transform them, it's up to you since you are going to have full control over the events.
- Give the movieclip you created an instance name, I named mine "myMovieClip".
- Place the movieclip on stage and in the same keyframe (different layer) add the following lines of code:
myMovieclip.onRollOver = function(){ trace("hihi, that tickles"); } myMovieclip.onPress = function(){ trace("hihi, that tickles too"); } myMovieclip.onRollOut = function(){ trace("ouch, now that hurts!!"); }
If you have a player limitation up to version 8 or you're not used to AS3 and you're building something with little interaction, this is the way to go.
Download example 2 to see this method in action.
You Can Actually Delegate
For more complex models, where the structure involves nested movieclips for instance, you can actually delegate functions and set a new scope for the function to act. This may sound confusing so just check the difference below.
//Regular code myMovieclip.stop_bt.onPress = function(){ this._parent.myAnimation.stop(); }; myMovieclip.play_bt.onPress = function(){ this._parent.myAnimation.play(); }; //Delegate import mx.utils.Delegate; myMovieclip.onPlayClick = function() { this.myAnimation.play(); }; myMovieclip.onStopClick = function() { this.myAnimation.stop(); }; myMovieclip.play_bt.onPress = Delegate.create(myMovieclip, myMovieclip.onPlayClick); myMovieclip.stop_bt.onPress = Delegate.create(myMovieclip, myMovieclip.onStopClick);
As you can see there's no need to call the parent, I can just re-scope to the object. This is a fairly simple example, but you can see how this could come in handy in a more complex situation.
Download example 3 to see this method in action.
3.0
That's all very pretty, but if you have no restrictions at all concerning the player version, you should ignore all the steps above and focus on ActionScript 3.0. Not feeling comfortable with the language is no excuse, you will never feel comfortable with something unless you use it. After a few hours understanding the syntax and a few days with the AS2 to AS3 cheat sheet next to you, you will feel right at home. It doesn't need to be completely OOP class based, if you are used to timeline programming you can keep doing that. The Flash IDE will build a MainTimeline class as soon as you export your movie.
Just write this in the first frame of your FLA, consider you have a movieclip symbol on that keyframe (different layer though, just to help organization) with an instance of myMovieClip.
myMovieClip.addEventListener(MouseEvent.CLICK,onClickHandler) function onClickHandler(e){ trace("I said that tickles!! NOW STOP!"); }
There are a few drawbacks to using this method though:
- Dispersed code, like when we have too many symbols on stage and lose track of where the code is sitting for a particular object
- Code reusability is a no-no, the only way you reuse anything is by copy-paste, and that's a bit lame isn't it?
But I must admit, I use this method way too often. Mostly for convenience, but I regret it most of the times. My advice is to program in the timeline only with banner ads and small simple mini/micro sites. Even in those cases you may want to import a slider class, a slideshow class, a tween class, a snow making class, etc. that you will build specifically for that project.
Download example 4 to see this method in action.
Full Structured Object Oriented Programming
Let's do the same with a full OOP approach. Say the designer has built the Flash file and left the graphics on stage, here's what to do.
In the Flash IDE convert the graphic to a symbol and give it an instance name. In a new AS file named Main.as write the following code:
package { import flash.display.Sprite; import flash.display.MovieClip; import flash.events.MouseEvent; public class Main extends Sprite{ private var myMovieClip:MovieClip; public function Main():void{ myMovieClip.addEventListener(MouseEvent.CLICK,onClickHandler); } private function onClickHandler(e:MouseEvent):void{ trace("that's the spot..."); } } }
Probably the method that causes nightmares to newcomers of the AS3 and OOP world, and probably the best method for mild-to-highly complex Flash projects.
Look at it as timeline programming with a few extra characters that will help you create a robust, reusable code. You will always know where it is, making reading and understanding your work easier.
Download example 5 to see this method in action.
Note: If the button's design is simple enough we could have built it inside the class with no need for Flash IDE and its fancy design tools. Most of the time it's just not practical.
Then "God" Created the Button Component
Back to the main story, Adam accidentally deleted the shape that someone had made as the button and since he didn't know how to use the rectangle tool to draw a new button he took the component route. Here's how he did it.
- He added the Button component to the library.
- He saved his code as MyButton.as in the same directory as his FLA file.
- He set the Document class in the FLA file to MyButton.
package { import fl.controls.Button; import flash.display.Sprite; import flash.events.MouseEvent; public class MyButton extends Sprite { private var b1:Button; public function MyButton () { setupButtons(); } private function setupButtons():void { b1 = new Button(); b1.width = 160; b1.move(10,10); b1.label = "Apple Juice"; b1.addEventListener(MouseEvent.CLICK, buttonClick); addChild(b1); } private function buttonClick(e:MouseEvent) { var button:Button = e.target as Button; trace(button.label + " tickles"); } } }
When to use this? If you're planning to build a user interface for a rich internet application and instead of using Flex you want to try out Flash, then that's the way to do it. (My advice would be to go with Flash Builder instead) or if you just need a simple UI for whatever form you're building which doesn't require much design work. Of course you can customize a button component, but that takes too long compared to building a button from scratch.
Download example 6 to see this method in action.
Conclusion
Ultimately the decision is yours. I've numbered the methods I've come to know and use throughout my Flash developing career and the opinions here mentioned are the ones I came to realize while working on different projects.
If you feel comfortable with your button making method and feel it suits you, then that's fine, as long as it works, but eventually you will come to understand why OOP structured ActionScript is a best practice. Not because it's geekier, but because it's actually easier, to write, to read and therefore to understand.
Thanks for reading, I hope you liked it, and have a great 2010!
Note: Adam managed to get hold of the apple juice box, which he gave to Eve. The rest of the tale, you probably know..
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/buttonology-a-walkthrough-of-button-making-methods--active-2893 | CC-MAIN-2020-40 | refinedweb | 1,713 | 65.01 |
I: > {-# LANGUAGE GADTs #-} > import Codec.Compression.GZip > import Control.Applicative > import Control.Concurrent.CHP > import qualified Control.Concurrent.CHP.Common as CHP > import Control.Concurrent.CHP.Enroll > import Control.Concurrent.CHP.Utils > import Control.Monad.State.Strict > import Data.Digest.Pure.MD5 > import Data.Maybe > import qualified Data.ByteString.Char8 as BS > import qualified Data.ByteString.Lazy.Char8 as LBS > import qualified Data.ByteString.Lazy.Internal as LBS > import System.Environment > import System.IO > import System.IO.Unsafe > > > calculateMD5 :: (ReadableChannel r, > Poisonable (r (Maybe BS.ByteString)), > WriteableChannel w, > Poisonable (w MD5Digest)) > => r (Maybe BS.ByteString) > -> w MD5Digest > -> CHP () > calculateMD5 in_ out = evalStateT (forever loop) md5InitialContext > `onPoisonRethrow` (poison in_ >> poison out) > where loop = liftCHP (readChannel in_) >>= > calc' > calc' Nothing = gets md5Finalize >>= > liftCHP . > writeChannel out >> > put md5InitialContext > calc' (Just b) = modify (flip md5Update > $ LBS.fromChunks [b]) Calculate MD5 hash of input stream. Nothing indicates EOF. > unsafeInterleaveCHP :: CHP a -> CHP a > unsafeInterleaveCHP = fromJust <.> liftIO <=< > unsafeInterleaveIO <.> embedCHP Helper function. It is suppose to move the execution in time - just as unsafeInterleaveIO. I belive that the main problem lives here. Especially that Maybe.fromJust: Nothing is the error. > chan2List :: (ReadableChannel r, Poisonable (r a)) > => r a -> CHP [a] > chan2List in_ = unsafeInterleaveCHP ((liftM2 (:) (readChannel in_) > (chan2List in_)) > `onPoisonTrap` return []) Changes channel to lazy read list. > chanMaybe2List :: (ReadableChannel r, > Poisonable (r (Maybe a))) > => r (Maybe a) > -> CHP [[a]] > chanMaybe2List in_ = splitByMaybe <$> chan2List > where splitByMaybe [] = [] > splitByMaybe (Nothing:xs) = > []:splitByMaybe xs > splitByMaybe (Just v :[]) = [[v]] > splitByMaybe (Just v :xs) = > let (y:ys) = splitByMaybe xs > in (v:y):ys Reads lazyly from channel o list of list > compressCHP :: (ReadableChannel r, > Poisonable (r (Maybe BS.ByteString)), > WriteableChannel w, > Poisonable (w (Maybe BS.ByteString))) > => r (Maybe BS.ByteString) > -> w (Maybe BS.ByteString) > -> CHP () > compressCHP in_ out = toOut >>= mapM_ sendBS > where in_' :: CHP [LBS.ByteString] > in_' = fmap LBS.fromChunks <$> > chanMaybe2List in_ > toOut :: CHP [LBS.ByteString] > toOut = fmap compress <$> in_' > sendBS :: LBS.ByteString -> CHP () > sendBS LBS.Empty = writeChannel out > Nothing > sendBS (LBS.Chunk c r) = writeChannel out > (Just c) > >> sendBS r Compress process > readFromFile :: (ReadableChannel r, > Poisonable (r String), > WriteableChannel w, > Poisonable (w (Maybe BS.ByteString))) > => r String > -> w (Maybe BS.ByteString) > -> CHP () > readFromFile file data_ = > forever (do path <- readChannel file > hnd <- liftIO $ openFile path ReadMode > let copy = liftIO (BS.hGet hnd LBS.defaultChunkSize) >>= > writeChannel data_ . Just > copy `onPoisonRethrow` liftIO (hClose hnd) > writeChannel data_ Nothing > liftIO $ hClose hnd) > `onPoisonRethrow` (poison file >> poison data_) Process reading from file > writeToFile :: (ReadableChannel r, > Poisonable (r String), > ReadableChannel r', > Poisonable (r' (Maybe BS.ByteString))) > => r String > -> r' (Maybe BS.ByteString) > -> CHP () > writeToFile file data_ = > forever (do path <- readChannel file > hnd <- liftIO $ openFile path WriteMode > let writeUntilNothing = readChannel data_ >>= > writeUntilNothing' > writeUntilNothing' Nothing = return () > writeUntilNothing' (Just v) = liftIO (BS.hPutStr > hnd v) >> > writeUntilNothing > writeUntilNothing `onPoisonFinally` liftIO (hClose hnd)) > `onPoisonRethrow` (poison file >> poison data_) Process writing to file > getFiles :: (WriteableChannel w, Poisonable (w String)) > => w String -> CHP () > getFiles out = mapM_ (writeChannel out) ["test1", "test2"] >> > poison (out) Sample files. Each contains "Test1\n" > pipeline1 :: CHP () > pipeline1 = do md5sum <- oneToOneChannel' $ chanLabel "MD5" > runParallel_ [(getFiles ->|^ > ("File", readFromFile) ->|^ > ("Data", calculateMD5)) > (writer md5sum), > forever $ readChannel (reader md5sum) >>= > liftIO . print] First pipeline. Output: fa029a7f2a3ca5a03fe682d3b77c7f0d fa029a7f2a3ca5a03fe682d3b77c7f0d < File."test1", Data.Just "Test1\n", Data.Nothing, MD5.fa029a7f2a3ca5a03fe682d3b77c7f0d, File."test2", Data.Just "Test1\n", Data.Nothing, MD5.fa029a7f2a3ca5a03fe682d3b77c7f0d > > pipeline2 :: CHP () > pipeline2 = enrolling $ do > file <- oneToManyChannel' $ chanLabel "File" > fileMD5 <- oneToOneChannel' $ chanLabel "File MD5" > data_ <- oneToOneChannel' $ chanLabel "Data" > md5 <- oneToOneChannel' $ chanLabel "MD5" > md5BS <- oneToOneChannel' $ chanLabel "MD5 ByteString" > fileMD5' <- Enroll (reader file) > fileData <- Enroll (reader file) > liftCHP $ runParallel_ [getFiles (writer file), > (forever $ readChannel fileMD5' >>= > writeChannel (writer fileMD5) . > (++".md5")) > `onPoisonRethrow` > (poison fileMD5' >> > poison (writer fileMD5)), > readFromFile fileData (writer data_), > calculateMD5 (reader data_) (writer md5), > (forever $ do v <- readChannel (reader md5) > let v' = Just $ BS.pack $ show v > writeChannel (writer md5BS) v' > writeChannel (writer md5BS) > Nothing) > `onPoisonRethrow` > (poison (writer md5BS) >> > poison (reader md5)), > writeToFile (reader fileMD5) (reader md5BS)] Correct pipeline (testing EnrollingT): < _b4, File MD5."test1.md5", Data.Just "Test1\n", Data.Nothing, MD5.fa029a7f2a3ca5a03fe682d3b77c7f0d, _b4, MD5 ByteString.Just "fa029a7f2a3ca5a03fe682d3b77c7f0d", Data.Just "Test1\n", Data.Nothing, MD5 ByteString.Nothing, MD5.fa029a7f2a3ca5a03fe682d3b77c7f0d, File MD5."test2.md5", MD5 ByteString.Just "fa029a7f2a3ca5a03fe682d3b77c7f0d", MD5 ByteString.Nothing > % cat test1.md5 fa029a7f2a3ca5a03fe682d3b77c7f0d% >" > > onPoisonFinally :: CHP a -> CHP () -> CHP a > onPoisonFinally m b = (m `onPoisonRethrow` b) <* b > Utility function (used for closing handles) > (<.>) :: Functor f => (b -> c) -> (a -> f b) -> a -> f c > f <.> g = fmap f . g <.> is for <$> as . to $. > instance MonadCHP m => MonadCHP (StateT s m) where > liftCHP = lift . liftCHP Missing instance for strict monad > (->|^) :: Show b > => (Chanout b -> CHP ()) -> (String, Chanin b -> c -> CHP ()) > -> (c -> CHP ()) > (->|^) p (l, q) x = do c <- oneToOneChannel' $ chanLabel l > runParallel_ [p (writer c), q (reader c) x] 'Missing' helper function > data EnrollingT a where > Lift :: CHP a -> EnrollingT a > Enroll :: (Enrollable b z) => b z -> EnrollingT (Enrolled b z) > > enrolling :: EnrollingT a -> CHP a > enrolling (Lift v) = v > enrolling (Enroll b) = enroll b return > > instance Monad EnrollingT where > (Lift m) >>= f = Lift $ m >>= enrolling . f > (Enroll b) >>= f = Lift $ enroll b (enrolling . f) > return = Lift . return > instance MonadIO EnrollingT where > liftIO = Lift . liftIO > instance MonadCHP EnrollingT where > liftCHP = Lift Helper monad for enrolling (I know T should stand for transforming but then I realize problems). Thanks in advance | http://www.haskell.org/pipermail/haskell-cafe/2010-January/071584.html | CC-MAIN-2014-15 | refinedweb | 845 | 52.76 |
A constructor is a special type of member function that initialises an object automatically when it is created.
Compiler identifies a given member function is a constructor by its name and the return type.
Constructor has the same name as that of the class and it does not have any return type. Also, the constructor is always public.
... .. ... class temporary { private: int x; float y; public: // Constructor temporary(): x(5), y(5.5) { // Body of constructor } ... .. ... }; int main() { Temporary t1; ... .. ... }
Above program shows a constructor is defined without a return type and the same name as the class.
How constructor works?
In the above pseudo code,
temporary() is a constructor.
When an object of class
temporary is created, the constructor is called automatically, and x is initialized to 5 and y is initialized to 5.5.
You can also initialise the data members inside the constructor's body as below. However, this method is not preferred.
temporary() { x = 5; y = 5.5; } // This method is not preferred.
Use of Constructor in C++
Suppose you are working on 100's of
Person objects and the default value of a data member age is 0. Initialising all objects manually will be a very tedious task.
Instead, you can define a constructor that initialises age to 0. Then, all you have to do is create a
Person object and the constructor will automatically initialise the age.
These situations arise frequently while handling array of objects.
Also, if you want to execute some code immediately after an object is created, you can place the code inside the body of the constructor.
Example 1: Constructor in C++
Calculate the area of a rectangle and display it.
#include <iostream> using namespace std; class Area { private: int length; int breadth; public: // Constructor Area(): length(5), breadth(2){ } void GetLength() { cout << "Enter length and breadth respectively: "; cin >> length >> breadth; } int AreaCalculation() { return (length * breadth); } void DisplayArea(int temp) { cout << "Area: " << temp; } }; int main() { Area A1, A2; int temp; A1.GetLength(); temp = A1.AreaCalculation(); A1.DisplayArea(temp); cout << endl << "Default Area when value is not taken from user" << endl; temp = A2.AreaCalculation(); A2.DisplayArea(temp); return 0; }
In this program, class Area is created to handle area related functionalities. It has two data members length and breadth.
A constructor is defined which initialises length to 5 and breadth to.
Then, the member function
GetLength() is invoked which takes the value of length and breadth from the user for object A1. This changes the length and breadth of the object A1.
Then, the area for the object A1 is calculated and stored in variable temp by calling
AreaCalculation() function and finally, it is displayed.
For object A2, no data is asked from the user. So, the length and breadth remains 5 and 2 respectively.
Then, the area for A2 is calculated and displayed which is 10.
Output
Enter length and breadth respectively: 6 7 Area: 42 Default Area when value is not taken from user Area: 10
Constructor Overloading
Constructor can be overloaded in a similar way as function overloading.
Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
Since, there are multiple constructors present, argument to the constructor should also be passed while creating an object.
Example 2: Constructor overloading
// Source Code to demonstrate the working of overloaded constructors #include <iostream> using namespace std; class Area { private: int length; int breadth; public: // Constructor with no arguments Area(): length(5), breadth(2) { } // Constructor with two arguments Area(int l, int b): length(l), breadth(b){ } void GetLength() { cout << "Enter length and breadth respectively: "; cin >> length >> breadth; } int AreaCalculation() { return length * breadth; } void DisplayArea(int temp) { cout << "Area: " << temp << endl; } }; int main() { Area A1, A2(2, 1); int temp; cout << "Default Area when no argument is passed." << endl; temp = A1.AreaCalculation(); A1.DisplayArea(temp); cout << "Area when (2,1) is passed as argument." << endl; temp = A2.AreaCalculation(); A2.DisplayArea(temp); return 0; }
For object A1, no argument is passed while creating the object.
Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, area of the object A1 will be 10.
For object A2, 2 and 1 are passed as arguments while creating the object.
Thus, the constructor with two arguments is invoked which initialises length to l (2 in this case) and breadth to b (1 in this case). Hence, area of the object A2 will be 2.
Output
Default Area when no argument is passed. Area: 10 Area when (2,1) is passed as argument. Area: 2
Default Copy Constructor
An object can be initialized with another object of same type. This is same as copying the contents of a class to another class.
In the above program, if you want to initialise an object A3 so that it contains same values as A2, this can be performed as:
.... int main() { Area A1, A2(2, 1); // Copies the content of A2 to A3 Area A3(A2); OR, Area A3 = A2; }
You might think, you need to create a new constructor to perform this task. But, no additional constructor is needed. This is because the copy constructor is already built into all classes by default. | https://cdn.programiz.com/cpp-programming/constructors | CC-MAIN-2020-24 | refinedweb | 882 | 64.61 |
Finance Archive: Questions from October 26, 2013
- 1 answer
- 1 answer
- 3 answers
- designate the responsibility centers and the support centers for the organization selected. Prepare a rationale for the structure you have designated. Bob's Practice0 answers
- Scottie, Inc. has received an offer from two major manufacturing companies for the latest product offering. Based on the length of the contracts he has asked you to evaluate the offers using discount0 answers
- Because of the increased demand for its product, West, Inc. is in the process of expanding the production capacity. Current plans call for a possible expenditure of $400 thousand on the project. The0 answers
- Your company is considering the replacement of an old delivery van with a new one that is more efficient. The old van cost $30,000 when it was purchased 5 years ago. The old van is being depreciated u1 answer
- 2 answers
- Percy Motors has a target capital structure of 45% debt and 55% common equity, with no preferred stock. The yield to maturity on the company's outstanding bonds is 10%, and its tax rate is 40%. Percy'2 answers
- Javits & Sons' common stock currently trades at $37.00 a share. It is expected to pay an annual dividend of $2.75 a share at the end of the year (D1 = $2.75), and the constant growth rate is 6% a1 answer
- 0 answers
- Project Selection Midwest Water Works estimates that its WACC is 10.46%. The company is considering the following capital budgeting projects. Assume that each of these projects is just as risky as the1 answer
- The future earnings, dividends, and common stock price of Carpetto Technologies Inc. are expected to grow 6% per year. Carpetto's common stock currently sells for $21.25 per share; its last dividend w3 answers
- barkley corportation has a bond issue outstanding with an annual coupon rate of 7% and years remaining until maturity. the par value of the bond is $1,000. A.) What is the price of the bond if presen1 answer
- The Evanec Company's next expected dividend, D1, is $3.49; its growth rate is 7%; and its common stock now sells for $38. New stock (external equity) can be sold to net $36.10 per share. What is Ev1 answer
- The acai berry is a fruit that grows in the Amazon rain forest making up over 40% of the diet of the healthy people in that region. Marketers of this berry purport it to be significantly high in antio1 answer
- Cost of Common Equity and WACC Patton Paints Corporation has a target capital structure of 40% debt and 60% common equity, with no preferred stock. Its before-tax cost of debt is 11% and its marginal1 answer
- WACC The Patrick Company's year-end balance sheet is shown below. Its cost of common equity is 17%, its before-tax cost of debt is 8%, and its marginal tax rate is 40%. Assume that the firm's long-ter1 answer
- Deirdre sold 176 shares of stock to her brother, James, for $5,456. Deirdre purchased the stock several years ago for $7,216. (Loss amounts should be indicated by a minus sign.) a. What g2 answers
- Russell Corporation sold a parcel of land valued at $477,500. Its basis in the land was $360,512. For the land, Russell received $117,750 in cash in year 0 and a note providing that Russell will recei0 answers
- Prater Inc. enters into an exchange in which it gives up its warehouse on 10 acres of land and receives a tract of land. A summary of the exchange is as follows: Transferred FMV Or1 answer
- Prater Inc. enters into an exchange in which it gives up its warehouse on 10 acres of land and receives a tract of land. A summary of the exchange is as follows: Transferred FMV Or1 answer
- Kase, an individual, purchased some property in Potomac, Maryland, for $225,000 approximately 10 years ago. Kase is approached by a real estate agent representing a client who would like to exchange a
Kase, an individual, purchased some property in Potomac, Maryland, for $225,000 approximately 10 years ago. Kase is approached by a real estate agent representing a client who would like to exchange a1 answer
- Aruna, a sole proprietor, wants to sell two assets that she no longer needs for her business. Both assets qualify as �1231 assets. The first is machinery and will generate a $12,500 �1231 loss on1 answer
- Lily Tucker (single) owns and operates a bike shop as a sole proprietorship. This year, she sells the following long-term assets used in her business: Asset Sales Price Cost Accumulated De0 answers
- At the beginning of the year, you bought a $1,000 par value corporate bond with a 6 percent annual coupon rate and a 10-year maturity date. When you bought the bond, it had an expected yield to maturi0 answers
- Assume the market price of a 5-year bond for Margaret Inc. is $900, and it has a par value of $1000. The bond has an annual interest rate of 6 percent that is paid semi-annually. What is the yield to1 answer
- Assume you have a bond with a semiannual interest payment of $35, a par value of $1000, and a current market price of $780. What is the current yield of the bond?1 answer
- 3 answers
- If a firm plans on reducing the level of debt in their capital structure, then this should cause the cost of debt to ___________ and the cost of equity to ___________.2 answers
- These figures show that a tax on clothing can reduce the price of food. Suppose that after the tax on clothing consumption is imposed, another tax is levied on the consumption of food. For example, th1 answer
- At the accounting break-even point, Swiss Mountain Gear sells 14,600 ski masks at a price of $12 each. At this level of production, the depreciation is $58,000 and the variable cost per unit is $4. Wh1 answer
- The Good Life Insurance Co. wants to sell you an annuity which will pay you $740 per quarter for 20 years. You want to earn a minimum annual rate of return of 5.9 percent. What is the most you are wil1 answer
- You havep $36,000 today and you would like to purchase a 10-year annuity. If the annual discount rate is 6.20 percent, what will the annual cash flow be? $3,600.00 $8,068.42 $5,173.081 answer
- George Jefferson established a trust fund that provides $174,500 in scholarships each year in perpetuity for worthy students. The trust fund earns a 2 percent annual rate of return. How much money did1 answer
- Mr. Miser loans money at an annual rate of 19 percent interest with daily compounding. What is the effective annual rate Mr. Miser is charging on his loans? 20.98 percent 20.68 percent1 answer
- Tidewater Fishing has a current beta of 1.21. The market risk premium is 8.9 percent and the risk-free rate of return is 3.2 percent. By how much will the cost of equity increase if the company expand2 answers
- Leslie's Unique Clothing Stores offers a common stock that pays an annual dividend of $1.70 a share. The company has promised to maintain a constant dividend. How much are you willing to pay for one s2 answers
- Railway Cabooses just paid its annual dividend of $3.70 per share. The company has been reducing the dividends by 12.3 percent each year. How much are you willing to pay today to purchase stock in thi1 answer
- Shares of common stock of the Samson Co. offer an expected total return of 20.6 percent. The dividend is increasing at a constant 4.9 percent per year. The dividend yield must be: 20.60 per2 answers
- Grand Adventure Properties offers a 8 percent coupon bond with annual payments. The yield to maturity is 6.85 percent and the maturity date is 9 years from today. What is the market price of this bond1 answer
- Yang Corp. is growing quickly. Dividends are expected to grow at a rate of 25 percent for the next three years, with the growth rate falling off to a constant 6 percent thereafter. If the required ret2 answers
- Suppose the real rate is 10 percent and the inflation rate is 1 percent. What rate would you expect to see on a Treasury bill? 12.21% 12.77% 9.99% 9.44% 11.10%3 answers
- A zero coupon bond with a face value of $1,000 is issued with an initial price of $400.50. The bond matures in 23 years. What is the implicit interest, in dollars, for the first year of the bond's lif2 answers
- This afternoon, you deposited $1,000 into a retirement savings account. The account will compound interest at 6 percent annually. You will not withdraw any principal or interest until you retire in fo1 answer
- You are comparing two investment options that each pay 5 percent interest, compounded annually. Both options will provide you with $12,000 of income. Option A pays three annual payments starting with1 answer
- Most corpoerations pay quarterly dividens on their common stock rather than annual dividends. Barring any unusual circumstances during the year, the board raises, lowers, or maintains the current divi1 answer
- 2 answers
- You expect interest rates to decline in the near future even though the bond market is not indicating any sign of this change. Which one of the following bonds should you purchase now to maximize your3 answers
- Caculate the price of a 6 year bond with annual coupon payments, if the bond pays 4% in even years and pays 0% in odd year and has a YTM of 11% and face value of $100,000 Caculate the price of a 7 y1 answer
- Case 2 Competition among the north american warehouse clubs: costco wholesale versus sam's club versus bj's wholesale 1. What is competition like in the north american wholesale club industry? Which1 answer
- A 12- year bond has a 10% semi-annual coupon and a face value of $1000. The bond has a nominal yield to maturity of 7%. The bond can be called in 5 years at a call price of $1050. What is the bond's y2 answers
- You are the Budgeting Manager for the Thirty-One-Hundred Corporation. You will prepare the monthly cash budget for Thirty-One-Hundred for the year 2014. <?xml:namespace prefix = o ns = "urn:schem1 answer
- This afternoon, you deposited $1,000 into a retirement savings account. The account will compound interest at 6 percent annually. You will not withdraw any principal or interest until you retire in fo3 answers
- Which one of the following compounding periods will yield the smallest present value given the same stated/quoted future value and annual percentage rate? annual semi-annual monthly dail1 answer
- High Country Builders currently pays an annual dividend of $1.35 and plans on increasing that amount by 2.5 percent each year. Valley High Builders currently pays an annual dividend of $1.20 and plans2 answers
- Sartain Corporation is in the process of preparing its annual budget. The following beginning and ending inventory levels are planned for the year. Each unit of finished goods requires 2 gr2 answers
- I can't quite figure this problem out about MIRR and the book seems confusing on how to do the problem! Any help owuld be great! The required return is 10%. I need answers for the discunting approach,0 answers
- 7. Forward Rate a. Determine the forward rate for various one-year interest rate scenarios if the two-year interest rate is 8 percent, assuming no liquidity premium. Explain the relationship between0 answers
- 1. The Fed- Briefly describe the origin of the Federal Reserve System. Describe the functions of the Fed district banks. <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /2 answers
- As market interest rates ______, the value of a bond will _____. Answer A. fall; fall B. fall; rise C. rise; rise D. rise; fall both B. and D. A b1 answer
- The cost of debt money is _____. Answer dividends interest depreciation none of the above A premium on a security if that security cannot be converted to cash on sho2 answers
- you buy a 13 year bond with a 10% coupon rate and a YTM of 6% at the face value of P,000. What will be you annualized holding period return on this investment if you hold the bond for 13 years, the YT0 answers
- Bond Yields. A bond with face value $1,000 has a current yield of 6% and a coupon rate of 8%. What is the bond price?0 answers
- 2 answers
- 1 answer
- 2 answers
- I have found the way to determine payback but am having trouble understand part 2 of the question. I am trying to solve using excel. 1) An investment project requires a net investment of $100,01 answer
- Project K costs $45,000, its expected cash inflows are $13,000 per year for 8 years, and its WACC is 11%. What is the project's NPV? Round your answer to the nearest cent.1 answer
- Capital budgeting criteria: ethical considerations An electric utility is considering a new power plant in northern Arizona. Power from the plant would be sold in the Phoenix area, where it is badly n1 answer
- Capital budgeting criteria A firm with a 13% WACC is evaluating two projects for this year's capital budget. After-tax cash flows, including depreciation, are as follows: 0 1 2 3 4 51 answer
- NPV Your division is considering two projects with the following cash flows (in millions): 0 1 2 3 Project A -$21 $14 $9 $3 Project B -$35 $20 $8 $15 What are the1 answer
- Project K costs $45,000, its expected cash inflows are $11,000 per year for 8 years, and its WACC is 8%. What is the project's discounted payback? Round your answer to two decimal places. years1 answer
- Project K costs $55,000, its expected cash inflows are $11,000 per year for 9 years, and its WACC is 13%. What is the project's payback? Round your answer to two decimal places. years2 answers
- Project K costs $55,000, its expected cash inflows are $10,000 per year for 8 years, and its WACC is 11%. What is the project's MIRR? Round your answer to two decimal places. %2 answers
- Project K costs $69,986.24, its expected cash inflows are $14,000 per year for 11 years, and its WACC is 9%. What is the project's IRR? Round your answer to two decimal places.1 answer
- Project K costs $45,000, its expected cash inflows are $13,000 per year for 8 years, and its WACC is 11%. What is the project's NPV? Round your answer to the nearest cent. $1 answer
- 1 answer
- 0 answers
- Your firm, which specializes in complex electronic products, has grown rapidly and you are now incorporating. Even after incorporation, a large percentage of the stock will be held by the founders, in1 answer
- The owner of a company is debating between factoring the accounts receivables of the company and investing the proceeds to invest in the stock market, or continue receiving the AR payments. If he fac2 answers | https://www.chegg.com/homework-help/questions-and-answers/finance-archive-2013-october-26 | CC-MAIN-2018-26 | refinedweb | 2,595 | 64.3 |
It seems like mxmlc generates different binary even when the source code is not changed.
for, example,
// Test.as
package
{
public class Test { }
}
and when i run mxmlc like this :
mxmlc Test.as -output case1.swf
mxmlc Test.as -output case2.swf
and case1.swf and case2.swf is different!
I found that mxmlc sets metadata and some timestamp in .swf file,
I could get the same binary by "unpacking" .swf, removing timestamp, and manually re-pack it.
( )
But it'll be happier when there is a special switch which generates same binary data ( That means, if mxmlc removes all timestamp and metadata which generated in compile time ) !
Is there any way to do it, or should i build specialized mxmlc compiler?
There is no option to do that.
Have you get some thing about it?
i am confused with this ,too | https://forums.adobe.com/thread/855581 | CC-MAIN-2015-40 | refinedweb | 142 | 80.48 |
After a bit of a break, I am ready to continue these exercises as well as put out some other things I have been working on. Chapter 7 exercise 3 wants us to create two functions using a structs given values, then use those functions and the struct in a program. Here is my solution to this problem:
3. Here is a structure declaration:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a. Write a function that passes a box structure by value and that displays the value of
each member.
b. Write a function that passes the address of a box structure and that sets the volume
member to the product of the other three dimensions.
c. Write a simple program that uses these two functions.
#include <iostream> using namespace std; struct box { char maker[40]; float height; float width; float length; float volume; }; void showValue(box); void setVolume(box*); int main() { box toyBox = {"Elf", 2.5, 3.3, 5.0, 0}; showValue(toyBox); setVolume(&toyBox); cout << "\n\nWith volume calculated: \n"; showValue(toyBox); return 0; } void showValue(box ourStruct) { cout << "Struct details\n"; cout << "Struct maker: " << ourStruct.maker << endl; cout << "Struct height: " << ourStruct.height << endl; cout << "Struct width: " << ourStruct.width << endl; cout << "Struct length: " << ourStruct.length << endl; cout << "Struct volume: " << ourStruct.volume << endl; } void setVolume(box* ourStruct) { ourStruct->volume = ourStruct->height * ourStruct->width * ourStruct->length; }
Advertisements | https://rundata.wordpress.com/2013/03/20/c-primer-plus-chapter-7-exercise-3/ | CC-MAIN-2017-26 | refinedweb | 233 | 73.17 |
Import python file.
Hello,
Is it possible to load a python file in another file in Drawbot? Have been googling for pure python solutions, but I can't get it to work.
Basically what I want:
I have my main python code which I run to generate a movie. I want to load the 'settings' (just a bunch of variables I set in the beginning of the code) from another file. This way I can update the code and have the designer save different sets of settings and load these. What would be the way to go about this?
I tried something like settings a function in the
settings.py!
@gferreira Thanks for your quick reply. I actually was trying something like that, but couldn't get the variables out.
It's working now, but I have to restart Drawbot everytime I want to load new settings. I can't just resave the settings file and rerun the script, it'll use the old variables.
I think it sounds best to load something from an external JSON file. I will look into that.
Basically I want the designers who use my code to keep a folder of different settings they can use for different outcomes. Now they save multiple versions of the code...
@snaders right, I forgot to mention: to update the contents of a module, you need to reload it:
from importlib import reload import settings reload(settings) from settings import * print(aVariable) print(anotherVariable)
cheers!
@gferreira Ah nice, that works.
Just have 2 questions/wishes left. Tried googling, but these things look so confusing to me...
I know have this:
from importlib import reload import settings_new reload(settings_new) from settings_new import *
Which works. Ideally I would let people set a variable (in this case) called
settings_new. | https://forum.drawbot.com/topic/222/import-python-file/3?lang=en-US | CC-MAIN-2020-16 | refinedweb | 298 | 75.2 |
Hello John, * John Calcote wrote on Thu, Mar 27, 2008 at 03:03:25PM CET: > > include_HEADERS = file1.h file2.h ... fileN.h > > But very often, these lists will contain shell expansions, like this: > > if ENABLED_ADDED_FUNCTIONALITY_A > added_functionality_a = fileX.h fileY.h > endif > > include_HEADERS = file1.h file2.h $(added_functionality_a) ... fileN.h FWIW, this is not a shell expansion, it's an automake conditional which sets a make variable which is used for setting include_HEADERS. > Now, here's my question: I've always been under the impression that > such dependency lists MUST be statically defined for the sake of > automake. Is this no longer true? Or was it ever true? Unfortunately, the answer is "it depends". It depends on the type of lists whether automake needs to know literal file names, and the type also makes a difference in "how" literal those names have to be. The fact that it depends poses one hidden complexity for Automake users, and changes to lessen that dependency are very welcome. Examples on different types of literal-ness: Assume that 'variable' is some automake-magic variable (like include_HEADERS, foo_SOURCES, etc). # completely literal: variable = foo bar baz # This works always. # completely literal, but (conditional) additions: variable = foo if CONDITION variable += bar endif variable += baz # This works for almost all stuff (but notably not yet for # info_TEXINFOS, that's still a TODO item). # using variable expansions with variables defined here, literally, # the variables containing sub-lists: variable = foo $(helper) baz helper = bar # This should work almost always, too. # using variable expansions with variables defined here, literally, # the variables containing sub-words: variable = foo $(subdir)/bar baz subdir = sub # This fails for example with dependency tracking and *_SOURCES, # because the code that generates the stub .deps/foo.Po files is # really dumb in that it greps the Makefile and thus has no idea # about variable expansion. # using variable expansions with substituted variables: # Here, configure.ac contains AC_SUBST([helper]). variable = foo $(helper) baz # This works often, but not always. In some cases it is possible # to get automake to emit the needed rules with EXTRA_ helpers, for # example see EXTRA_PROGRAMS in 'info Automake Uniform', or by using # different magic variables, for example man1_MANS instead of man_MANS # (with the latter, automake needs to be able to extract the man section # from the name). # using shell expansions: variable = fo* # This is almost always a bad idea, because if $(variable) ends up in # some prerequisite list, it will not do the right thing. # using GNU make-specific expansions: variable = $(wildcard fo*) # This works with lists where automake doesn't have to do much except # know that they exist. However, one should keep in mind that automake # can not parse these expansions. Hope that helps. Cheers, Ralf | http://lists.gnu.org/archive/html/automake/2008-03/msg00098.html | CC-MAIN-2014-35 | refinedweb | 452 | 53.41 |
The method getQueryString in class org.apache.catalina.connector.Request returns
null, instead of an empty string for a URL of the form? as
required by the specification. A correct implementation of the method is as
follows:
/**
* Return the query string associated with this request.
*/
public String getQueryString() {
Object qStrObj = coyoteRequest.queryString();
return ((qStrObj == null) ? null : qStrObj.toString());
}
This is fixed in the SVN trunk, and will appear in 5.5.16
(In reply to comment #1)
> This is fixed in the SVN trunk, and will appear in 5.5.16
The fix is not correct.
Following jsp:
<jsp:expression>"" + request.getQueryString()</jsp:expression>
does not write 'null' to the page, even if not question mark on the url.
While javadoc of HttpServletRequest#getQueryString states:
public java.lang.String getQueryString()
Returns the query string that is contained in the request URL after the
path. This method returns null if the URL does not have a query string. Same as
the value of the CGI variable QUERY_STRING.
(Sorry if this results in a duplicate post, BugZilla seems to be very flacky
today and commiting comments does not seem to work)
I agree. This "fix" breaks webapps: JForum, and maybe others.
The original assumption behind this change was incorrect, the specification
clearly states that getQueryString() *should* return null, not an empty string.
(In reply to comment #3)
> I agree. This "fix" breaks webapps: JForum, and maybe others.
>
> The original assumption behind this change was incorrect, the specification
> clearly states that getQueryString() *should* return null, not an empty string.
Most likely, this will be the one and only time I agree with you on something.? means there's no query String -> it should most likely return
null anyway (and if it shouldn't, it's not actually specified anywhere).
Ok, so I reverted the fix.
Please read specifications:
5.2.1. Pre-parse the Base URI
other components may be empty or undefined....
A component is undefined if its associated delimiter does not appear
in the URI reference; the path component is never undefined, though it may be empty.
--------------------------------------------------------------
So for query we have two values null and "".
Please fix this because Tomcat is the only tested container (even 6.28) which is not capable to tell difference between /aaa? and /aaa.
(WAS, WLS and many others correctly return "" and null) for suplied data.
If you so afraid about old ignorant existing apps, please implement as switch.
I've fixed this for Tomcat 7.0.x. It will be included in 7.0.3 onwards.
I'll propose a back port (off by default, configured via a system property) for 5.5.x and 6.0.x.
Backports proposed.
Fixed in 5.5.x and will be in 5.5.31 onwards.
Fixed in 6.0.x and will be included in 6.0.30 onwards. | https://bz.apache.org/bugzilla/show_bug.cgi?id=38113 | CC-MAIN-2016-50 | refinedweb | 473 | 68.97 |
.
- Date Field - a date object with year/month/day and optional time.
- Geopoint Field - a data object with latitude and longitude coordinates.
The maximum size of a document is 1 MB.
Indexes may be increased to up to 200GB by submitting a request from the Google Cloud Console App Engine Search page.":
def simple_search(index): index.search('rose water')
This one searches for documents with date fields that contain the date July 4, 1776, or text fields that include the string "1776-07-04":
def search_date(index): index.search('1776-07-04'):
def search_terms(index): # search for documents with pianos that cost less than $5000 index.search("product = piano AND price < 5000") call to
search()can only return a limited number of matching documents. Your search may find more documents than can be returned in a single call. Each search call returns an instance of the.
Documents and fieldsThe Document class represents documents. Each document has a document identifier and a list of fields.
Document identifier
Every document in an index must have a unique document identifier, or
doc_id.
The identifier can be used to retrieve a document from an index without performing
a search. By default, the Search API automatically generates a
doc_id when
a document is created. You can also specify the
doc_id yourself when you
create a document. A
doc_id_id in a search. Consider this scenario: You
have an index with documents that represent parts, using the part's serial
number as the
doc_id..
- Date Field: A
datetime.dateor
datetime.datetime.
- Geopoint Field: A point on earth described by latitude and longitude coordinates.
The field types are specified by the classes
TextField,
HtmlField,
AtomField,
NumberField,
DateField,
and
GeoField.
Special treatment of string and date fields
When a document with date,, backsl allowed.
.
For the purpose of indexing and searching the
date field, any time component is
ignored and the date is converted to the number of days since 1/1/1970 UTC. This
means that even though a date field
can contain a precise time value a date query can only specify a
date field value in the form
yyyy-mm-dd. This also means the sorted order of
date fields with the same date is
not well-defined. property specifies the language in which the fields are encoded.
See the
Document
class reference page for more details about these attributes.
Linking from a document to other resources
You can use a document's
doc_id and other fields as links to other
resources in your application. For example, if you use
Blobstore you can associate
the document with a specific blob by setting the
doc_id or the value of an
Atom field to the BlobKey of the data.
Creating a
Working with an index
Putting documents in an index
When you put a document into an index, the document is copied to persistent
storage and each of its fields is indexed according to its name, type, and the
doc_id.
The following code example shows how to access an Index and put a document into it.
def add_document_to_index(document): index = search.Index('products') index.put(document)
put()method. Batching puts is more efficient than adding documents one at a time.
When you put a document into an index and the index already contains a document
with the same
doc_id, the new document replaces the old one. No warning is
given. You can call
Index.get(id)
before creating or adding a document to an index to check whether a specific
doc_id already exists.
Note that creating an instance of the
Index
class does not guarantee that a
persistent index actually exists. A persistent index is created the first time
you add a document to it with the
put method.
If you want to check whether or not an
index actually exists before you start to use it, use the
search.get_indexes()
function.
Updating documents
A document cannot be changed once you've added it to an index. You can't add or
remove fields, or change a field's value. However, you can replace the document
with a new document that has the same
doc_id.
Retrieving documents by doc_idThere are two ways to retrieve documents from an index using document identifiers:
- Use
Index.get()to fetch a single document by its
doc_id.
- Use
Index.get
Searching for documents by their contents
To retrieve documents from an index, you construct a query string and call
Index.search().
The query string can be passed directly
as the argument, or you can include the string in a
Query
object which is passed as the argument.
By default,
search() returns matching
documents sorted in order of decreasing rank. To control how many documents are
returned, how they are sorted, or add computed fields to the results, you need
to use a
Query object, which contains a query string and can also specify
other search and sorting options..You can view the schemas for your indexes like this:. | https://cloud.google.com/appengine/docs/standard/python/search?hl=zh-tw | CC-MAIN-2020-45 | refinedweb | 825 | 64 |
On the 17th of April, Oracle Labs presented the community the first release cadence for their new universal virtual machine called GraalVM. Graal is a Polyglot VM that can run multiple languages and can interop between them without any overhead. In this blog post I will go into details what this means for Scala and especially for Play Framework and what runtime characteristics the new VM has, when running Play on top of it.
Graal currently comes in two flavors, one is the Community Edition which is open source and comes with the same license as a regular OpenJDK VM. Sadly at the moment the Community Edition is only available for Linux, which is good for production but mostly not enough for everyday development if you are not running Linux on your development machine.
There is also another edition called the Enterprise Edition which is not open source and you need to acquire a license to use it in production, but according to the docs it’s safe to use for development and evaluation. The Enterprise Edition is currently available for macOS and Linux, it has further benefits (comes with a smaller footprint and has more sandbox capabilities).
In the future the Graal team will probably present us with more options regarding the operating system. For our blog post we stick to the Community Edition on Linux.
Play Production Mode
Running Play or any Scala application on Graal is probably as easy as just switching to another Java VM. We will build the Play example project, via sbt-assembly and copy the production JAR to a regular server.
After downloading Graal and unpacking it, one can just run the application via
$GRAAL_HOME/bin/java -Xms3G -Xmx3G -XX:+UseG1GC -jar play-scala-starter-example-assembly-1.0-SNAPSHOT.jar. Keep in mind for a production run, one would use a service manager or run the application inside an orchestration system like Kubernetes.
The Play application started without any problem and one could use
curl to ensure it is running via
curl and it will print the Play “hello world page”.
“Performance” of Graal
After having the application running we can check how many requests/s it can serve via Graal, so we start up
wrk with the following params:
wrk -c100 -d1m -t2 and get an output like that (after a few runs):
Running 1m test @ 2 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 33.83ms 62.66ms 1.56s 94.36% Req/Sec 2.15k 314.10 3.17k 68.92% 255800 requests in 1.00m, 1.76GB read Requests/sec: 4260.50 Transfer/sec: 30.07MB
We can also compare that with a regular JVM which will output the following (after a few runs):
Running 1m test @ 2 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 38.41ms 70.39ms 1.79s 97.70% Req/Sec 1.62k 219.60 3.10k 74.37% 193123 requests in 1.00m, 1.33GB read Requests/sec: 3216.56 Transfer/sec: 22.70MB
As we can see Graal will be way faster compared to a regular JVM. The performance boost probably comes from better escape analysis. Keep in mind that the performance will be less on your own tests since you probably won’t run “hello world” on your systems.
AoT compilation
Currently Graal also has a way to compile a Java application to a single binary via
native-image. However on Scala 2.12
native-image won’t work since Scala 2.12 relies on the invokedynamic bytecode instruction which as of now is not supported in SubstrateVM. But for reference I tried to use native-image on Scala 2.11.
To make that work I used sbt-assembly to create a standalone JAR that I can use as a reference to my
native-image.
Sadly that also won’t work and will fail with the following error:
native-image --no-server -jar target/scala-2.11/play-scala-seed-assembly-1.0-SNAPSHOT.jar classlist: 10,847.38 ms (cap): 4,676.51 ms setup: 5,769.91 ms warning: unknown locality of class Lplay/api/ApplicationLoader$JavaApplicationLoaderAdapter$1;, assuming class is not local. To remove the warning report an issue to the library or language author. The issue is caused by Lplay/api/ApplicationLoader$JavaApplicationLoaderAdapter$1; which is not following the naming convention. analysis: 8,730.53 ms error: unsupported features in 3 methods Detailed message: Error: Must not have a FileDescriptor in the image heap. Trace: object java.io.FileOutputStream object java.io.BufferedOutputStream
Polyglot
One feature I was excited the most was support for Polyglot, which means that you can run other languages on top of the GraalVM. This is useful for interop with “native” languages or even JavaScript.
Sadly in the current form JavaScript can’t run NodeJS code from a Java Context which means that if I start my program with
java my.package.Main and try to call into JavaScript that it can’t run Node. See: for more details on the problem.
But what worked perfectly fine, was calling into native code. In the following example I just try to make a request to example.com via libcurl and print the response code inside my play controller.
For that to work we first need to create a C file:
#include <stdio.h> #include <curl/curl.h> long request() { CURL *curl = curl_easy_init(); long response_code = -1; if(curl) { CURLcode res; curl_easy_setopt(curl, CURLOPT_URL, ""); res = curl_easy_perform(curl); if(res == CURLE_OK) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); } curl_easy_cleanup(curl); } return response_code; }
and turn it into bitcode via:
clang -c -O1 -emit-llvm graal.c .
Than we need to add
graal-sdk to our
build.sbt via:
libraryDependencies += "org.graalvm" % "graal-sdk" % "1.0.0-rc1"
After that we can change one of our Play controllers to invoke it:
private val cpart = { val polyglot = Context .newBuilder() .allowAllAccess(true) .option("llvm.libraries", "/usr/lib/libcurl.dylib") .build() val source = Source .newBuilder("llvm", new File("/Users/play/projects/scala/play-scala-seed/graal.bc")) .build() polyglot.eval(source) } def index() = Action { implicit request: Request[AnyContent] => val responseValue = cpart.getMember("request").execute() val responseCode = responseValue.asLong() Ok(s”$responseCode”) }
Creating a polyglot
Context from Java and calling into another language currently works for the following languages (some which might be more experimental than others): JavaScript, all languages which can be turned into bitcode (C, C++, Rust, etc…), Python 3, R and Ruby.
Conclusion
In most cases Graal will actually run your Play application way faster than a regular JVM. Graal is especially good in running Scala code, since it has a way better escape analysis. However it can depend on your workload and what you do, so it’s probably a good idea to take a look at Graal by yourself.
If you are trying to interop with other languages Graal might also be a really good fit, since most languages can just be executed/run from a simple “Context” and Graal will also try his best to make the code as performant as possible. | https://blog.playframework.com/play-on-graal/ | CC-MAIN-2020-45 | refinedweb | 1,179 | 55.74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.